From 0ca163d02143e16b7e9cdeb78b30ac298cbff0c3 Mon Sep 17 00:00:00 2001 From: kotori0 Date: Sun, 24 Jan 2021 14:35:12 +0800 Subject: [PATCH] merge all subprojects into one dex --- .github/workflows/android.yml | 32 +- build.gradle | 2 +- dalvikdx/.gitignore | 2 - dalvikdx/build.gradle | 33 - dalvikdx/src/main/AndroidManifest.xml | 1 - dexmaker/.gitignore | 2 - dexmaker/build.gradle | 39 - dexmaker/src/main/AndroidManifest.xml | 1 - edxp-common/.gitignore | 1 - edxp-common/build.gradle | 61 - edxp-common/src/main/AndroidManifest.xml | 1 - edxp-core/build.gradle | 299 +- {edxp-common => edxp-core}/proguard-rules.pro | 0 .../src/main/cpp/main/src/config_manager.cpp | 8 +- .../src/main/cpp/main/src/config_manager.h | 19 +- .../src/main/cpp/main/src/edxp_context.cpp | 23 +- .../src/main/cpp/main/src/edxp_context.h | 2 +- .../java/android/app/AndroidAppHelper.java | 223 + .../main/java/android/app/package-info.java | 4 + .../android/content/res/XModuleResources.java | 54 + .../android/content/res/XResForwarder.java | 34 + .../java/android/content/res/XResources.java | 1749 +++++ .../android/content/res/package-info.java | 4 + .../com/elderdrivers/riru/common/KeepAll.java | 0 .../elderdrivers/riru/common/KeepMembers.java | 0 .../riru/edxp/_hooker/impl/HandleBindApp.java | 0 .../riru/edxp/_hooker/impl/LoadedApkCstr.java | 0 .../edxp/_hooker/impl/LoadedApkGetCL.java | 0 .../_hooker/impl/StartBootstrapServices.java | 0 .../riru/edxp/_hooker/impl/SystemMain.java | 0 .../_hooker/yahfa/HandleBindAppHooker.java | 0 .../yahfa/LoadedApkConstructorHooker.java | 0 .../yahfa/StartBootstrapServicesHooker.java | 0 .../yahfa/StartBootstrapServicesHooker11.java | 0 .../edxp/_hooker/yahfa/SystemMainHooker.java | 0 .../riru/edxp/art/ClassLinker.java | 0 .../com/elderdrivers/riru/edxp/art/Heap.java | 0 .../riru/edxp/config/BaseEdxpConfig.java | 0 .../riru/edxp/config/BaseHookProvider.java | 0 .../riru/edxp/config/ConfigManager.java | 0 .../riru/edxp/config/EdXpConfigGlobal.java | 23 + .../riru/edxp/config/EdxpConfig.java | 20 + .../riru/edxp/core/BaseEdxpImpl.java | 0 .../elderdrivers/riru/edxp/core/EdxpImpl.java | 0 .../com/elderdrivers/riru/edxp/core/Main.java | 38 +- .../elderdrivers/riru/edxp/core/Proxy.java | 0 .../riru/edxp/core/ResourcesHook.java | 0 .../elderdrivers/riru/edxp/core/Yahfa.java | 0 .../riru/edxp/core/yahfa/HookMain.java | 0 .../riru/edxp/deopt/InlinedMethodCallers.java | 0 .../edxp/deopt/PrebuiltMethodsDeopter.java | 0 .../entry/yahfa/AppBootstrapHookInfo.java | 0 .../entry/yahfa/SysBootstrapHookInfo.java | 0 .../edxp/entry/yahfa/SysInnerHookInfo.java | 0 .../riru/edxp/framework/Zygote.java | 0 .../riru/edxp/hook/HookProvider.java | 31 + .../riru/edxp/hooker/SliceProviderFix.java | 0 .../edxp/hooker/XposedInstallerHooker.java | 4 +- .../riru/edxp/proxy/BaseProxy.java | 0 .../riru/edxp/proxy/BaseRouter.java | 0 .../riru/edxp/proxy/NormalProxy.java | 0 .../elderdrivers/riru/edxp/proxy/Router.java | 0 .../sandhook/config/SandHookEdxpConfig.java | 0 .../sandhook/config/SandHookProvider.java | 0 .../edxp/sandhook/core/SandHookEdxpImpl.java | 0 .../edxp/sandhook/core/SandHookRouter.java | 0 .../sandhook/entry/AppBootstrapHookInfo.java | 0 .../sandhook/entry/SysBootstrapHookInfo.java | 0 .../edxp/sandhook/entry/SysInnerHookInfo.java | 0 .../sandhook/hooker/HandleBindAppHooker.java | 0 .../hooker/LoadedApkConstructorHooker.java | 0 .../hooker/StartBootstrapServicesHooker.java | 0 .../StartBootstrapServicesHooker11.java | 0 .../sandhook/hooker/SystemMainHooker.java | 0 .../riru/edxp/service/PackageReceiver.java | 0 .../riru/edxp/service/ServiceProxy.java | 0 .../riru/edxp/util/ClassLoaderUtils.java | 4 +- .../riru/edxp/util/ClassUtils.java | 0 .../elderdrivers/riru/edxp/util/DexUtils.java | 0 .../riru/edxp/util/FileUtils.java | 0 .../elderdrivers/riru/edxp/util/Hookers.java | 0 .../riru/edxp/util/MetaDataReader.java | 120 + .../riru/edxp/util/ProcessUtils.java | 0 .../riru/edxp/util/ProxyClassLoader.java | 0 .../elderdrivers/riru/edxp/util/Unsafe.java | 0 .../elderdrivers/riru/edxp/util/Utils.java | 2 +- .../elderdrivers/riru/edxp/util/Versions.java | 0 .../edxp/yahfa/config/YahfaEdxpConfig.java | 0 .../edxp/yahfa/config/YahfaHookProvider.java | 0 .../riru/edxp/yahfa/core/YahfaEdxpImpl.java | 0 .../riru/edxp/yahfa/core/YahfaRouter.java | 0 .../riru/edxp/yahfa/dexmaker/DexLog.java | 2 +- .../edxp/yahfa/dexmaker/DexMakerUtils.java | 0 .../edxp/yahfa/dexmaker/DynamicBridge.java | 0 .../edxp/yahfa/dexmaker/HookerDexMaker.java | 2 +- .../riru/edxp/yahfa/dexmaker/MethodInfo.java | 0 .../sandhook/xposedcompat/XposedCompat.java | 0 .../hookstub/CallOriginCallBack.java | 0 .../hookstub/HookMethodEntity.java | 0 .../hookstub/HookStubManager.java | 2 +- .../hookstub/MethodHookerStubs32.java | 0 .../hookstub/MethodHookerStubs64.java | 0 .../xposedcompat/methodgen/ErrorCatch.java | 0 .../xposedcompat/methodgen/HookMaker.java | 0 .../methodgen/HookerDexMaker.java | 0 .../methodgen/HookerDexMakerNew.java | 0 .../methodgen/SandHookXposedBridge.java | 0 .../xposedcompat/utils/ApplicationUtils.java | 0 .../sandhook/xposedcompat/utils/DexLog.java | 2 +- .../xposedcompat/utils/DexMakerUtils.java | 0 .../de/robv/android/xposed/DexCreator.java | 235 + .../robv/android/xposed/IModuleContext.java | 6 + .../android/xposed/IXposedHookCmdInit.java | 28 + .../IXposedHookInitPackageResources.java | 45 + .../xposed/IXposedHookLoadPackage.java | 45 + .../android/xposed/IXposedHookZygoteInit.java | 71 + .../de/robv/android/xposed/IXposedMod.java | 4 + .../de/robv/android/xposed/PendingHooks.java | 44 + .../de/robv/android/xposed/SELinuxHelper.java | 118 + .../de/robv/android/xposed/XC_MethodHook.java | 168 + .../android/xposed/XC_MethodReplacement.java | 88 + .../android/xposed/XSharedPreferences.java | 538 ++ .../de/robv/android/xposed/XposedBridge.java | 615 ++ .../de/robv/android/xposed/XposedHelpers.java | 1725 +++++ .../de/robv/android/xposed/XposedInit.java | 511 ++ .../xposed/annotation/ApiSensitive.java | 17 + .../robv/android/xposed/annotation/Level.java | 9 + .../android/xposed/callbacks/IXUnhook.java | 25 + .../callbacks/XC_InitPackageResources.java | 57 + .../xposed/callbacks/XC_InitZygote.java | 39 + .../xposed/callbacks/XC_LayoutInflated.java | 99 + .../xposed/callbacks/XC_LoadPackage.java | 63 + .../android/xposed/callbacks/XCallback.java | 154 + .../xposed/callbacks/package-info.java | 9 + .../de/robv/android/xposed/package-info.java | 4 + .../android/xposed/services/BaseService.java | 179 + .../xposed/services/BinderService.java | 166 + .../xposed/services/DirectAccessService.java | 113 + .../android/xposed/services/FileResult.java | 60 + .../xposed/services/ZygoteService.java | 54 + .../android/xposed/services/package-info.java | 4 + .../external/com/android/dex/Annotation.java | 0 .../external/com/android/dex/CallSiteId.java | 0 .../external/com/android/dex/ClassData.java | 0 .../external/com/android/dex/ClassDef.java | 0 .../java/external/com/android/dex/Code.java | 0 .../java/external/com/android/dex/Dex.java | 0 .../com/android/dex/DexException.java | 0 .../external/com/android/dex/DexFormat.java | 0 .../dex/DexIndexOverflowException.java | 0 .../com/android/dex/EncodedValue.java | 0 .../com/android/dex/EncodedValueCodec.java | 0 .../com/android/dex/EncodedValueReader.java | 0 .../external/com/android/dex/FieldId.java | 0 .../java/external/com/android/dex/Leb128.java | 0 .../com/android/dex/MethodHandle.java | 0 .../external/com/android/dex/MethodId.java | 0 .../java/external/com/android/dex/Mutf8.java | 0 .../external/com/android/dex/ProtoId.java | 0 .../java/external/com/android/dex/SizeOf.java | 0 .../com/android/dex/TableOfContents.java | 0 .../external/com/android/dex/TypeList.java | 0 .../android/dex/util/ByteArrayByteInput.java | 0 .../com/android/dex/util/ByteInput.java | 0 .../com/android/dex/util/ByteOutput.java | 0 .../dex/util/ExceptionWithContext.java | 0 .../com/android/dex/util/FileUtils.java | 0 .../com/android/dex/util/Unsigned.java | 0 .../external/com/android/dx/AnnotationId.java | 0 .../com/android/dx/AppDataDirGuesser.java | 0 .../external/com/android/dx/BinaryOp.java | 0 .../java/external/com/android/dx/Code.java | 0 .../external/com/android/dx/Comparison.java | 0 .../external/com/android/dx/Constants.java | 0 .../external/com/android/dx/DexMaker.java | 0 .../java/external/com/android/dx/FieldId.java | 0 .../java/external/com/android/dx/Label.java | 0 .../java/external/com/android/dx/Local.java | 0 .../external/com/android/dx/MethodId.java | 0 .../java/external/com/android/dx/TypeId.java | 0 .../external/com/android/dx/TypeList.java | 0 .../java/external/com/android/dx/UnaryOp.java | 0 .../java/external/com/android/dx/Version.java | 0 .../dx/cf/attrib/AttAnnotationDefault.java | 0 .../dx/cf/attrib/AttBootstrapMethods.java | 0 .../com/android/dx/cf/attrib/AttCode.java | 0 .../dx/cf/attrib/AttConstantValue.java | 0 .../android/dx/cf/attrib/AttDeprecated.java | 0 .../dx/cf/attrib/AttEnclosingMethod.java | 0 .../android/dx/cf/attrib/AttExceptions.java | 0 .../android/dx/cf/attrib/AttInnerClasses.java | 0 .../dx/cf/attrib/AttLineNumberTable.java | 0 .../dx/cf/attrib/AttLocalVariableTable.java | 0 .../cf/attrib/AttLocalVariableTypeTable.java | 0 .../AttRuntimeInvisibleAnnotations.java | 0 ...tRuntimeInvisibleParameterAnnotations.java | 0 .../attrib/AttRuntimeVisibleAnnotations.java | 0 ...AttRuntimeVisibleParameterAnnotations.java | 0 .../android/dx/cf/attrib/AttSignature.java | 0 .../dx/cf/attrib/AttSourceDebugExtension.java | 0 .../android/dx/cf/attrib/AttSourceFile.java | 0 .../android/dx/cf/attrib/AttSynthetic.java | 0 .../android/dx/cf/attrib/BaseAnnotations.java | 0 .../android/dx/cf/attrib/BaseAttribute.java | 0 .../dx/cf/attrib/BaseLocalVariables.java | 0 .../cf/attrib/BaseParameterAnnotations.java | 0 .../android/dx/cf/attrib/InnerClassList.java | 0 .../android/dx/cf/attrib/RawAttribute.java | 0 .../com/android/dx/cf/attrib/package.html | 0 .../com/android/dx/cf/code/BaseMachine.java | 0 .../com/android/dx/cf/code/BasicBlocker.java | 0 .../cf/code/BootstrapMethodArgumentsList.java | 0 .../dx/cf/code/BootstrapMethodsList.java | 0 .../com/android/dx/cf/code/ByteBlock.java | 0 .../com/android/dx/cf/code/ByteBlockList.java | 0 .../com/android/dx/cf/code/ByteCatchList.java | 0 .../com/android/dx/cf/code/ByteOps.java | 0 .../com/android/dx/cf/code/BytecodeArray.java | 0 .../android/dx/cf/code/ConcreteMethod.java | 0 .../android/dx/cf/code/ExecutionStack.java | 0 .../com/android/dx/cf/code/Frame.java | 0 .../android/dx/cf/code/LineNumberList.java | 0 .../android/dx/cf/code/LocalVariableList.java | 0 .../com/android/dx/cf/code/LocalsArray.java | 0 .../android/dx/cf/code/LocalsArraySet.java | 0 .../com/android/dx/cf/code/Machine.java | 0 .../com/android/dx/cf/code/Merger.java | 0 .../android/dx/cf/code/OneLocalsArray.java | 0 .../com/android/dx/cf/code/ReturnAddress.java | 0 .../com/android/dx/cf/code/Ropper.java | 0 .../com/android/dx/cf/code/RopperMachine.java | 0 .../com/android/dx/cf/code/SimException.java | 0 .../com/android/dx/cf/code/Simulator.java | 0 .../com/android/dx/cf/code/SwitchList.java | 0 .../android/dx/cf/code/ValueAwareMachine.java | 0 .../com/android/dx/cf/code/package.html | 0 .../android/dx/cf/cst/ConstantPoolParser.java | 0 .../com/android/dx/cf/cst/ConstantTags.java | 0 .../android/dx/cf/cst/MethodHandleKind.java | 0 .../dx/cf/direct/AnnotationParser.java | 0 .../dx/cf/direct/AttributeFactory.java | 0 .../dx/cf/direct/AttributeListParser.java | 0 .../android/dx/cf/direct/ClassPathOpener.java | 0 .../android/dx/cf/direct/CodeObserver.java | 0 .../android/dx/cf/direct/DirectClassFile.java | 0 .../android/dx/cf/direct/FieldListParser.java | 0 .../dx/cf/direct/MemberListParser.java | 0 .../dx/cf/direct/MethodListParser.java | 0 .../dx/cf/direct/StdAttributeFactory.java | 0 .../com/android/dx/cf/direct/package.html | 0 .../com/android/dx/cf/iface/Attribute.java | 0 .../android/dx/cf/iface/AttributeList.java | 0 .../com/android/dx/cf/iface/ClassFile.java | 0 .../com/android/dx/cf/iface/Field.java | 0 .../com/android/dx/cf/iface/FieldList.java | 0 .../com/android/dx/cf/iface/HasAttribute.java | 0 .../com/android/dx/cf/iface/Member.java | 0 .../com/android/dx/cf/iface/Method.java | 0 .../com/android/dx/cf/iface/MethodList.java | 0 .../android/dx/cf/iface/ParseException.java | 0 .../android/dx/cf/iface/ParseObserver.java | 0 .../android/dx/cf/iface/StdAttributeList.java | 0 .../com/android/dx/cf/iface/StdField.java | 0 .../com/android/dx/cf/iface/StdFieldList.java | 0 .../com/android/dx/cf/iface/StdMember.java | 0 .../com/android/dx/cf/iface/StdMethod.java | 0 .../android/dx/cf/iface/StdMethodList.java | 0 .../com/android/dx/cf/iface/package.html | 0 .../external/com/android/dx/command/Main.java | 0 .../android/dx/command/UsageException.java | 0 .../dx/command/annotool/AnnotationLister.java | 0 .../com/android/dx/command/annotool/Main.java | 0 .../android/dx/command/dexer/DxContext.java | 0 .../com/android/dx/command/dexer/Main.java | 0 .../com/android/dx/command/dump/Args.java | 0 .../android/dx/command/dump/BaseDumper.java | 0 .../android/dx/command/dump/BlockDumper.java | 0 .../android/dx/command/dump/ClassDumper.java | 0 .../android/dx/command/dump/DotDumper.java | 0 .../com/android/dx/command/dump/Main.java | 0 .../android/dx/command/dump/SsaDumper.java | 0 .../dx/command/findusages/FindUsages.java | 0 .../android/dx/command/findusages/Main.java | 0 .../com/android/dx/command/grep/Grep.java | 0 .../com/android/dx/command/grep/Main.java | 0 .../com/android/dx/dex/DexOptions.java | 0 .../dx/dex/cf/AttributeTranslator.java | 0 .../com/android/dx/dex/cf/CfOptions.java | 0 .../com/android/dx/dex/cf/CfTranslator.java | 0 .../com/android/dx/dex/cf/CodeStatistics.java | 0 .../android/dx/dex/cf/OptimizerOptions.java | 0 .../com/android/dx/dex/cf/package.html | 0 .../com/android/dx/dex/code/ArrayData.java | 0 .../android/dx/dex/code/BlockAddresses.java | 0 .../com/android/dx/dex/code/CatchBuilder.java | 0 .../android/dx/dex/code/CatchHandlerList.java | 0 .../com/android/dx/dex/code/CatchTable.java | 0 .../com/android/dx/dex/code/CodeAddress.java | 0 .../com/android/dx/dex/code/CstInsn.java | 0 .../com/android/dx/dex/code/DalvCode.java | 0 .../com/android/dx/dex/code/DalvInsn.java | 0 .../com/android/dx/dex/code/DalvInsnList.java | 0 .../external/com/android/dx/dex/code/Dop.java | 0 .../com/android/dx/dex/code/Dops.java | 0 .../android/dx/dex/code/FixedSizeInsn.java | 0 .../dx/dex/code/HighRegisterPrefix.java | 0 .../com/android/dx/dex/code/InsnFormat.java | 0 .../com/android/dx/dex/code/LocalList.java | 0 .../android/dx/dex/code/LocalSnapshot.java | 0 .../com/android/dx/dex/code/LocalStart.java | 0 .../com/android/dx/dex/code/MultiCstInsn.java | 0 .../com/android/dx/dex/code/OddSpacer.java | 0 .../android/dx/dex/code/OutputCollector.java | 0 .../android/dx/dex/code/OutputFinisher.java | 0 .../com/android/dx/dex/code/PositionList.java | 0 .../com/android/dx/dex/code/RopToDop.java | 0 .../android/dx/dex/code/RopTranslator.java | 0 .../com/android/dx/dex/code/SimpleInsn.java | 0 .../android/dx/dex/code/StdCatchBuilder.java | 0 .../com/android/dx/dex/code/SwitchData.java | 0 .../com/android/dx/dex/code/TargetInsn.java | 0 .../android/dx/dex/code/VariableSizeInsn.java | 0 .../com/android/dx/dex/code/ZeroSizeInsn.java | 0 .../com/android/dx/dex/code/form/Form10t.java | 0 .../com/android/dx/dex/code/form/Form10x.java | 0 .../com/android/dx/dex/code/form/Form11n.java | 0 .../com/android/dx/dex/code/form/Form11x.java | 0 .../com/android/dx/dex/code/form/Form12x.java | 0 .../com/android/dx/dex/code/form/Form20t.java | 0 .../com/android/dx/dex/code/form/Form21c.java | 0 .../com/android/dx/dex/code/form/Form21h.java | 0 .../com/android/dx/dex/code/form/Form21s.java | 0 .../com/android/dx/dex/code/form/Form21t.java | 0 .../com/android/dx/dex/code/form/Form22b.java | 0 .../com/android/dx/dex/code/form/Form22c.java | 0 .../com/android/dx/dex/code/form/Form22s.java | 0 .../com/android/dx/dex/code/form/Form22t.java | 0 .../com/android/dx/dex/code/form/Form22x.java | 0 .../com/android/dx/dex/code/form/Form23x.java | 0 .../com/android/dx/dex/code/form/Form30t.java | 0 .../com/android/dx/dex/code/form/Form31c.java | 0 .../com/android/dx/dex/code/form/Form31i.java | 0 .../com/android/dx/dex/code/form/Form31t.java | 0 .../com/android/dx/dex/code/form/Form32x.java | 0 .../com/android/dx/dex/code/form/Form35c.java | 0 .../com/android/dx/dex/code/form/Form3rc.java | 0 .../android/dx/dex/code/form/Form45cc.java | 0 .../android/dx/dex/code/form/Form4rcc.java | 0 .../com/android/dx/dex/code/form/Form51l.java | 0 .../dx/dex/code/form/SpecialFormat.java | 0 .../android/dx/dex/file/AnnotationItem.java | 0 .../dx/dex/file/AnnotationSetItem.java | 0 .../dx/dex/file/AnnotationSetRefItem.java | 0 .../android/dx/dex/file/AnnotationUtils.java | 0 .../dx/dex/file/AnnotationsDirectoryItem.java | 0 .../android/dx/dex/file/CallSiteIdItem.java | 0 .../dx/dex/file/CallSiteIdsSection.java | 0 .../com/android/dx/dex/file/CallSiteItem.java | 0 .../com/android/dx/dex/file/CatchStructs.java | 0 .../android/dx/dex/file/ClassDataItem.java | 0 .../com/android/dx/dex/file/ClassDefItem.java | 0 .../android/dx/dex/file/ClassDefsSection.java | 0 .../com/android/dx/dex/file/CodeItem.java | 0 .../dx/dex/file/DebugInfoConstants.java | 0 .../android/dx/dex/file/DebugInfoDecoder.java | 0 .../android/dx/dex/file/DebugInfoEncoder.java | 0 .../android/dx/dex/file/DebugInfoItem.java | 0 .../com/android/dx/dex/file/DexFile.java | 0 .../android/dx/dex/file/EncodedArrayItem.java | 0 .../com/android/dx/dex/file/EncodedField.java | 0 .../android/dx/dex/file/EncodedMember.java | 0 .../android/dx/dex/file/EncodedMethod.java | 0 .../dx/dex/file/FieldAnnotationStruct.java | 0 .../com/android/dx/dex/file/FieldIdItem.java | 0 .../android/dx/dex/file/FieldIdsSection.java | 0 .../com/android/dx/dex/file/HeaderItem.java | 0 .../android/dx/dex/file/HeaderSection.java | 0 .../com/android/dx/dex/file/IdItem.java | 0 .../com/android/dx/dex/file/IndexedItem.java | 0 .../com/android/dx/dex/file/Item.java | 0 .../com/android/dx/dex/file/ItemType.java | 0 .../com/android/dx/dex/file/MapItem.java | 0 .../com/android/dx/dex/file/MemberIdItem.java | 0 .../android/dx/dex/file/MemberIdsSection.java | 0 .../dx/dex/file/MethodAnnotationStruct.java | 0 .../android/dx/dex/file/MethodHandleItem.java | 0 .../dx/dex/file/MethodHandlesSection.java | 0 .../com/android/dx/dex/file/MethodIdItem.java | 0 .../android/dx/dex/file/MethodIdsSection.java | 0 .../android/dx/dex/file/MixedItemSection.java | 0 .../android/dx/dex/file/OffsettedItem.java | 0 .../dex/file/ParameterAnnotationStruct.java | 0 .../com/android/dx/dex/file/ProtoIdItem.java | 0 .../android/dx/dex/file/ProtoIdsSection.java | 0 .../com/android/dx/dex/file/Section.java | 0 .../com/android/dx/dex/file/Statistics.java | 0 .../android/dx/dex/file/StringDataItem.java | 0 .../com/android/dx/dex/file/StringIdItem.java | 0 .../android/dx/dex/file/StringIdsSection.java | 0 .../com/android/dx/dex/file/TypeIdItem.java | 0 .../android/dx/dex/file/TypeIdsSection.java | 0 .../com/android/dx/dex/file/TypeListItem.java | 0 .../dx/dex/file/UniformItemSection.java | 0 .../android/dx/dex/file/UniformListItem.java | 0 .../com/android/dx/dex/file/ValueEncoder.java | 0 .../com/android/dx/io/CodeReader.java | 0 .../com/android/dx/io/DexIndexPrinter.java | 0 .../external/com/android/dx/io/IndexType.java | 0 .../com/android/dx/io/OpcodeInfo.java | 0 .../external/com/android/dx/io/Opcodes.java | 0 .../dx/io/instructions/AddressMap.java | 0 .../dx/io/instructions/BaseCodeCursor.java | 0 .../dx/io/instructions/CodeCursor.java | 0 .../android/dx/io/instructions/CodeInput.java | 0 .../dx/io/instructions/CodeOutput.java | 0 .../io/instructions/DecodedInstruction.java | 0 ...illArrayDataPayloadDecodedInstruction.java | 0 .../FiveRegisterDecodedInstruction.java | 0 .../FourRegisterDecodedInstruction.java | 0 .../dx/io/instructions/InstructionCodec.java | 0 .../InvokePolymorphicDecodedInstruction.java | 0 ...okePolymorphicRangeDecodedInstruction.java | 0 .../OneRegisterDecodedInstruction.java | 0 ...PackedSwitchPayloadDecodedInstruction.java | 0 .../RegisterRangeDecodedInstruction.java | 0 .../io/instructions/ShortArrayCodeInput.java | 0 .../io/instructions/ShortArrayCodeOutput.java | 0 ...SparseSwitchPayloadDecodedInstruction.java | 0 .../ThreeRegisterDecodedInstruction.java | 0 .../TwoRegisterDecodedInstruction.java | 0 .../ZeroRegisterDecodedInstruction.java | 0 .../com/android/dx/merge/CollisionPolicy.java | 0 .../com/android/dx/merge/DexMerger.java | 0 .../com/android/dx/merge/IndexMap.java | 0 .../dx/merge/InstructionTransformer.java | 0 .../com/android/dx/merge/SortableType.java | 0 .../android/dx/rop/annotation/Annotation.java | 0 .../rop/annotation/AnnotationVisibility.java | 0 .../dx/rop/annotation/Annotations.java | 0 .../dx/rop/annotation/AnnotationsList.java | 0 .../dx/rop/annotation/NameValuePair.java | 0 .../com/android/dx/rop/code/AccessFlags.java | 0 .../com/android/dx/rop/code/BasicBlock.java | 0 .../android/dx/rop/code/BasicBlockList.java | 0 .../code/ConservativeTranslationAdvice.java | 0 .../com/android/dx/rop/code/CstInsn.java | 0 .../dx/rop/code/DexTranslationAdvice.java | 0 .../com/android/dx/rop/code/Exceptions.java | 0 .../dx/rop/code/FillArrayDataInsn.java | 0 .../com/android/dx/rop/code/Insn.java | 0 .../com/android/dx/rop/code/InsnList.java | 0 .../dx/rop/code/InvokePolymorphicInsn.java | 0 .../com/android/dx/rop/code/LocalItem.java | 0 .../dx/rop/code/LocalVariableExtractor.java | 0 .../dx/rop/code/LocalVariableInfo.java | 0 .../com/android/dx/rop/code/PlainCstInsn.java | 0 .../com/android/dx/rop/code/PlainInsn.java | 0 .../com/android/dx/rop/code/RegOps.java | 0 .../com/android/dx/rop/code/RegisterSpec.java | 0 .../android/dx/rop/code/RegisterSpecList.java | 0 .../android/dx/rop/code/RegisterSpecSet.java | 0 .../external/com/android/dx/rop/code/Rop.java | 0 .../com/android/dx/rop/code/RopMethod.java | 0 .../com/android/dx/rop/code/Rops.java | 0 .../android/dx/rop/code/SourcePosition.java | 0 .../com/android/dx/rop/code/SwitchInsn.java | 0 .../android/dx/rop/code/ThrowingCstInsn.java | 0 .../com/android/dx/rop/code/ThrowingInsn.java | 0 .../dx/rop/code/TranslationAdvice.java | 0 .../com/android/dx/rop/code/package.html | 0 .../com/android/dx/rop/cst/Constant.java | 0 .../com/android/dx/rop/cst/ConstantPool.java | 0 .../com/android/dx/rop/cst/CstAnnotation.java | 0 .../com/android/dx/rop/cst/CstArray.java | 0 .../android/dx/rop/cst/CstBaseMethodRef.java | 0 .../com/android/dx/rop/cst/CstBoolean.java | 0 .../com/android/dx/rop/cst/CstByte.java | 0 .../com/android/dx/rop/cst/CstCallSite.java | 0 .../android/dx/rop/cst/CstCallSiteRef.java | 0 .../com/android/dx/rop/cst/CstChar.java | 0 .../com/android/dx/rop/cst/CstDouble.java | 0 .../com/android/dx/rop/cst/CstEnumRef.java | 0 .../com/android/dx/rop/cst/CstFieldRef.java | 0 .../com/android/dx/rop/cst/CstFloat.java | 0 .../com/android/dx/rop/cst/CstInteger.java | 0 .../dx/rop/cst/CstInterfaceMethodRef.java | 0 .../android/dx/rop/cst/CstInvokeDynamic.java | 0 .../com/android/dx/rop/cst/CstKnownNull.java | 0 .../com/android/dx/rop/cst/CstLiteral32.java | 0 .../com/android/dx/rop/cst/CstLiteral64.java | 0 .../android/dx/rop/cst/CstLiteralBits.java | 0 .../com/android/dx/rop/cst/CstLong.java | 0 .../com/android/dx/rop/cst/CstMemberRef.java | 0 .../android/dx/rop/cst/CstMethodHandle.java | 0 .../com/android/dx/rop/cst/CstMethodRef.java | 0 .../com/android/dx/rop/cst/CstNat.java | 0 .../com/android/dx/rop/cst/CstProtoRef.java | 0 .../com/android/dx/rop/cst/CstShort.java | 0 .../com/android/dx/rop/cst/CstString.java | 0 .../com/android/dx/rop/cst/CstType.java | 0 .../android/dx/rop/cst/StdConstantPool.java | 0 .../com/android/dx/rop/cst/TypedConstant.java | 0 .../com/android/dx/rop/cst/Zeroes.java | 0 .../com/android/dx/rop/cst/package.html | 0 .../com/android/dx/rop/package-info.java | 0 .../com/android/dx/rop/type/Prototype.java | 0 .../com/android/dx/rop/type/StdTypeList.java | 0 .../com/android/dx/rop/type/Type.java | 0 .../com/android/dx/rop/type/TypeBearer.java | 0 .../com/android/dx/rop/type/TypeList.java | 0 .../com/android/dx/rop/type/package.html | 0 .../android/dx/ssa/BasicRegisterMapper.java | 0 .../com/android/dx/ssa/ConstCollector.java | 0 .../com/android/dx/ssa/DeadCodeRemover.java | 0 .../external/com/android/dx/ssa/DomFront.java | 0 .../com/android/dx/ssa/Dominators.java | 0 .../com/android/dx/ssa/EscapeAnalysis.java | 0 .../dx/ssa/InterferenceRegisterMapper.java | 0 .../com/android/dx/ssa/LiteralOpUpgrader.java | 0 .../dx/ssa/LocalVariableExtractor.java | 0 .../com/android/dx/ssa/LocalVariableInfo.java | 0 .../com/android/dx/ssa/MoveParamCombiner.java | 0 .../com/android/dx/ssa/NormalSsaInsn.java | 0 .../com/android/dx/ssa/Optimizer.java | 0 .../external/com/android/dx/ssa/PhiInsn.java | 0 .../com/android/dx/ssa/PhiTypeResolver.java | 0 .../com/android/dx/ssa/RegisterMapper.java | 0 .../external/com/android/dx/ssa/SCCP.java | 0 .../com/android/dx/ssa/SetFactory.java | 0 .../com/android/dx/ssa/SsaBasicBlock.java | 0 .../com/android/dx/ssa/SsaConverter.java | 0 .../external/com/android/dx/ssa/SsaInsn.java | 0 .../com/android/dx/ssa/SsaMethod.java | 0 .../com/android/dx/ssa/SsaRenamer.java | 0 .../dx/ssa/back/FirstFitAllocator.java | 0 .../back/FirstFitLocalCombiningAllocator.java | 0 .../dx/ssa/back/IdenticalBlockCombiner.java | 0 .../dx/ssa/back/InterferenceGraph.java | 0 .../android/dx/ssa/back/LivenessAnalyzer.java | 0 .../dx/ssa/back/NullRegisterAllocator.java | 0 .../dx/ssa/back/RegisterAllocator.java | 0 .../com/android/dx/ssa/back/SsaToRop.java | 0 .../com/android/dx/ssa/package-info.java | 0 .../com/android/dx/stock/ProxyBuilder.java | 0 .../com/android/dx/util/AnnotatedOutput.java | 0 .../com/android/dx/util/BitIntSet.java | 0 .../external/com/android/dx/util/Bits.java | 0 .../com/android/dx/util/ByteArray.java | 0 .../dx/util/ByteArrayAnnotatedOutput.java | 0 .../com/android/dx/util/FixedSizeList.java | 0 .../external/com/android/dx/util/Hex.java | 0 .../com/android/dx/util/HexParser.java | 0 .../com/android/dx/util/IndentingWriter.java | 0 .../com/android/dx/util/IntIterator.java | 0 .../external/com/android/dx/util/IntList.java | 0 .../external/com/android/dx/util/IntSet.java | 0 .../com/android/dx/util/LabeledItem.java | 0 .../com/android/dx/util/LabeledList.java | 0 .../com/android/dx/util/ListIntSet.java | 0 .../android/dx/util/MutabilityControl.java | 0 .../android/dx/util/MutabilityException.java | 0 .../external/com/android/dx/util/Output.java | 0 .../external/com/android/dx/util/ToHuman.java | 0 .../com/android/dx/util/TwoColumnOutput.java | 0 .../external/com/android/dx/util/Warning.java | 0 .../external/com/android/dx/util/Writers.java | 0 .../external/com/android/dx/util/package.html | 0 .../android/multidex/ArchivePathElement.java | 0 .../android/multidex/ClassPathElement.java | 0 .../multidex/ClassReferenceListBuilder.java | 0 .../android/multidex/FolderPathElement.java | 0 .../android/multidex/MainDexListBuilder.java | 0 .../external/com/android/multidex/Path.java | 0 .../org/apache/commons/lang3/ArrayUtils.java | 5797 +++++++++++++++ .../commons/lang3/CharSequenceUtils.java | 197 + .../org/apache/commons/lang3/CharUtils.java | 539 ++ .../org/apache/commons/lang3/ClassUtils.java | 1135 +++ .../org/apache/commons/lang3/JavaVersion.java | 168 + .../org/apache/commons/lang3/LICENSE.txt | 202 + .../apache/commons/lang3/MODIFICATIONS.txt | 44 + .../org/apache/commons/lang3/NOTICE.txt | 8 + .../org/apache/commons/lang3/ObjectUtils.java | 609 ++ .../apache/commons/lang3/RELEASE-NOTES.txt | 40 + .../org/apache/commons/lang3/StringUtils.java | 6582 +++++++++++++++++ .../org/apache/commons/lang3/SystemUtils.java | 1443 ++++ .../org/apache/commons/lang3/Validate.java | 1070 +++ .../apache/commons/lang3/builder/Builder.java | 89 + .../lang3/builder/CompareToBuilder.java | 1020 +++ .../commons/lang3/builder/EqualsBuilder.java | 945 +++ .../lang3/builder/HashCodeBuilder.java | 961 +++ .../apache/commons/lang3/builder/IDKey.java | 74 + .../builder/ReflectionToStringBuilder.java | 691 ++ .../lang3/builder/ToStringBuilder.java | 1079 +++ .../commons/lang3/builder/ToStringStyle.java | 2271 ++++++ .../apache/commons/lang3/builder/package.html | 28 + .../lang3/exception/CloneFailedException.java | 62 + .../commons/lang3/exception/package.html | 27 + .../apache/commons/lang3/mutable/Mutable.java | 54 + .../commons/lang3/mutable/MutableInt.java | 273 + .../apache/commons/lang3/mutable/package.html | 29 + .../org/apache/commons/lang3/overview.html | 23 + .../org/apache/commons/lang3/package.html | 25 + .../commons/lang3/reflect/MemberUtils.java | 185 + .../commons/lang3/reflect/MethodUtils.java | 537 ++ .../apache/commons/lang3/reflect/package.html | 29 + .../commons/lang3/tuple/ImmutablePair.java | 103 + .../org/apache/commons/lang3/tuple/Pair.java | 177 + .../apache/commons/lang3/tuple/package.html | 22 + .../src/main/java/pxb/android/ResConst.java | 33 + .../src/main/java/pxb/android/StringItem.java | 61 + .../main/java/pxb/android/StringItems.java | 163 + .../java/pxb/android/arsc/ArscDumper.java | 73 + .../java/pxb/android/arsc/ArscParser.java | 317 + .../java/pxb/android/arsc/ArscWriter.java | 400 + .../main/java/pxb/android/arsc/BagValue.java | 70 + .../main/java/pxb/android/arsc/Config.java | 34 + .../src/main/java/pxb/android/arsc/Pkg.java | 54 + .../main/java/pxb/android/arsc/ResEntry.java | 35 + .../main/java/pxb/android/arsc/ResSpec.java | 36 + .../src/main/java/pxb/android/arsc/Type.java | 44 + .../src/main/java/pxb/android/arsc/Value.java | 37 + .../src/main/java/pxb/android/axml/Axml.java | 142 + .../java/pxb/android/axml/AxmlParser.java | 274 + .../java/pxb/android/axml/AxmlReader.java | 94 + .../java/pxb/android/axml/AxmlVisitor.java | 47 + .../java/pxb/android/axml/AxmlWriter.java | 442 ++ .../java/pxb/android/axml/DumpAdapter.java | 116 + .../java/pxb/android/axml/NodeVisitor.java | 97 + .../src/main/java/pxb/android/axml/Util.java | 78 + .../java/pxb/android/axml/ValueWrapper.java | 34 + .../src/main/java/pxb/android/package.html | 2 + edxp-core/template_override/customize.sh | 3 - edxp-core/template_override/verify.sh | 4 +- edxp-core/tpl/edconfig.tpl | 2 +- edxp-core/tpl/module.prop.tpl | 4 +- edxp-sandhook/.gitignore | 2 - edxp-sandhook/build.gradle | 81 - edxp-sandhook/genhookstubs.py | 196 - edxp-sandhook/proguard-rules.pro | 38 - edxp-sandhook/src/main/AndroidManifest.xml | 1 - edxp-service/.gitignore | 2 - edxp-service/build.gradle | 73 - edxp-service/proguard-rules.pro | 34 - edxp-service/src/main/AndroidManifest.xml | 1 - edxp-yahfa/.gitignore | 2 - edxp-yahfa/build.gradle | 74 - edxp-yahfa/proguard-rules.pro | 36 - edxp-yahfa/src/main/AndroidManifest.xml | 1 - settings.gradle | 2 +- xposed-bridge/build.gradle | 1 - 650 files changed, 37013 insertions(+), 902 deletions(-) delete mode 100644 dalvikdx/.gitignore delete mode 100644 dalvikdx/build.gradle delete mode 100644 dalvikdx/src/main/AndroidManifest.xml delete mode 100644 dexmaker/.gitignore delete mode 100644 dexmaker/build.gradle delete mode 100644 dexmaker/src/main/AndroidManifest.xml delete mode 100644 edxp-common/.gitignore delete mode 100644 edxp-common/build.gradle delete mode 100644 edxp-common/src/main/AndroidManifest.xml rename {edxp-common => edxp-core}/proguard-rules.pro (100%) create mode 100644 edxp-core/src/main/java/android/app/AndroidAppHelper.java create mode 100644 edxp-core/src/main/java/android/app/package-info.java create mode 100644 edxp-core/src/main/java/android/content/res/XModuleResources.java create mode 100644 edxp-core/src/main/java/android/content/res/XResForwarder.java create mode 100644 edxp-core/src/main/java/android/content/res/XResources.java create mode 100644 edxp-core/src/main/java/android/content/res/package-info.java rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/common/KeepAll.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/common/KeepMembers.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/HandleBindApp.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/LoadedApkCstr.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/LoadedApkGetCL.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/StartBootstrapServices.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/SystemMain.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/HandleBindAppHooker.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/LoadedApkConstructorHooker.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/StartBootstrapServicesHooker.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/StartBootstrapServicesHooker11.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/SystemMainHooker.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/art/ClassLinker.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/art/Heap.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/config/BaseEdxpConfig.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/config/BaseHookProvider.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/config/ConfigManager.java (100%) create mode 100644 edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/EdXpConfigGlobal.java create mode 100644 edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/EdxpConfig.java rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/core/BaseEdxpImpl.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/core/EdxpImpl.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/core/Main.java (71%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/core/Proxy.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/core/ResourcesHook.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/core/Yahfa.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/core/yahfa/HookMain.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/deopt/InlinedMethodCallers.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/deopt/PrebuiltMethodsDeopter.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/AppBootstrapHookInfo.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/SysBootstrapHookInfo.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/SysInnerHookInfo.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/framework/Zygote.java (100%) create mode 100644 edxp-core/src/main/java/com/elderdrivers/riru/edxp/hook/HookProvider.java rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/hooker/SliceProviderFix.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/hooker/XposedInstallerHooker.java (99%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/proxy/BaseProxy.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/proxy/BaseRouter.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/proxy/NormalProxy.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/proxy/Router.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/config/SandHookEdxpConfig.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/config/SandHookProvider.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/core/SandHookEdxpImpl.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/core/SandHookRouter.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/AppBootstrapHookInfo.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/SysBootstrapHookInfo.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/SysInnerHookInfo.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/HandleBindAppHooker.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/LoadedApkConstructorHooker.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/StartBootstrapServicesHooker.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/StartBootstrapServicesHooker11.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/SystemMainHooker.java (100%) rename {edxp-service => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/service/PackageReceiver.java (100%) rename {edxp-service => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/service/ServiceProxy.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/util/ClassLoaderUtils.java (98%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/util/ClassUtils.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/util/DexUtils.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/util/FileUtils.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/util/Hookers.java (100%) create mode 100644 edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/MetaDataReader.java rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/util/ProcessUtils.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/util/ProxyClassLoader.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/util/Unsafe.java (100%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/util/Utils.java (96%) rename {edxp-common => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/util/Versions.java (100%) rename {edxp-yahfa => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/yahfa/config/YahfaEdxpConfig.java (100%) rename {edxp-yahfa => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/yahfa/config/YahfaHookProvider.java (100%) rename {edxp-yahfa => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/yahfa/core/YahfaEdxpImpl.java (100%) rename {edxp-yahfa => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/yahfa/core/YahfaRouter.java (100%) rename {edxp-yahfa => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexLog.java (92%) rename {edxp-yahfa => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexMakerUtils.java (100%) rename {edxp-yahfa => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DynamicBridge.java (100%) rename {edxp-yahfa => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/HookerDexMaker.java (99%) rename {edxp-yahfa => edxp-core}/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/MethodInfo.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/XposedCompat.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/hookstub/CallOriginCallBack.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookMethodEntity.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookStubManager.java (99%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/hookstub/MethodHookerStubs32.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/hookstub/MethodHookerStubs64.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/methodgen/ErrorCatch.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookMaker.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookerDexMaker.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookerDexMakerNew.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/methodgen/SandHookXposedBridge.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/utils/ApplicationUtils.java (100%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/utils/DexLog.java (95%) rename {edxp-sandhook => edxp-core}/src/main/java/com/swift/sandhook/xposedcompat/utils/DexMakerUtils.java (100%) create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/DexCreator.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/IModuleContext.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/IXposedHookCmdInit.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/IXposedHookInitPackageResources.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/IXposedHookLoadPackage.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/IXposedHookZygoteInit.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/IXposedMod.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/PendingHooks.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/SELinuxHelper.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/XC_MethodHook.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/XC_MethodReplacement.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/XSharedPreferences.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/XposedBridge.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/XposedHelpers.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/XposedInit.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/annotation/ApiSensitive.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/annotation/Level.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/callbacks/IXUnhook.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_InitPackageResources.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_InitZygote.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_LayoutInflated.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_LoadPackage.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/callbacks/XCallback.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/callbacks/package-info.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/package-info.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/services/BaseService.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/services/BinderService.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/services/DirectAccessService.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/services/FileResult.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/services/ZygoteService.java create mode 100644 edxp-core/src/main/java/de/robv/android/xposed/services/package-info.java rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/Annotation.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/CallSiteId.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/ClassData.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/ClassDef.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/Code.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/Dex.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/DexException.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/DexFormat.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/DexIndexOverflowException.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/EncodedValue.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/EncodedValueCodec.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/EncodedValueReader.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/FieldId.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/Leb128.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/MethodHandle.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/MethodId.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/Mutf8.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/ProtoId.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/SizeOf.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/TableOfContents.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/TypeList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/util/ByteArrayByteInput.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/util/ByteInput.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/util/ByteOutput.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/util/ExceptionWithContext.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/util/FileUtils.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dex/util/Unsigned.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/AnnotationId.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/AppDataDirGuesser.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/BinaryOp.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/Code.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/Comparison.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/Constants.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/DexMaker.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/FieldId.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/Label.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/Local.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/MethodId.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/TypeId.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/TypeList.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/UnaryOp.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/Version.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttAnnotationDefault.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttBootstrapMethods.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttCode.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttConstantValue.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttDeprecated.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttEnclosingMethod.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttExceptions.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttInnerClasses.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttLineNumberTable.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttLocalVariableTable.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttLocalVariableTypeTable.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeInvisibleAnnotations.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeInvisibleParameterAnnotations.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeVisibleAnnotations.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeVisibleParameterAnnotations.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttSignature.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttSourceDebugExtension.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttSourceFile.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/AttSynthetic.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/BaseAnnotations.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/BaseAttribute.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/BaseLocalVariables.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/BaseParameterAnnotations.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/InnerClassList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/RawAttribute.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/attrib/package.html (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/BaseMachine.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/BasicBlocker.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/BootstrapMethodArgumentsList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/BootstrapMethodsList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/ByteBlock.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/ByteBlockList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/ByteCatchList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/ByteOps.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/BytecodeArray.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/ConcreteMethod.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/ExecutionStack.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/Frame.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/LineNumberList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/LocalVariableList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/LocalsArray.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/LocalsArraySet.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/Machine.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/Merger.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/OneLocalsArray.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/ReturnAddress.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/Ropper.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/RopperMachine.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/SimException.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/Simulator.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/SwitchList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/ValueAwareMachine.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/code/package.html (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/cst/ConstantPoolParser.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/cst/ConstantTags.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/cst/MethodHandleKind.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/AnnotationParser.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/AttributeFactory.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/AttributeListParser.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/ClassPathOpener.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/CodeObserver.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/DirectClassFile.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/FieldListParser.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/MemberListParser.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/MethodListParser.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/StdAttributeFactory.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/direct/package.html (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/Attribute.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/AttributeList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/ClassFile.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/Field.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/FieldList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/HasAttribute.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/Member.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/Method.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/MethodList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/ParseException.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/ParseObserver.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/StdAttributeList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/StdField.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/StdFieldList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/StdMember.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/StdMethod.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/StdMethodList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/cf/iface/package.html (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/Main.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/UsageException.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/annotool/AnnotationLister.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/annotool/Main.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/dexer/DxContext.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/dexer/Main.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/dump/Args.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/dump/BaseDumper.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/dump/BlockDumper.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/dump/ClassDumper.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/dump/DotDumper.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/dump/Main.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/dump/SsaDumper.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/findusages/FindUsages.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/findusages/Main.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/grep/Grep.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/command/grep/Main.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/DexOptions.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/cf/AttributeTranslator.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/cf/CfOptions.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/cf/CfTranslator.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/cf/CodeStatistics.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/cf/OptimizerOptions.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/cf/package.html (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/ArrayData.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/BlockAddresses.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/CatchBuilder.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/CatchHandlerList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/CatchTable.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/CodeAddress.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/CstInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/DalvCode.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/DalvInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/DalvInsnList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/Dop.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/Dops.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/FixedSizeInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/HighRegisterPrefix.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/InsnFormat.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/LocalList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/LocalSnapshot.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/LocalStart.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/MultiCstInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/OddSpacer.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/OutputCollector.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/OutputFinisher.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/PositionList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/RopToDop.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/RopTranslator.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/SimpleInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/StdCatchBuilder.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/SwitchData.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/TargetInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/VariableSizeInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/ZeroSizeInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form10t.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form10x.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form11n.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form11x.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form12x.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form20t.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form21c.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form21h.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form21s.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form21t.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form22b.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form22c.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form22s.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form22t.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form22x.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form23x.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form30t.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form31c.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form31i.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form31t.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form32x.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form35c.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form3rc.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form45cc.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form4rcc.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/Form51l.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/code/form/SpecialFormat.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/AnnotationItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/AnnotationSetItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/AnnotationSetRefItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/AnnotationUtils.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/AnnotationsDirectoryItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/CallSiteIdItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/CallSiteIdsSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/CallSiteItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/CatchStructs.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/ClassDataItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/ClassDefItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/ClassDefsSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/CodeItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/DebugInfoConstants.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/DebugInfoDecoder.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/DebugInfoEncoder.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/DebugInfoItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/DexFile.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/EncodedArrayItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/EncodedField.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/EncodedMember.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/EncodedMethod.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/FieldAnnotationStruct.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/FieldIdItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/FieldIdsSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/HeaderItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/HeaderSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/IdItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/IndexedItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/Item.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/ItemType.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/MapItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/MemberIdItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/MemberIdsSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/MethodAnnotationStruct.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/MethodHandleItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/MethodHandlesSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/MethodIdItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/MethodIdsSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/MixedItemSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/OffsettedItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/ParameterAnnotationStruct.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/ProtoIdItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/ProtoIdsSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/Section.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/Statistics.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/StringDataItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/StringIdItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/StringIdsSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/TypeIdItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/TypeIdsSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/TypeListItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/UniformItemSection.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/UniformListItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/dex/file/ValueEncoder.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/CodeReader.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/DexIndexPrinter.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/IndexType.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/OpcodeInfo.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/Opcodes.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/AddressMap.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/BaseCodeCursor.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/CodeCursor.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/CodeInput.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/CodeOutput.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/DecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/FillArrayDataPayloadDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/FiveRegisterDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/FourRegisterDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/InstructionCodec.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/InvokePolymorphicDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/InvokePolymorphicRangeDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/OneRegisterDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/PackedSwitchPayloadDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/RegisterRangeDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/ShortArrayCodeInput.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/ShortArrayCodeOutput.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/SparseSwitchPayloadDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/ThreeRegisterDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/TwoRegisterDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/io/instructions/ZeroRegisterDecodedInstruction.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/merge/CollisionPolicy.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/merge/DexMerger.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/merge/IndexMap.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/merge/InstructionTransformer.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/merge/SortableType.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/annotation/Annotation.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/annotation/AnnotationVisibility.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/annotation/Annotations.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/annotation/AnnotationsList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/annotation/NameValuePair.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/AccessFlags.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/BasicBlock.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/BasicBlockList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/ConservativeTranslationAdvice.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/CstInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/DexTranslationAdvice.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/Exceptions.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/FillArrayDataInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/Insn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/InsnList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/InvokePolymorphicInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/LocalItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/LocalVariableExtractor.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/LocalVariableInfo.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/PlainCstInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/PlainInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/RegOps.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/RegisterSpec.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/RegisterSpecList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/RegisterSpecSet.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/Rop.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/RopMethod.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/Rops.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/SourcePosition.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/SwitchInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/ThrowingCstInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/ThrowingInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/TranslationAdvice.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/code/package.html (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/Constant.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/ConstantPool.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstAnnotation.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstArray.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstBaseMethodRef.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstBoolean.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstByte.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstCallSite.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstCallSiteRef.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstChar.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstDouble.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstEnumRef.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstFieldRef.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstFloat.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstInteger.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstInterfaceMethodRef.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstInvokeDynamic.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstKnownNull.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstLiteral32.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstLiteral64.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstLiteralBits.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstLong.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstMemberRef.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstMethodHandle.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstMethodRef.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstNat.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstProtoRef.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstShort.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstString.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/CstType.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/StdConstantPool.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/TypedConstant.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/Zeroes.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/cst/package.html (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/package-info.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/type/Prototype.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/type/StdTypeList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/type/Type.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/type/TypeBearer.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/type/TypeList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/rop/type/package.html (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/BasicRegisterMapper.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/ConstCollector.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/DeadCodeRemover.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/DomFront.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/Dominators.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/EscapeAnalysis.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/InterferenceRegisterMapper.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/LiteralOpUpgrader.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/LocalVariableExtractor.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/LocalVariableInfo.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/MoveParamCombiner.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/NormalSsaInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/Optimizer.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/PhiInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/PhiTypeResolver.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/RegisterMapper.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/SCCP.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/SetFactory.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/SsaBasicBlock.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/SsaConverter.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/SsaInsn.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/SsaMethod.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/SsaRenamer.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/back/FirstFitAllocator.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/back/FirstFitLocalCombiningAllocator.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/back/IdenticalBlockCombiner.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/back/InterferenceGraph.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/back/LivenessAnalyzer.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/back/NullRegisterAllocator.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/back/RegisterAllocator.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/back/SsaToRop.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/ssa/package-info.java (100%) rename {dexmaker => edxp-core}/src/main/java/external/com/android/dx/stock/ProxyBuilder.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/AnnotatedOutput.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/BitIntSet.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/Bits.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/ByteArray.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/ByteArrayAnnotatedOutput.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/FixedSizeList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/Hex.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/HexParser.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/IndentingWriter.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/IntIterator.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/IntList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/IntSet.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/LabeledItem.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/LabeledList.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/ListIntSet.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/MutabilityControl.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/MutabilityException.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/Output.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/ToHuman.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/TwoColumnOutput.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/Warning.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/Writers.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/dx/util/package.html (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/multidex/ArchivePathElement.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/multidex/ClassPathElement.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/multidex/ClassReferenceListBuilder.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/multidex/FolderPathElement.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/multidex/MainDexListBuilder.java (100%) rename {dalvikdx => edxp-core}/src/main/java/external/com/android/multidex/Path.java (100%) create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/ArrayUtils.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/CharSequenceUtils.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/CharUtils.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/ClassUtils.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/JavaVersion.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/LICENSE.txt create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/MODIFICATIONS.txt create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/NOTICE.txt create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/ObjectUtils.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/RELEASE-NOTES.txt create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/StringUtils.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/SystemUtils.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/Validate.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/builder/Builder.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/builder/CompareToBuilder.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/builder/EqualsBuilder.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/builder/HashCodeBuilder.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/builder/IDKey.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ToStringBuilder.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ToStringStyle.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/builder/package.html create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/exception/CloneFailedException.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/exception/package.html create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/Mutable.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/MutableInt.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/package.html create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/overview.html create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/package.html create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/MemberUtils.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/MethodUtils.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/package.html create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/ImmutablePair.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/Pair.java create mode 100644 edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/package.html create mode 100644 edxp-core/src/main/java/pxb/android/ResConst.java create mode 100644 edxp-core/src/main/java/pxb/android/StringItem.java create mode 100644 edxp-core/src/main/java/pxb/android/StringItems.java create mode 100644 edxp-core/src/main/java/pxb/android/arsc/ArscDumper.java create mode 100644 edxp-core/src/main/java/pxb/android/arsc/ArscParser.java create mode 100644 edxp-core/src/main/java/pxb/android/arsc/ArscWriter.java create mode 100644 edxp-core/src/main/java/pxb/android/arsc/BagValue.java create mode 100644 edxp-core/src/main/java/pxb/android/arsc/Config.java create mode 100644 edxp-core/src/main/java/pxb/android/arsc/Pkg.java create mode 100644 edxp-core/src/main/java/pxb/android/arsc/ResEntry.java create mode 100644 edxp-core/src/main/java/pxb/android/arsc/ResSpec.java create mode 100644 edxp-core/src/main/java/pxb/android/arsc/Type.java create mode 100644 edxp-core/src/main/java/pxb/android/arsc/Value.java create mode 100644 edxp-core/src/main/java/pxb/android/axml/Axml.java create mode 100644 edxp-core/src/main/java/pxb/android/axml/AxmlParser.java create mode 100644 edxp-core/src/main/java/pxb/android/axml/AxmlReader.java create mode 100644 edxp-core/src/main/java/pxb/android/axml/AxmlVisitor.java create mode 100644 edxp-core/src/main/java/pxb/android/axml/AxmlWriter.java create mode 100644 edxp-core/src/main/java/pxb/android/axml/DumpAdapter.java create mode 100644 edxp-core/src/main/java/pxb/android/axml/NodeVisitor.java create mode 100644 edxp-core/src/main/java/pxb/android/axml/Util.java create mode 100644 edxp-core/src/main/java/pxb/android/axml/ValueWrapper.java create mode 100644 edxp-core/src/main/java/pxb/android/package.html delete mode 100644 edxp-sandhook/.gitignore delete mode 100644 edxp-sandhook/build.gradle delete mode 100644 edxp-sandhook/genhookstubs.py delete mode 100644 edxp-sandhook/proguard-rules.pro delete mode 100644 edxp-sandhook/src/main/AndroidManifest.xml delete mode 100644 edxp-service/.gitignore delete mode 100644 edxp-service/build.gradle delete mode 100644 edxp-service/proguard-rules.pro delete mode 100644 edxp-service/src/main/AndroidManifest.xml delete mode 100644 edxp-yahfa/.gitignore delete mode 100644 edxp-yahfa/build.gradle delete mode 100644 edxp-yahfa/proguard-rules.pro delete mode 100644 edxp-yahfa/src/main/AndroidManifest.xml diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index e87b2afe..fd3ff122 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -20,36 +20,22 @@ jobs: - name: Get version code run: echo APPVEYOR_BUILD_NUMBER=$(expr $GITHUB_RUN_NUMBER + 4999) >> $GITHUB_ENV - name: Build with Gradle - run: bash ./gradlew zipYahfaRelease zipSandhookRelease zipYahfaDebug zipSandhookDebug + run: bash ./gradlew zipRelease zipDebug - name: Prepare artifact if: success() - run: unzip edxp-core/release/EdXposed-YAHFA-v*-release.zip -d EdXposed-YAHFA-release; - unzip edxp-core/release/EdXposed-SandHook-v*-release.zip -d EdXposed-SandHook-release; - unzip edxp-core/release/EdXposed-YAHFA-v*-debug.zip -d EdXposed-YAHFA-debug; - unzip edxp-core/release/EdXposed-SandHook-v*-debug.zip -d EdXposed-SandHook-debug - - name: Upload YAHFA release + run: unzip edxp-core/release/LSPosed-v*-release.zip -d LSPosed-release; + unzip edxp-core/release/LSPosed-v*-debug.zip -d LSPosed-debug; + - name: Upload release uses: actions/upload-artifact@v2 with: - name: EdXposed-YAHFA-release - path: './EdXposed-YAHFA-release/*' - - name: Upload Sandhook release - if: success() - uses: actions/upload-artifact@v2 - with: - name: EdXposed-SandHook-release - path: './EdXposed-SandHook-release/*' - - name: Upload YAHFA debug + name: LSPosed-release + path: './LSPosed-release/*' + - name: Upload debug # if: ${{ github.event_name == 'pull_request' && success() }} uses: actions/upload-artifact@v2 with: - name: EdXposed-YAHFA-debug - path: './EdXposed-YAHFA-debug/*' - - name: Upload Sandhook debug -# if: ${{ github.event_name == 'pull_request' && success() }} - uses: actions/upload-artifact@v2 - with: - name: EdXposed-SandHook-debug - path: './EdXposed-SandHook-debug/*' + name: LSPosed-debug + path: './LSPosed-debug/*' # - name: Prepare publish artifact # if: ${{ github.event_name == 'push' && success() }} # run: mkdir -p to_publish && mv edxp-core/release/EdXposed-YAHFA-v*-release.zip to_publish/EdXposed-YAHFA-release.zip && mv edxp-core/release/EdXposed-SandHook-v*-release.zip to_publish/EdXposed-SandHook-release.zip && echo $APPVEYOR_BUILD_NUMBER > to_publish/version diff --git a/build.gradle b/build.gradle index 348d5bc5..9a59cafe 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:4.1.1' + classpath 'com.android.tools.build:gradle:4.1.2' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files diff --git a/dalvikdx/.gitignore b/dalvikdx/.gitignore deleted file mode 100644 index 8b8c3dc1..00000000 --- a/dalvikdx/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build -dex diff --git a/dalvikdx/build.gradle b/dalvikdx/build.gradle deleted file mode 100644 index a1d358bc..00000000 --- a/dalvikdx/build.gradle +++ /dev/null @@ -1,33 +0,0 @@ -apply plugin: 'com.android.application' - -repositories { - jcenter() -} - -android { - compileSdkVersion androidCompileSdkVersion.toInteger() - ndkVersion androidCompileNdkVersion -} - -afterEvaluate { - android.applicationVariants.all { variant -> - def variantNameCapped = variant.name.capitalize() - def variantNameLowered = variant.name.toLowerCase() - - task("copyDex${variantNameCapped}", type: Copy) { - dependsOn "assemble${variantNameCapped}" - def dexOutPath = "${buildDir}/intermediates/dex/${variantNameLowered}/mergeDex${variantNameCapped}" - from (dexOutPath){ - rename("classes.dex", "eddalvikdx.dex") - } - destinationDir file(templateRootPath + "system/framework/") - outputs.upToDateWhen { false } - } - task("makeJar${variantNameCapped}", type: Jar, dependsOn: "assemble${variantNameCapped}") { - dependsOn "assemble${variantNameCapped}" - from "${buildDir}/intermediates/javac/${variantNameLowered}/classes" - baseName "dalvikdx" - outputs.file(archivePath) - } - } -} diff --git a/dalvikdx/src/main/AndroidManifest.xml b/dalvikdx/src/main/AndroidManifest.xml deleted file mode 100644 index 7474421e..00000000 --- a/dalvikdx/src/main/AndroidManifest.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/dexmaker/.gitignore b/dexmaker/.gitignore deleted file mode 100644 index 8b8c3dc1..00000000 --- a/dexmaker/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build -dex diff --git a/dexmaker/build.gradle b/dexmaker/build.gradle deleted file mode 100644 index a3a6cc1b..00000000 --- a/dexmaker/build.gradle +++ /dev/null @@ -1,39 +0,0 @@ -apply plugin: 'com.android.application' - -description = "A utility for doing compile or runtime code generation targeting Android's Dalvik VM" - -repositories { - jcenter() -} - -android { - compileSdkVersion androidCompileSdkVersion.toInteger() - ndkVersion androidCompileNdkVersion -} - -dependencies { - compileOnly files(project(":dalvikdx").tasks.getByName("makeJarRelease").outputs) -} - -afterEvaluate { - android.applicationVariants.all { variant -> - def variantNameCapped = variant.name.capitalize() - def variantNameLowered = variant.name.toLowerCase() - - task("copyDex${variantNameCapped}", type: Copy) { - dependsOn "assemble${variantNameCapped}" - def dexOutPath = "${buildDir}/intermediates/dex/${variantNameLowered}/mergeDex${variantNameCapped}" - from (dexOutPath){ - rename("classes.dex", "eddexmaker.dex") - } - destinationDir file(templateRootPath + "system/framework/") - outputs.upToDateWhen { false } - } - task("makeJar${variantNameCapped}", type: Jar, dependsOn: "assemble${variantNameCapped}") { - dependsOn "assemble${variantNameCapped}" - from "${buildDir}/intermediates/javac/${variantNameLowered}/classes" - baseName "dexmaker" - outputs.file(archivePath) - } - } -} \ No newline at end of file diff --git a/dexmaker/src/main/AndroidManifest.xml b/dexmaker/src/main/AndroidManifest.xml deleted file mode 100644 index 419831dd..00000000 --- a/dexmaker/src/main/AndroidManifest.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/edxp-common/.gitignore b/edxp-common/.gitignore deleted file mode 100644 index 796b96d1..00000000 --- a/edxp-common/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/edxp-common/build.gradle b/edxp-common/build.gradle deleted file mode 100644 index e94a4d20..00000000 --- a/edxp-common/build.gradle +++ /dev/null @@ -1,61 +0,0 @@ -apply plugin: 'com.android.library' - -android { - compileSdkVersion androidCompileSdkVersion.toInteger() - - defaultConfig { - minSdkVersion androidMinSdkVersion.toInteger() - targetSdkVersion androidTargetSdkVersion.toInteger() - versionCode 1 - versionName "1.0" - } - - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' - buildConfigField("String", "VERSION_NAME", "\"${rootProject.ext.versionName}\"") - buildConfigField("Integer", "VERSION_CODE", String.valueOf(rootProject.ext.versionCode)) - } - debug { - buildConfigField("String", "VERSION_NAME", "\"${rootProject.ext.versionName}\"") - buildConfigField("Integer", "VERSION_CODE", String.valueOf(rootProject.ext.versionCode)) - } - } - - ndkVersion androidCompileNdkVersion -} - -dependencies { - compileOnly project(':hiddenapi-stubs') - api project(':xposed-bridge') - compileOnly project(':dexmaker') - compileOnly 'com.android.support:support-annotations:28.0.0' -} - - -preBuild.doLast { - def imlFile = file(project.name + ".iml") - try { - def parsedXml = (new groovy.util.XmlParser()).parse(imlFile) - def jdkNode = parsedXml.component[1].orderEntry.find { it.'@type' == 'jdk' } - parsedXml.component[1].remove(jdkNode) - def sdkString = "Android API " + android.compileSdkVersion.substring("android-".length()) + " Platform" - new groovy.util.Node(parsedXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': sdkString, 'jdkType': 'Android SDK']) - groovy.xml.XmlUtil.serialize(parsedXml, new FileOutputStream(imlFile)) - } catch (FileNotFoundException e) { - // nop, iml not found - } -} - -afterEvaluate { - - tasks.withType(JavaCompile) { - options.compilerArgs.add("-Xbootclasspath/p:${hiddenApiStubJarFilePath}") - } - - task("copyCommonProperties", type: Copy) { - from file("${projectDir}/template_override/") - into file(templateRootPath) - } -} \ No newline at end of file diff --git a/edxp-common/src/main/AndroidManifest.xml b/edxp-common/src/main/AndroidManifest.xml deleted file mode 100644 index d879e9df..00000000 --- a/edxp-common/src/main/AndroidManifest.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/edxp-core/build.gradle b/edxp-core/build.gradle index 617be754..45091fe6 100644 --- a/edxp-core/build.gradle +++ b/edxp-core/build.gradle @@ -1,9 +1,10 @@ +import groovy.xml.XmlUtil import org.apache.tools.ant.filters.FixCrLfFilter import org.gradle.internal.os.OperatingSystem import java.security.MessageDigest -apply plugin: 'com.android.library' +apply plugin: 'com.android.application' static def calcSha256(file) { def md = MessageDigest.getInstance("SHA-256") @@ -30,16 +31,13 @@ if (System.env.APPVEYOR_BUILD_NUMBER != null) { version buildVersionName ext { - module_name = "EdXposed" + module_name = "LSPosed" jar_dest_dir = "${projectDir}/template_override/system/framework/" is_windows = OperatingSystem.current().isWindows() - backends = ["YAHFA", "SandHook"] - yahfa_module_id = "riru_edxposed" - sandhook_module_id = yahfa_module_id + "_sandhook" - yahfa_authors = "solohsu, MlgmXyysd & rk700" - sandhook_authors = "solohsu, MlgmXyysd & ganyao114" + module_id = "riru_lsposed" + authors = "LSPosed Developers" - riruModuleId = "edxp" + riruModuleId = "lsposed" moduleMinRiruApiVersion = 10 moduleMinRiruVersionName = "v23.0" @@ -54,13 +52,18 @@ repositories { dependencies { implementation 'rikka.ndk:riru:10' + implementation project(path: ':sandhook-hooklib') + compileOnly project(':hiddenapi-stubs') + compileOnly 'com.android.support:support-annotations:28.0.0' } android { compileSdkVersion androidCompileSdkVersion.toInteger() defaultConfig { + applicationId "com.elderdrivers.riru.edxp" minSdkVersion androidMinSdkVersion.toInteger() targetSdkVersion androidTargetSdkVersion.toInteger() + multiDexEnabled false buildFeatures { prefab true @@ -76,6 +79,10 @@ android { "-DRIRU_MODULE_VERSION_NAME:STRING=\"$rootProject.ext.versionName\"" } } + + buildConfigField("int", "API_CODE", "$apiCode") + buildConfigField("String", "VERSION_NAME", "\"${rootProject.ext.versionName}\"") + buildConfigField("Integer", "VERSION_CODE", String.valueOf(rootProject.ext.versionCode)) } buildTypes { @@ -88,14 +95,15 @@ android { } } release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + externalNativeBuild { cmake { cppFlags "-fvisibility=hidden -fvisibility-inlines-hidden -O2 -s -Wno-unused-value -fomit-frame-pointer" cFlags "-fvisibility=hidden -fvisibility-inlines-hidden -O2 -s -Wno-unused-value -fomit-frame-pointer" } } - minifyEnabled true - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } externalNativeBuild { @@ -104,153 +112,178 @@ android { } } ndkVersion androidCompileNdkVersion + compileOptions { + targetCompatibility JavaVersion.VERSION_1_7 + sourceCompatibility JavaVersion.VERSION_1_7 + } } task cleanTemplate(type: Delete) { delete file(templateSystemx86Path) } +preBuild.doLast { + def imlFile = file(project.name + ".iml") + try { + def parsedXml = (new XmlParser()).parse(imlFile) + def jdkNode = parsedXml.component[1].orderEntry.find { it.'@type' == 'jdk' } + parsedXml.component[1].remove(jdkNode) + def sdkString = "Android API " + android.compileSdkVersion.substring("android-".length()) + " Platform" + new Node(parsedXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': sdkString, 'jdkType': 'Android SDK']) + XmlUtil.serialize(parsedXml, new FileOutputStream(imlFile)) + } catch (FileNotFoundException ignored) { + // nop, iml not found + } +} + afterEvaluate { + tasks.withType(JavaCompile) { + dependsOn tasks.getByPath(":hiddenapi-stubs:makeStubJar") + options.compilerArgs.add("-Xbootclasspath/p:${hiddenApiStubJarFilePath}") + } - android.libraryVariants.all { variant -> + task("copyCommonProperties", type: Copy) { + from file("${projectDir}/template_override/") + into file(templateRootPath) + } + android.applicationVariants.all { variant -> def variantCapped = variant.name.capitalize() def variantLowered = variant.name.toLowerCase() + def zipFileName = "${module_name}-${project.version}-${variantLowered}.zip" - backends.each { backend -> - def backendLowered = backend.toLowerCase() - def backendCapped = backendLowered.capitalize() - def authorList = property("${backendLowered}" + "_authors") - def magiskModuleId = property("${backendLowered}" + "_module_id") - - delete file(zipPathMagiskReleasePath) - - def prepareJarsTask = task("prepareJars${backendCapped}${variantCapped}") { - dependsOn cleanTemplate - dependsOn tasks.getByPath(":dexmaker:copyDex${variantCapped}") - dependsOn tasks.getByPath(":dalvikdx:copyDex${variantCapped}") - dependsOn tasks.getByPath(":edxp-service:copyDex${variantCapped}") - dependsOn tasks.getByPath(":edxp-${backendLowered}:copyDex${variantCapped}") + task("copyMainDex${variantCapped}", type: Copy) { + def dexOutPath = variant.name.contains("release") ? + "${buildDir}/intermediates/dex/${variantLowered}/minify${variantCapped}WithR8" : + "${buildDir}/intermediates/dex/${variantLowered}/mergeDex${variantCapped}" + from (dexOutPath){ + rename("classes.dex", "edxp.dex") } + destinationDir file(zipPathMagiskReleasePath + "system/framework/") + outputs.upToDateWhen { false } + } - def prepareMagiskFilesTask = task("prepareMagiskFiles${backendCapped}${variantCapped}", type: Delete) { - dependsOn prepareJarsTask, "assemble${variantCapped}" - doFirst { - copy { - from "${projectDir}/tpl/edconfig.tpl" - into templateFrameworkPath - rename "edconfig.tpl", "edconfig.jar" - expand(version: "$version", backend: "$backend", apiCode: "$apiCode") - } - copy { - from "${projectDir}/tpl/module.prop.tpl" - into templateRootPath - rename "module.prop.tpl", "module.prop" - expand(moduleId: "$magiskModuleId", backend: "$backendCapped", - versionName: "$version" + " ($backend)", - versionCode: "$versionCode", authorList: "$authorList", - apiCode: "$apiCode", minApi: "$moduleMinRiruApiVersion") - filter(FixCrLfFilter.class, eol: FixCrLfFilter.CrLf.newInstance("lf")) - } + delete file(zipPathMagiskReleasePath) + + def prepareMagiskFilesTask = task("prepareMagiskFiles${variantCapped}", type: Delete) { + dependsOn "assemble${variantCapped}" + dependsOn tasks.getByPath(":sandhook-hooklib:copySandHook${variantCapped}LibraryToMagiskTemplate") + doFirst { + copy { + from "${projectDir}/tpl/edconfig.tpl" + into templateFrameworkPath + rename "edconfig.tpl", "edconfig.jar" + expand(version: "$version", apiCode: "$apiCode") } - def libPathRelease = "${buildDir}/intermediates/cmake/${variantLowered}/obj" - def exclude_list = ["riru.sh"] - doLast { - copy { - from "${projectDir}/template_override" - into zipPathMagiskReleasePath - exclude exclude_list - } - copy { - from "${projectDir}/template_override" - into zipPathMagiskReleasePath - include 'util_functions.sh' - filter { line -> - line.replaceAll('%%%RIRU_MODULE_ID%%%', riruModuleId) - .replaceAll('%%%RIRU_MIN_API_VERSION%%%', moduleMinRiruApiVersion.toString()) - .replaceAll('%%%RIRU_MIN_VERSION_NAME%%%', moduleMinRiruVersionName) - } - filter(FixCrLfFilter.class, - eol: FixCrLfFilter.CrLf.newInstance("lf")) - } - copy { - include "libriru_edxp.so" - from "$libPathRelease/armeabi-v7a" - into "$zipPathMagiskReleasePath/system/lib" - } - copy { - include "libriru_edxp.so" - from "$libPathRelease/arm64-v8a" - into "$zipPathMagiskReleasePath/system/lib64" - } - copy { - include "libriru_edxp.so" - from "$libPathRelease/x86" - into "$zipPathMagiskReleasePath/system_x86/lib" - } - copy { - include "libriru_edxp.so" - from "$libPathRelease/x86_64" - into "$zipPathMagiskReleasePath/system_x86/lib64" - } - // generate sha1sum - fileTree(zipPathMagiskReleasePath).matching { - exclude "README.md", "META-INF" - }.visit { f -> - if (f.directory) return - file(f.file.path + ".s").text = calcSha256(f.file) - } + copy { + from "${projectDir}/tpl/module.prop.tpl" + into templateRootPath + rename "module.prop.tpl", "module.prop" + expand(moduleId: "$module_id", + versionName: "$version", + versionCode: "$versionCode", authorList: "$authors", + apiCode: "$apiCode", minApi: "$moduleMinRiruApiVersion") + filter(FixCrLfFilter.class, eol: FixCrLfFilter.CrLf.newInstance("lf")) } } - - def zipTask = task("zip${backendCapped}${variantCapped}", type: Zip) { - dependsOn prepareMagiskFilesTask - archiveName "${module_name}-${backend}-${project.version}-${variantLowered}.zip" - destinationDir file("$projectDir/release") - from "$zipPathMagiskReleasePath" - } - - task("push${backendCapped}${variantCapped}", type: Exec) { - dependsOn zipTask - workingDir "${projectDir}/release" - def commands = [android.adbExecutable, "push", - "${module_name}-${backend}-${project.version}-${variantLowered}.zip", - "/data/local/tmp/"] - if (is_windows) { - commandLine 'cmd', '/c', commands.join(" ") - } else { - commandLine commands + def libPathRelease = "${buildDir}/intermediates/cmake/${variantLowered}/obj" + def exclude_list = ["riru.sh"] + doLast { + def dexOutPath = variant.name.contains("release") ? + "${buildDir}/intermediates/dex/${variantLowered}/minify${variantCapped}WithR8" : + "${buildDir}/intermediates/dex/${variantLowered}/mergeDex${variantCapped}" + copy { + from (dexOutPath){ + rename("classes.dex", "edxp.dex") + } + into file(zipPathMagiskReleasePath + "system/framework/") } - } - task("flash${backendCapped}${variantCapped}", type: Exec) { - dependsOn tasks.getByPath("push${backendCapped}${variantCapped}") - workingDir "${projectDir}/release" - def commands = [android.adbExecutable, "shell", "su", "-c", - "magisk --install-module /data/local/tmp/${module_name}-${backend}-${project.version}-${variantLowered}.zip"] - if (is_windows) { - commandLine 'cmd', '/c', commands.join(" ") - } else { - commandLine commands + copy { + from "${projectDir}/template_override" + into zipPathMagiskReleasePath + exclude exclude_list } - } - task("flashAndReboot${backendCapped}${variantCapped}", type: Exec) { - dependsOn tasks.getByPath("flash${backendCapped}${variantCapped}") - workingDir "${projectDir}/release" - def commands = [android.adbExecutable, "shell", "reboot"] - if (is_windows) { - commandLine 'cmd', '/c', commands.join(" ") - } else { - commandLine commands + copy { + from "${projectDir}/template_override" + into zipPathMagiskReleasePath + include 'util_functions.sh' + filter { line -> + line.replaceAll('%%%RIRU_MODULE_ID%%%', riruModuleId) + .replaceAll('%%%RIRU_MIN_API_VERSION%%%', moduleMinRiruApiVersion.toString()) + .replaceAll('%%%RIRU_MIN_VERSION_NAME%%%', moduleMinRiruVersionName) + } + filter(FixCrLfFilter.class, + eol: FixCrLfFilter.CrLf.newInstance("lf")) + } + copy { + include "libriru_edxp.so" + from "$libPathRelease/armeabi-v7a" + into "$zipPathMagiskReleasePath/system/lib" + } + copy { + include "libriru_edxp.so" + from "$libPathRelease/arm64-v8a" + into "$zipPathMagiskReleasePath/system/lib64" + } + copy { + include "libriru_edxp.so" + from "$libPathRelease/x86" + into "$zipPathMagiskReleasePath/system_x86/lib" + } + copy { + include "libriru_edxp.so" + from "$libPathRelease/x86_64" + into "$zipPathMagiskReleasePath/system_x86/lib64" + } + // generate sha1sum + fileTree(zipPathMagiskReleasePath).matching { + exclude "README.md", "META-INF" + }.visit { f -> + if (f.directory) return + file(f.file.path + ".sha256").text = calcSha256(f.file) } } } - // backward compatible - task("zip${variantCapped}") { - dependsOn "zipYahfa${variantCapped}" + def zipTask = task("zip${variantCapped}", type: Zip) { + dependsOn prepareMagiskFilesTask + archiveName zipFileName + destinationDir file("$projectDir/release") + from "$zipPathMagiskReleasePath" } - task("push${variantCapped}") { - dependsOn "pushYahfa${variantCapped}" + + task("push${variantCapped}", type: Exec) { + dependsOn zipTask + workingDir "${projectDir}/release" + def commands = [android.adbExecutable, "push", + zipFileName, + "/data/local/tmp/"] + if (is_windows) { + commandLine 'cmd', '/c', commands.join(" ") + } else { + commandLine commands + } + } + task("flash${variantCapped}", type: Exec) { + dependsOn tasks.getByPath("push${variantCapped}") + workingDir "${projectDir}/release" + def commands = [android.adbExecutable, "shell", "su", "-c", + "magisk --install-module /data/local/tmp/${zipFileName}"] + if (is_windows) { + commandLine 'cmd', '/c', commands.join(" ") + } else { + commandLine commands + } + } + task("flashAndReboot${variantCapped}", type: Exec) { + dependsOn tasks.getByPath("flash${variantCapped}") + workingDir "${projectDir}/release" + def commands = [android.adbExecutable, "shell", "reboot"] + if (is_windows) { + commandLine 'cmd', '/c', commands.join(" ") + } else { + commandLine commands + } } } diff --git a/edxp-common/proguard-rules.pro b/edxp-core/proguard-rules.pro similarity index 100% rename from edxp-common/proguard-rules.pro rename to edxp-core/proguard-rules.pro diff --git a/edxp-core/src/main/cpp/main/src/config_manager.cpp b/edxp-core/src/main/cpp/main/src/config_manager.cpp index b6e80090..c62c37f5 100644 --- a/edxp-core/src/main/cpp/main/src/config_manager.cpp +++ b/edxp-core/src/main/cpp/main/src/config_manager.cpp @@ -151,7 +151,7 @@ namespace edxp { ConfigManager::ConfigManager(uid_t user, bool initialized) : user_(user), - data_path_prefix_(fs::path(use_prot_storage_ ? "/data/user_de" : "/data/user") / + data_path_prefix_(fs::path("/data/user_de") / std::to_string(user_)), base_config_path_(RetrieveBaseConfigPath()), initialized_(initialized || InitConfigPath()), @@ -344,11 +344,7 @@ namespace edxp { return !std::isspace(ch); }).base(), path.end()); misc_path_ = fs::path("/data/misc") / path; - std::transform(kXposedInjectDexPath.begin(), kXposedInjectDexPath.end(), - std::back_inserter(inject_dex_paths_), - [](auto i) { - return GetFrameworkPath(i); - }); + inject_dex_path_ = GetFrameworkPath(kXposedInjectDexPath); LOGI("Got base config path: %s", misc_path_.c_str()); } catch (const RirudSocket::RirudSocketException &e) { LOGE("%s", e.what()); diff --git a/edxp-core/src/main/cpp/main/src/config_manager.h b/edxp-core/src/main/cpp/main/src/config_manager.h index ac5478b2..e52160b0 100644 --- a/edxp-core/src/main/cpp/main/src/config_manager.h +++ b/edxp-core/src/main/cpp/main/src/config_manager.h @@ -14,16 +14,11 @@ namespace edxp { - class ConfigManager { private: inline static const auto kPrimaryInstallerPkgName = "org.meowcat.edxposed.manager"s; inline static const auto kXposedPropName = "edconfig.jar"s; - inline static const std::vector kXposedInjectDexPath = { - "edxp.dex", - "eddalvikdx.dex", - "eddexmaker.dex", - }; + inline static const auto kXposedInjectDexPath = "edxp.dex"; public: static void Init(); @@ -105,22 +100,22 @@ namespace edxp { void EnsurePermission(const std::string &pkg_name, uid_t uid) const; - static const auto &GetInjectDexPaths() { return inject_dex_paths_; }; + static const auto &GetInjectDexPath() { return inject_dex_path_; }; bool IsInstaller(const std::string &pkg_name) const { return pkg_name == installer_pkg_name_ || pkg_name == kPrimaryInstallerPkgName; } + private: inline static std::unordered_map> instances_{}; inline static uid_t current_user_ = 0u; - inline static std::filesystem::path misc_path_; - inline static std::vector inject_dex_paths_; - inline static const bool use_prot_storage_ = GetAndroidApiLevel() >= __ANDROID_API_N__; + inline static std::filesystem::path misc_path_; // /data/misc/edxp_xxxx + inline static std::filesystem::path inject_dex_path_; const uid_t user_; - const std::filesystem::path data_path_prefix_; - const std::filesystem::path base_config_path_; + const std::filesystem::path data_path_prefix_; // /data/user_de/{user} + const std::filesystem::path base_config_path_; // /data/misc/edxp_xxxx/{user} const bool initialized_ = false; const std::filesystem::path installer_pkg_name_; const bool white_list_enable_ = false; diff --git a/edxp-core/src/main/cpp/main/src/edxp_context.cpp b/edxp-core/src/main/cpp/main/src/edxp_context.cpp index 8f4bb751..74a8a0f9 100644 --- a/edxp-core/src/main/cpp/main/src/edxp_context.cpp +++ b/edxp-core/src/main/cpp/main/src/edxp_context.cpp @@ -54,18 +54,17 @@ namespace edxp { CallPostFixupStaticTrampolinesCallback(class_ptr, post_fixup_static_mid_); } - void Context::PreLoadDex(const std::vector &dex_paths) { + void Context::PreLoadDex(const fs::path &dex_path) { if (LIKELY(!dexes.empty())) return; - for (const auto &path: dex_paths) { - std::ifstream is(path, std::ios::binary); - if (!is.good()) { - LOGE("Cannot load path %s", path.c_str()); - continue; - } - dexes.emplace_back(std::istreambuf_iterator(is), - std::istreambuf_iterator()); - LOGI("Loaded %s with size %zu", path.c_str(), dexes.back().size()); + + std::ifstream is(dex_path, std::ios::binary); + if (!is.good()) { + LOGE("Cannot load path %s", dex_path.c_str()); + return; } + dexes.emplace_back(std::istreambuf_iterator(is), + std::istreambuf_iterator()); + LOGI("Loaded %s with size %zu", dex_path.c_str(), dexes.back().size()); } void Context::InjectDexAndInit(JNIEnv *env) { @@ -227,7 +226,7 @@ namespace edxp { LOGD("skip injecting into android because no module hooks it"); } if (!skip_) { - PreLoadDex(ConfigManager::GetInjectDexPaths()); + PreLoadDex(ConfigManager::GetInjectDexPath()); } ConfigManager::GetInstance()->EnsurePermission("android", 1000); } @@ -410,7 +409,7 @@ namespace edxp { }, is_child_zygote); if (!skip_) { ConfigManager::GetInstance()->EnsurePermission(package_name, uid); - PreLoadDex(ConfigManager::GetInjectDexPaths()); + PreLoadDex(ConfigManager::GetInjectDexPath()); } } diff --git a/edxp-core/src/main/cpp/main/src/edxp_context.h b/edxp-core/src/main/cpp/main/src/edxp_context.h index a5a175c0..ae174daf 100644 --- a/edxp-core/src/main/cpp/main/src/edxp_context.h +++ b/edxp-core/src/main/cpp/main/src/edxp_context.h @@ -95,7 +95,7 @@ namespace edxp { Context() {} - void PreLoadDex(const std::vector &dex_path); + void PreLoadDex(const std::filesystem::path &dex_paths); void InjectDexAndInit(JNIEnv *env); diff --git a/edxp-core/src/main/java/android/app/AndroidAppHelper.java b/edxp-core/src/main/java/android/app/AndroidAppHelper.java new file mode 100644 index 00000000..c9160c5a --- /dev/null +++ b/edxp-core/src/main/java/android/app/AndroidAppHelper.java @@ -0,0 +1,223 @@ +package android.app; + +import android.content.SharedPreferences; +import android.content.pm.ApplicationInfo; +import android.content.res.CompatibilityInfo; +import android.content.res.Configuration; +import android.content.res.Resources; +import android.os.Build; +import android.os.IBinder; +import android.view.Display; + +import java.lang.ref.WeakReference; +import java.util.Map; + +import de.robv.android.xposed.XSharedPreferences; +import de.robv.android.xposed.XposedBridge; + +import static de.robv.android.xposed.XposedHelpers.findClass; +import static de.robv.android.xposed.XposedHelpers.findFieldIfExists; +import static de.robv.android.xposed.XposedHelpers.findMethodExactIfExists; +import static de.robv.android.xposed.XposedHelpers.getObjectField; +import static de.robv.android.xposed.XposedHelpers.newInstance; +import static de.robv.android.xposed.XposedHelpers.setFloatField; + +/** + * Contains various methods for information about the current app. + * + *

For historical reasons, this class is in the {@code android.app} package. It can't be moved + * without breaking compatibility with existing modules. + */ +public final class AndroidAppHelper { + private AndroidAppHelper() {} + + private static final Class CLASS_RESOURCES_KEY; + private static final boolean HAS_IS_THEMEABLE; + private static final boolean HAS_THEME_CONFIG_PARAMETER; + + static { + CLASS_RESOURCES_KEY = (Build.VERSION.SDK_INT < 19) ? + findClass("android.app.ActivityThread$ResourcesKey", null) + : findClass("android.content.res.ResourcesKey", null); + + HAS_IS_THEMEABLE = findFieldIfExists(CLASS_RESOURCES_KEY, "mIsThemeable") != null; + HAS_THEME_CONFIG_PARAMETER = HAS_IS_THEMEABLE && Build.VERSION.SDK_INT >= 21 + && findMethodExactIfExists("android.app.ResourcesManager", null, "getThemeConfig") != null; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static Map getResourcesMap(ActivityThread activityThread) { + if (Build.VERSION.SDK_INT >= 24) { + Object resourcesManager = getObjectField(activityThread, "mResourcesManager"); + return (Map) getObjectField(resourcesManager, "mResourceImpls"); + } else if (Build.VERSION.SDK_INT >= 19) { + Object resourcesManager = getObjectField(activityThread, "mResourcesManager"); + return (Map) getObjectField(resourcesManager, "mActiveResources"); + } else { + return (Map) getObjectField(activityThread, "mActiveResources"); + } + } + + /* For SDK 15 & 16 */ + private static Object createResourcesKey(String resDir, float scale) { + try { + if (HAS_IS_THEMEABLE) + return newInstance(CLASS_RESOURCES_KEY, resDir, scale, false); + else + return newInstance(CLASS_RESOURCES_KEY, resDir, scale); + } catch (Throwable t) { + XposedBridge.log(t); + return null; + } + } + + /* For SDK 17 & 18 & 23 */ + private static Object createResourcesKey(String resDir, int displayId, Configuration overrideConfiguration, float scale) { + try { + if (HAS_THEME_CONFIG_PARAMETER) + return newInstance(CLASS_RESOURCES_KEY, resDir, displayId, overrideConfiguration, scale, false, null); + else if (HAS_IS_THEMEABLE) + return newInstance(CLASS_RESOURCES_KEY, resDir, displayId, overrideConfiguration, scale, false); + else + return newInstance(CLASS_RESOURCES_KEY, resDir, displayId, overrideConfiguration, scale); + } catch (Throwable t) { + XposedBridge.log(t); + return null; + } + } + + /* For SDK 19 - 22 */ + private static Object createResourcesKey(String resDir, int displayId, Configuration overrideConfiguration, float scale, IBinder token) { + try { + if (HAS_THEME_CONFIG_PARAMETER) + return newInstance(CLASS_RESOURCES_KEY, resDir, displayId, overrideConfiguration, scale, false, null, token); + else if (HAS_IS_THEMEABLE) + return newInstance(CLASS_RESOURCES_KEY, resDir, displayId, overrideConfiguration, scale, false, token); + else + return newInstance(CLASS_RESOURCES_KEY, resDir, displayId, overrideConfiguration, scale, token); + } catch (Throwable t) { + XposedBridge.log(t); + return null; + } + } + + /* For SDK 24+ */ + private static Object createResourcesKey(String resDir, String[] splitResDirs, String[] overlayDirs, String[] libDirs, int displayId, Configuration overrideConfiguration, CompatibilityInfo compatInfo) { + try { + return newInstance(CLASS_RESOURCES_KEY, resDir, splitResDirs, overlayDirs, libDirs, displayId, overrideConfiguration, compatInfo); + } catch (Throwable t) { + XposedBridge.log(t); + return null; + } + } + + /** @hide */ + public static void addActiveResource(String resDir, float scale, boolean isThemeable, Resources resources) { + addActiveResource(resDir, resources); + } + + /** @hide */ + public static void addActiveResource(String resDir, Resources resources) { + ActivityThread thread = ActivityThread.currentActivityThread(); + if (thread == null) { + return; + } + + Object resourcesKey; + if (Build.VERSION.SDK_INT >= 24) { + CompatibilityInfo compatInfo = (CompatibilityInfo) newInstance(CompatibilityInfo.class); + setFloatField(compatInfo, "applicationScale", resources.hashCode()); + resourcesKey = createResourcesKey(resDir, null, null, null, Display.DEFAULT_DISPLAY, null, compatInfo); + } else if (Build.VERSION.SDK_INT == 23) { + resourcesKey = createResourcesKey(resDir, Display.DEFAULT_DISPLAY, null, resources.hashCode()); + } else if (Build.VERSION.SDK_INT >= 19) { + resourcesKey = createResourcesKey(resDir, Display.DEFAULT_DISPLAY, null, resources.hashCode(), null); + } else if (Build.VERSION.SDK_INT >= 17) { + resourcesKey = createResourcesKey(resDir, Display.DEFAULT_DISPLAY, null, resources.hashCode()); + } else { + resourcesKey = createResourcesKey(resDir, resources.hashCode()); + } + + if (resourcesKey != null) { + if (Build.VERSION.SDK_INT >= 24) { + Object resImpl = getObjectField(resources, "mResourcesImpl"); + getResourcesMap(thread).put(resourcesKey, new WeakReference<>(resImpl)); + } else { + getResourcesMap(thread).put(resourcesKey, new WeakReference<>(resources)); + } + } + } + + /** + * Returns the name of the current process. It's usually the same as the main package name. + */ + public static String currentProcessName() { + String processName = ActivityThread.currentPackageName(); + if (processName == null) + return "android"; + return processName; + } + + /** + * Returns information about the main application in the current process. + * + *

In a few cases, multiple apps might run in the same process, e.g. the SystemUI and the + * Keyguard which both have {@code android:process="com.android.systemui"} set in their + * manifest. In those cases, the first application that was initialized will be returned. + */ + public static ApplicationInfo currentApplicationInfo() { + ActivityThread am = ActivityThread.currentActivityThread(); + if (am == null) + return null; + + Object boundApplication = getObjectField(am, "mBoundApplication"); + if (boundApplication == null) + return null; + + return (ApplicationInfo) getObjectField(boundApplication, "appInfo"); + } + + /** + * Returns the Android package name of the main application in the current process. + * + *

In a few cases, multiple apps might run in the same process, e.g. the SystemUI and the + * Keyguard which both have {@code android:process="com.android.systemui"} set in their + * manifest. In those cases, the first application that was initialized will be returned. + */ + public static String currentPackageName() { + ApplicationInfo ai = currentApplicationInfo(); + return (ai != null) ? ai.packageName : "android"; + } + + /** + * Returns the main {@link android.app.Application} object in the current process. + * + *

In a few cases, multiple apps might run in the same process, e.g. the SystemUI and the + * Keyguard which both have {@code android:process="com.android.systemui"} set in their + * manifest. In those cases, the first application that was initialized will be returned. + */ + public static Application currentApplication() { + return ActivityThread.currentApplication(); + } + + /** @deprecated Use {@link XSharedPreferences} instead. */ + @SuppressWarnings("UnusedParameters") + @Deprecated + public static SharedPreferences getSharedPreferencesForPackage(String packageName, String prefFileName, int mode) { + return new XSharedPreferences(packageName, prefFileName); + } + + /** @deprecated Use {@link XSharedPreferences} instead. */ + @Deprecated + public static SharedPreferences getDefaultSharedPreferencesForPackage(String packageName) { + return new XSharedPreferences(packageName); + } + + /** @deprecated Use {@link XSharedPreferences#reload} instead. */ + @Deprecated + public static void reloadSharedPreferencesIfNeeded(SharedPreferences pref) { + if (pref instanceof XSharedPreferences) { + ((XSharedPreferences) pref).reload(); + } + } +} diff --git a/edxp-core/src/main/java/android/app/package-info.java b/edxp-core/src/main/java/android/app/package-info.java new file mode 100644 index 00000000..98b6207b --- /dev/null +++ b/edxp-core/src/main/java/android/app/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains {@link android.app.AndroidAppHelper} with various methods for information about the current app. + */ +package android.app; diff --git a/edxp-core/src/main/java/android/content/res/XModuleResources.java b/edxp-core/src/main/java/android/content/res/XModuleResources.java new file mode 100644 index 00000000..57464b35 --- /dev/null +++ b/edxp-core/src/main/java/android/content/res/XModuleResources.java @@ -0,0 +1,54 @@ +package android.content.res; + +import android.app.AndroidAppHelper; +import android.util.DisplayMetrics; + +import de.robv.android.xposed.IXposedHookInitPackageResources; +import de.robv.android.xposed.IXposedHookZygoteInit; +import de.robv.android.xposed.IXposedHookZygoteInit.StartupParam; +import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam; + +/** + * Provides access to resources from a certain path (usually the module's own path). + */ +public class XModuleResources extends Resources { + private XModuleResources(AssetManager assets, DisplayMetrics metrics, Configuration config) { + super(assets, metrics, config); + } + + /** + * Creates a new instance. + * + *

This is usually called with {@link StartupParam#modulePath} from + * {@link IXposedHookZygoteInit#initZygote} and {@link InitPackageResourcesParam#res} from + * {@link IXposedHookInitPackageResources#handleInitPackageResources} (or {@code null} for + * system-wide replacements). + * + * @param path The path to the APK from which the resources should be loaded. + * @param origRes The resources object from which settings like the display metrics and the + * configuration should be copied. May be {@code null}. + */ + public static XModuleResources createInstance(String path, XResources origRes) { + if (path == null) + throw new IllegalArgumentException("path must not be null"); + + AssetManager assets = new AssetManager(); + assets.addAssetPath(path); + + XModuleResources res; + if (origRes != null) + res = new XModuleResources(assets, origRes.getDisplayMetrics(), origRes.getConfiguration()); + else + res = new XModuleResources(assets, null, null); + + AndroidAppHelper.addActiveResource(path, res); + return res; + } + + /** + * Creates an {@link XResForwarder} instance that forwards requests to {@code id} in this resource. + */ + public XResForwarder fwd(int id) { + return new XResForwarder(this, id); + } +} diff --git a/edxp-core/src/main/java/android/content/res/XResForwarder.java b/edxp-core/src/main/java/android/content/res/XResForwarder.java new file mode 100644 index 00000000..7d659052 --- /dev/null +++ b/edxp-core/src/main/java/android/content/res/XResForwarder.java @@ -0,0 +1,34 @@ +package android.content.res; + +/** + * Instances of this class can be used for {@link XResources#setReplacement(String, String, String, Object)} + * and its variants. They forward the resource request to a different {@link android.content.res.Resources} + * instance with a possibly different ID. + * + *

Usually, instances aren't created directly but via {@link XModuleResources#fwd}. + */ +public class XResForwarder { + private final Resources res; + private final int id; + + /** + * Creates a new instance. + * + * @param res The target {@link android.content.res.Resources} instance to forward requests to. + * @param id The target resource ID. + */ + public XResForwarder(Resources res, int id) { + this.res = res; + this.id = id; + } + + /** Returns the target {@link android.content.res.Resources} instance. */ + public Resources getResources() { + return res; + } + + /** Returns the target resource ID. */ + public int getId() { + return id; + } +} diff --git a/edxp-core/src/main/java/android/content/res/XResources.java b/edxp-core/src/main/java/android/content/res/XResources.java new file mode 100644 index 00000000..ae73428f --- /dev/null +++ b/edxp-core/src/main/java/android/content/res/XResources.java @@ -0,0 +1,1749 @@ +package android.content.res; + +import android.content.Context; +import android.content.pm.PackageParser; +import android.content.pm.PackageParser.PackageParserException; +import android.graphics.Color; +import android.graphics.Movie; +import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.Drawable; +import android.os.Build; +import android.os.StrictMode; +import android.text.Html; +import android.util.AttributeSet; +import android.util.DisplayMetrics; +import android.util.SparseArray; +import android.util.TypedValue; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import org.xmlpull.v1.XmlPullParser; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.WeakHashMap; + +import de.robv.android.xposed.IXposedHookZygoteInit; +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XC_MethodHook.MethodHookParam; +import de.robv.android.xposed.XposedBridge; +import de.robv.android.xposed.XposedBridge.CopyOnWriteSortedSet; +import de.robv.android.xposed.callbacks.XC_LayoutInflated; +import de.robv.android.xposed.callbacks.XC_LayoutInflated.LayoutInflatedParam; +import de.robv.android.xposed.callbacks.XCallback; +import xposed.dummy.XResourcesSuperClass; +import xposed.dummy.XTypedArraySuperClass; + +import static de.robv.android.xposed.XposedHelpers.decrementMethodDepth; +import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; +import static de.robv.android.xposed.XposedHelpers.getIntField; +import static de.robv.android.xposed.XposedHelpers.getLongField; +import static de.robv.android.xposed.XposedHelpers.getObjectField; +import static de.robv.android.xposed.XposedHelpers.incrementMethodDepth; + +/** + * {@link android.content.res.Resources} subclass that allows replacing individual resources. + * + *

Xposed replaces the standard resources with this class, which overrides the methods used for + * retrieving individual resources and adds possibilities to replace them. These replacements can + * be set using the methods made available via the API methods in this class. + */ +@SuppressWarnings("JniMissingFunction") +public class XResources extends XResourcesSuperClass { + private static final SparseArray> sReplacements = new SparseArray<>(); + private static final SparseArray> sResourceNames = new SparseArray<>(); + + private static final byte[] sSystemReplacementsCache = new byte[256]; // bitmask: 0x000700ff => 2048 bit => 256 bytes + private byte[] mReplacementsCache; // bitmask: 0x0007007f => 1024 bit => 128 bytes + private static final HashMap sReplacementsCacheMap = new HashMap<>(); + private static final SparseArray sColorStateListCache = new SparseArray<>(0); + + private static final SparseArray>> sLayoutCallbacks = new SparseArray<>(); + private static final WeakHashMap sXmlInstanceDetails = new WeakHashMap<>(); + + private static final String EXTRA_XML_INSTANCE_DETAILS = "xmlInstanceDetails"; + private static final ThreadLocal> sIncludedLayouts = new ThreadLocal>() { + @Override + protected LinkedList initialValue() { + return new LinkedList<>(); + } + }; + + private static final HashMap sResDirLastModified = new HashMap<>(); + private static final HashMap sResDirPackageNames = new HashMap<>(); + private static ThreadLocal sLatestResKey = null; + + private boolean mIsObjectInited; + private String mResDir; + private String mPackageName; + + public XResources(ClassLoader classLoader) { + super(classLoader); + } + + /** Dummy, will never be called (objects are transferred to this class only). */ +// private XResources() { +// throw new UnsupportedOperationException(); +// } + + /** @hide */ + public void initObject(String resDir) { + if (mIsObjectInited) + throw new IllegalStateException("Object has already been initialized"); + + this.mResDir = resDir; + this.mPackageName = getPackageName(resDir); + + if (resDir != null) { + synchronized (sReplacementsCacheMap) { + mReplacementsCache = sReplacementsCacheMap.get(resDir); + if (mReplacementsCache == null) { + mReplacementsCache = new byte[128]; + sReplacementsCacheMap.put(resDir, mReplacementsCache); + } + } + } + + this.mIsObjectInited = true; + } + + /** @hide */ + public boolean isFirstLoad() { + synchronized (sReplacements) { + if (mResDir == null) + return false; + + final StrictMode.ThreadPolicy policy = StrictMode.allowThreadDiskReads(); + Long lastModification = new File(mResDir).lastModified(); + Long oldModified = sResDirLastModified.get(mResDir); + StrictMode.setThreadPolicy(policy); + if (lastModification.equals(oldModified)) + return false; + + sResDirLastModified.put(mResDir, lastModification); + + if (oldModified == null) + return true; + + // file was changed meanwhile => remove old replacements + for (int i = 0; i < sReplacements.size(); i++) { + sReplacements.valueAt(i).remove(mResDir); + } + Arrays.fill(mReplacementsCache, (byte) 0); + return true; + } + } + + /** @hide */ + public static void setPackageNameForResDir(String packageName, String resDir) { + synchronized (sResDirPackageNames) { + sResDirPackageNames.put(resDir, packageName); + } + } + + /** + * Returns the name of the package that these resources belong to, or "android" for system resources. + */ + public String getPackageName() { + return mPackageName; + } + + private static String getPackageName(String resDir) { + if (resDir == null) + return "android"; + + String packageName; + synchronized (sResDirPackageNames) { + packageName = sResDirPackageNames.get(resDir); + } + + if (packageName != null) + return packageName; + + PackageParser.PackageLite pkgInfo; + if (Build.VERSION.SDK_INT >= 21) { + try { + pkgInfo = PackageParser.parsePackageLite(new File(resDir), 0); + } catch (PackageParserException e) { + throw new IllegalStateException("Could not determine package name for " + resDir, e); + } + } else { + pkgInfo = PackageParser.parsePackageLite(resDir, 0); + } + if (pkgInfo != null && pkgInfo.packageName != null) { +// Log.w(XposedBridge.TAG, "Package name for " + resDir + " had to be retrieved via parser"); + packageName = pkgInfo.packageName; + setPackageNameForResDir(packageName, resDir); + return packageName; + } + + throw new IllegalStateException("Could not determine package name for " + resDir); + } + + /** + * Special case of {@link #getPackageName} during object creation. + * + *

For a short moment during/after the creation of a new {@link android.content.res Resources} + * object, it isn't an instance of {@link XResources} yet. For any hooks that need information + * about the just created object during this particular stage, this method will return the + * package name. + * + *

If you call this method outside of {@code getTopLevelResources()}, it + * throws an {@code IllegalStateException}. + */ + public static String getPackageNameDuringConstruction() { + Object key; + if (sLatestResKey == null || (key = sLatestResKey.get()) == null) + throw new IllegalStateException("This method can only be called during getTopLevelResources()"); + + String resDir = (String) getObjectField(key, "mResDir"); + return getPackageName(resDir); + } + + /** @hide */ + public static void init(ThreadLocal latestResKey) throws Exception { + sLatestResKey = latestResKey; + + 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 (sXmlInstanceDetails) { + details = sXmlInstanceDetails.get(param.args[0]); + } + if (details != null) { + LayoutInflatedParam liparam = new LayoutInflatedParam(details.callbacks); + liparam.view = (View) param.getResult(); + liparam.resNames = details.resNames; + liparam.variant = details.variant; + liparam.res = details.res; + XCallback.callAll(liparam); + } + } + }); + + final XC_MethodHook parseIncludeHook = new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) throws Throwable { + sIncludedLayouts.get().push(param); + } + + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + sIncludedLayouts.get().pop(); + + if (param.hasThrowable()) + return; + + // filled in by our implementation of getLayout() + XMLInstanceDetails details = (XMLInstanceDetails) param.getObjectExtra(EXTRA_XML_INSTANCE_DETAILS); + if (details != null) { + LayoutInflatedParam liparam = new LayoutInflatedParam(details.callbacks); + ViewGroup group = (ViewGroup) param.args[(Build.VERSION.SDK_INT < 23) ? 1 : 2]; + liparam.view = group.getChildAt(group.getChildCount() - 1); + liparam.resNames = details.resNames; + liparam.variant = details.variant; + liparam.res = details.res; + XCallback.callAll(liparam); + } + } + }; + if (Build.VERSION.SDK_INT < 21) { + findAndHookMethod(LayoutInflater.class, "parseInclude", XmlPullParser.class, View.class, + AttributeSet.class, parseIncludeHook); + } else if (Build.VERSION.SDK_INT < 23) { + findAndHookMethod(LayoutInflater.class, "parseInclude", XmlPullParser.class, View.class, + AttributeSet.class, boolean.class, parseIncludeHook); + } else { + findAndHookMethod(LayoutInflater.class, "parseInclude", XmlPullParser.class, Context.class, + View.class, AttributeSet.class, parseIncludeHook); + } + } + + /** + * Wrapper for information about an indiviual resource. + */ + public static class ResourceNames { + /** The resource ID. */ + public final int id; + /** The resource package name as returned by {@link #getResourcePackageName}. */ + public final String pkg; + /** The resource entry name as returned by {@link #getResourceEntryName}. */ + public final String name; + /** The resource type name as returned by {@link #getResourceTypeName}. */ + public final String type; + /** The full resource nameas returned by {@link #getResourceName}. */ + public final String fullName; + + private ResourceNames(int id, String pkg, String name, String type) { + this.id = id; + this.pkg = pkg; + this.name = name; + this.type = type; + this.fullName = pkg + ":" + type + "/" + name; + } + + /** + * Returns whether all non-null parameters match the values of this object. + */ + public boolean equals(String pkg, String name, String type, int id) { + return (pkg == null || pkg.equals(this.pkg)) + && (name == null || name.equals(this.name)) + && (type == null || type.equals(this.type)) + && (id == 0 || id == this.id); + } + } + + private ResourceNames getResourceNames(int id) { + return new ResourceNames( + id, + getResourcePackageName(id), + getResourceTypeName(id), + getResourceEntryName(id)); + } + + private static ResourceNames getSystemResourceNames(int id) { + Resources sysRes = getSystem(); + return new ResourceNames( + id, + sysRes.getResourcePackageName(id), + sysRes.getResourceTypeName(id), + sysRes.getResourceEntryName(id)); + } + + private static void putResourceNames(String resDir, ResourceNames resNames) { + int id = resNames.id; + synchronized (sResourceNames) { + HashMap inner = sResourceNames.get(id); + if (inner == null) { + inner = new HashMap<>(); + sResourceNames.put(id, inner); + } + synchronized (inner) { + inner.put(resDir, resNames); + } + } + } + + // ======================================================= + // DEFINING REPLACEMENTS + // ======================================================= + + /** + * Sets a replacement for an individual resource. See {@link #setReplacement(String, String, String, Object)}. + * + * @param id The ID of the resource which should be replaced. + * @param replacement The replacement, see above. + */ + public void setReplacement(int id, Object replacement) { + setReplacement(id, replacement, this); + } + + /** + * Sets a replacement for an individual resource. See {@link #setReplacement(String, String, String, Object)}. + * + * @deprecated Use {@link #setReplacement(String, String, String, Object)} instead. + * + * @param fullName The full resource name, e.g. {@code com.example.myapplication:string/app_name}. + * See {@link #getResourceName}. + * @param replacement The replacement. + */ + @Deprecated + public void setReplacement(String fullName, Object replacement) { + int id = getIdentifier(fullName, null, null); + if (id == 0) + throw new NotFoundException(fullName); + setReplacement(id, replacement, this); + } + + /** + * Sets a replacement for an individual resource. If called more than once for the same ID, the + * replacement from the last call is used. Setting the replacement to {@code null} removes it. + * + *

The allowed replacements depend on the type of the source. All types accept an + * {@link XResForwarder} object, which is usually created with {@link XModuleResources#fwd}. + * The resource request will then be forwarded to another {@link android.content.res.Resources} + * object. In addition to that, the following replacement types are accepted: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Resource type Additional allowed replacement types (*) Returned from (**)
Animation none{@link #getAnimation}
Bool{@link Boolean}{@link #getBoolean}
Color{@link Integer} (you might want to use {@link Color#parseColor}){@link #getColor}
+ * {@link #getDrawable} (creates a {@link ColorDrawable})
+ * {@link #getColorStateList} (calls {@link android.content.res.ColorStateList#valueOf}) + *
Color State List{@link android.content.res.ColorStateList}
+ * {@link Integer} (calls {@link android.content.res.ColorStateList#valueOf}) + *
{@link #getColorStateList}
Dimension{@link DimensionReplacement} (since v50){@link #getDimension}
+ * {@link #getDimensionPixelOffset}
+ * {@link #getDimensionPixelSize} + *
Drawable + * (including mipmap){@link DrawableLoader}
+ * {@link Integer} (creates a {@link ColorDrawable}) + *
{@link #getDrawable}
+ * {@link #getDrawableForDensity} + *
Fraction none{@link #getFraction}
Integer{@link Integer}{@link #getInteger}
Integer Array{@code int[]}{@link #getIntArray}
Layout none, but see {@link #hookLayout}{@link #getLayout}
Movie none{@link #getMovie}
Quantity Strings (Plurals) none{@link #getQuantityString}
+ * {@link #getQuantityText} + *
String{@link String}
+ * {@link CharSequence} (for styled texts, see also {@link Html#fromHtml}) + *
{@link #getString}
+ * {@link #getText} + *
String Array{@code String[]}
+ * {@code CharSequence[]} (for styled texts, see also {@link Html#fromHtml}) + *
{@link #getStringArray}
+ * {@link #getTextArray} + *
XML none{@link #getXml}
+ * {@link #getQuantityText} + *
+ * + *

Other resource types, such as + * styles/themes, + * {@linkplain #openRawResource raw resources} and + * typed arrays + * can't be replaced. + * + *

+ * * Auto-boxing allows you to use literals like {@code 123} where an {@link Integer} is + * accepted, so you don't neeed to call methods like {@link Integer#valueOf(int)} manually.
+ * ** Some of these methods have multiple variants, only one of them is mentioned here. + *
+ * + * @param pkg The package name, e.g. {@code com.example.myapplication}. + * See {@link #getResourcePackageName}. + * @param type The type name, e.g. {@code string}. + * See {@link #getResourceTypeName}. + * @param name The entry name, e.g. {@code app_name}. + * See {@link #getResourceEntryName}. + * @param replacement The replacement. + */ + public void setReplacement(String pkg, String type, String name, Object replacement) { + int id = getIdentifier(name, type, pkg); + if (id == 0) + throw new NotFoundException(pkg + ":" + type + "/" + name); + setReplacement(id, replacement, this); + } + + /** + * Sets a replacement for an individual Android framework resource (in the {@code android} package). + * See {@link #setSystemWideReplacement(String, String, String, Object)}. + * + * @param id The ID of the resource which should be replaced. + * @param replacement The replacement. + */ + public static void setSystemWideReplacement(int id, Object replacement) { + setReplacement(id, replacement, null); + } + + /** + * Sets a replacement for an individual Android framework resource (in the {@code android} package). + * See {@link #setSystemWideReplacement(String, String, String, Object)}. + * + * @deprecated Use {@link #setSystemWideReplacement(String, String, String, Object)} instead. + * + * @param fullName The full resource name, e.g. {@code android:string/yes}. + * See {@link #getResourceName}. + * @param replacement The replacement. + */ + @Deprecated + public static void setSystemWideReplacement(String fullName, Object replacement) { + int id = getSystem().getIdentifier(fullName, null, null); + if (id == 0) + throw new NotFoundException(fullName); + setReplacement(id, replacement, null); + } + + /** + * Sets a replacement for an individual Android framework resource (in the {@code android} package). + * + *

Some resources are part of the Android framework and can be used in any app. They're + * accessible via {@link android.R android.R} and are not bound to a specific + * {@link android.content.res.Resources} instance. Such resources can be replaced in + * {@link IXposedHookZygoteInit#initZygote initZygote()} for all apps. As there is no + * {@link XResources} object easily available in that scope, this static method can be used + * to set resource replacements. All other details (e.g. how certain types can be replaced) are + * mentioned in {@link #setReplacement(String, String, String, Object)}. + * + * @param pkg The package name, should always be {@code android} here. + * See {@link #getResourcePackageName}. + * @param type The type name, e.g. {@code string}. + * See {@link #getResourceTypeName}. + * @param name The entry name, e.g. {@code yes}. + * See {@link #getResourceEntryName}. + * @param replacement The replacement. + */ + public static void setSystemWideReplacement(String pkg, String type, String name, Object replacement) { + int id = getSystem().getIdentifier(name, type, pkg); + if (id == 0) + throw new NotFoundException(pkg + ":" + type + "/" + name); + setReplacement(id, replacement, null); + } + + private static void setReplacement(int id, Object replacement, XResources res) { + String resDir = (res != null) ? res.mResDir : null; + if (id == 0) + throw new IllegalArgumentException("id 0 is not an allowed resource identifier"); + else if (resDir == null && id >= 0x7f000000) + throw new IllegalArgumentException("ids >= 0x7f000000 are app specific and cannot be set for the framework"); + + if (replacement instanceof Drawable) + throw new IllegalArgumentException("Drawable replacements are deprecated since Xposed 2.1. Use DrawableLoader instead."); + + // Cache that we have a replacement for this ID, false positives are accepted to save memory. + if (id < 0x7f000000) { + int cacheKey = (id & 0x00070000) >> 11 | (id & 0xf8) >> 3; + synchronized (sSystemReplacementsCache) { + sSystemReplacementsCache[cacheKey] |= 1 << (id & 7); + } + } else { + int cacheKey = (id & 0x00070000) >> 12 | (id & 0x78) >> 3; + synchronized (res.mReplacementsCache) { + res.mReplacementsCache[cacheKey] |= 1 << (id & 7); + } + } + + synchronized (sReplacements) { + HashMap inner = sReplacements.get(id); + if (inner == null) { + inner = new HashMap<>(); + sReplacements.put(id, inner); + } + inner.put(resDir, replacement); + } + } + + // ======================================================= + // RETURNING REPLACEMENTS + // ======================================================= + + private Object getReplacement(int id) { + if (id <= 0) + return null; + + // Check the cache whether it's worth looking for replacements + if (id < 0x7f000000) { + int cacheKey = (id & 0x00070000) >> 11 | (id & 0xf8) >> 3; + if ((sSystemReplacementsCache[cacheKey] & (1 << (id & 7))) == 0) + return null; + } else if (mResDir != null) { + int cacheKey = (id & 0x00070000) >> 12 | (id & 0x78) >> 3; + if ((mReplacementsCache[cacheKey] & (1 << (id & 7))) == 0) + return null; + } + + HashMap inner; + synchronized (sReplacements) { + inner = sReplacements.get(id); + } + + if (inner == null) + return null; + + synchronized (inner) { + Object result = inner.get(mResDir); + if (result != null || mResDir == null) + return result; + return inner.get(null); + } + } + + /** @hide */ + @Override + public XmlResourceParser getAnimation(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + + boolean loadedFromCache = isXmlCached(repRes, repId); + XmlResourceParser result = repRes.getAnimation(repId); + + if (!loadedFromCache) { + long parseState = (Build.VERSION.SDK_INT >= 21) + ? getLongField(result, "mParseState") + : getIntField(result, "mParseState"); + rewriteXmlReferencesNative(parseState, this, repRes); + } + + return result; + } + return super.getAnimation(id); + } + + /** @hide */ + @Override + public boolean getBoolean(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof Boolean) { + return (Boolean) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getBoolean(repId); + } + return super.getBoolean(id); + } + + /** @hide */ + @Override + public int getColor(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof Integer) { + return (Integer) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getColor(repId); + } + return super.getColor(id); + } + + /** @hide */ + @Override + public ColorStateList getColorStateList(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof ColorStateList) { + return (ColorStateList) replacement; + } else if (replacement instanceof Integer) { + int color = (Integer) replacement; + synchronized (sColorStateListCache) { + ColorStateList result = sColorStateListCache.get(color); + if (result == null) { + result = ColorStateList.valueOf(color); + sColorStateListCache.put(color, result); + } + return result; + } + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getColorStateList(repId); + } + return super.getColorStateList(id); + } + + /** @hide */ + @Override + public float getDimension(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof DimensionReplacement) { + return ((DimensionReplacement) replacement).getDimension(getDisplayMetrics()); + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getDimension(repId); + } + return super.getDimension(id); + } + + /** @hide */ + @Override + public int getDimensionPixelOffset(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof DimensionReplacement) { + return ((DimensionReplacement) replacement).getDimensionPixelOffset(getDisplayMetrics()); + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getDimensionPixelOffset(repId); + } + return super.getDimensionPixelOffset(id); + } + + /** @hide */ + @Override + public int getDimensionPixelSize(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof DimensionReplacement) { + return ((DimensionReplacement) replacement).getDimensionPixelSize(getDisplayMetrics()); + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getDimensionPixelSize(repId); + } + return super.getDimensionPixelSize(id); + } + + /** @hide */ + @Override + public Drawable getDrawable(int id) throws NotFoundException { + try { + if (incrementMethodDepth("getDrawable") == 1) { + Object replacement = getReplacement(id); + if (replacement instanceof DrawableLoader) { + try { + Drawable result = ((DrawableLoader) replacement).newDrawable(this, id); + 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(); + return repRes.getDrawable(repId); + } + } + return super.getDrawable(id); + } finally { + decrementMethodDepth("getDrawable"); + } + } + + /** @hide */ + @Override + public Drawable getDrawable(int id, Theme theme) throws NotFoundException { + try { + if (incrementMethodDepth("getDrawable") == 1) { + Object replacement = getReplacement(id); + if (replacement instanceof DrawableLoader) { + try { + Drawable result = ((DrawableLoader) replacement).newDrawable(this, id); + 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(); + return repRes.getDrawable(repId); + } + } + return super.getDrawable(id, theme); + } finally { + decrementMethodDepth("getDrawable"); + } + } + + /** @hide */ + @Override + public Drawable getDrawable(int id, Theme theme, boolean supportComposedIcons) throws NotFoundException { + try { + if (incrementMethodDepth("getDrawable") == 1) { + Object replacement = getReplacement(id); + if (replacement instanceof DrawableLoader) { + try { + Drawable result = ((DrawableLoader) replacement).newDrawable(this, id); + 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(); + return repRes.getDrawable(repId); + } + } + return super.getDrawable(id, theme, supportComposedIcons); + } finally { + decrementMethodDepth("getDrawable"); + } + } + + /** @hide */ + @Override + public Drawable getDrawableForDensity(int id, int density) throws NotFoundException { + try { + if (incrementMethodDepth("getDrawableForDensity") == 1) { + Object replacement = getReplacement(id); + if (replacement instanceof DrawableLoader) { + try { + Drawable result = ((DrawableLoader) replacement).newDrawableForDensity(this, id, density); + 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(); + return repRes.getDrawableForDensity(repId, density); + } + } + return super.getDrawableForDensity(id, density); + } finally { + decrementMethodDepth("getDrawableForDensity"); + } + } + + /** @hide */ + @Override + public Drawable getDrawableForDensity(int id, int density, Theme theme) throws NotFoundException { + try { + if (incrementMethodDepth("getDrawableForDensity") == 1) { + Object replacement = getReplacement(id); + if (replacement instanceof DrawableLoader) { + try { + Drawable result = ((DrawableLoader) replacement).newDrawableForDensity(this, id, density); + 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(); + return repRes.getDrawableForDensity(repId, density); + } + } + return super.getDrawableForDensity(id, density, theme); + } finally { + decrementMethodDepth("getDrawableForDensity"); + } + } + + /** @hide */ + @Override + public Drawable getDrawableForDensity(int id, int density, Theme theme, boolean supportComposedIcons) throws NotFoundException { + try { + if (incrementMethodDepth("getDrawableForDensity") == 1) { + Object replacement = getReplacement(id); + if (replacement instanceof DrawableLoader) { + try { + Drawable result = ((DrawableLoader) replacement).newDrawableForDensity(this, id, density); + 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(); + return repRes.getDrawableForDensity(repId, density); + } + } + return super.getDrawableForDensity(id, density, theme, supportComposedIcons); + } finally { + decrementMethodDepth("getDrawableForDensity"); + } + } + + /** @hide */ + @Override + public float getFraction(int id, int base, int pbase) { + Object replacement = getReplacement(id); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getFraction(repId, base, pbase); + } + return super.getFraction(id, base, pbase); + } + + /** @hide */ + @Override + public int getInteger(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof Integer) { + return (Integer) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getInteger(repId); + } + return super.getInteger(id); + } + + /** @hide */ + @Override + public int[] getIntArray(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof int[]) { + return (int[]) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getIntArray(repId); + } + return super.getIntArray(id); + } + + /** @hide */ + @Override + public XmlResourceParser getLayout(int id) throws NotFoundException { + XmlResourceParser result; + Object replacement = getReplacement(id); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + + boolean loadedFromCache = isXmlCached(repRes, repId); + result = repRes.getLayout(repId); + + if (!loadedFromCache) { + long parseState = (Build.VERSION.SDK_INT >= 21) + ? getLongField(result, "mParseState") + : getIntField(result, "mParseState"); + rewriteXmlReferencesNative(parseState, this, repRes); + } + } else { + result = super.getLayout(id); + } + + // Check whether this layout is hooked + HashMap> inner; + synchronized (sLayoutCallbacks) { + inner = sLayoutCallbacks.get(id); + } + if (inner != null) { + CopyOnWriteSortedSet callbacks; + synchronized (inner) { + callbacks = inner.get(mResDir); + if (callbacks == null && mResDir != null) + callbacks = inner.get(null); + } + if (callbacks != null) { + String variant = "layout"; + TypedValue value = (TypedValue) getObjectField(this, "mTmpValue"); + getValue(id, value, true); + if (value.type == TypedValue.TYPE_STRING) { + String[] components = value.string.toString().split("/", 3); + if (components.length == 3) + variant = components[1]; + else + XposedBridge.log("Unexpected resource path \"" + value.string.toString() + + "\" for resource id 0x" + Integer.toHexString(id)); + } else { + XposedBridge.log(new NotFoundException("Could not find file name for resource id 0x") + Integer.toHexString(id)); + } + + synchronized (sXmlInstanceDetails) { + synchronized (sResourceNames) { + HashMap resNamesInner = sResourceNames.get(id); + if (resNamesInner != null) { + synchronized (resNamesInner) { + XMLInstanceDetails details = new XMLInstanceDetails(resNamesInner.get(mResDir), variant, callbacks); + sXmlInstanceDetails.put(result, details); + + // if we were called inside LayoutInflater.parseInclude, store the details for it + MethodHookParam top = sIncludedLayouts.get().peek(); + if (top != null) + top.setObjectExtra(EXTRA_XML_INSTANCE_DETAILS, details); + } + } + } + } + } + } + + return result; + } + + /** @hide */ + @Override + public Movie getMovie(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getMovie(repId); + } + return super.getMovie(id); + } + + /** @hide */ + @Override + public CharSequence getQuantityText(int id, int quantity) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getQuantityText(repId, quantity); + } + return super.getQuantityText(id, quantity); + } + // these are handled by getQuantityText: + // public String getQuantityString(int id, int quantity); + // public String getQuantityString(int id, int quantity, Object... formatArgs); + + /** @hide */ + @Override + public String[] getStringArray(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof String[]) { + return (String[]) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getStringArray(repId); + } + return super.getStringArray(id); + } + + /** @hide */ + @Override + public CharSequence getText(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof CharSequence) { + return (CharSequence) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getText(repId); + } + return super.getText(id); + } + // these are handled by getText: + // public String getString(int id); + // public String getString(int id, Object... formatArgs); + + /** @hide */ + @Override + public CharSequence getText(int id, CharSequence def) { + Object replacement = getReplacement(id); + if (replacement instanceof CharSequence) { + return (CharSequence) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getText(repId, def); + } + return super.getText(id, def); + } + + /** @hide */ + @Override + public CharSequence[] getTextArray(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof CharSequence[]) { + return (CharSequence[]) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getTextArray(repId); + } + return super.getTextArray(id); + } + + /** @hide */ + @Override + public XmlResourceParser getXml(int id) throws NotFoundException { + Object replacement = getReplacement(id); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + + boolean loadedFromCache = isXmlCached(repRes, repId); + XmlResourceParser result = repRes.getXml(repId); + + if (!loadedFromCache) { + long parseState = (Build.VERSION.SDK_INT >= 21) + ? getLongField(result, "mParseState") + : getIntField(result, "mParseState"); + rewriteXmlReferencesNative(parseState, this, repRes); + } + + return result; + } + return super.getXml(id); + } + + private static boolean isXmlCached(Resources res, int id) { + int[] mCachedXmlBlockIds = (int[]) getObjectField(getObjectField(res, "mResourcesImpl"), "mCachedXmlBlockCookies"); + synchronized (mCachedXmlBlockIds) { + for (int cachedId : mCachedXmlBlockIds) { + if (cachedId == id) + return true; + } + } + return false; + } + + private static native void rewriteXmlReferencesNative(long parserPtr, XResources origRes, Resources repRes); + + /** + * Used to replace reference IDs in XMLs. + * + * When resource requests are forwarded to modules, the may include references to resources with the same + * name as in the original resources, but the IDs generated by aapt will be different. rewriteXmlReferencesNative + * walks through all references and calls this function to find out the original ID, which it then writes to + * the compiled XML file in the memory. + */ + private static int translateResId(int id, XResources origRes, Resources repRes) { + try { + String entryName = repRes.getResourceEntryName(id); + String entryType = repRes.getResourceTypeName(id); + String origPackage = origRes.mPackageName; + int origResId = 0; + try { + // look for a resource with the same name and type in the original package + origResId = origRes.getIdentifier(entryName, entryType, origPackage); + } catch (NotFoundException ignored) {} + + boolean repResDefined = false; + try { + final TypedValue tmpValue = new TypedValue(); + repRes.getValue(id, tmpValue, false); + // if a resource has not been defined (i.e. only a resource ID has been created), it will equal "false" + // this means a boolean "false" value is not detected of it is directly referenced in an XML file + repResDefined = !(tmpValue.type == TypedValue.TYPE_INT_BOOLEAN && tmpValue.data == 0); + } catch (NotFoundException ignored) {} + + if (!repResDefined && origResId == 0 && !entryType.equals("id")) { + XposedBridge.log(entryType + "/" + entryName + " is neither defined in module nor in original resources"); + return 0; + } + + // exists only in module, so create a fake resource id + if (origResId == 0) + origResId = getFakeResId(repRes, id); + + // IDs will never be loaded, no need to set a replacement + if (repResDefined && !entryType.equals("id")) + origRes.setReplacement(origResId, new XResForwarder(repRes, id)); + + return origResId; + } catch (Exception e) { + XposedBridge.log(e); + return id; + } + } + + /** + * Generates a fake resource ID. + * + *

The parameter is just hashed, it doesn't have a deeper meaning. However, it's recommended + * to use values with a low risk for conflicts, such as a full resource name. Calling this + * method multiple times will return the same ID. + * + * @param resName A used for hashing, see above. + * @return The fake resource ID. + */ + public static int getFakeResId(String resName) { + return 0x7e000000 | (resName.hashCode() & 0x00ffffff); + } + + /** + * Generates a fake resource ID. + * + *

This variant uses the result of {@link #getResourceName} to create the hash that the ID is + * based on. The given resource doesn't need to match the {@link XResources} instance for which + * the fake resource ID is going to be used. + * + * @param res The {@link android.content.res.Resources} object to be used for hashing. + * @param id The resource ID to be used for hashing. + * @return The fake resource ID. + */ + public static int getFakeResId(Resources res, int id) { + return getFakeResId(res.getResourceName(id)); + } + + /** + * Makes any individual resource available from another {@link android.content.res.Resources} + * instance available in this {@link XResources} instance. + * + *

This method combines calls to {@link #getFakeResId(Resources, int)} and + * {@link #setReplacement(int, Object)} to generate a fake resource ID and set up a replacement + * for it which forwards to the given resource. + * + *

The returned ID can only be used to retrieve the resource, it won't work for methods like + * {@link #getResourceName} etc. + * + * @param res The target {@link android.content.res.Resources} instance. + * @param id The target resource ID. + * @return The fake resource ID (see above). + */ + public int addResource(Resources res, int id) { + int fakeId = getFakeResId(res, id); + synchronized (sReplacements) { + if (sReplacements.indexOfKey(fakeId) < 0) + setReplacement(fakeId, new XResForwarder(res, id)); + } + return fakeId; + } + + /** + * Similar to {@link #translateResId}, but used to determine the original ID of attribute names. + */ + private static int translateAttrId(String attrName, XResources origRes) { + String origPackage = origRes.mPackageName; + int origAttrId = 0; + try { + origAttrId = origRes.getIdentifier(attrName, "attr", origPackage); + } catch (NotFoundException e) { + XposedBridge.log("Attribute " + attrName + " not found in original resources"); + } + return origAttrId; + } + + // ======================================================= + // XTypedArray class + // ======================================================= + /** + * {@link android.content.res.TypedArray} replacement that replaces values on-the-fly. + * Mainly used when inflating layouts. + * @hide + */ + public static class XTypedArray extends XTypedArraySuperClass { + + public XTypedArray(Resources resources) { + super(resources); + } + + /** Dummy, will never be called (objects are transferred to this class only). */ +// private XTypedArray() { +// super(null, null, null, 0); +// throw new UnsupportedOperationException(); +// } + + @Override + public boolean getBoolean(int index, boolean defValue) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof Boolean) { + return (Boolean) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getBoolean(repId); + } + return super.getBoolean(index, defValue); + } + + @Override + public int getColor(int index, int defValue) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof Integer) { + return (Integer) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getColor(repId); + } + return super.getColor(index, defValue); + } + + @Override + public ColorStateList getColorStateList(int index) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof ColorStateList) { + return (ColorStateList) replacement; + } else if (replacement instanceof Integer) { + int color = (Integer) replacement; + synchronized (sColorStateListCache) { + ColorStateList result = sColorStateListCache.get(color); + if (result == null) { + result = ColorStateList.valueOf(color); + sColorStateListCache.put(color, result); + } + return result; + } + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getColorStateList(repId); + } + return super.getColorStateList(index); + } + + @Override + public float getDimension(int index, float defValue) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getDimension(repId); + } + return super.getDimension(index, defValue); + } + + @Override + public int getDimensionPixelOffset(int index, int defValue) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getDimensionPixelOffset(repId); + } + return super.getDimensionPixelOffset(index, defValue); + } + + @Override + public int getDimensionPixelSize(int index, int defValue) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getDimensionPixelSize(repId); + } + return super.getDimensionPixelSize(index, defValue); + } + + @Override + public Drawable getDrawable(int index) { + final int resId = getResourceId(index, 0); + XResources xres = (XResources) getResources(); + Object replacement = xres.getReplacement(resId); + if (replacement instanceof DrawableLoader) { + try { + Drawable result = ((DrawableLoader) replacement).newDrawable(xres, resId); + 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(); + return repRes.getDrawable(repId); + } + return super.getDrawable(index); + } + + @Override + public float getFloat(int index, float defValue) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + // dimensions seem to be the only way to define floats by references + return repRes.getDimension(repId); + } + return super.getFloat(index, defValue); + } + + @Override + public float getFraction(int index, int base, int pbase, float defValue) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + // dimensions seem to be the only way to define floats by references + return repRes.getFraction(repId, base, pbase); + } + return super.getFraction(index, base, pbase, defValue); + } + + @Override + public int getInt(int index, int defValue) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof Integer) { + return (Integer) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getInteger(repId); + } + return super.getInt(index, defValue); + } + + @Override + public int getInteger(int index, int defValue) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof Integer) { + return (Integer) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getInteger(repId); + } + return super.getInteger(index, defValue); + } + + @Override + public int getLayoutDimension(int index, int defValue) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getDimensionPixelSize(repId); + } + return super.getLayoutDimension(index, defValue); + } + + @Override + public int getLayoutDimension(int index, String name) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getDimensionPixelSize(repId); + } + return super.getLayoutDimension(index, name); + } + + @Override + public String getString(int index) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof CharSequence) { + return replacement.toString(); + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getString(repId); + } + return super.getString(index); + } + + @Override + public CharSequence getText(int index) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof CharSequence) { + return (CharSequence) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getText(repId); + } + return super.getText(index); + } + + @Override + public CharSequence[] getTextArray(int index) { + Object replacement = ((XResources) getResources()).getReplacement(getResourceId(index, 0)); + if (replacement instanceof CharSequence[]) { + return (CharSequence[]) replacement; + } else if (replacement instanceof XResForwarder) { + Resources repRes = ((XResForwarder) replacement).getResources(); + int repId = ((XResForwarder) replacement).getId(); + return repRes.getTextArray(repId); + } + return super.getTextArray(index); + } + } + + + // ======================================================= + // DrawableLoader class + // ======================================================= + /** + * Callback for drawable replacements. Instances of this class can passed to + * {@link #setReplacement(String, String, String, Object)} and its variants. + * + *

Make sure to always return new {@link Drawable} instances, as drawables + * usually can't be reused. + */ + @SuppressWarnings("UnusedParameters") + public static abstract class DrawableLoader { + /** + * Constructor. + */ + public DrawableLoader() {} + + /** + * Called when the hooked drawable resource has been requested. + * + * @param res The {@link XResources} object in which the hooked drawable resides. + * @param id The resource ID which has been requested. + * @return The {@link Drawable} which should be used as replacement. {@code null} is ignored. + * @throws Throwable Everything the callback throws is caught and logged. + */ + public abstract Drawable newDrawable(XResources res, int id) throws Throwable; + + /** + * Like {@link #newDrawable}, but called for {@link #getDrawableForDensity}. The default + * implementation is to use the result of {@link #newDrawable}. + * + * @param res The {@link XResources} object in which the hooked drawable resides. + * @param id The resource ID which has been requested. + * @param density The desired screen density indicated by the resource as found in + * {@link DisplayMetrics}. + * @return The {@link Drawable} which should be used as replacement. {@code null} is ignored. + * @throws Throwable Everything the callback throws is caught and logged. + */ + public Drawable newDrawableForDensity(XResources res, int id, int density) throws Throwable { + return newDrawable(res, id); + } + } + + + // ======================================================= + // DimensionReplacement class + // ======================================================= + /** + * Callback for dimension replacements. Instances of this class can passed to + * {@link #setReplacement(String, String, String, Object)} and its variants. + */ + public static class DimensionReplacement { + private final float mValue; + private final int mUnit; + + /** + * Creates an instance that can be used for {@link #setReplacement(String, String, String, Object)} + * to replace a dimension resource. + * + * @param value The value of the replacement, in the unit specified with the next parameter. + * @param unit One of the {@code COMPLEX_UNIT_*} constants in {@link TypedValue}. + */ + public DimensionReplacement(float value, int unit) { + mValue = value; + mUnit = unit; + } + + /** Called by {@link android.content.res.Resources#getDimension}. */ + public float getDimension(DisplayMetrics metrics) { + return TypedValue.applyDimension(mUnit, mValue, metrics); + } + + /** Called by {@link android.content.res.Resources#getDimensionPixelOffset}. */ + public int getDimensionPixelOffset(DisplayMetrics metrics) { + return (int) TypedValue.applyDimension(mUnit, mValue, metrics); + } + + /** Called by {@link android.content.res.Resources#getDimensionPixelSize}. */ + public int getDimensionPixelSize(DisplayMetrics metrics) { + final float f = TypedValue.applyDimension(mUnit, mValue, metrics); + final int res = (int)(f+0.5f); + if (res != 0) return res; + if (mValue == 0) return 0; + if (mValue > 0) return 1; + return -1; + } + } + + // ======================================================= + // INFLATING LAYOUTS + // ======================================================= + + private class XMLInstanceDetails { + public final ResourceNames resNames; + public final String variant; + public final CopyOnWriteSortedSet callbacks; + public final XResources res = XResources.this; + + private XMLInstanceDetails(ResourceNames resNames, String variant, CopyOnWriteSortedSet callbacks) { + this.resNames = resNames; + this.variant = variant; + this.callbacks = callbacks; + } + } + + /** + * Hook the inflation of a layout. + * + * @param id The ID of the resource which should be replaced. + * @param callback The callback to be executed when the layout has been inflated. + * @return An object which can be used to remove the callback again. + */ + public XC_LayoutInflated.Unhook hookLayout(int id, XC_LayoutInflated callback) { + return hookLayoutInternal(mResDir, id, getResourceNames(id), callback); + } + + /** + * Hook the inflation of a layout. + * + * @deprecated Use {@link #hookLayout(String, String, String, XC_LayoutInflated)} instead. + * + * @param fullName The full resource name, e.g. {@code com.android.systemui:layout/statusbar}. + * See {@link #getResourceName}. + * @param callback The callback to be executed when the layout has been inflated. + * @return An object which can be used to remove the callback again. + */ + @Deprecated + public XC_LayoutInflated.Unhook hookLayout(String fullName, XC_LayoutInflated callback) { + int id = getIdentifier(fullName, null, null); + if (id == 0) + throw new NotFoundException(fullName); + return hookLayout(id, callback); + } + + /** + * Hook the inflation of a layout. + * + * @param pkg The package name, e.g. {@code com.android.systemui}. + * See {@link #getResourcePackageName}. + * @param type The type name, e.g. {@code layout}. + * See {@link #getResourceTypeName}. + * @param name The entry name, e.g. {@code statusbar}. + * See {@link #getResourceEntryName}. + * @param callback The callback to be executed when the layout has been inflated. + * @return An object which can be used to remove the callback again. + */ + public XC_LayoutInflated.Unhook hookLayout(String pkg, String type, String name, XC_LayoutInflated callback) { + int id = getIdentifier(name, type, pkg); + if (id == 0) + throw new NotFoundException(pkg + ":" + type + "/" + name); + return hookLayout(id, callback); + } + + /** + * Hook the inflation of an Android framework layout (in the {@code android} package). + * See {@link #hookSystemWideLayout(String, String, String, XC_LayoutInflated)}. + * + * @param id The ID of the resource which should be replaced. + * @param callback The callback to be executed when the layout has been inflated. + * @return An object which can be used to remove the callback again. + */ + public static XC_LayoutInflated.Unhook hookSystemWideLayout(int id, XC_LayoutInflated callback) { + if (id >= 0x7f000000) + throw new IllegalArgumentException("ids >= 0x7f000000 are app specific and cannot be set for the framework"); + return hookLayoutInternal(null, id, getSystemResourceNames(id), callback); + } + + /** + * Hook the inflation of an Android framework layout (in the {@code android} package). + * See {@link #hookSystemWideLayout(String, String, String, XC_LayoutInflated)}. + * + * @deprecated Use {@link #hookSystemWideLayout(String, String, String, XC_LayoutInflated)} instead. + * + * @param fullName The full resource name, e.g. {@code android:layout/simple_list_item_1}. + * See {@link #getResourceName}. + * @param callback The callback to be executed when the layout has been inflated. + * @return An object which can be used to remove the callback again. + */ + @Deprecated + public static XC_LayoutInflated.Unhook hookSystemWideLayout(String fullName, XC_LayoutInflated callback) { + int id = getSystem().getIdentifier(fullName, null, null); + if (id == 0) + throw new NotFoundException(fullName); + return hookSystemWideLayout(id, callback); + } + + /** + * Hook the inflation of an Android framework layout (in the {@code android} package). + * + *

Some layouts are part of the Android framework and can be used in any app. They're + * accessible via {@link android.R.layout android.R.layout} and are not bound to a specific + * {@link android.content.res.Resources} instance. Such resources can be replaced in + * {@link IXposedHookZygoteInit#initZygote initZygote()} for all apps. As there is no + * {@link XResources} object easily available in that scope, this static method can be used + * to hook layouts. + * + * @param pkg The package name, e.g. {@code android}. + * See {@link #getResourcePackageName}. + * @param type The type name, e.g. {@code layout}. + * See {@link #getResourceTypeName}. + * @param name The entry name, e.g. {@code simple_list_item_1}. + * See {@link #getResourceEntryName}. + * @param callback The callback to be executed when the layout has been inflated. + * @return An object which can be used to remove the callback again. + */ + public static XC_LayoutInflated.Unhook hookSystemWideLayout(String pkg, String type, String name, XC_LayoutInflated callback) { + int id = getSystem().getIdentifier(name, type, pkg); + if (id == 0) + throw new NotFoundException(pkg + ":" + type + "/" + name); + return hookSystemWideLayout(id, callback); + } + + private static XC_LayoutInflated.Unhook hookLayoutInternal(String resDir, int id, ResourceNames resNames, XC_LayoutInflated callback) { + if (id == 0) + throw new IllegalArgumentException("id 0 is not an allowed resource identifier"); + + HashMap> inner; + synchronized (sLayoutCallbacks) { + inner = sLayoutCallbacks.get(id); + if (inner == null) { + inner = new HashMap<>(); + sLayoutCallbacks.put(id, inner); + } + } + + CopyOnWriteSortedSet callbacks; + synchronized (inner) { + callbacks = inner.get(resDir); + if (callbacks == null) { + callbacks = new CopyOnWriteSortedSet<>(); + inner.put(resDir, callbacks); + } + } + + callbacks.add(callback); + + putResourceNames(resDir, resNames); + + return callback.new Unhook(resDir, id); + } + + /** @hide */ + public static void unhookLayout(String resDir, int id, XC_LayoutInflated callback) { + HashMap> inner; + synchronized (sLayoutCallbacks) { + inner = sLayoutCallbacks.get(id); + if (inner == null) + return; + } + + CopyOnWriteSortedSet callbacks; + synchronized (inner) { + callbacks = inner.get(resDir); + if (callbacks == null) + return; + } + + callbacks.remove(callback); + } +} diff --git a/edxp-core/src/main/java/android/content/res/package-info.java b/edxp-core/src/main/java/android/content/res/package-info.java new file mode 100644 index 00000000..4016398e --- /dev/null +++ b/edxp-core/src/main/java/android/content/res/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains classes that are required for replacing resources. + */ +package android.content.res; diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/common/KeepAll.java b/edxp-core/src/main/java/com/elderdrivers/riru/common/KeepAll.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/common/KeepAll.java rename to edxp-core/src/main/java/com/elderdrivers/riru/common/KeepAll.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/common/KeepMembers.java b/edxp-core/src/main/java/com/elderdrivers/riru/common/KeepMembers.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/common/KeepMembers.java rename to edxp-core/src/main/java/com/elderdrivers/riru/common/KeepMembers.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/HandleBindApp.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/HandleBindApp.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/HandleBindApp.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/HandleBindApp.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/LoadedApkCstr.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/LoadedApkCstr.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/LoadedApkCstr.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/LoadedApkCstr.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/LoadedApkGetCL.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/LoadedApkGetCL.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/LoadedApkGetCL.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/LoadedApkGetCL.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/StartBootstrapServices.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/StartBootstrapServices.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/StartBootstrapServices.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/StartBootstrapServices.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/SystemMain.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/SystemMain.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/SystemMain.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/impl/SystemMain.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/HandleBindAppHooker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/HandleBindAppHooker.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/HandleBindAppHooker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/HandleBindAppHooker.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/LoadedApkConstructorHooker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/LoadedApkConstructorHooker.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/LoadedApkConstructorHooker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/LoadedApkConstructorHooker.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/StartBootstrapServicesHooker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/StartBootstrapServicesHooker.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/StartBootstrapServicesHooker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/StartBootstrapServicesHooker.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/StartBootstrapServicesHooker11.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/StartBootstrapServicesHooker11.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/StartBootstrapServicesHooker11.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/StartBootstrapServicesHooker11.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/SystemMainHooker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/SystemMainHooker.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/SystemMainHooker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/_hooker/yahfa/SystemMainHooker.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/art/ClassLinker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/art/ClassLinker.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/art/ClassLinker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/art/ClassLinker.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/art/Heap.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/art/Heap.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/art/Heap.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/art/Heap.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/config/BaseEdxpConfig.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/BaseEdxpConfig.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/config/BaseEdxpConfig.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/BaseEdxpConfig.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/config/BaseHookProvider.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/BaseHookProvider.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/config/BaseHookProvider.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/BaseHookProvider.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/config/ConfigManager.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/ConfigManager.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/config/ConfigManager.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/ConfigManager.java diff --git a/edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/EdXpConfigGlobal.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/EdXpConfigGlobal.java new file mode 100644 index 00000000..6cb93ac5 --- /dev/null +++ b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/EdXpConfigGlobal.java @@ -0,0 +1,23 @@ +package com.elderdrivers.riru.edxp.config; + +import com.elderdrivers.riru.edxp.hook.HookProvider; + +public class EdXpConfigGlobal { + + public static volatile EdxpConfig sConfig; + public static volatile HookProvider sHookProvider; + + public static EdxpConfig getConfig() { + if (sConfig == null) { + throw new IllegalArgumentException("sConfig should not be null."); + } + return sConfig; + } + + public static HookProvider getHookProvider() { + if (sHookProvider == null) { + throw new IllegalArgumentException("sHookProvider should not be null."); + } + return sHookProvider; + } +} diff --git a/edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/EdxpConfig.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/EdxpConfig.java new file mode 100644 index 00000000..c291563a --- /dev/null +++ b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/config/EdxpConfig.java @@ -0,0 +1,20 @@ +package com.elderdrivers.riru.edxp.config; + +public interface EdxpConfig { + + String getConfigPath(String suffix); + + String getDataPathPrefix(); + + String getInstallerPackageName(); + + String getLibSandHookName(); + + boolean isNoModuleLogEnabled(); + + boolean isResourcesHookEnabled(); + + boolean isBlackWhiteListMode(); + + String getModulesList(); +} diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/BaseEdxpImpl.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/BaseEdxpImpl.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/BaseEdxpImpl.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/BaseEdxpImpl.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/EdxpImpl.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/EdxpImpl.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/EdxpImpl.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/EdxpImpl.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/Main.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/Main.java similarity index 71% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/Main.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/Main.java index c4ac4727..a06ceac3 100644 --- a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/Main.java +++ b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/Main.java @@ -3,16 +3,13 @@ package com.elderdrivers.riru.edxp.core; import android.annotation.SuppressLint; import com.elderdrivers.riru.common.KeepAll; +import com.elderdrivers.riru.edxp.config.ConfigManager; import com.elderdrivers.riru.edxp.util.Utils; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.Iterator; -import java.util.ServiceLoader; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.concurrent.atomic.AtomicReference; -import static com.elderdrivers.riru.edxp.core.EdxpImpl.NONE; - @SuppressLint("DefaultLocale") public class Main implements KeepAll { private static final AtomicReference edxpImplRef = new AtomicReference<>(null); @@ -73,16 +70,31 @@ public class Main implements KeepAll { } private static void loadEdxpImpls() { - // We don't have Manifest now, so we have to load manually. + String file_name = ConfigManager.getConfigPath("variant"); + int variant = EdxpImpl.NONE; try { - Class.forName("com.elderdrivers.riru.edxp.sandhook.core.SandHookEdxpImpl"); - }catch(Throwable ignored) { - Utils.logD("not using sandhook"); + String f = new String(Files.readAllBytes(Paths.get(file_name))); + variant = Integer.parseInt(f); + } catch (Exception ignored) { + } + + Utils.logD("Loading variant " + variant); + try { - Class.forName("com.elderdrivers.riru.edxp.yahfa.core.YahfaEdxpImpl"); - }catch(Throwable ignored) { - Utils.logD("not using yahfa"); + switch (variant) { + case EdxpImpl.YAHFA: + Class.forName("com.elderdrivers.riru.edxp.yahfa.core.YahfaEdxpImpl"); + break; + case EdxpImpl.SANDHOOK: + Class.forName("com.elderdrivers.riru.edxp.sandhook.core.SandHookEdxpImpl"); + break; + default: + Utils.logE("Unsupported variant" + variant); + + } + } catch (ClassNotFoundException e) { + Utils.logE("loadEdxpImpls: Class not found", e); } } } diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/Proxy.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/Proxy.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/Proxy.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/Proxy.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/ResourcesHook.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/ResourcesHook.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/ResourcesHook.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/ResourcesHook.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/Yahfa.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/Yahfa.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/Yahfa.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/Yahfa.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/yahfa/HookMain.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/yahfa/HookMain.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/core/yahfa/HookMain.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/core/yahfa/HookMain.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/deopt/InlinedMethodCallers.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/deopt/InlinedMethodCallers.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/deopt/InlinedMethodCallers.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/deopt/InlinedMethodCallers.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/deopt/PrebuiltMethodsDeopter.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/deopt/PrebuiltMethodsDeopter.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/deopt/PrebuiltMethodsDeopter.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/deopt/PrebuiltMethodsDeopter.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/AppBootstrapHookInfo.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/AppBootstrapHookInfo.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/AppBootstrapHookInfo.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/AppBootstrapHookInfo.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/SysBootstrapHookInfo.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/SysBootstrapHookInfo.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/SysBootstrapHookInfo.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/SysBootstrapHookInfo.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/SysInnerHookInfo.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/SysInnerHookInfo.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/SysInnerHookInfo.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/entry/yahfa/SysInnerHookInfo.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/framework/Zygote.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/framework/Zygote.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/framework/Zygote.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/framework/Zygote.java diff --git a/edxp-core/src/main/java/com/elderdrivers/riru/edxp/hook/HookProvider.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/hook/HookProvider.java new file mode 100644 index 00000000..929a9de8 --- /dev/null +++ b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/hook/HookProvider.java @@ -0,0 +1,31 @@ +package com.elderdrivers.riru.edxp.hook; + +import java.lang.reflect.Member; + +import de.robv.android.xposed.XposedBridge; + +public interface HookProvider { + + void hookMethod(Member method, XposedBridge.AdditionalHookInfo additionalInfo); + + void unhookMethod(Member method); + + Object invokeOriginalMethod(Member method, long methodId, Object thisObject, Object[] args) throws Throwable; + + Member findMethodNative(Member hookMethod); + + void deoptMethods(String packageName, ClassLoader classLoader); + + long getMethodId(Member member); + + Object findMethodNative(Class clazz, String methodName, String methodSig); + + void deoptMethodNative(Object method); + + boolean initXResourcesNative(); + + boolean removeFinalFlagNative(Class clazz); + + boolean methodHooked(Member target); + +} diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/hooker/SliceProviderFix.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/hooker/SliceProviderFix.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/hooker/SliceProviderFix.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/hooker/SliceProviderFix.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/hooker/XposedInstallerHooker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/hooker/XposedInstallerHooker.java similarity index 99% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/hooker/XposedInstallerHooker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/hooker/XposedInstallerHooker.java index ddce5f6c..6e24572f 100644 --- a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/hooker/XposedInstallerHooker.java +++ b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/hooker/XposedInstallerHooker.java @@ -10,7 +10,7 @@ import android.view.ViewGroup; import com.elderdrivers.riru.edxp.config.ConfigManager; import com.elderdrivers.riru.edxp.config.EdXpConfigGlobal; -import com.elderdrivers.riru.edxp.common.BuildConfig; +import com.elderdrivers.riru.edxp.BuildConfig; import com.elderdrivers.riru.edxp.core.EdxpImpl; import com.elderdrivers.riru.edxp.core.Main; import com.elderdrivers.riru.edxp.util.Utils; @@ -184,7 +184,7 @@ public class XposedInstallerHooker { Object method = XposedHelpers.findMethodExact(clazz, methodName, params); EdXpConfigGlobal.getHookProvider().deoptMethodNative(method); - } catch (Exception e) { + } catch (Throwable e) { Utils.logE("Error when deoptimizing " + className + ":" + methodName, e); } diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/proxy/BaseProxy.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/proxy/BaseProxy.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/proxy/BaseProxy.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/proxy/BaseProxy.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/proxy/BaseRouter.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/proxy/BaseRouter.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/proxy/BaseRouter.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/proxy/BaseRouter.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/proxy/NormalProxy.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/proxy/NormalProxy.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/proxy/NormalProxy.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/proxy/NormalProxy.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/proxy/Router.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/proxy/Router.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/proxy/Router.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/proxy/Router.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/config/SandHookEdxpConfig.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/config/SandHookEdxpConfig.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/config/SandHookEdxpConfig.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/config/SandHookEdxpConfig.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/config/SandHookProvider.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/config/SandHookProvider.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/config/SandHookProvider.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/config/SandHookProvider.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/core/SandHookEdxpImpl.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/core/SandHookEdxpImpl.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/core/SandHookEdxpImpl.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/core/SandHookEdxpImpl.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/core/SandHookRouter.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/core/SandHookRouter.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/core/SandHookRouter.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/core/SandHookRouter.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/AppBootstrapHookInfo.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/AppBootstrapHookInfo.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/AppBootstrapHookInfo.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/AppBootstrapHookInfo.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/SysBootstrapHookInfo.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/SysBootstrapHookInfo.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/SysBootstrapHookInfo.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/SysBootstrapHookInfo.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/SysInnerHookInfo.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/SysInnerHookInfo.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/SysInnerHookInfo.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/entry/SysInnerHookInfo.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/HandleBindAppHooker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/HandleBindAppHooker.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/HandleBindAppHooker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/HandleBindAppHooker.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/LoadedApkConstructorHooker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/LoadedApkConstructorHooker.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/LoadedApkConstructorHooker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/LoadedApkConstructorHooker.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/StartBootstrapServicesHooker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/StartBootstrapServicesHooker.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/StartBootstrapServicesHooker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/StartBootstrapServicesHooker.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/StartBootstrapServicesHooker11.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/StartBootstrapServicesHooker11.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/StartBootstrapServicesHooker11.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/StartBootstrapServicesHooker11.java diff --git a/edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/SystemMainHooker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/SystemMainHooker.java similarity index 100% rename from edxp-sandhook/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/SystemMainHooker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/sandhook/hooker/SystemMainHooker.java diff --git a/edxp-service/src/main/java/com/elderdrivers/riru/edxp/service/PackageReceiver.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/service/PackageReceiver.java similarity index 100% rename from edxp-service/src/main/java/com/elderdrivers/riru/edxp/service/PackageReceiver.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/service/PackageReceiver.java diff --git a/edxp-service/src/main/java/com/elderdrivers/riru/edxp/service/ServiceProxy.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/service/ServiceProxy.java similarity index 100% rename from edxp-service/src/main/java/com/elderdrivers/riru/edxp/service/ServiceProxy.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/service/ServiceProxy.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/ClassLoaderUtils.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/ClassLoaderUtils.java similarity index 98% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/ClassLoaderUtils.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/ClassLoaderUtils.java index 2af555e8..7d385e07 100644 --- a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/ClassLoaderUtils.java +++ b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/ClassLoaderUtils.java @@ -3,7 +3,7 @@ package com.elderdrivers.riru.edxp.util; import android.os.Build; import android.util.ArrayMap; -import com.elderdrivers.riru.edxp.common.BuildConfig; +import com.elderdrivers.riru.edxp.BuildConfig; import java.lang.reflect.Field; import java.util.ArrayList; @@ -21,7 +21,7 @@ import de.robv.android.xposed.annotation.Level; @ApiSensitive(Level.LOW) public class ClassLoaderUtils { - public static final String DEXPATH = "/system/framework/edxp.dex:/system/framework/eddalvikdx.dex:/system/framework/eddexmaker.dex"; + public static final String DEXPATH = "/system/framework/edxp.dex"; public static void replaceParentClassLoader(ClassLoader appClassLoader) { if (appClassLoader == null) { diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/ClassUtils.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/ClassUtils.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/ClassUtils.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/ClassUtils.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/DexUtils.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/DexUtils.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/DexUtils.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/DexUtils.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/FileUtils.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/FileUtils.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/FileUtils.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/FileUtils.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/Hookers.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/Hookers.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/Hookers.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/Hookers.java diff --git a/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/MetaDataReader.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/MetaDataReader.java new file mode 100644 index 00000000..bbefcb67 --- /dev/null +++ b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/MetaDataReader.java @@ -0,0 +1,120 @@ +package com.elderdrivers.riru.edxp.util; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.jar.JarFile; + +import pxb.android.axml.AxmlReader; +import pxb.android.axml.AxmlVisitor; +import pxb.android.axml.NodeVisitor; + +public class MetaDataReader { + private final HashMap metaData = new HashMap<>(); + + public static Map getMetaData(File apk) throws IOException { + return new MetaDataReader(apk).metaData; + } + + private MetaDataReader(File apk) throws IOException { + try(JarFile zip = new JarFile(apk)) { + InputStream is = zip.getInputStream(zip.getEntry("AndroidManifest.xml")); + byte[] bytes = getBytesFromInputStream(is); + AxmlReader reader = new AxmlReader(bytes); + reader.accept(new AxmlVisitor() { + @Override + public NodeVisitor child(String ns, String name) { + NodeVisitor child = super.child(ns, name); + return new ManifestTagVisitor(child); + } + }); + } + } + + public static byte[] getBytesFromInputStream(InputStream inputStream) throws IOException { + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + byte[] b = new byte[1024]; + int n; + while ((n = inputStream.read(b)) != -1) { + bos.write(b, 0, n); + } + byte[] data = bos.toByteArray(); + return data; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + private class ManifestTagVisitor extends NodeVisitor { + public ManifestTagVisitor(NodeVisitor child) { + super(child); + } + + @Override + public NodeVisitor child(String ns, String name) { + NodeVisitor child = super.child(ns, name); + if ("application".equals(name)) { + return new ApplicationTagVisitor(child); + } + return child; + } + + private class ApplicationTagVisitor extends NodeVisitor { + public ApplicationTagVisitor(NodeVisitor child) { + super(child); + } + + @Override + public NodeVisitor child(String ns, String name) { + NodeVisitor child = super.child(ns, name); + if("meta-data".equals(name)) { + return new MetaDataVisitor(child); + } + return child; + } + } + } + + private class MetaDataVisitor extends NodeVisitor { + public String name = null; + public Object value = null; + public MetaDataVisitor(NodeVisitor child) { + super(child); + } + + @Override + public void attr(String ns, String name, int resourceId, int type, Object obj) { + if (type == 3 && "name".equals(name)) { + this.name = (String)obj; + } + if ("value".equals(name) ) { + value = obj; + } + super.attr(ns, name, resourceId, type, obj); + } + + @Override + public void end() { + if(name != null && value != null) { + metaData.put(name, value); + } + super.end(); + } + } + + public static int extractIntPart(String str) { + int result = 0, length = str.length(); + for (int offset = 0; offset < length; offset++) { + char c = str.charAt(offset); + if ('0' <= c && c <= '9') + result = result * 10 + (c - '0'); + else + break; + } + return result; + } +} diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/ProcessUtils.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/ProcessUtils.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/ProcessUtils.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/ProcessUtils.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/ProxyClassLoader.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/ProxyClassLoader.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/ProxyClassLoader.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/ProxyClassLoader.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/Unsafe.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/Unsafe.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/Unsafe.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/Unsafe.java diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/Utils.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/Utils.java similarity index 96% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/Utils.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/Utils.java index b1fa3741..cb48178e 100644 --- a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/Utils.java +++ b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/Utils.java @@ -2,7 +2,7 @@ package com.elderdrivers.riru.edxp.util; import android.util.Log; -import com.elderdrivers.riru.edxp.common.BuildConfig; +import com.elderdrivers.riru.edxp.BuildConfig; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.annotation.ApiSensitive; diff --git a/edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/Versions.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/Versions.java similarity index 100% rename from edxp-common/src/main/java/com/elderdrivers/riru/edxp/util/Versions.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/util/Versions.java diff --git a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/config/YahfaEdxpConfig.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/config/YahfaEdxpConfig.java similarity index 100% rename from edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/config/YahfaEdxpConfig.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/config/YahfaEdxpConfig.java diff --git a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/config/YahfaHookProvider.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/config/YahfaHookProvider.java similarity index 100% rename from edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/config/YahfaHookProvider.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/config/YahfaHookProvider.java diff --git a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/core/YahfaEdxpImpl.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/core/YahfaEdxpImpl.java similarity index 100% rename from edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/core/YahfaEdxpImpl.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/core/YahfaEdxpImpl.java diff --git a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/core/YahfaRouter.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/core/YahfaRouter.java similarity index 100% rename from edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/core/YahfaRouter.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/core/YahfaRouter.java diff --git a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexLog.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexLog.java similarity index 92% rename from edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexLog.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexLog.java index 0471190f..9f415499 100644 --- a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexLog.java +++ b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexLog.java @@ -2,7 +2,7 @@ package com.elderdrivers.riru.edxp.yahfa.dexmaker; import android.util.Log; -import com.elderdrivers.riru.edxp.yahfa.BuildConfig; +import com.elderdrivers.riru.edxp.BuildConfig; public class DexLog { diff --git a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexMakerUtils.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexMakerUtils.java similarity index 100% rename from edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexMakerUtils.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DexMakerUtils.java diff --git a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DynamicBridge.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DynamicBridge.java similarity index 100% rename from edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DynamicBridge.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/DynamicBridge.java diff --git a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/HookerDexMaker.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/HookerDexMaker.java similarity index 99% rename from edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/HookerDexMaker.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/HookerDexMaker.java index 6620ae0c..a8596531 100644 --- a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/HookerDexMaker.java +++ b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/HookerDexMaker.java @@ -7,7 +7,7 @@ import com.elderdrivers.riru.edxp.config.ConfigManager; import com.elderdrivers.riru.edxp.core.Yahfa; import com.elderdrivers.riru.edxp.core.yahfa.HookMain; import com.elderdrivers.riru.edxp.util.ProxyClassLoader; -import com.elderdrivers.riru.edxp.yahfa.BuildConfig; +import com.elderdrivers.riru.edxp.BuildConfig; import java.io.File; import java.lang.reflect.Constructor; diff --git a/edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/MethodInfo.java b/edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/MethodInfo.java similarity index 100% rename from edxp-yahfa/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/MethodInfo.java rename to edxp-core/src/main/java/com/elderdrivers/riru/edxp/yahfa/dexmaker/MethodInfo.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/XposedCompat.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/XposedCompat.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/XposedCompat.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/XposedCompat.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/CallOriginCallBack.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/CallOriginCallBack.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/CallOriginCallBack.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/CallOriginCallBack.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookMethodEntity.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookMethodEntity.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookMethodEntity.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookMethodEntity.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookStubManager.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookStubManager.java similarity index 99% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookStubManager.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookStubManager.java index 3f44f27e..ae98830c 100644 --- a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookStubManager.java +++ b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/HookStubManager.java @@ -2,7 +2,7 @@ package com.swift.sandhook.xposedcompat.hookstub; import android.util.Log; -import com.elderdrivers.riru.edxp.sandhook.BuildConfig; +import com.elderdrivers.riru.edxp.BuildConfig; import com.swift.sandhook.SandHook; import com.swift.sandhook.SandHookMethodResolver; import com.swift.sandhook.utils.ParamWrapper; diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/MethodHookerStubs32.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/MethodHookerStubs32.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/MethodHookerStubs32.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/MethodHookerStubs32.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/MethodHookerStubs64.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/MethodHookerStubs64.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/hookstub/MethodHookerStubs64.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/hookstub/MethodHookerStubs64.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/methodgen/ErrorCatch.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/methodgen/ErrorCatch.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/methodgen/ErrorCatch.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/methodgen/ErrorCatch.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookMaker.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookMaker.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookMaker.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookMaker.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookerDexMaker.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookerDexMaker.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookerDexMaker.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookerDexMaker.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookerDexMakerNew.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookerDexMakerNew.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookerDexMakerNew.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/methodgen/HookerDexMakerNew.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/methodgen/SandHookXposedBridge.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/methodgen/SandHookXposedBridge.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/methodgen/SandHookXposedBridge.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/methodgen/SandHookXposedBridge.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/utils/ApplicationUtils.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/utils/ApplicationUtils.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/utils/ApplicationUtils.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/utils/ApplicationUtils.java diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/utils/DexLog.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/utils/DexLog.java similarity index 95% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/utils/DexLog.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/utils/DexLog.java index 4aec875b..f69cef61 100644 --- a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/utils/DexLog.java +++ b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/utils/DexLog.java @@ -2,7 +2,7 @@ package com.swift.sandhook.xposedcompat.utils; import android.util.Log; -import com.elderdrivers.riru.edxp.sandhook.BuildConfig; +import com.elderdrivers.riru.edxp.BuildConfig; import java.lang.reflect.Member; diff --git a/edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/utils/DexMakerUtils.java b/edxp-core/src/main/java/com/swift/sandhook/xposedcompat/utils/DexMakerUtils.java similarity index 100% rename from edxp-sandhook/src/main/java/com/swift/sandhook/xposedcompat/utils/DexMakerUtils.java rename to edxp-core/src/main/java/com/swift/sandhook/xposedcompat/utils/DexMakerUtils.java diff --git a/edxp-core/src/main/java/de/robv/android/xposed/DexCreator.java b/edxp-core/src/main/java/de/robv/android/xposed/DexCreator.java new file mode 100644 index 00000000..f79b4443 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/DexCreator.java @@ -0,0 +1,235 @@ +package de.robv.android.xposed; + +import android.os.Environment; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.security.DigestException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.zip.Adler32; + +import static de.robv.android.xposed.XposedHelpers.inputStreamToByteArray; + +/** + * Helper class which can create a very simple .dex file, containing only a class definition + * with a super class (no methods, fields, ...). + */ +/*package*/ class DexCreator { + public static File DALVIK_CACHE = new File(Environment.getDataDirectory(), "dalvik-cache"); + + /** Returns the default dex file name for the class. */ + public static File getDefaultFile(String childClz) { + return new File(DALVIK_CACHE, "xposed_" + childClz.substring(childClz.lastIndexOf('.') + 1) + ".dex"); + } + + /** + * Creates (or returns) the path to a dex file which defines the superclass of {@clz} as extending + * {@code realSuperClz}, which by itself must extend {@code topClz}. + */ + public static File ensure(String clz, Class realSuperClz, Class topClz) throws IOException { + if (!topClz.isAssignableFrom(realSuperClz)) { + throw new ClassCastException("Cannot initialize " + clz + " because " + realSuperClz + " does not extend " + topClz); + } + + try { + return ensure("xposed.dummy." + clz + "SuperClass", realSuperClz); + } catch (IOException e) { + throw new IOException("Failed to create a superclass for " + clz, e); + } + } + + /** Like {@link #ensure(File, String, String)}, just for the default dex file name. */ + public static File ensure(String childClz, Class superClz) throws IOException { + return ensure(getDefaultFile(childClz), childClz, superClz.getName()); + } + + /** + * Makes sure that the given file is a simple dex file containing the given classes. + * Creates the file if that's not the case. + */ + public static File ensure(File file, String childClz, String superClz) throws IOException { + // First check if a valid file exists. + try { + byte[] dex = inputStreamToByteArray(new FileInputStream(file)); + if (matches(dex, childClz, superClz)) { + return file; + } else { + file.delete(); + } + } catch (IOException e) { + file.delete(); + } + + // If not, create a new dex file. + byte[] dex = create(childClz, superClz); + FileOutputStream fos = new FileOutputStream(file); + fos.write(dex); + fos.close(); + return file; + } + + /** + * Checks whether the Dex file fits to the class names. + * Assumes that the file has been created with this class. + */ + public static boolean matches(byte[] dex, String childClz, String superClz) throws IOException { + boolean childFirst = childClz.compareTo(superClz) < 0; + byte[] childBytes = stringToBytes("L" + childClz.replace('.', '/') + ";"); + byte[] superBytes = stringToBytes("L" + superClz.replace('.', '/') + ";"); + + int pos = 0xa0; + if (pos + childBytes.length + superBytes.length >= dex.length) { + return false; + } + + for (byte b : childFirst ? childBytes : superBytes) { + if (dex[pos++] != b) { + return false; + } + } + + for (byte b : childFirst ? superBytes: childBytes) { + if (dex[pos++] != b) { + return false; + } + } + + return true; + } + + /** Creates the byte array for the dex file. */ + public static byte[] create(String childClz, String superClz) throws IOException { + boolean childFirst = childClz.compareTo(superClz) < 0; + byte[] childBytes = stringToBytes("L" + childClz.replace('.', '/') + ";"); + byte[] superBytes = stringToBytes("L" + superClz.replace('.', '/') + ";"); + int stringsSize = childBytes.length + superBytes.length; + int padding = -stringsSize & 3; + stringsSize += padding; + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + // header + out.write("dex\n035\0".getBytes()); // magic + out.write(new byte[24]); // placeholder for checksum and signature + writeInt(out, 0xfc + stringsSize); // file size + writeInt(out, 0x70); // header size + writeInt(out, 0x12345678); // endian constant + writeInt(out, 0); // link size + writeInt(out, 0); // link offset + writeInt(out, 0xa4 + stringsSize); // map offset + writeInt(out, 2); // strings count + writeInt(out, 0x70); // strings offset + writeInt(out, 2); // types count + writeInt(out, 0x78); // types offset + writeInt(out, 0); // prototypes count + writeInt(out, 0); // prototypes offset + writeInt(out, 0); // fields count + writeInt(out, 0); // fields offset + writeInt(out, 0); // methods count + writeInt(out, 0); // methods offset + writeInt(out, 1); // classes count + writeInt(out, 0x80); // classes offset + writeInt(out, 0x5c + stringsSize); // data size + writeInt(out, 0xa0); // data offset + + // string map + writeInt(out, 0xa0); + writeInt(out, 0xa0 + (childFirst ? childBytes.length : superBytes.length)); + + // types + writeInt(out, 0); // first type = first string + writeInt(out, 1); // second type = second string + + // class definitions + writeInt(out, childFirst ? 0 : 1); // class to define = child type + writeInt(out, 1); // access flags = public + writeInt(out, childFirst ? 1 : 0); // super class = super type + writeInt(out, 0); // no interface + writeInt(out, -1); // no source file + writeInt(out, 0); // no annotations + writeInt(out, 0); // no class data + writeInt(out, 0); // no static values + + // string data + out.write(childFirst ? childBytes : superBytes); + out.write(childFirst ? superBytes : childBytes); + out.write(new byte[padding]); + + // annotations + writeInt(out, 0); // no items + + // map + writeInt(out, 7); // items count + writeMapItem(out, 0, 1, 0); // header + writeMapItem(out, 1, 2, 0x70); // strings + writeMapItem(out, 2, 2, 0x78); // types + writeMapItem(out, 6, 1, 0x80); // classes + writeMapItem(out, 0x2002, 2, 0xa0); // string data + writeMapItem(out, 0x1003, 1, 0xa0 + stringsSize); // annotations + writeMapItem(out, 0x1000, 1, 0xa4 + stringsSize); // map list + + byte[] buf = out.toByteArray(); + updateSignature(buf); + updateChecksum(buf); + return buf; + } + + private static void updateSignature(byte[] dex) { + // Update SHA-1 signature + try { + MessageDigest md = MessageDigest.getInstance("SHA-1"); + md.update(dex, 32, dex.length - 32); + md.digest(dex, 12, 20); + } catch (NoSuchAlgorithmException | DigestException e) { + throw new RuntimeException(e); + } + } + + private static void updateChecksum(byte[] dex) { + // Update Adler32 checksum + Adler32 a32 = new Adler32(); + a32.update(dex, 12, dex.length - 12); + int chksum = (int) a32.getValue(); + dex[8] = (byte) (chksum & 0xff); + dex[9] = (byte) (chksum >> 8 & 0xff); + dex[10] = (byte) (chksum >> 16 & 0xff); + dex[11] = (byte) (chksum >> 24 & 0xff); + } + + private static void writeUleb128(OutputStream out, int value) throws IOException { + while (value > 0x7f) { + out.write((value & 0x7f) | 0x80); + value >>>= 7; + } + out.write(value); + } + + private static void writeInt(OutputStream out, int value) throws IOException { + out.write(value); + out.write(value >> 8); + out.write(value >> 16); + out.write(value >> 24); + } + + private static void writeMapItem(OutputStream out, int type, int count, int offset) throws IOException { + writeInt(out, type); + writeInt(out, count); + writeInt(out, offset); + } + + private static byte[] stringToBytes(String s) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + writeUleb128(bytes, s.length()); + // This isn't MUTF-8, but should be OK. + bytes.write(s.getBytes("UTF-8")); + bytes.write(0); + return bytes.toByteArray(); + } + + private DexCreator() {} +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/IModuleContext.java b/edxp-core/src/main/java/de/robv/android/xposed/IModuleContext.java new file mode 100644 index 00000000..1cd6e561 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/IModuleContext.java @@ -0,0 +1,6 @@ +package de.robv.android.xposed; + +public interface IModuleContext { + + String getApkPath(); +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookCmdInit.java b/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookCmdInit.java new file mode 100644 index 00000000..6f99ac9d --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookCmdInit.java @@ -0,0 +1,28 @@ +package de.robv.android.xposed; + + +/** + * Hook the initialization of Java-based command-line tools (like pm). + * + * @hide Xposed no longer hooks command-line tools, therefore this interface shouldn't be + * implemented anymore. + */ +public interface IXposedHookCmdInit extends IXposedMod { + /** + * Called very early during startup of a command-line tool. + * @param startupParam Details about the module itself and the started process. + * @throws Throwable Everything is caught, but it will prevent further initialization of the module. + */ + void initCmdApp(StartupParam startupParam) throws Throwable; + + /** Data holder for {@link #initCmdApp}. */ + final class StartupParam { + /*package*/ StartupParam() {} + + /** The path to the module's APK. */ + public String modulePath; + + /** The class name of the tools that the hook was invoked for. */ + public String startClassName; + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookInitPackageResources.java b/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookInitPackageResources.java new file mode 100644 index 00000000..4000cc13 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookInitPackageResources.java @@ -0,0 +1,45 @@ +package de.robv.android.xposed; + +import android.content.res.XResources; + +import de.robv.android.xposed.callbacks.XC_InitPackageResources; +import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam; + +/** + * Get notified when the resources for an app are initialized. + * In {@link #handleInitPackageResources}, resource replacements can be created. + * + *

This interface should be implemented by the module's main class. Xposed will take care of + * registering it as a callback automatically. + */ +public interface IXposedHookInitPackageResources extends IXposedMod { + /** + * This method is called when resources for an app are being initialized. + * Modules can call special methods of the {@link XResources} class in order to replace resources. + * + * @param resparam Information about the resources. + * @throws Throwable Everything the callback throws is caught and logged. + */ + void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable; + + /** @hide */ + final class Wrapper extends XC_InitPackageResources { + private final IXposedHookInitPackageResources instance; + private final String apkPath; + + public Wrapper(IXposedHookInitPackageResources instance, String apkPath) { + this.instance = instance; + this.apkPath = apkPath; + } + + @Override + public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable { + instance.handleInitPackageResources(resparam); + } + + @Override + public String getApkPath() { + return apkPath; + } + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookLoadPackage.java b/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookLoadPackage.java new file mode 100644 index 00000000..6446262a --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookLoadPackage.java @@ -0,0 +1,45 @@ +package de.robv.android.xposed; + +import android.app.Application; + +import de.robv.android.xposed.callbacks.XC_LoadPackage; +import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; + +/** + * Get notified when an app ("Android package") is loaded. + * This is especially useful to hook some app-specific methods. + * + *

This interface should be implemented by the module's main class. Xposed will take care of + * registering it as a callback automatically. + */ +public interface IXposedHookLoadPackage extends IXposedMod { + /** + * This method is called when an app is loaded. It's called very early, even before + * {@link Application#onCreate} is called. + * Modules can set up their app-specific hooks here. + * + * @param lpparam Information about the app. + * @throws Throwable Everything the callback throws is caught and logged. + */ + void handleLoadPackage(LoadPackageParam lpparam) throws Throwable; + + /** @hide */ + final class Wrapper extends XC_LoadPackage { + private final IXposedHookLoadPackage instance; + private final String apkPath; + + public Wrapper(IXposedHookLoadPackage instance, String apkPath) { + this.instance = instance; + this.apkPath = apkPath; + } + @Override + public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable { + instance.handleLoadPackage(lpparam); + } + + @Override + public String getApkPath() { + return apkPath; + } + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookZygoteInit.java b/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookZygoteInit.java new file mode 100644 index 00000000..d789af24 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/IXposedHookZygoteInit.java @@ -0,0 +1,71 @@ +package de.robv.android.xposed; + +import de.robv.android.xposed.callbacks.XC_InitZygote; +import de.robv.android.xposed.callbacks.XCallback; + +/** + * Hook the initialization of Zygote process(es), from which all the apps are forked. + * + *

Implement this interface in your module's main class in order to be notified when Android is + * starting up. In {@link IXposedHookZygoteInit}, you can modify objects and place hooks that should + * be applied for every app. Only the Android framework/system classes are available at that point + * in time. Use {@code null} as class loader for {@link XposedHelpers#findAndHookMethod(String, ClassLoader, String, Object...)} + * and its variants. + * + *

If you want to hook one/multiple specific apps, use {@link IXposedHookLoadPackage} instead. + */ +public interface IXposedHookZygoteInit extends IXposedMod { + /** + * Called very early during startup of Zygote. + * @param startupParam Details about the module itself and the started process. + * @throws Throwable everything is caught, but will prevent further initialization of the module. + */ + void initZygote(StartupParam startupParam) throws Throwable; + + /** Data holder for {@link #initZygote}. */ + final class StartupParam extends XCallback.Param { + /*package*/ StartupParam() {} + + /** + * @param callbacks + * @hide + */ + public StartupParam(XposedBridge.CopyOnWriteSortedSet callbacks) { + super(callbacks); + } + + /** The path to the module's APK. */ + public String modulePath; + + /** + * Always {@code true} on 32-bit ROMs. On 64-bit, it's only {@code true} for the primary + * process that starts the system_server. + */ + public boolean startsSystemServer; + } + + /** + * @hide + */ + final class Wrapper extends XC_InitZygote { + private final IXposedHookZygoteInit instance; + private final StartupParam startupParam; + + public Wrapper(IXposedHookZygoteInit instance, StartupParam startupParam) { + this.instance = instance; + this.startupParam = startupParam; + } + + @Override + public void initZygote(StartupParam startupParam) throws Throwable { + // NOTE: parameter startupParam not used + // cause startupParam info is generated and saved along with instance here + instance.initZygote(this.startupParam); + } + + @Override + public String getApkPath() { + return startupParam.modulePath; + } + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/IXposedMod.java b/edxp-core/src/main/java/de/robv/android/xposed/IXposedMod.java new file mode 100644 index 00000000..7723cd83 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/IXposedMod.java @@ -0,0 +1,4 @@ +package de.robv.android.xposed; + +/** Marker interface for Xposed modules. Cannot be implemented directly. */ +/* package */ interface IXposedMod {} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/PendingHooks.java b/edxp-core/src/main/java/de/robv/android/xposed/PendingHooks.java new file mode 100644 index 00000000..4c884077 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/PendingHooks.java @@ -0,0 +1,44 @@ +package de.robv.android.xposed; + +import java.lang.reflect.Member; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +import static de.robv.android.xposed.XposedBridge.hookMethodNative; + +public final class PendingHooks { + + // GuardedBy("PendingHooks.class") + private static final ConcurrentHashMap, ConcurrentHashMap> + sPendingHooks = new ConcurrentHashMap<>(); + + public synchronized static void hookPendingMethod(Class clazz) { + if (sPendingHooks.containsKey(clazz)) { + for (Map.Entry hook : sPendingHooks.get(clazz).entrySet()) { + hookMethodNative(hook.getKey(), clazz, 0, hook.getValue()); + } + } + } + + public synchronized static void recordPendingMethod(Member hookMethod, + XposedBridge.AdditionalHookInfo additionalInfo) { + ConcurrentHashMap pending = + sPendingHooks.computeIfAbsent(hookMethod.getDeclaringClass(), + new Function, ConcurrentHashMap>() { + @Override + public ConcurrentHashMap apply(Class aClass) { + return new ConcurrentHashMap<>(); + } + }); + + pending.put(hookMethod, additionalInfo); + recordPendingMethodNative(hookMethod.getDeclaringClass()); + } + + public synchronized void cleanUp() { + sPendingHooks.clear(); + } + + private static native void recordPendingMethodNative(Class clazz); +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/SELinuxHelper.java b/edxp-core/src/main/java/de/robv/android/xposed/SELinuxHelper.java new file mode 100644 index 00000000..0d23657f --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/SELinuxHelper.java @@ -0,0 +1,118 @@ +package de.robv.android.xposed; + +import android.os.SELinux; +import android.util.Log; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +import de.robv.android.xposed.services.BaseService; +import de.robv.android.xposed.services.BinderService; +import de.robv.android.xposed.services.DirectAccessService; +import de.robv.android.xposed.services.ZygoteService; + +/** + * A helper to work with (or without) SELinux, abstracting much of its big complexity. + */ +public final class SELinuxHelper { + private SELinuxHelper() {} + + /** + * Determines whether SELinux is disabled or enabled. + * + * @return A boolean indicating whether SELinux is enabled. + */ + public static boolean isSELinuxEnabled() { + return sIsSELinuxEnabled; + } + + /** + * Determines whether SELinux is permissive or enforcing. + * + * @return A boolean indicating whether SELinux is enforcing. + */ + public static boolean isSELinuxEnforced() { + if (!sIsSELinuxEnabled) { + return false; + } + boolean result = false; + final File SELINUX_STATUS_FILE = new File("/sys/fs/selinux/enforce"); + if (SELINUX_STATUS_FILE.exists()) { + try { + FileInputStream fis = new FileInputStream(SELINUX_STATUS_FILE); + int status = fis.read(); + switch (status) { + case 49: + result = true; + break; + case 48: + result = false; + break; + default: + XposedBridge.log("Unexpected byte " + status + " in /sys/fs/selinux/enforce"); + } + fis.close(); + } catch (IOException e) { + if (e.getMessage().contains("Permission denied")) { + result = true; + } else { + XposedBridge.log("Failed to read SELinux status: " + e.getMessage()); + result = false; + } + } + } + return result; + } + + /** + * Gets the security context of the current process. + * + * @return A String representing the security context of the current process. + */ + public static String getContext() { + return sIsSELinuxEnabled ? SELinux.getContext() : null; + } + + /** + * Retrieve the service to be used when accessing files in {@code /data/data/*}. + * + *

IMPORTANT: If you call this from the Zygote process, + * don't re-use the result in different process! + * + * @return An instance of the service. + */ + public static BaseService getAppDataFileService() { + if (sServiceAppDataFile != null) + return sServiceAppDataFile; + throw new UnsupportedOperationException(); + } + + + // ---------------------------------------------------------------------------- + // TODO: SELinux status + private static boolean sIsSELinuxEnabled = false; + private static BaseService sServiceAppDataFile = new DirectAccessService(); // ed: initialized directly + + /*package*/ public static void initOnce() { + // ed: we assume all selinux policies have been added lively using magiskpolicy + try { + sIsSELinuxEnabled = SELinux.isSELinuxEnabled(); + } catch (NoClassDefFoundError ignored) {} + } + + /*package*/ static void initForProcess(String packageName) { + // ed: sServiceAppDataFile has been initialized with default value +// if (sIsSELinuxEnabled) { +// if (packageName == null) { // Zygote +// sServiceAppDataFile = new ZygoteService(); +// } else if (packageName.equals("android")) { //system_server +// sServiceAppDataFile = BinderService.getService(BinderService.TARGET_APP); +// } else { // app +// sServiceAppDataFile = new DirectAccessService(); +// } +// } else { +// sServiceAppDataFile = new DirectAccessService(); +// } + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/XC_MethodHook.java b/edxp-core/src/main/java/de/robv/android/xposed/XC_MethodHook.java new file mode 100644 index 00000000..068616ab --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/XC_MethodHook.java @@ -0,0 +1,168 @@ +package de.robv.android.xposed; + +import java.lang.reflect.Member; + +import de.robv.android.xposed.callbacks.IXUnhook; +import de.robv.android.xposed.callbacks.XCallback; + +/** + * Callback class for method hooks. + * + *

Usually, anonymous subclasses of this class are created which override + * {@link #beforeHookedMethod} and/or {@link #afterHookedMethod}. + */ +public abstract class XC_MethodHook extends XCallback { + /** + * Creates a new callback with default priority. + */ + @SuppressWarnings("deprecation") + public XC_MethodHook() { + super(); + } + + /** + * Creates a new callback with a specific priority. + * + *

Note that {@link #afterHookedMethod} will be called in reversed order, i.e. + * the callback with the highest priority will be called last. This way, the callback has the + * final control over the return value. {@link #beforeHookedMethod} is called as usual, i.e. + * highest priority first. + * + * @param priority See {@link XCallback#priority}. + */ + public XC_MethodHook(int priority) { + super(priority); + } + + /** + * Called before the invocation of the method. + * + *

You can use {@link MethodHookParam#setResult} and {@link MethodHookParam#setThrowable} + * to prevent the original method from being called. + * + *

Note that implementations shouldn't call {@code super(param)}, it's not necessary. + * + * @param param Information about the method call. + * @throws Throwable Everything the callback throws is caught and logged. + */ + protected void beforeHookedMethod(MethodHookParam param) throws Throwable {} + + public void callBeforeHookedMethod(MethodHookParam param) throws Throwable { + beforeHookedMethod(param); + } + + /** + * Called after the invocation of the method. + * + *

You can use {@link MethodHookParam#setResult} and {@link MethodHookParam#setThrowable} + * to modify the return value of the original method. + * + *

Note that implementations shouldn't call {@code super(param)}, it's not necessary. + * + * @param param Information about the method call. + * @throws Throwable Everything the callback throws is caught and logged. + */ + protected void afterHookedMethod(MethodHookParam param) throws Throwable {} + + public void callAfterHookedMethod(MethodHookParam param) throws Throwable { + afterHookedMethod(param); + } + + /** + * Wraps information about the method call and allows to influence it. + */ + public static final class MethodHookParam extends XCallback.Param { + /** @hide */ + @SuppressWarnings("deprecation") + public MethodHookParam() { + super(); + } + + /** The hooked method/constructor. */ + public Member method; + + /** The {@code this} reference for an instance method, or {@code null} for static methods. */ + public Object thisObject; + + /** Arguments to the method call. */ + public Object[] args; + + private Object result = null; + private Throwable throwable = null; + public boolean returnEarly = false; + + /** Returns the result of the method call. */ + public Object getResult() { + return result; + } + + /** + * Modify the result of the method call. + * + *

If called from {@link #beforeHookedMethod}, it prevents the call to the original method. + */ + public void setResult(Object result) { + this.result = result; + this.throwable = null; + this.returnEarly = true; + } + + /** Returns the {@link Throwable} thrown by the method, or {@code null}. */ + public Throwable getThrowable() { + return throwable; + } + + /** Returns true if an exception was thrown by the method. */ + public boolean hasThrowable() { + return throwable != null; + } + + /** + * Modify the exception thrown of the method call. + * + *

If called from {@link #beforeHookedMethod}, it prevents the call to the original method. + */ + public void setThrowable(Throwable throwable) { + this.throwable = throwable; + this.result = null; + this.returnEarly = true; + } + + /** Returns the result of the method call, or throws the Throwable caused by it. */ + public Object getResultOrThrowable() throws Throwable { + if (throwable != null) + throw throwable; + return result; + } + } + + /** + * An object with which the method/constructor can be unhooked. + */ + public class Unhook implements IXUnhook { + private final Member hookMethod; + + /*package*/ Unhook(Member hookMethod) { + this.hookMethod = hookMethod; + } + + /** + * Returns the method/constructor that has been hooked. + */ + public Member getHookedMethod() { + return hookMethod; + } + + @Override + public XC_MethodHook getCallback() { + return XC_MethodHook.this; + } + + @SuppressWarnings("deprecation") + @Override + public void unhook() { + XposedBridge.unhookMethod(hookMethod, XC_MethodHook.this); + } + + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/XC_MethodReplacement.java b/edxp-core/src/main/java/de/robv/android/xposed/XC_MethodReplacement.java new file mode 100644 index 00000000..bde14534 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/XC_MethodReplacement.java @@ -0,0 +1,88 @@ +package de.robv.android.xposed; + +import de.robv.android.xposed.callbacks.XCallback; + +/** + * A special case of {@link XC_MethodHook} which completely replaces the original method. + */ +public abstract class XC_MethodReplacement extends XC_MethodHook { + /** + * Creates a new callback with default priority. + */ + public XC_MethodReplacement() { + super(); + } + + /** + * Creates a new callback with a specific priority. + * + * @param priority See {@link XCallback#priority}. + */ + public XC_MethodReplacement(int priority) { + super(priority); + } + + /** @hide */ + @Override + protected final void beforeHookedMethod(MethodHookParam param) throws Throwable { + try { + Object result = replaceHookedMethod(param); + param.setResult(result); + } catch (Throwable t) { + XposedBridge.log(t); + param.setThrowable(t); + } + } + + /** @hide */ + @Override + @SuppressWarnings("EmptyMethod") + protected final void afterHookedMethod(MethodHookParam param) throws Throwable {} + + /** + * Shortcut for replacing a method completely. Whatever is returned/thrown here is taken + * instead of the result of the original method (which will not be called). + * + *

Note that implementations shouldn't call {@code super(param)}, it's not necessary. + * + * @param param Information about the method call. + * @throws Throwable Anything that is thrown by the callback will be passed on to the original caller. + */ + @SuppressWarnings("UnusedParameters") + protected abstract Object replaceHookedMethod(MethodHookParam param) throws Throwable; + + /** + * Predefined callback that skips the method without replacements. + */ + public static final XC_MethodReplacement DO_NOTHING = new XC_MethodReplacement(PRIORITY_HIGHEST*2) { + @Override + protected Object replaceHookedMethod(MethodHookParam param) throws Throwable { + return null; + } + }; + + /** + * Creates a callback which always returns a specific value. + * + * @param result The value that should be returned to callers of the hooked method. + */ + public static XC_MethodReplacement returnConstant(final Object result) { + return returnConstant(PRIORITY_DEFAULT, result); + } + + /** + * Like {@link #returnConstant(Object)}, but allows to specify a priority for the callback. + * + * @param priority See {@link XCallback#priority}. + * @param result The value that should be returned to callers of the hooked method. + */ + public static XC_MethodReplacement returnConstant(int priority, final Object result) { + return new XC_MethodReplacement(priority) { + @Override + protected Object replaceHookedMethod(MethodHookParam param) throws Throwable { + return result; + } + }; + } + +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/XSharedPreferences.java b/edxp-core/src/main/java/de/robv/android/xposed/XSharedPreferences.java new file mode 100644 index 00000000..61092753 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/XSharedPreferences.java @@ -0,0 +1,538 @@ +package de.robv.android.xposed; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Environment; +import android.preference.PreferenceManager; +import android.util.Log; + +import com.android.internal.util.XmlUtils; +import com.elderdrivers.riru.edxp.BuildConfig; +import com.elderdrivers.riru.edxp.util.MetaDataReader; + +import org.xmlpull.v1.XmlPullParserException; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.AccessDeniedException; +import java.nio.file.Path; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import de.robv.android.xposed.services.FileResult; + +/** + * This class is basically the same as SharedPreferencesImpl from AOSP, but + * read-only and without listeners support. Instead, it is made to be + * compatible with all ROMs. + */ +public final class XSharedPreferences implements SharedPreferences { + private static final String TAG = "XSharedPreferences"; + private static final HashMap sInstances = new HashMap<>(); + private static final Object sContent = new Object(); + private static Thread sDaemon = null; + private static WatchService sWatcher; + + private final HashMap mListeners = new HashMap<>(); + private final File mFile; + private final String mFilename; + private Map mMap; + private boolean mLoaded = false; + private long mLastModified; + private long mFileSize; + private boolean mWatcherEnabled; + + private static synchronized WatchService getWatcher() { + if (sWatcher == null) { + try { + sWatcher = new File(XposedInit.prefsBasePath).toPath().getFileSystem().newWatchService(); + if (BuildConfig.DEBUG) Log.d(TAG, "Created WatchService instance"); + } catch (IOException e) { + Log.e(TAG, "Failed to create WatchService", e); + } + } + + if (sWatcher != null && (sDaemon == null || !sDaemon.isAlive())) { + initWatcherDaemon(); + } + + return sWatcher; + } + + private static void initWatcherDaemon() { + sDaemon = new Thread() { + @Override + public void run() { + Log.d(TAG, "Watcher daemon thread started"); + while (true) { + WatchKey key; + try { + key = sWatcher.take(); + } catch (InterruptedException ignored) { + return; + } + for (WatchEvent event : key.pollEvents()) { + WatchEvent.Kind kind = event.kind(); + if (kind == StandardWatchEventKinds.OVERFLOW) { + continue; + } + Path dir = (Path) key.watchable(); + Path path = dir.resolve((Path) event.context()); + String pathStr = path.toString(); + if (BuildConfig.DEBUG) Log.v(TAG, "File " + path.toString() + " event: " + kind.name()); + // We react to both real and backup files due to rare race conditions + if (pathStr.endsWith(".bak")) { + if (kind != StandardWatchEventKinds.ENTRY_DELETE) { + continue; + } else { + pathStr = path.getFileName().toString(); + path = dir.resolve(pathStr.substring(0, pathStr.length() - 4)); + } + } else if (SELinuxHelper.getAppDataFileService().checkFileExists(pathStr + ".bak")) { + continue; + } + PrefsData data = sInstances.get(path); + if (data != null && data.hasChanged()) { + for (OnSharedPreferenceChangeListener l : data.mPrefs.mListeners.keySet()) { + try { + l.onSharedPreferenceChanged(data.mPrefs, null); + } catch (Throwable t) { + if (BuildConfig.DEBUG) Log.e(TAG, "Fail in preference change listener", t); + } + } + } + } + key.reset(); + } + } + }; + sDaemon.setName(TAG + "-Daemon"); + sDaemon.setDaemon(true); + sDaemon.start(); + } + + /** + * Read settings from the specified file. + * + * @param prefFile The file to read the preferences from. + * @param enableWatcher Whether to enable support for preference change listeners + */ + public XSharedPreferences(File prefFile, boolean enableWatcher) { + mFile = prefFile; + mFilename = prefFile.getAbsolutePath(); + mWatcherEnabled = enableWatcher; + init(); + } + + /** + * Read settings from the specified file. + * + * @param prefFile The file to read the preferences from. + */ + public XSharedPreferences(File prefFile) { + this(prefFile, false); + } + + /** + * Read settings from the default preferences for a package. + * These preferences are returned by {@link PreferenceManager#getDefaultSharedPreferences}. + * + * @param packageName The package name. + */ + public XSharedPreferences(String packageName) { + this(packageName, packageName + "_preferences"); + } + + /** + * Read settings from a custom preferences file for a package. + * These preferences are returned by {@link Context#getSharedPreferences(String, int)}. + * + * @param packageName The package name. + * @param prefFileName The file name without ".xml". + */ + public XSharedPreferences(String packageName, String prefFileName) { + boolean newModule = false; + Set modules = XposedInit.getLoadedModules(); + for (String m : modules) { + if (m.contains("/" + packageName + "-")) { + boolean isModule = false; + int xposedminversion = -1; + boolean xposedsharedprefs = false; + try { + Map metaData = MetaDataReader.getMetaData(new File(m)); + isModule = metaData.containsKey("xposedmodule"); + if (isModule) { + Object minVersionRaw = metaData.get("xposedminversion"); + if (minVersionRaw instanceof Integer) { + xposedminversion = (Integer) minVersionRaw; + } else if (minVersionRaw instanceof String) { + xposedminversion = MetaDataReader.extractIntPart((String) minVersionRaw); + } + xposedsharedprefs = metaData.containsKey("xposedsharedprefs"); + mWatcherEnabled = metaData.containsKey("xposedsharedprefswatcher"); + } + } catch (NumberFormatException | IOException e) { + Log.w(TAG, "Apk parser fails: " + e); + } + newModule = isModule && (xposedminversion > 92 || xposedsharedprefs); + } + } + if (newModule && XposedInit.prefsBasePath != null) { + mFile = new File(XposedInit.prefsBasePath, packageName + "/" + prefFileName + ".xml"); + } else { + mFile = new File(Environment.getDataDirectory(), "data/" + packageName + "/shared_prefs/" + prefFileName + ".xml"); + } + mFilename = mFile.getAbsolutePath(); + init(); + } + + private void tryRegisterWatcher() { + if (!mWatcherEnabled) { + return; + } + Path path = mFile.toPath(); + if (sInstances.containsKey(path)) { + return; + } + try { + path.getParent().register(getWatcher(), StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); + sInstances.put(path, new PrefsData(this)); + if (BuildConfig.DEBUG) Log.d(TAG, "tryRegisterWatcher: registered file watcher for " + path); + } catch (AccessDeniedException accDeniedEx) { + if (BuildConfig.DEBUG) Log.d(TAG, "tryRegisterWatcher: access denied to " + path); + } catch (Exception e) { + Log.d(TAG, "tryRegisterWatcher: failed to register file watcher", e); + } + } + + private void init() { + tryRegisterWatcher(); + startLoadFromDisk(); + } + + private static long tryGetFileSize(String filename) { + try { + return SELinuxHelper.getAppDataFileService().getFileSize(filename); + } catch (IOException ignored) { + return 0; + } + } + + private static byte[] tryGetFileHash(String filename) { + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + try (InputStream is = SELinuxHelper.getAppDataFileService().getFileInputStream(filename)) { + byte[] buf = new byte[4096]; + int read; + while ((read = is.read(buf)) != -1) { + md.update(buf, 0, read); + } + } + return md.digest(); + } catch (Exception ignored) { + return new byte[0]; + } + } + + /** + * Tries to make the preferences file world-readable. + * + *

Warning: This is only meant to work around permission "fix" functions that are part + * of some recoveries. It doesn't replace the need to open preferences with {@code MODE_WORLD_READABLE} + * in the module's UI code. Otherwise, Android will set stricter permissions again during the next save. + * + *

This will only work if executed as root (e.g. {@code initZygote()}) and only if SELinux is disabled. + * + * @return {@code true} in case the file could be made world-readable. + */ + @SuppressLint("SetWorldReadable") + public boolean makeWorldReadable() { + if (!SELinuxHelper.getAppDataFileService().hasDirectFileAccess()) + return false; // It doesn't make much sense to make the file readable if we wouldn't be able to access it anyway. + + if (!mFile.exists()) // Just in case - the file should never be created if it doesn't exist. + return false; + + if (!mFile.setReadable(true, false)) + return false; + + tryRegisterWatcher(); + return true; + } + + /** + * Returns the file that is backing these preferences. + * + *

Warning: The file might not be accessible directly. + */ + public File getFile() { + return mFile; + } + + private void startLoadFromDisk() { + synchronized (this) { + mLoaded = false; + } + new Thread("XSharedPreferences-load") { + @Override + public void run() { + synchronized (XSharedPreferences.this) { + loadFromDiskLocked(); + } + } + }.start(); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private void loadFromDiskLocked() { + if (mLoaded) { + return; + } + + Map map = null; + FileResult result = null; + try { + result = SELinuxHelper.getAppDataFileService().getFileInputStream(mFilename, mFileSize, mLastModified); + if (result.stream != null) { + map = XmlUtils.readMapXml(result.stream); + result.stream.close(); + } else { + // The file is unchanged, keep the current values + map = mMap; + } + } catch (XmlPullParserException e) { + Log.w(TAG, "getSharedPreferences failed for: " + mFilename, e); + } catch (FileNotFoundException ignored) { + // SharedPreferencesImpl has a canRead() check, so it doesn't log anything in case the file doesn't exist + } catch (IOException e) { + Log.w(TAG, "getSharedPreferences failed for: " + mFilename, e); + } finally { + if (result != null && result.stream != null) { + try { + result.stream.close(); + } catch (RuntimeException rethrown) { + throw rethrown; + } catch (Exception ignored) { + } + } + } + + mLoaded = true; + if (map != null) { + mMap = map; + mLastModified = result.mtime; + mFileSize = result.size; + } else { + mMap = new HashMap<>(); + } + notifyAll(); + } + + /** + * Reload the settings from file if they have changed. + * + *

Warning: With enforcing SELinux, this call might be quite expensive. + */ + public synchronized void reload() { + if (hasFileChanged()) { + init(); + } + } + + /** + * Check whether the file has changed since the last time it has been loaded. + * + *

Warning: With enforcing SELinux, this call might be quite expensive. + */ + public synchronized boolean hasFileChanged() { + try { + FileResult result = SELinuxHelper.getAppDataFileService().statFile(mFilename); + return mLastModified != result.mtime || mFileSize != result.size; + } catch (FileNotFoundException ignored) { + // SharedPreferencesImpl doesn't log anything in case the file doesn't exist + return true; + } catch (IOException e) { + Log.w(TAG, "hasFileChanged", e); + return true; + } + } + + private void awaitLoadedLocked() { + while (!mLoaded) { + try { + wait(); + } catch (InterruptedException unused) { + } + } + } + + /** + * @hide + */ + @Override + public Map getAll() { + synchronized (this) { + awaitLoadedLocked(); + return new HashMap<>(mMap); + } + } + + /** + * @hide + */ + @Override + public String getString(String key, String defValue) { + synchronized (this) { + awaitLoadedLocked(); + String v = (String) mMap.get(key); + return v != null ? v : defValue; + } + } + + /** + * @hide + */ + @Override + @SuppressWarnings("unchecked") + public Set getStringSet(String key, Set defValues) { + synchronized (this) { + awaitLoadedLocked(); + Set v = (Set) mMap.get(key); + return v != null ? v : defValues; + } + } + + /** + * @hide + */ + @Override + public int getInt(String key, int defValue) { + synchronized (this) { + awaitLoadedLocked(); + Integer v = (Integer) mMap.get(key); + return v != null ? v : defValue; + } + } + + /** + * @hide + */ + @Override + public long getLong(String key, long defValue) { + synchronized (this) { + awaitLoadedLocked(); + Long v = (Long) mMap.get(key); + return v != null ? v : defValue; + } + } + + /** + * @hide + */ + @Override + public float getFloat(String key, float defValue) { + synchronized (this) { + awaitLoadedLocked(); + Float v = (Float) mMap.get(key); + return v != null ? v : defValue; + } + } + + /** + * @hide + */ + @Override + public boolean getBoolean(String key, boolean defValue) { + synchronized (this) { + awaitLoadedLocked(); + Boolean v = (Boolean) mMap.get(key); + return v != null ? v : defValue; + } + } + + /** + * @hide + */ + @Override + public boolean contains(String key) { + synchronized (this) { + awaitLoadedLocked(); + return mMap.containsKey(key); + } + } + + /** + * @deprecated Not supported by this implementation. + */ + @Deprecated + @Override + public Editor edit() { + throw new UnsupportedOperationException("read-only implementation"); + } + + @Deprecated + @Override + public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { + if (!mWatcherEnabled) + throw new UnsupportedOperationException("File watcher feature is disabled for this instance"); + + synchronized(this) { + mListeners.put(listener, sContent); + } + } + + @Deprecated + @Override + public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { + if (!mWatcherEnabled) + throw new UnsupportedOperationException("File watcher feature is disabled for this instance"); + + synchronized(this) { + mListeners.remove(listener); + } + } + + private static class PrefsData { + public final XSharedPreferences mPrefs; + private long mSize; + private byte[] mHash; + + public PrefsData(XSharedPreferences prefs) { + mPrefs = prefs; + mSize = tryGetFileSize(prefs.mFilename); + mHash = tryGetFileHash(prefs.mFilename); + } + + public boolean hasChanged() { + long size = tryGetFileSize(mPrefs.mFilename); + if (size < 1) { + if (BuildConfig.DEBUG) Log.d(TAG, "Ignoring empty prefs file"); + return false; + } + if (size != mSize) { + mSize = size; + mHash = tryGetFileHash(mPrefs.mFilename); + if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file size changed"); + return true; + } + byte[] hash = tryGetFileHash(mPrefs.mFilename); + if (!Arrays.equals(hash, mHash)) { + mHash = hash; + if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file hash changed"); + return true; + } + if (BuildConfig.DEBUG) Log.d(TAG, "Prefs file not changed"); + return false; + } + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/XposedBridge.java b/edxp-core/src/main/java/de/robv/android/xposed/XposedBridge.java new file mode 100644 index 00000000..1f9f88c8 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/XposedBridge.java @@ -0,0 +1,615 @@ +package de.robv.android.xposed; + +import android.content.res.Resources; +import android.content.res.TypedArray; +import android.util.Log; + +import com.elderdrivers.riru.edxp.BuildConfig; +import com.elderdrivers.riru.edxp.config.EdXpConfigGlobal; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import dalvik.system.InMemoryDexClassLoader; +import de.robv.android.xposed.XC_MethodHook.MethodHookParam; +import de.robv.android.xposed.annotation.ApiSensitive; +import de.robv.android.xposed.annotation.Level; +import de.robv.android.xposed.callbacks.XC_InitPackageResources; +import de.robv.android.xposed.callbacks.XC_InitZygote; +import de.robv.android.xposed.callbacks.XC_LoadPackage; +import de.robv.android.xposed.callbacks.XCallback; +import external.com.android.dx.DexMaker; +import external.com.android.dx.TypeId; + +import static de.robv.android.xposed.XposedHelpers.getIntField; +import static de.robv.android.xposed.XposedHelpers.setObjectField; + +/** + * This class contains most of Xposed's central logic, such as initialization and callbacks used by + * the native side. It also includes methods to add new hooks. + */ +@SuppressWarnings("JniMissingFunction") +public final class XposedBridge { + /** + * The system class loader which can be used to locate Android framework classes. + * Application classes cannot be retrieved from it. + * + * @see ClassLoader#getSystemClassLoader + */ + public static final ClassLoader BOOTCLASSLOADER = XposedBridge.class.getClassLoader(); + + /** @hide */ + public static final String TAG = "EdXposed-Bridge"; + + /** @deprecated Use {@link #getXposedVersion()} instead. */ + @Deprecated + public static int XPOSED_BRIDGE_VERSION; + + /*package*/ static boolean isZygote = true; // ed: RuntimeInit.main() tool process not supported yet + + private static int runtime = 2; // ed: only support art + private static final int RUNTIME_DALVIK = 1; + private static final int RUNTIME_ART = 2; + + public static boolean disableHooks = false; + + // This field is set "magically" on MIUI. + /*package*/ static long BOOT_START_TIME; + + private static final Object[] EMPTY_ARRAY = new Object[0]; + + // built-in handlers + public static final Map> sHookedMethodCallbacks = new HashMap<>(); + public static final CopyOnWriteSortedSet sLoadedPackageCallbacks = new CopyOnWriteSortedSet<>(); + /*package*/ static final CopyOnWriteSortedSet sInitPackageResourcesCallbacks = new CopyOnWriteSortedSet<>(); + /*package*/ static final CopyOnWriteSortedSet sInitZygoteCallbacks = new CopyOnWriteSortedSet<>(); + + private XposedBridge() {} + + /** + * Called when native methods and other things are initialized, but before preloading classes etc. + * @hide + */ + @SuppressWarnings("deprecation") + public static void main(String[] args) { + // ed: moved + } + + /** @hide */ +// protected static final class ToolEntryPoint { +// protected static void main(String[] args) { +// isZygote = false; +// XposedBridge.main(args); +// } +// } + + public static volatile ClassLoader dummyClassLoader = null; + + @ApiSensitive(Level.MIDDLE) + public static void initXResources() { + if (dummyClassLoader != null) { + return; + } + try { + Resources res = Resources.getSystem(); + Class resClass = res.getClass(); + Class taClass = TypedArray.class; + try { + TypedArray ta = res.obtainTypedArray(res.getIdentifier( + "preloaded_drawables", "array", "android")); + taClass = ta.getClass(); + ta.recycle(); + } catch (Resources.NotFoundException nfe) { + XposedBridge.log(nfe); + } + XposedBridge.removeFinalFlagNative(resClass); + XposedBridge.removeFinalFlagNative(taClass); + DexMaker dexMaker = new DexMaker(); + dexMaker.declare(TypeId.get("Lxposed/dummy/XResourcesSuperClass;"), + "XResourcesSuperClass.java", + Modifier.PUBLIC, TypeId.get(resClass)); + dexMaker.declare(TypeId.get("Lxposed/dummy/XTypedArraySuperClass;"), + "XTypedArraySuperClass.java", + Modifier.PUBLIC, TypeId.get(taClass)); + ClassLoader myCL = XposedBridge.class.getClassLoader(); + dummyClassLoader = new InMemoryDexClassLoader( + ByteBuffer.wrap(dexMaker.generate()), myCL.getParent()); + dummyClassLoader.loadClass("xposed.dummy.XResourcesSuperClass"); + dummyClassLoader.loadClass("xposed.dummy.XTypedArraySuperClass"); + setObjectField(myCL, "parent", dummyClassLoader); + } catch (Throwable throwable) { + XposedBridge.log(throwable); + XposedInit.disableResources = true; + } + } + +// private static boolean hadInitErrors() { +// // ed: assuming never had errors +// return false; +// } +// private static native int getRuntime(); +// /*package*/ static native boolean startsSystemServer(); +// /*package*/ static native String getStartClassName(); +// /*package*/ native static boolean initXResourcesNative(); + + /** + * Returns the currently installed version of the Xposed framework. + */ + public static int getXposedVersion() { + return BuildConfig.API_CODE; + } + + /** + * Writes a message to the Xposed modules log. + * + *

DON'T FLOOD THE LOG!!! This is only meant for error logging. + * If you want to write information/debug messages, use logcat. + * + * @param text The log message. + */ + public synchronized static void log(String text) { + if (EdXpConfigGlobal.getConfig().isNoModuleLogEnabled()) { + return; + } + Log.i(TAG, text); + } + + /** + * Logs a stack trace to the Xposed modules log. + * + *

DON'T FLOOD THE LOG!!! This is only meant for error logging. + * If you want to write information/debug messages, use logcat. + * + * @param t The Throwable object for the stack trace. + */ + public synchronized static void log(Throwable t) { + Log.e(TAG, Log.getStackTraceString(t)); + } + + /** + * Hook any method (or constructor) with the specified callback. See below for some wrappers + * that make it easier to find a method/constructor in one step. + * + * @param hookMethod The method to be hooked. + * @param callback The callback to be executed when the hooked method is called. + * @return An object that can be used to remove the hook. + * + * @see XposedHelpers#findAndHookMethod(String, ClassLoader, String, Object...) + * @see XposedHelpers#findAndHookMethod(Class, String, Object...) + * @see #hookAllMethods + * @see XposedHelpers#findAndHookConstructor(String, ClassLoader, Object...) + * @see XposedHelpers#findAndHookConstructor(Class, Object...) + * @see #hookAllConstructors + */ + public static XC_MethodHook.Unhook hookMethod(Member hookMethod, XC_MethodHook callback) { + if (!(hookMethod instanceof Method) && !(hookMethod instanceof Constructor)) { + throw new IllegalArgumentException("Only methods and constructors can be hooked: " + hookMethod.toString()); + } else if (hookMethod.getDeclaringClass().isInterface()) { + throw new IllegalArgumentException("Cannot hook interfaces: " + hookMethod.toString()); + } else if (Modifier.isAbstract(hookMethod.getModifiers())) { + throw new IllegalArgumentException("Cannot hook abstract methods: " + hookMethod.toString()); + } + + if (callback == null) { + throw new IllegalArgumentException("callback should not be null!"); + } + + boolean newMethod = false; + CopyOnWriteSortedSet callbacks; + synchronized (sHookedMethodCallbacks) { + callbacks = sHookedMethodCallbacks.get(hookMethod); + if (callbacks == null) { + callbacks = new CopyOnWriteSortedSet<>(); + sHookedMethodCallbacks.put(hookMethod, callbacks); + newMethod = true; + } + } + callbacks.add(callback); + + if (newMethod) { + Class declaringClass = hookMethod.getDeclaringClass(); + int slot; + Class[] parameterTypes; + Class returnType; + if (runtime == RUNTIME_ART) { + slot = 0; + parameterTypes = null; + returnType = null; + } else if (hookMethod instanceof Method) { + slot = getIntField(hookMethod, "slot"); + parameterTypes = ((Method) hookMethod).getParameterTypes(); + returnType = ((Method) hookMethod).getReturnType(); + } else { + slot = getIntField(hookMethod, "slot"); + parameterTypes = ((Constructor) hookMethod).getParameterTypes(); + returnType = null; + } + + AdditionalHookInfo additionalInfo = new AdditionalHookInfo(callbacks, parameterTypes, returnType); + Member reflectMethod = EdXpConfigGlobal.getHookProvider().findMethodNative(hookMethod); + if (reflectMethod != null) { + hookMethodNative(reflectMethod, declaringClass, slot, additionalInfo); + } else { + PendingHooks.recordPendingMethod(hookMethod, additionalInfo); + } + } + + return callback.new Unhook(hookMethod); + } + + /** + * Removes the callback for a hooked method/constructor. + * + * @deprecated Use {@link XC_MethodHook.Unhook#unhook} instead. An instance of the {@code Unhook} + * class is returned when you hook the method. + * + * @param hookMethod The method for which the callback should be removed. + * @param callback The reference to the callback as specified in {@link #hookMethod}. + */ + @Deprecated + public static void unhookMethod(Member hookMethod, XC_MethodHook callback) { + EdXpConfigGlobal.getHookProvider().unhookMethod(hookMethod); + CopyOnWriteSortedSet callbacks; + synchronized (sHookedMethodCallbacks) { + callbacks = sHookedMethodCallbacks.get(hookMethod); + if (callbacks == null) + return; + } + callbacks.remove(callback); + } + + /** + * Hooks all methods with a certain name that were declared in the specified class. Inherited + * methods and constructors are not considered. For constructors, use + * {@link #hookAllConstructors} instead. + * + * @param hookClass The class to check for declared methods. + * @param methodName The name of the method(s) to hook. + * @param callback The callback to be executed when the hooked methods are called. + * @return A set containing one object for each found method which can be used to unhook it. + */ + @SuppressWarnings("UnusedReturnValue") + public static Set hookAllMethods(Class hookClass, String methodName, XC_MethodHook callback) { + Set unhooks = new HashSet<>(); + for (Member method : hookClass.getDeclaredMethods()) + if (method.getName().equals(methodName)) + unhooks.add(hookMethod(method, callback)); + return unhooks; + } + + /** + * Hook all constructors of the specified class. + * + * @param hookClass The class to check for constructors. + * @param callback The callback to be executed when the hooked constructors are called. + * @return A set containing one object for each found constructor which can be used to unhook it. + */ + @SuppressWarnings("UnusedReturnValue") + public static Set hookAllConstructors(Class hookClass, XC_MethodHook callback) { + Set unhooks = new HashSet<>(); + for (Member constructor : hookClass.getDeclaredConstructors()) + unhooks.add(hookMethod(constructor, callback)); + return unhooks; + } + + /** + * This method is called as a replacement for hooked methods. + */ + public static Object handleHookedMethod(Member method, long originalMethodId, Object additionalInfoObj, + Object thisObject, Object[] args) throws Throwable { + AdditionalHookInfo additionalInfo = (AdditionalHookInfo) additionalInfoObj; + + if (disableHooks) { + try { + return invokeOriginalMethodNative(method, originalMethodId, additionalInfo.parameterTypes, + additionalInfo.returnType, thisObject, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + + Object[] callbacksSnapshot = additionalInfo.callbacks.getSnapshot(); + final int callbacksLength = callbacksSnapshot.length; + if (callbacksLength == 0) { + try { + return invokeOriginalMethodNative(method, originalMethodId, additionalInfo.parameterTypes, + additionalInfo.returnType, thisObject, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + + MethodHookParam param = new MethodHookParam(); + param.method = method; + param.thisObject = thisObject; + param.args = args; + + // call "before method" callbacks + int beforeIdx = 0; + do { + try { + ((XC_MethodHook) callbacksSnapshot[beforeIdx]).beforeHookedMethod(param); + } catch (Throwable t) { + XposedBridge.log(t); + + // reset result (ignoring what the unexpectedly exiting callback did) + param.setResult(null); + param.returnEarly = false; + continue; + } + + if (param.returnEarly) { + // skip remaining "before" callbacks and corresponding "after" callbacks + beforeIdx++; + break; + } + } while (++beforeIdx < callbacksLength); + + // call original method if not requested otherwise + if (!param.returnEarly) { + try { + param.setResult(invokeOriginalMethodNative(method, originalMethodId, + additionalInfo.parameterTypes, additionalInfo.returnType, param.thisObject, param.args)); + } catch (InvocationTargetException e) { + param.setThrowable(e.getCause()); + } + } + + // call "after method" callbacks + int afterIdx = beforeIdx - 1; + do { + Object lastResult = param.getResult(); + Throwable lastThrowable = param.getThrowable(); + + try { + ((XC_MethodHook) callbacksSnapshot[afterIdx]).afterHookedMethod(param); + } catch (Throwable t) { + XposedBridge.log(t); + + // reset to last result (ignoring what the unexpectedly exiting callback did) + if (lastThrowable == null) + param.setResult(lastResult); + else + param.setThrowable(lastThrowable); + } + } while (--afterIdx >= 0); + + // return + if (param.hasThrowable()) + throw param.getThrowable(); + else + return param.getResult(); + } + + /** + * Adds a callback to be executed when an app ("Android package") is loaded. + * + *

You probably don't need to call this. Simply implement {@link IXposedHookLoadPackage} + * in your module class and Xposed will take care of registering it as a callback. + * + * @param callback The callback to be executed. + * @hide + */ + public static void hookLoadPackage(XC_LoadPackage callback) { + synchronized (sLoadedPackageCallbacks) { + sLoadedPackageCallbacks.add(callback); + } + } + + public static void clearLoadedPackages() { + synchronized (sLoadedPackageCallbacks) { + sLoadedPackageCallbacks.clear(); + } + } + + /** + * Adds a callback to be executed when the resources for an app are initialized. + * + *

You probably don't need to call this. Simply implement {@link IXposedHookInitPackageResources} + * in your module class and Xposed will take care of registering it as a callback. + * + * @param callback The callback to be executed. + * @hide + */ + public static void hookInitPackageResources(XC_InitPackageResources callback) { + synchronized (sInitPackageResourcesCallbacks) { + sInitPackageResourcesCallbacks.add(callback); + } + } + + public static void clearInitPackageResources() { + synchronized (sInitPackageResourcesCallbacks) { + sInitPackageResourcesCallbacks.clear(); + } + } + + public static void hookInitZygote(XC_InitZygote callback) { + synchronized (sInitZygoteCallbacks) { + sInitZygoteCallbacks.add(callback); + } + } + + public static void clearInitZygotes() { + synchronized (sInitZygoteCallbacks) { + sInitZygoteCallbacks.clear(); + } + } + + public static void callInitZygotes() { + XCallback.callAll(new IXposedHookZygoteInit.StartupParam(sInitZygoteCallbacks)); + } + + public static void clearAllCallbacks() { + clearLoadedPackages(); + clearInitPackageResources(); + clearInitZygotes(); + } + + /** + * Intercept every call to the specified method and call a handler function instead. + * @param method The method to intercept + */ + /*package*/ synchronized static void hookMethodNative(final Member method, Class declaringClass, + int slot, final Object additionalInfoObj) { + EdXpConfigGlobal.getHookProvider().hookMethod(method, (AdditionalHookInfo) additionalInfoObj); + } + + private static Object invokeOriginalMethodNative(Member method, long methodId, + Class[] parameterTypes, + Class returnType, + Object thisObject, Object[] args) + throws Throwable { + return EdXpConfigGlobal.getHookProvider().invokeOriginalMethod(method, methodId, thisObject, args); + } + + /** + * Basically the same as {@link Method#invoke}, but calls the original method + * as it was before the interception by Xposed. Also, access permissions are not checked. + * + *

There are very few cases where this method is needed. A common mistake is + * to replace a method and then invoke the original one based on dynamic conditions. This + * creates overhead and skips further hooks by other modules. Instead, just hook (don't replace) + * the method and call {@code param.setResult(null)} in {@link XC_MethodHook#beforeHookedMethod} + * if the original method should be skipped. + * + * @param method The method to be called. + * @param thisObject For non-static calls, the "this" pointer, otherwise {@code null}. + * @param args Arguments for the method call as Object[] array. + * @return The result returned from the invoked method. + * @throws NullPointerException + * if {@code receiver == null} for a non-static method + * @throws IllegalAccessException + * if this method is not accessible (see {@link AccessibleObject}) + * @throws IllegalArgumentException + * if the number of arguments doesn't match the number of parameters, the receiver + * is incompatible with the declaring class, or an argument could not be unboxed + * or converted by a widening conversion to the corresponding parameter type + * @throws InvocationTargetException + * if an exception was thrown by the invoked method + */ + public static Object invokeOriginalMethod(Member method, Object thisObject, Object[] args) + throws Throwable { + if (args == null) { + args = EMPTY_ARRAY; + } + + Class[] parameterTypes; + Class returnType; + if (runtime == RUNTIME_ART && (method instanceof Method || method instanceof Constructor)) { + parameterTypes = null; + returnType = null; + } else if (method instanceof Method) { + parameterTypes = ((Method) method).getParameterTypes(); + returnType = ((Method) method).getReturnType(); + } else if (method instanceof Constructor) { + parameterTypes = ((Constructor) method).getParameterTypes(); + returnType = null; + } else { + throw new IllegalArgumentException("method must be of type Method or Constructor"); + } + + long methodId = EdXpConfigGlobal.getHookProvider().getMethodId(method); + return invokeOriginalMethodNative(method, methodId, parameterTypes, returnType, thisObject, args); + } + + /*package*/ static void setObjectClass(Object obj, Class clazz) { + if (clazz.isAssignableFrom(obj.getClass())) { + throw new IllegalArgumentException("Cannot transfer object from " + obj.getClass() + " to " + clazz); + } + setObjectClassNative(obj, clazz); + } + + private static native void setObjectClassNative(Object obj, Class clazz); + /*package*/ static native void dumpObjectNative(Object obj); + + /*package*/ static Object cloneToSubclass(Object obj, Class targetClazz) { + if (obj == null) + return null; + + if (!obj.getClass().isAssignableFrom(targetClazz)) + throw new ClassCastException(targetClazz + " doesn't extend " + obj.getClass()); + + return cloneToSubclassNative(obj, targetClazz); + } + + private static native Object cloneToSubclassNative(Object obj, Class targetClazz); + + private static void removeFinalFlagNative(Class clazz) { + EdXpConfigGlobal.getHookProvider().removeFinalFlagNative(clazz); + } + +// /*package*/ static native void closeFilesBeforeForkNative(); +// /*package*/ static native void reopenFilesAfterForkNative(); +// +// /*package*/ static native void invalidateCallersNative(Member[] methods); + + /** @hide */ + public static final class CopyOnWriteSortedSet { + private transient volatile Object[] elements = EMPTY_ARRAY; + + @SuppressWarnings("UnusedReturnValue") + public synchronized boolean add(E e) { + int index = indexOf(e); + if (index >= 0) + return false; + + Object[] newElements = new Object[elements.length + 1]; + System.arraycopy(elements, 0, newElements, 0, elements.length); + newElements[elements.length] = e; + Arrays.sort(newElements); + elements = newElements; + return true; + } + + @SuppressWarnings("UnusedReturnValue") + public synchronized boolean remove(E e) { + int index = indexOf(e); + if (index == -1) + return false; + + Object[] newElements = new Object[elements.length - 1]; + System.arraycopy(elements, 0, newElements, 0, index); + System.arraycopy(elements, index + 1, newElements, index, elements.length - index - 1); + elements = newElements; + return true; + } + + private int indexOf(Object o) { + for (int i = 0; i < elements.length; i++) { + if (o.equals(elements[i])) + return i; + } + return -1; + } + + public Object[] getSnapshot() { + return elements; + } + + public synchronized void clear() { + elements = EMPTY_ARRAY; + } + } + + public static class AdditionalHookInfo { + public final CopyOnWriteSortedSet callbacks; + public final Class[] parameterTypes; + public final Class returnType; + + private AdditionalHookInfo(CopyOnWriteSortedSet callbacks, Class[] parameterTypes, Class returnType) { + this.callbacks = callbacks; + this.parameterTypes = parameterTypes; + this.returnType = returnType; + } + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/XposedHelpers.java b/edxp-core/src/main/java/de/robv/android/xposed/XposedHelpers.java new file mode 100644 index 00000000..337cd4f9 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/XposedHelpers.java @@ -0,0 +1,1725 @@ +package de.robv.android.xposed; + +import android.content.res.AssetManager; +import android.content.res.Resources; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.WeakHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.zip.ZipFile; + +import dalvik.system.DexFile; +import external.org.apache.commons.lang3.ClassUtils; +import external.org.apache.commons.lang3.reflect.MemberUtils; + +/** + * Helpers that simplify hooking and calling methods/constructors, getting and settings fields, ... + */ +public final class XposedHelpers { + private XposedHelpers() {} + + private static final HashMap fieldCache = new HashMap<>(); + private static final HashMap methodCache = new HashMap<>(); + private static final HashMap> constructorCache = new HashMap<>(); + private static final WeakHashMap> additionalFields = new WeakHashMap<>(); + private static final HashMap> sMethodDepth = new HashMap<>(); + + /** + * Look up a class with the specified class loader. + * + *

There are various allowed syntaxes for the class name, but it's recommended to use one of + * these: + *

    + *
  • {@code java.lang.String} + *
  • {@code java.lang.String[]} (array) + *
  • {@code android.app.ActivityThread.ResourcesKey} + *
  • {@code android.app.ActivityThread$ResourcesKey} + *
+ * + * @param className The class name in one of the formats mentioned above. + * @param classLoader The class loader, or {@code null} for the boot class loader. + * @return A reference to the class. + * @throws ClassNotFoundError In case the class was not found. + */ + public static Class findClass(String className, ClassLoader classLoader) { + if (classLoader == null) + classLoader = XposedBridge.BOOTCLASSLOADER; + try { + return ClassUtils.getClass(classLoader, className, false); + } catch (ClassNotFoundException e) { + throw new ClassNotFoundError(e); + } + } + + /** + * Look up and return a class if it exists. + * Like {@link #findClass}, but doesn't throw an exception if the class doesn't exist. + * + * @param className The class name. + * @param classLoader The class loader, or {@code null} for the boot class loader. + * @return A reference to the class, or {@code null} if it doesn't exist. + */ + public static Class findClassIfExists(String className, ClassLoader classLoader) { + try { + return findClass(className, classLoader); + } catch (ClassNotFoundError e) { + return null; + } + } + + /** + * Look up a field in a class and set it to accessible. + * + * @param clazz The class which either declares or inherits the field. + * @param fieldName The field name. + * @return A reference to the field. + * @throws NoSuchFieldError In case the field was not found. + */ + public static Field findField(Class clazz, String fieldName) { + String fullFieldName = clazz.getName() + '#' + fieldName; + + if (fieldCache.containsKey(fullFieldName)) { + Field field = fieldCache.get(fullFieldName); + if (field == null) + throw new NoSuchFieldError(fullFieldName); + return field; + } + + try { + Field field = findFieldRecursiveImpl(clazz, fieldName); + field.setAccessible(true); + fieldCache.put(fullFieldName, field); + return field; + } catch (NoSuchFieldException e) { + fieldCache.put(fullFieldName, null); + throw new NoSuchFieldError(fullFieldName); + } + } + + /** + * Look up and return a field if it exists. + * Like {@link #findField}, but doesn't throw an exception if the field doesn't exist. + * + * @param clazz The class which either declares or inherits the field. + * @param fieldName The field name. + * @return A reference to the field, or {@code null} if it doesn't exist. + */ + public static Field findFieldIfExists(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName); + } catch (NoSuchFieldError e) { + return null; + } + } + + private static Field findFieldRecursiveImpl(Class clazz, String fieldName) throws NoSuchFieldException { + try { + return clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + while (true) { + clazz = clazz.getSuperclass(); + if (clazz == null || clazz.equals(Object.class)) + break; + + try { + return clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException ignored) {} + } + throw e; + } + } + + /** + * Returns the first field of the given type in a class. + * Might be useful for Proguard'ed classes to identify fields with unique types. + * + * @param clazz The class which either declares or inherits the field. + * @param type The type of the field. + * @return A reference to the first field of the given type. + * @throws NoSuchFieldError In case no matching field was not found. + */ + public static Field findFirstFieldByExactType(Class clazz, Class type) { + Class clz = clazz; + do { + for (Field field : clz.getDeclaredFields()) { + if (field.getType() == type) { + field.setAccessible(true); + return field; + } + } + } while ((clz = clz.getSuperclass()) != null); + + throw new NoSuchFieldError("Field of type " + type.getName() + " in class " + clazz.getName()); + } + + /** + * Look up a method and hook it. See {@link #findAndHookMethod(String, ClassLoader, String, Object...)} + * for details. + */ + public static XC_MethodHook.Unhook findAndHookMethod(Class clazz, String methodName, Object... parameterTypesAndCallback) { + if (parameterTypesAndCallback.length == 0 || !(parameterTypesAndCallback[parameterTypesAndCallback.length-1] instanceof XC_MethodHook)) + throw new IllegalArgumentException("no callback defined"); + + XC_MethodHook callback = (XC_MethodHook) parameterTypesAndCallback[parameterTypesAndCallback.length-1]; + Method m = findMethodExact(clazz, methodName, getParameterClasses(clazz.getClassLoader(), parameterTypesAndCallback)); + + return XposedBridge.hookMethod(m, callback); + } + + /** + * Look up a method and hook it. The last argument must be the callback for the hook. + * + *

This combines calls to {@link #findMethodExact(Class, String, Object...)} and + * {@link XposedBridge#hookMethod}. + * + *

The method must be declared or overridden in the given class, inherited + * methods are not considered! That's because each method implementation exists only once in + * the memory, and when classes inherit it, they just get another reference to the implementation. + * Hooking a method therefore applies to all classes inheriting the same implementation. You + * have to expect that the hook applies to subclasses (unless they override the method), but you + * shouldn't have to worry about hooks applying to superclasses, hence this "limitation". + * There could be undesired or even dangerous hooks otherwise, e.g. if you hook + * {@code SomeClass.equals()} and that class doesn't override the {@code equals()} on some ROMs, + * making you hook {@code Object.equals()} instead. + * + *

There are two ways to specify the parameter types. If you already have a reference to the + * {@link Class}, use that. For Android framework classes, you can often use something like + * {@code String.class}. If you don't have the class reference, you can simply use the + * full class name as a string, e.g. {@code java.lang.String} or {@code com.example.MyClass}. + * It will be passed to {@link #findClass} with the same class loader that is used for the target + * method, see its documentation for the allowed notations. + * + *

Primitive types, such as {@code int}, can be specified using {@code int.class} (recommended) + * or {@code Integer.TYPE}. Note that {@code Integer.class} doesn't refer to {@code int} but to + * {@code Integer}, which is a normal class (boxed primitive). Therefore it must not be used when + * the method expects an {@code int} parameter - it has to be used for {@code Integer} parameters + * though, so check the method signature in detail. + * + *

As last argument to this method (after the list of target method parameters), you need + * to specify the callback that should be executed when the method is invoked. It's usually + * an anonymous subclass of {@link XC_MethodHook} or {@link XC_MethodReplacement}. + * + *

Example + *

+	 * // In order to hook this method ...
+	 * package com.example;
+	 * public class SomeClass {
+	 *   public int doSomething(String s, int i, MyClass m) {
+	 *     ...
+	 *   }
+	 * }
+	 *
+	 * // ... you can use this call:
+	 * findAndHookMethod("com.example.SomeClass", lpparam.classLoader, String.class, int.class, "com.example.MyClass", new XC_MethodHook() {
+	 *   @Override
+	 *   protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
+	 *     String oldText = (String) param.args[0];
+	 *     Log.d("MyModule", oldText);
+	 *
+	 *     param.args[0] = "test";
+	 *     param.args[1] = 42; // auto-boxing is working here
+	 *     setBooleanField(param.args[2], "great", true);
+	 *
+	 *     // This would not work (as MyClass can't be resolved at compile time):
+	 *     //   MyClass myClass = (MyClass) param.args[2];
+	 *     //   myClass.great = true;
+	 *   }
+	 * });
+	 * 
+ * + * @param className The name of the class which implements the method. + * @param classLoader The class loader for resolving the target and parameter classes. + * @param methodName The target method name. + * @param parameterTypesAndCallback The parameter types of the target method, plus the callback. + * @throws NoSuchMethodError In case the method was not found. + * @throws ClassNotFoundError In case the target class or one of the parameter types couldn't be resolved. + * @return An object which can be used to remove the callback again. + */ + public static XC_MethodHook.Unhook findAndHookMethod(String className, ClassLoader classLoader, String methodName, Object... parameterTypesAndCallback) { + return findAndHookMethod(findClass(className, classLoader), methodName, parameterTypesAndCallback); + } + + /** + * Look up a method in a class and set it to accessible. + * See {@link #findMethodExact(String, ClassLoader, String, Object...)} for details. + */ + public static Method findMethodExact(Class clazz, String methodName, Object... parameterTypes) { + return findMethodExact(clazz, methodName, getParameterClasses(clazz.getClassLoader(), parameterTypes)); + } + + /** + * Look up and return a method if it exists. + * See {@link #findMethodExactIfExists(String, ClassLoader, String, Object...)} for details. + */ + public static Method findMethodExactIfExists(Class clazz, String methodName, Object... parameterTypes) { + try { + return findMethodExact(clazz, methodName, parameterTypes); + } catch (ClassNotFoundError | NoSuchMethodError e) { + return null; + } + } + + /** + * Look up a method in a class and set it to accessible. + * The method must be declared or overridden in the given class. + * + *

See {@link #findAndHookMethod(String, ClassLoader, String, Object...)} for details about + * the method and parameter type resolution. + * + * @param className The name of the class which implements the method. + * @param classLoader The class loader for resolving the target and parameter classes. + * @param methodName The target method name. + * @param parameterTypes The parameter types of the target method. + * @throws NoSuchMethodError In case the method was not found. + * @throws ClassNotFoundError In case the target class or one of the parameter types couldn't be resolved. + * @return A reference to the method. + */ + public static Method findMethodExact(String className, ClassLoader classLoader, String methodName, Object... parameterTypes) { + return findMethodExact(findClass(className, classLoader), methodName, getParameterClasses(classLoader, parameterTypes)); + } + + /** + * Look up and return a method if it exists. + * Like {@link #findMethodExact(String, ClassLoader, String, Object...)}, but doesn't throw an + * exception if the method doesn't exist. + * + * @param className The name of the class which implements the method. + * @param classLoader The class loader for resolving the target and parameter classes. + * @param methodName The target method name. + * @param parameterTypes The parameter types of the target method. + * @return A reference to the method, or {@code null} if it doesn't exist. + */ + public static Method findMethodExactIfExists(String className, ClassLoader classLoader, String methodName, Object... parameterTypes) { + try { + return findMethodExact(className, classLoader, methodName, parameterTypes); + } catch (ClassNotFoundError | NoSuchMethodError e) { + return null; + } + } + + /** + * Look up a method in a class and set it to accessible. + * See {@link #findMethodExact(String, ClassLoader, String, Object...)} for details. + * + *

This variant requires that you already have reference to all the parameter types. + */ + public static Method findMethodExact(Class clazz, String methodName, Class... parameterTypes) { + String fullMethodName = clazz.getName() + '#' + methodName + getParametersString(parameterTypes) + "#exact"; + + if (methodCache.containsKey(fullMethodName)) { + Method method = methodCache.get(fullMethodName); + if (method == null) + throw new NoSuchMethodError(fullMethodName); + return method; + } + + try { + Method method = clazz.getDeclaredMethod(methodName, parameterTypes); + method.setAccessible(true); + methodCache.put(fullMethodName, method); + return method; + } catch (NoSuchMethodException e) { + methodCache.put(fullMethodName, null); + throw new NoSuchMethodError(fullMethodName); + } + } + + /** + * Returns an array of all methods declared/overridden in a class with the specified parameter types. + * + *

The return type is optional, it will not be compared if it is {@code null}. + * Use {@code void.class} if you want to search for methods returning nothing. + * + * @param clazz The class to look in. + * @param returnType The return type, or {@code null} (see above). + * @param parameterTypes The parameter types. + * @return An array with matching methods, all set to accessible already. + */ + public static Method[] findMethodsByExactParameters(Class clazz, Class returnType, Class... parameterTypes) { + List result = new LinkedList<>(); + for (Method method : clazz.getDeclaredMethods()) { + if (returnType != null && returnType != method.getReturnType()) + continue; + + Class[] methodParameterTypes = method.getParameterTypes(); + if (parameterTypes.length != methodParameterTypes.length) + continue; + + boolean match = true; + for (int i = 0; i < parameterTypes.length; i++) { + if (parameterTypes[i] != methodParameterTypes[i]) { + match = false; + break; + } + } + + if (!match) + continue; + + method.setAccessible(true); + result.add(method); + } + return result.toArray(new Method[result.size()]); + } + + /** + * Look up a method in a class and set it to accessible. + * + *

This does'nt only look for exact matches, but for the best match. All considered candidates + * must be compatible with the given parameter types, i.e. the parameters must be assignable + * to the method's formal parameters. Inherited methods are considered here. + * + * @param clazz The class which declares, inherits or overrides the method. + * @param methodName The method name. + * @param parameterTypes The types of the method's parameters. + * @return A reference to the best-matching method. + * @throws NoSuchMethodError In case no suitable method was found. + */ + public static Method findMethodBestMatch(Class clazz, String methodName, Class... parameterTypes) { + String fullMethodName = clazz.getName() + '#' + methodName + getParametersString(parameterTypes) + "#bestmatch"; + + if (methodCache.containsKey(fullMethodName)) { + Method method = methodCache.get(fullMethodName); + if (method == null) + throw new NoSuchMethodError(fullMethodName); + return method; + } + + try { + Method method = findMethodExact(clazz, methodName, parameterTypes); + methodCache.put(fullMethodName, method); + return method; + } catch (NoSuchMethodError ignored) {} + + Method bestMatch = null; + Class clz = clazz; + boolean considerPrivateMethods = true; + do { + for (Method method : clz.getDeclaredMethods()) { + // don't consider private methods of superclasses + if (!considerPrivateMethods && Modifier.isPrivate(method.getModifiers())) + continue; + + // 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; + } + } + } + considerPrivateMethods = false; + } while ((clz = clz.getSuperclass()) != null); + + if (bestMatch != null) { + bestMatch.setAccessible(true); + methodCache.put(fullMethodName, bestMatch); + return bestMatch; + } else { + NoSuchMethodError e = new NoSuchMethodError(fullMethodName); + methodCache.put(fullMethodName, null); + throw e; + } + } + + /** + * Look up a method in a class and set it to accessible. + * + *

See {@link #findMethodBestMatch(Class, String, Class...)} for details. This variant + * determines the parameter types from the classes of the given objects. + */ + public static Method findMethodBestMatch(Class clazz, String methodName, Object... args) { + return findMethodBestMatch(clazz, methodName, getParameterTypes(args)); + } + + /** + * Look up a method in a class and set it to accessible. + * + *

See {@link #findMethodBestMatch(Class, String, Class...)} for details. This variant + * determines the parameter types from the classes of the given objects. For any item that is + * {@code null}, the type is taken from {@code parameterTypes} instead. + */ + public static Method findMethodBestMatch(Class clazz, String methodName, Class[] parameterTypes, Object[] args) { + Class[] argsClasses = null; + for (int i = 0; i < parameterTypes.length; i++) { + if (parameterTypes[i] != null) + continue; + if (argsClasses == null) + argsClasses = getParameterTypes(args); + parameterTypes[i] = argsClasses[i]; + } + return findMethodBestMatch(clazz, methodName, parameterTypes); + } + + /** + * Returns an array with the classes of the given objects. + */ + public static Class[] getParameterTypes(Object... args) { + Class[] clazzes = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + clazzes[i] = (args[i] != null) ? args[i].getClass() : null; + } + return clazzes; + } + + /** + * Retrieve classes from an array, where each element might either be a Class + * already, or a String with the full class name. + */ + private static Class[] getParameterClasses(ClassLoader classLoader, Object[] parameterTypesAndCallback) { + Class[] parameterClasses = null; + for (int i = parameterTypesAndCallback.length - 1; i >= 0; i--) { + Object type = parameterTypesAndCallback[i]; + if (type == null) + throw new ClassNotFoundError("parameter type must not be null", null); + + // ignore trailing callback + if (type instanceof XC_MethodHook) + continue; + + if (parameterClasses == null) + parameterClasses = new Class[i+1]; + + if (type instanceof Class) + parameterClasses[i] = (Class) type; + else if (type instanceof String) + parameterClasses[i] = findClass((String) type, classLoader); + else + throw new ClassNotFoundError("parameter type must either be specified as Class or String", null); + } + + // if there are no arguments for the method + if (parameterClasses == null) + parameterClasses = new Class[0]; + + return parameterClasses; + } + + /** + * Returns an array of the given classes. + */ + public static Class[] getClassesAsArray(Class... clazzes) { + return clazzes; + } + + private static String getParametersString(Class... clazzes) { + StringBuilder sb = new StringBuilder("("); + boolean first = true; + for (Class clazz : clazzes) { + if (first) + first = false; + else + sb.append(","); + + if (clazz != null) + sb.append(clazz.getCanonicalName()); + else + sb.append("null"); + } + sb.append(")"); + return sb.toString(); + } + + /** + * Look up a constructor of a class and set it to accessible. + * See {@link #findMethodExact(String, ClassLoader, String, Object...)} for details. + */ + public static Constructor findConstructorExact(Class clazz, Object... parameterTypes) { + return findConstructorExact(clazz, getParameterClasses(clazz.getClassLoader(), parameterTypes)); + } + + /** + * Look up and return a constructor if it exists. + * See {@link #findMethodExactIfExists(String, ClassLoader, String, Object...)} for details. + */ + public static Constructor findConstructorExactIfExists(Class clazz, Object... parameterTypes) { + try { + return findConstructorExact(clazz, parameterTypes); + } catch (ClassNotFoundError | NoSuchMethodError e) { + return null; + } + } + + /** + * Look up a constructor of a class and set it to accessible. + * See {@link #findMethodExact(String, ClassLoader, String, Object...)} for details. + */ + public static Constructor findConstructorExact(String className, ClassLoader classLoader, Object... parameterTypes) { + return findConstructorExact(findClass(className, classLoader), getParameterClasses(classLoader, parameterTypes)); + } + + /** + * Look up and return a constructor if it exists. + * See {@link #findMethodExactIfExists(String, ClassLoader, String, Object...)} for details. + */ + public static Constructor findConstructorExactIfExists(String className, ClassLoader classLoader, Object... parameterTypes) { + try { + return findConstructorExact(className, classLoader, parameterTypes); + } catch (ClassNotFoundError | NoSuchMethodError e) { + return null; + } + } + + /** + * Look up a constructor of a class and set it to accessible. + * See {@link #findMethodExact(String, ClassLoader, String, Object...)} for details. + */ + public static Constructor findConstructorExact(Class clazz, Class... parameterTypes) { + String fullConstructorName = clazz.getName() + getParametersString(parameterTypes) + "#exact"; + + if (constructorCache.containsKey(fullConstructorName)) { + Constructor constructor = constructorCache.get(fullConstructorName); + if (constructor == null) + throw new NoSuchMethodError(fullConstructorName); + return constructor; + } + + try { + Constructor constructor = clazz.getDeclaredConstructor(parameterTypes); + constructor.setAccessible(true); + constructorCache.put(fullConstructorName, constructor); + return constructor; + } catch (NoSuchMethodException e) { + constructorCache.put(fullConstructorName, null); + throw new NoSuchMethodError(fullConstructorName); + } + } + + /** + * Look up a constructor and hook it. See {@link #findAndHookMethod(String, ClassLoader, String, Object...)} + * for details. + */ + public static XC_MethodHook.Unhook findAndHookConstructor(Class clazz, Object... parameterTypesAndCallback) { + if (parameterTypesAndCallback.length == 0 || !(parameterTypesAndCallback[parameterTypesAndCallback.length-1] instanceof XC_MethodHook)) + throw new IllegalArgumentException("no callback defined"); + + XC_MethodHook callback = (XC_MethodHook) parameterTypesAndCallback[parameterTypesAndCallback.length-1]; + Constructor m = findConstructorExact(clazz, getParameterClasses(clazz.getClassLoader(), parameterTypesAndCallback)); + + return XposedBridge.hookMethod(m, callback); + } + + /** + * Look up a constructor and hook it. See {@link #findAndHookMethod(String, ClassLoader, String, Object...)} + * for details. + */ + public static XC_MethodHook.Unhook findAndHookConstructor(String className, ClassLoader classLoader, Object... parameterTypesAndCallback) { + return findAndHookConstructor(findClass(className, classLoader), parameterTypesAndCallback); + } + + /** + * Look up a constructor in a class and set it to accessible. + * + *

See {@link #findMethodBestMatch(Class, String, Class...)} for details. + */ + public static Constructor findConstructorBestMatch(Class clazz, Class... parameterTypes) { + String fullConstructorName = clazz.getName() + getParametersString(parameterTypes) + "#bestmatch"; + + if (constructorCache.containsKey(fullConstructorName)) { + Constructor constructor = constructorCache.get(fullConstructorName); + if (constructor == null) + throw new NoSuchMethodError(fullConstructorName); + return constructor; + } + + try { + Constructor constructor = findConstructorExact(clazz, parameterTypes); + constructorCache.put(fullConstructorName, constructor); + return constructor; + } catch (NoSuchMethodError ignored) {} + + Constructor bestMatch = null; + Constructor[] constructors = clazz.getDeclaredConstructors(); + for (Constructor constructor : constructors) { + // compare name and parameters + if (ClassUtils.isAssignable(parameterTypes, constructor.getParameterTypes(), true)) { + // get accessible version of method + if (bestMatch == null || MemberUtils.compareParameterTypes( + constructor.getParameterTypes(), + bestMatch.getParameterTypes(), + parameterTypes) < 0) { + bestMatch = constructor; + } + } + } + + if (bestMatch != null) { + bestMatch.setAccessible(true); + constructorCache.put(fullConstructorName, bestMatch); + return bestMatch; + } else { + NoSuchMethodError e = new NoSuchMethodError(fullConstructorName); + constructorCache.put(fullConstructorName, null); + throw e; + } + } + + /** + * Look up a constructor in a class and set it to accessible. + * + *

See {@link #findMethodBestMatch(Class, String, Class...)} for details. This variant + * determines the parameter types from the classes of the given objects. + */ + public static Constructor findConstructorBestMatch(Class clazz, Object... args) { + return findConstructorBestMatch(clazz, getParameterTypes(args)); + } + + /** + * Look up a constructor in a class and set it to accessible. + * + *

See {@link #findMethodBestMatch(Class, String, Class...)} for details. This variant + * determines the parameter types from the classes of the given objects. For any item that is + * {@code null}, the type is taken from {@code parameterTypes} instead. + */ + public static Constructor findConstructorBestMatch(Class clazz, Class[] parameterTypes, Object[] args) { + Class[] argsClasses = null; + for (int i = 0; i < parameterTypes.length; i++) { + if (parameterTypes[i] != null) + continue; + if (argsClasses == null) + argsClasses = getParameterTypes(args); + parameterTypes[i] = argsClasses[i]; + } + return findConstructorBestMatch(clazz, parameterTypes); + } + + /** + * Thrown when a class loader is unable to find a class. Unlike {@link ClassNotFoundException}, + * callers are not forced to explicitly catch this. If uncaught, the error will be passed to the + * next caller in the stack. + */ + public static final class ClassNotFoundError extends Error { + private static final long serialVersionUID = -1070936889459514628L; + + /** @hide */ + public ClassNotFoundError(Throwable cause) { + super(cause); + } + + /** @hide */ + public ClassNotFoundError(String detailMessage, Throwable cause) { + super(detailMessage, cause); + } + } + + /** + * Returns the index of the first parameter declared with the given type. + * + * @throws NoSuchFieldError if there is no parameter with that type. + * @hide + */ + public static int getFirstParameterIndexByType(Member method, Class type) { + Class[] classes = (method instanceof Method) ? + ((Method) method).getParameterTypes() : ((Constructor) method).getParameterTypes(); + for (int i = 0 ; i < classes.length; i++) { + if (classes[i] == type) { + return i; + } + } + throw new NoSuchFieldError("No parameter of type " + type + " found in " + method); + } + + /** + * Returns the index of the parameter declared with the given type, ensuring that there is exactly one such parameter. + * + * @throws NoSuchFieldError if there is no or more than one parameter with that type. + * @hide + */ + public static int getParameterIndexByType(Member method, Class type) { + Class[] classes = (method instanceof Method) ? + ((Method) method).getParameterTypes() : ((Constructor) method).getParameterTypes(); + int idx = -1; + for (int i = 0 ; i < classes.length; i++) { + if (classes[i] == type) { + if (idx == -1) { + idx = i; + } else { + throw new NoSuchFieldError("More than one parameter of type " + type + " found in " + method); + } + } + } + if (idx != -1) { + return idx; + } else { + throw new NoSuchFieldError("No parameter of type " + type + " found in " + method); + } + } + + //################################################################################################# + /** Sets the value of an object field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static void setObjectField(Object obj, String fieldName, Object value) { + try { + findField(obj.getClass(), fieldName).set(obj, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a {@code boolean} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static void setBooleanField(Object obj, String fieldName, boolean value) { + try { + findField(obj.getClass(), fieldName).setBoolean(obj, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a {@code byte} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static void setByteField(Object obj, String fieldName, byte value) { + try { + findField(obj.getClass(), fieldName).setByte(obj, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a {@code char} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static void setCharField(Object obj, String fieldName, char value) { + try { + findField(obj.getClass(), fieldName).setChar(obj, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a {@code double} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static void setDoubleField(Object obj, String fieldName, double value) { + try { + findField(obj.getClass(), fieldName).setDouble(obj, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a {@code float} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static void setFloatField(Object obj, String fieldName, float value) { + try { + findField(obj.getClass(), fieldName).setFloat(obj, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of an {@code int} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static void setIntField(Object obj, String fieldName, int value) { + try { + findField(obj.getClass(), fieldName).setInt(obj, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a {@code long} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static void setLongField(Object obj, String fieldName, long value) { + try { + findField(obj.getClass(), fieldName).setLong(obj, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a {@code short} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static void setShortField(Object obj, String fieldName, short value) { + try { + findField(obj.getClass(), fieldName).setShort(obj, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + //################################################################################################# + /** Returns the value of an object field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static Object getObjectField(Object obj, String fieldName) { + try { + return findField(obj.getClass(), fieldName).get(obj); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** For inner classes, returns the surrounding instance, i.e. the {@code this} reference of the surrounding class. */ + public static Object getSurroundingThis(Object obj) { + return getObjectField(obj, "this$0"); + } + + /** Returns the value of a {@code boolean} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public static boolean getBooleanField(Object obj, String fieldName) { + try { + return findField(obj.getClass(), fieldName).getBoolean(obj); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Returns the value of a {@code byte} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static byte getByteField(Object obj, String fieldName) { + try { + return findField(obj.getClass(), fieldName).getByte(obj); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Returns the value of a {@code char} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static char getCharField(Object obj, String fieldName) { + try { + return findField(obj.getClass(), fieldName).getChar(obj); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Returns the value of a {@code double} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static double getDoubleField(Object obj, String fieldName) { + try { + return findField(obj.getClass(), fieldName).getDouble(obj); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Returns the value of a {@code float} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static float getFloatField(Object obj, String fieldName) { + try { + return findField(obj.getClass(), fieldName).getFloat(obj); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Returns the value of an {@code int} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static int getIntField(Object obj, String fieldName) { + try { + return findField(obj.getClass(), fieldName).getInt(obj); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Returns the value of a {@code long} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static long getLongField(Object obj, String fieldName) { + try { + return findField(obj.getClass(), fieldName).getLong(obj); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Returns the value of a {@code short} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */ + public static short getShortField(Object obj, String fieldName) { + try { + return findField(obj.getClass(), fieldName).getShort(obj); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + //################################################################################################# + /** Sets the value of a static object field in the given class. See also {@link #findField}. */ + public static void setStaticObjectField(Class clazz, String fieldName, Object value) { + try { + findField(clazz, fieldName).set(null, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code boolean} field in the given class. See also {@link #findField}. */ + public static void setStaticBooleanField(Class clazz, String fieldName, boolean value) { + try { + findField(clazz, fieldName).setBoolean(null, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code byte} field in the given class. See also {@link #findField}. */ + public static void setStaticByteField(Class clazz, String fieldName, byte value) { + try { + findField(clazz, fieldName).setByte(null, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code char} field in the given class. See also {@link #findField}. */ + public static void setStaticCharField(Class clazz, String fieldName, char value) { + try { + findField(clazz, fieldName).setChar(null, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code double} field in the given class. See also {@link #findField}. */ + public static void setStaticDoubleField(Class clazz, String fieldName, double value) { + try { + findField(clazz, fieldName).setDouble(null, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code float} field in the given class. See also {@link #findField}. */ + public static void setStaticFloatField(Class clazz, String fieldName, float value) { + try { + findField(clazz, fieldName).setFloat(null, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code int} field in the given class. See also {@link #findField}. */ + public static void setStaticIntField(Class clazz, String fieldName, int value) { + try { + findField(clazz, fieldName).setInt(null, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code long} field in the given class. See also {@link #findField}. */ + public static void setStaticLongField(Class clazz, String fieldName, long value) { + try { + findField(clazz, fieldName).setLong(null, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code short} field in the given class. See also {@link #findField}. */ + public static void setStaticShortField(Class clazz, String fieldName, short value) { + try { + findField(clazz, fieldName).setShort(null, value); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + //################################################################################################# + /** Returns the value of a static object field in the given class. See also {@link #findField}. */ + public static Object getStaticObjectField(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName).get(null); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Returns the value of a static {@code boolean} field in the given class. See also {@link #findField}. */ + public static boolean getStaticBooleanField(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName).getBoolean(null); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code byte} field in the given class. See also {@link #findField}. */ + public static byte getStaticByteField(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName).getByte(null); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code char} field in the given class. See also {@link #findField}. */ + public static char getStaticCharField(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName).getChar(null); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code double} field in the given class. See also {@link #findField}. */ + public static double getStaticDoubleField(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName).getDouble(null); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code float} field in the given class. See also {@link #findField}. */ + public static float getStaticFloatField(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName).getFloat(null); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code int} field in the given class. See also {@link #findField}. */ + public static int getStaticIntField(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName).getInt(null); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code long} field in the given class. See also {@link #findField}. */ + public static long getStaticLongField(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName).getLong(null); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + /** Sets the value of a static {@code short} field in the given class. See also {@link #findField}. */ + public static short getStaticShortField(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName).getShort(null); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + //################################################################################################# + /** + * Calls an instance or static method of the given object. + * The method is resolved using {@link #findMethodBestMatch(Class, String, Object...)}. + * + * @param obj The object instance. A class reference is not sufficient! + * @param methodName The method name. + * @param args The arguments for the method call. + * @throws NoSuchMethodError In case no suitable method was found. + * @throws InvocationTargetError In case an exception was thrown by the invoked method. + */ + public static Object callMethod(Object obj, String methodName, Object... args) { + try { + return findMethodBestMatch(obj.getClass(), methodName, args).invoke(obj, args); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } catch (InvocationTargetException e) { + throw new InvocationTargetError(e.getCause()); + } + } + + /** + * Calls an instance or static method of the given object. + * See {@link #callMethod(Object, String, Object...)}. + * + *

This variant allows you to specify parameter types, which can help in case there are multiple + * methods with the same name, especially if you call it with {@code null} parameters. + */ + public static Object callMethod(Object obj, String methodName, Class[] parameterTypes, Object... args) { + try { + return findMethodBestMatch(obj.getClass(), methodName, parameterTypes, args).invoke(obj, args); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } catch (InvocationTargetException e) { + throw new InvocationTargetError(e.getCause()); + } + } + + /** + * Calls a static method of the given class. + * The method is resolved using {@link #findMethodBestMatch(Class, String, Object...)}. + * + * @param clazz The class reference. + * @param methodName The method name. + * @param args The arguments for the method call. + * @throws NoSuchMethodError In case no suitable method was found. + * @throws InvocationTargetError In case an exception was thrown by the invoked method. + */ + public static Object callStaticMethod(Class clazz, String methodName, Object... args) { + try { + return findMethodBestMatch(clazz, methodName, args).invoke(null, args); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } catch (InvocationTargetException e) { + throw new InvocationTargetError(e.getCause()); + } + } + + /** + * Calls a static method of the given class. + * See {@link #callStaticMethod(Class, String, Object...)}. + * + *

This variant allows you to specify parameter types, which can help in case there are multiple + * methods with the same name, especially if you call it with {@code null} parameters. + */ + public static Object callStaticMethod(Class clazz, String methodName, Class[] parameterTypes, Object... args) { + try { + return findMethodBestMatch(clazz, methodName, parameterTypes, args).invoke(null, args); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } catch (InvocationTargetException e) { + throw new InvocationTargetError(e.getCause()); + } + } + + /** + * This class provides a wrapper for an exception thrown by a method invocation. + * + * @see #callMethod(Object, String, Object...) + * @see #callStaticMethod(Class, String, Object...) + * @see #newInstance(Class, Object...) + */ + public static final class InvocationTargetError extends Error { + private static final long serialVersionUID = -1070936889459514628L; + + /** @hide */ + public InvocationTargetError(Throwable cause) { + super(cause); + } + } + + //################################################################################################# + /** + * Creates a new instance of the given class. + * The constructor is resolved using {@link #findConstructorBestMatch(Class, Object...)}. + * + * @param clazz The class reference. + * @param args The arguments for the constructor call. + * @throws NoSuchMethodError In case no suitable constructor was found. + * @throws InvocationTargetError In case an exception was thrown by the invoked method. + * @throws InstantiationError In case the class cannot be instantiated. + */ + public static Object newInstance(Class clazz, Object... args) { + try { + return findConstructorBestMatch(clazz, args).newInstance(args); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } catch (InvocationTargetException e) { + throw new InvocationTargetError(e.getCause()); + } catch (InstantiationException e) { + throw new InstantiationError(e.getMessage()); + } + } + + /** + * Creates a new instance of the given class. + * See {@link #newInstance(Class, Object...)}. + * + *

This variant allows you to specify parameter types, which can help in case there are multiple + * constructors with the same name, especially if you call it with {@code null} parameters. + */ + public static Object newInstance(Class clazz, Class[] parameterTypes, Object... args) { + try { + return findConstructorBestMatch(clazz, parameterTypes, args).newInstance(args); + } catch (IllegalAccessException e) { + // should not happen + XposedBridge.log(e); + throw new IllegalAccessError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw e; + } catch (InvocationTargetException e) { + throw new InvocationTargetError(e.getCause()); + } catch (InstantiationException e) { + throw new InstantiationError(e.getMessage()); + } + } + + //################################################################################################# + + /** + * Attaches any value to an object instance. This simulates adding an instance field. + * The value can be retrieved again with {@link #getAdditionalInstanceField}. + * + * @param obj The object instance for which the value should be stored. + * @param key The key in the value map for this object instance. + * @param value The value to store. + * @return The previously stored value for this instance/key combination, or {@code null} if there was none. + */ + public static Object setAdditionalInstanceField(Object obj, String key, Object value) { + if (obj == null) + throw new NullPointerException("object must not be null"); + if (key == null) + throw new NullPointerException("key must not be null"); + + HashMap objectFields; + synchronized (additionalFields) { + objectFields = additionalFields.get(obj); + if (objectFields == null) { + objectFields = new HashMap<>(); + additionalFields.put(obj, objectFields); + } + } + + synchronized (objectFields) { + return objectFields.put(key, value); + } + } + + /** + * Returns a value which was stored with {@link #setAdditionalInstanceField}. + * + * @param obj The object instance for which the value has been stored. + * @param key The key in the value map for this object instance. + * @return The stored value for this instance/key combination, or {@code null} if there is none. + */ + public static Object getAdditionalInstanceField(Object obj, String key) { + if (obj == null) + throw new NullPointerException("object must not be null"); + if (key == null) + throw new NullPointerException("key must not be null"); + + HashMap objectFields; + synchronized (additionalFields) { + objectFields = additionalFields.get(obj); + if (objectFields == null) + return null; + } + + synchronized (objectFields) { + return objectFields.get(key); + } + } + + /** + * Removes and returns a value which was stored with {@link #setAdditionalInstanceField}. + * + * @param obj The object instance for which the value has been stored. + * @param key The key in the value map for this object instance. + * @return The previously stored value for this instance/key combination, or {@code null} if there was none. + */ + public static Object removeAdditionalInstanceField(Object obj, String key) { + if (obj == null) + throw new NullPointerException("object must not be null"); + if (key == null) + throw new NullPointerException("key must not be null"); + + HashMap objectFields; + synchronized (additionalFields) { + objectFields = additionalFields.get(obj); + if (objectFields == null) + return null; + } + + synchronized (objectFields) { + return objectFields.remove(key); + } + } + + /** Like {@link #setAdditionalInstanceField}, but the value is stored for the class of {@code obj}. */ + public static Object setAdditionalStaticField(Object obj, String key, Object value) { + return setAdditionalInstanceField(obj.getClass(), key, value); + } + + /** Like {@link #getAdditionalInstanceField}, but the value is returned for the class of {@code obj}. */ + public static Object getAdditionalStaticField(Object obj, String key) { + return getAdditionalInstanceField(obj.getClass(), key); + } + + /** Like {@link #removeAdditionalInstanceField}, but the value is removed and returned for the class of {@code obj}. */ + public static Object removeAdditionalStaticField(Object obj, String key) { + return removeAdditionalInstanceField(obj.getClass(), key); + } + + /** Like {@link #setAdditionalInstanceField}, but the value is stored for {@code clazz}. */ + public static Object setAdditionalStaticField(Class clazz, String key, Object value) { + return setAdditionalInstanceField(clazz, key, value); + } + + /** Like {@link #setAdditionalInstanceField}, but the value is returned for {@code clazz}. */ + public static Object getAdditionalStaticField(Class clazz, String key) { + return getAdditionalInstanceField(clazz, key); + } + + /** Like {@link #setAdditionalInstanceField}, but the value is removed and returned for {@code clazz}. */ + public static Object removeAdditionalStaticField(Class clazz, String key) { + return removeAdditionalInstanceField(clazz, key); + } + + //################################################################################################# + /** + * Loads an asset from a resource object and returns the content as {@code byte} array. + * + * @param res The resources from which the asset should be loaded. + * @param path The path to the asset, as in {@link AssetManager#open}. + * @return The content of the asset. + */ + public static byte[] assetAsByteArray(Resources res, String path) throws IOException { + return inputStreamToByteArray(res.getAssets().open(path)); + } + + /*package*/ static byte[] inputStreamToByteArray(InputStream is) throws IOException { + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + byte[] temp = new byte[1024]; + int read; + + while ((read = is.read(temp)) > 0) { + buf.write(temp, 0, read); + } + is.close(); + return buf.toByteArray(); + } + + /** + * Invokes the {@link Closeable#close()} method, ignoring IOExceptions. + */ + /*package*/ static void closeSilently(Closeable c) { + if (c != null) { + try { + c.close(); + } catch (IOException ignored) {} + } + } + + /** + * Invokes the {@link DexFile#close()} method, ignoring IOExceptions. + */ + /*package*/ static void closeSilently(DexFile dexFile) { + if (dexFile != null) { + try { + dexFile.close(); + } catch (IOException ignored) {} + } + } + + /** + * Invokes the {@link ZipFile#close()} method, ignoring IOExceptions. + */ + /*package*/ static void closeSilently(ZipFile zipFile) { + if (zipFile != null) { + try { + zipFile.close(); + } catch (IOException ignored) {} + } + } + + /** + * Returns the lowercase hex string representation of a file's MD5 hash sum. + */ + public static String getMD5Sum(String file) throws IOException { + try { + MessageDigest digest = MessageDigest.getInstance("MD5"); + InputStream is = new FileInputStream(file); + byte[] buffer = new byte[8192]; + int read; + while ((read = is.read(buffer)) > 0) { + digest.update(buffer, 0, read); + } + is.close(); + byte[] md5sum = digest.digest(); + BigInteger bigInt = new BigInteger(1, md5sum); + return bigInt.toString(16); + } catch (NoSuchAlgorithmException e) { + return ""; + } + } + + //################################################################################################# + /** + * Increments the depth counter for the given method. + * + *

The intention of the method depth counter is to keep track of the call depth for recursive + * methods, e.g. to override parameters only for the outer call. The Xposed framework uses this + * to load drawable replacements only once per call, even when multiple + * {@link Resources#getDrawable} variants call each other. + * + * @param method The method name. Should be prefixed with a unique, module-specific string. + * @return The updated depth. + */ + public static int incrementMethodDepth(String method) { + return getMethodDepthCounter(method).get().incrementAndGet(); + } + + /** + * Decrements the depth counter for the given method. + * See {@link #incrementMethodDepth} for details. + * + * @param method The method name. Should be prefixed with a unique, module-specific string. + * @return The updated depth. + */ + public static int decrementMethodDepth(String method) { + return getMethodDepthCounter(method).get().decrementAndGet(); + } + + /** + * Returns the current depth counter for the given method. + * See {@link #incrementMethodDepth} for details. + * + * @param method The method name. Should be prefixed with a unique, module-specific string. + * @return The updated depth. + */ + public static int getMethodDepth(String method) { + return getMethodDepthCounter(method).get().get(); + } + + private static ThreadLocal getMethodDepthCounter(String method) { + synchronized (sMethodDepth) { + ThreadLocal counter = sMethodDepth.get(method); + if (counter == null) { + counter = new ThreadLocal() { + @Override + protected AtomicInteger initialValue() { + return new AtomicInteger(); + } + }; + sMethodDepth.put(method, counter); + } + return counter; + } + } + + /*package*/ static boolean fileContains(File file, String str) throws IOException { + // There are certainly more efficient algorithms (e.g. Boyer-Moore used in grep), + // but the naive approach should be sufficient here. + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(file)); + String line; + while ((line = in.readLine()) != null) { + if (line.contains(str)) { + return true; + } + } + return false; + } finally { + closeSilently(in); + } + } + + //################################################################################################# + + /** + * Returns the method that is overridden by the given method. + * It returns {@code null} if the method doesn't override another method or if that method is + * abstract, i.e. if this is the first implementation in the hierarchy. + */ + /*package*/ static Method getOverriddenMethod(Method method) { + int modifiers = method.getModifiers(); + if (Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers)) { + return null; + } + + String name = method.getName(); + Class[] parameters = method.getParameterTypes(); + Class clazz = method.getDeclaringClass().getSuperclass(); + while (clazz != null) { + try { + Method superMethod = clazz.getDeclaredMethod(name, parameters); + modifiers = superMethod.getModifiers(); + if (!Modifier.isPrivate(modifiers) && !Modifier.isAbstract(modifiers)) { + return superMethod; + } else { + return null; + } + } catch (NoSuchMethodException ignored) { + clazz = clazz.getSuperclass(); + } + } + return null; + } + + /** + * Returns all methods which this class overrides. + */ + /*package*/ static Set getOverriddenMethods(Class clazz) { + Set methods = new HashSet<>(); + for (Method method : clazz.getDeclaredMethods()) { + Method overridden = getOverriddenMethod(method); + if (overridden != null) { + methods.add(overridden); + } + } + return methods; + } + + //################################################################################################# + // TODO helpers for view traversing + /*To make it easier, I will try and implement some more helpers: + - add view before/after existing view (I already mentioned that I think) + - get index of view in its parent + - get next/previous sibling (maybe with an optional argument "type", that might be ImageView.class and gives you the next sibling that is an ImageView)? + - get next/previous element (similar to the above, but would also work if the next element has a different parent, it would just go up the hierarchy and then down again until it finds a matching element) + - find the first child that is an instance of a specified class + - find all (direct or indirect) children of a specified class + */ + +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/XposedInit.java b/edxp-core/src/main/java/de/robv/android/xposed/XposedInit.java new file mode 100644 index 00000000..271b02e6 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/XposedInit.java @@ -0,0 +1,511 @@ +package de.robv.android.xposed; + +import android.app.ActivityThread; +import android.app.AndroidAppHelper; +import android.content.pm.ApplicationInfo; +import android.content.res.Resources; +import android.content.res.ResourcesImpl; +import android.content.res.TypedArray; +import android.content.res.XResources; +import android.os.Build; +import android.os.IBinder; +import android.os.Process; +import android.util.ArraySet; +import android.util.Log; + +import com.android.internal.os.ZygoteInit; +import com.elderdrivers.riru.edxp.config.EdXpConfigGlobal; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.ref.WeakReference; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import dalvik.system.PathClassLoader; +import de.robv.android.xposed.annotation.ApiSensitive; +import de.robv.android.xposed.annotation.Level; +import de.robv.android.xposed.callbacks.XC_InitPackageResources; +import de.robv.android.xposed.callbacks.XC_InitZygote; +import de.robv.android.xposed.callbacks.XC_LoadPackage; +import de.robv.android.xposed.callbacks.XCallback; +import de.robv.android.xposed.services.BaseService; + +import static de.robv.android.xposed.XposedBridge.clearAllCallbacks; +import static de.robv.android.xposed.XposedBridge.hookAllConstructors; +import static de.robv.android.xposed.XposedBridge.hookAllMethods; +import static de.robv.android.xposed.XposedBridge.sInitPackageResourcesCallbacks; +import static de.robv.android.xposed.XposedBridge.sInitZygoteCallbacks; +import static de.robv.android.xposed.XposedBridge.sLoadedPackageCallbacks; +import static de.robv.android.xposed.XposedHelpers.callMethod; +import static de.robv.android.xposed.XposedHelpers.closeSilently; +import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; +import static de.robv.android.xposed.XposedHelpers.findClass; +import static de.robv.android.xposed.XposedHelpers.findFieldIfExists; +import static de.robv.android.xposed.XposedHelpers.getObjectField; +import static de.robv.android.xposed.XposedHelpers.getParameterIndexByType; +import static de.robv.android.xposed.XposedHelpers.setStaticBooleanField; +import static de.robv.android.xposed.XposedHelpers.setStaticLongField; +import static de.robv.android.xposed.XposedHelpers.setStaticObjectField; + +public final class XposedInit { + private static final String TAG = XposedBridge.TAG; + public static boolean startsSystemServer = false; + private static final String startClassName = ""; // ed: no support for tool process anymore + + private static final String INSTANT_RUN_CLASS = "com.android.tools.fd.runtime.BootstrapApplication"; + public static volatile boolean disableResources = false; + private static final String[] XRESOURCES_CONFLICTING_PACKAGES = {"com.sygic.aura"}; + public static String prefsBasePath = null; + + private XposedInit() { + } + + /** + * Hook some methods which we want to create an easier interface for developers. + */ + /*package*/ + public static void initForZygote(boolean isSystem) throws Throwable { + // TODO Are these still needed for us? + // MIUI + if (findFieldIfExists(ZygoteInit.class, "BOOT_START_TIME") != null) { + setStaticLongField(ZygoteInit.class, "BOOT_START_TIME", XposedBridge.BOOT_START_TIME); + } + // Samsung + if (Build.VERSION.SDK_INT >= 24) { + Class zygote = findClass("com.android.internal.os.Zygote", null); + try { + setStaticBooleanField(zygote, "isEnhancedZygoteASLREnabled", false); + } catch (NoSuchFieldError ignored) { + } + } + + hookResources(); + } + + @ApiSensitive(Level.MIDDLE) + private static void hookResources() throws Throwable { + if (!EdXpConfigGlobal.getConfig().isResourcesHookEnabled() || disableResources) { + return; + } + + if (!EdXpConfigGlobal.getHookProvider().initXResourcesNative()) { + Log.e(TAG, "Cannot hook resources"); + disableResources = true; + return; + } + + findAndHookMethod("android.app.ApplicationPackageManager", null, "getResourcesForApplication", + ApplicationInfo.class, new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) throws Throwable { + ApplicationInfo app = (ApplicationInfo) param.args[0]; + XResources.setPackageNameForResDir(app.packageName, + app.uid == Process.myUid() ? app.sourceDir : app.publicSourceDir); + } + }); + + /* + * getTopLevelResources(a) + * -> getTopLevelResources(b) + * -> key = new ResourcesKey() + * -> r = new Resources() + * -> mActiveResources.put(key, r) + * -> return r + */ + + final Class classGTLR; + final Class classResKey; + final ThreadLocal latestResKey = new ThreadLocal<>(); + + if (Build.VERSION.SDK_INT <= 18) { + classGTLR = ActivityThread.class; + classResKey = Class.forName("android.app.ActivityThread$ResourcesKey"); + } else { + classGTLR = Class.forName("android.app.ResourcesManager"); + classResKey = Class.forName("android.content.res.ResourcesKey"); + } + + if (Build.VERSION.SDK_INT >= 24) { + hookAllMethods(classGTLR, "getOrCreateResources", new XC_MethodHook() { + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + // At least on OnePlus 5, the method has an additional parameter compared to AOSP. + final int activityTokenIdx = getParameterIndexByType(param.method, IBinder.class); + final int resKeyIdx = getParameterIndexByType(param.method, classResKey); + + String resDir = (String) getObjectField(param.args[resKeyIdx], "mResDir"); + XResources newRes = cloneToXResources(param, resDir); + if (newRes == null) { + return; + } + + Object activityToken = param.args[activityTokenIdx]; + synchronized (param.thisObject) { + ArrayList> resourceReferences; + if (activityToken != null) { + Object activityResources = callMethod(param.thisObject, "getOrCreateActivityResourcesStructLocked", activityToken); + resourceReferences = (ArrayList>) getObjectField(activityResources, "activityResources"); + } else { + resourceReferences = (ArrayList>) getObjectField(param.thisObject, "mResourceReferences"); + } + resourceReferences.add(new WeakReference(newRes)); + } + } + }); + } else { + hookAllConstructors(classResKey, new XC_MethodHook() { + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + latestResKey.set(param.thisObject); + } + }); + + hookAllMethods(classGTLR, "getTopLevelResources", new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) throws Throwable { + latestResKey.set(null); + } + + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + Object key = latestResKey.get(); + if (key == null) { + return; + } + latestResKey.set(null); + + String resDir = (String) getObjectField(key, "mResDir"); + XResources newRes = cloneToXResources(param, resDir); + if (newRes == null) { + return; + } + + @SuppressWarnings("unchecked") + Map> mActiveResources = + (Map>) getObjectField(param.thisObject, "mActiveResources"); + Object lockObject = (Build.VERSION.SDK_INT <= 18) + ? getObjectField(param.thisObject, "mPackages") : param.thisObject; + + synchronized (lockObject) { + WeakReference existing = mActiveResources.put(key, new WeakReference(newRes)); + if (existing != null && existing.get() != null && existing.get().getAssets() != newRes.getAssets()) { + existing.get().getAssets().close(); + } + } + } + }); + + if (Build.VERSION.SDK_INT >= 19) { + // This method exists only on CM-based ROMs + hookAllMethods(classGTLR, "getTopLevelThemedResources", new XC_MethodHook() { + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + String resDir = (String) param.args[0]; + cloneToXResources(param, resDir); + } + }); + } + } + + // Invalidate callers of methods overridden by XTypedArray +// if (Build.VERSION.SDK_INT >= 24) { +// Set methods = getOverriddenMethods(XResources.XTypedArray.class); +// XposedBridge.invalidateCallersNative(methods.toArray(new Member[methods.size()])); +// } + + // Replace TypedArrays with XTypedArrays +// hookAllConstructors(TypedArray.class, new XC_MethodHook() { +// @Override +// protected void afterHookedMethod(MethodHookParam param) throws Throwable { +// TypedArray typedArray = (TypedArray) param.thisObject; +// Resources res = typedArray.getResources(); +// if (res instanceof XResources) { +// XResources.XTypedArray newTypedArray = new XResources.XTypedArray(res); +// XposedBridge.setObjectClass(typedArray, XResources.XTypedArray.class); +// } +// } +// }); + + findAndHookMethod(TypedArray.class, "obtain", Resources.class, int.class, + new XC_MethodHook() { + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + if (param.getResult() instanceof XResources.XTypedArray) { + return; + } + if (!(param.args[0] instanceof XResources)) { + return; + } + XResources.XTypedArray newResult = + new XResources.XTypedArray((Resources) param.args[0]); + int len = (int) param.args[1]; + Method resizeMethod = XposedHelpers.findMethodBestMatch( + TypedArray.class, "resize", new Class[]{int.class}); + resizeMethod.setAccessible(true); + resizeMethod.invoke(newResult, len); + param.setResult(newResult); + } + }); + + // Replace system resources + XResources systemRes = new XResources( + (ClassLoader) XposedHelpers.getObjectField(Resources.getSystem(), "mClassLoader")); + systemRes.setImpl((ResourcesImpl) XposedHelpers.getObjectField(Resources.getSystem(), "mResourcesImpl")); + systemRes.initObject(null); + setStaticObjectField(Resources.class, "mSystem", systemRes); + + XResources.init(latestResKey); + } + + @ApiSensitive(Level.MIDDLE) + private static XResources cloneToXResources(XC_MethodHook.MethodHookParam param, String resDir) { + Object result = param.getResult(); + if (result == null || result instanceof XResources || + Arrays.binarySearch(XRESOURCES_CONFLICTING_PACKAGES, AndroidAppHelper.currentPackageName()) == 0) { + return null; + } + + // Replace the returned resources with our subclass. + XResources newRes = new XResources( + (ClassLoader) XposedHelpers.getObjectField(param.getResult(), "mClassLoader")); + newRes.setImpl((ResourcesImpl) XposedHelpers.getObjectField(param.getResult(), "mResourcesImpl")); + newRes.initObject(resDir); + + // Invoke handleInitPackageResources(). + if (newRes.isFirstLoad()) { + String packageName = newRes.getPackageName(); + XC_InitPackageResources.InitPackageResourcesParam resparam = new XC_InitPackageResources.InitPackageResourcesParam(XposedBridge.sInitPackageResourcesCallbacks); + resparam.packageName = packageName; + resparam.res = newRes; + XCallback.callAll(resparam); + } + + param.setResult(newRes); + return newRes; + } + + private static boolean needsToCloseFilesForFork() { + // ed: we always start to do our work after forking finishes + return false; + } + + /** + * Try to load all modules defined in INSTALLER_DATA_BASE_DIR/conf/modules.list + */ + private static final AtomicBoolean modulesLoaded = new AtomicBoolean(false); + private static final Object moduleLoadLock = new Object(); + // @GuardedBy("moduleLoadLock") + private static final ArraySet loadedModules = new ArraySet<>(); + + public static ArraySet getLoadedModules() { + synchronized (moduleLoadLock) { + return loadedModules; + } + } + + public static boolean loadModules(boolean callInitZygote) throws IOException { + boolean hasLoaded = !modulesLoaded.compareAndSet(false, true); + if (hasLoaded) { + return false; + } + synchronized (moduleLoadLock) { + ClassLoader topClassLoader = XposedBridge.BOOTCLASSLOADER; + ClassLoader parent; + while ((parent = topClassLoader.getParent()) != null) { + topClassLoader = parent; + } + + String moduleList = EdXpConfigGlobal.getConfig().getModulesList(); + InputStream stream = new ByteArrayInputStream(moduleList.getBytes()); + BufferedReader apks = new BufferedReader(new InputStreamReader(stream)); + ArraySet newLoadedApk = new ArraySet<>(); + String apk; + while ((apk = apks.readLine()) != null) { + if (loadedModules.contains(apk)) { + newLoadedApk.add(apk); + } else { + loadedModules.add(apk); // temporarily add it for XSharedPreference + boolean loadSuccess = loadModule(apk, topClassLoader, callInitZygote); + if (loadSuccess) { + newLoadedApk.add(apk); + } + } + } + loadedModules.clear(); + loadedModules.addAll(newLoadedApk); + apks.close(); + + // refresh callback according to current loaded module list + pruneCallbacks(loadedModules); + } + return true; + } + + // remove deactivated or outdated module callbacks + private static void pruneCallbacks(Set loadedModules) { + synchronized (moduleLoadLock) { + Object[] loadedPkgSnapshot = sLoadedPackageCallbacks.getSnapshot(); + Object[] initPkgResSnapshot = sInitPackageResourcesCallbacks.getSnapshot(); + Object[] initZygoteSnapshot = sInitZygoteCallbacks.getSnapshot(); + for (Object loadedPkg : loadedPkgSnapshot) { + if (loadedPkg instanceof IModuleContext) { + if (!loadedModules.contains(((IModuleContext) loadedPkg).getApkPath())) { + sLoadedPackageCallbacks.remove((XC_LoadPackage) loadedPkg); + } + } + } + for (Object initPkgRes : initPkgResSnapshot) { + if (initPkgRes instanceof IModuleContext) { + if (!loadedModules.contains(((IModuleContext) initPkgRes).getApkPath())) { + sInitPackageResourcesCallbacks.remove((XC_InitPackageResources) initPkgRes); + } + } + } + for (Object initZygote : initZygoteSnapshot) { + if (initZygote instanceof IModuleContext) { + if (!loadedModules.contains(((IModuleContext) initZygote).getApkPath())) { + sInitZygoteCallbacks.remove((XC_InitZygote) initZygote); + } + } + } + } + } + + /** + * Load a module from an APK by calling the init(String) method for all classes defined + * in assets/xposed_init. + */ + private static boolean loadModule(String apk, ClassLoader topClassLoader, boolean callInitZygote) { + Log.i(TAG, "Loading modules from " + apk); + + if (!new File(apk).exists()) { + Log.e(TAG, " File does not exist"); + return false; + } + + ClassLoader mcl = new PathClassLoader(apk, topClassLoader); + try { + if (mcl.loadClass(INSTANT_RUN_CLASS) != null) { + Log.e(TAG, " Cannot load module, please disable \"Instant Run\" in Android Studio."); + return false; + } + } catch (ClassNotFoundException ignored) { + } + + try { + if (mcl.loadClass(XposedBridge.class.getName()) != null) { + Log.e(TAG, " Cannot load module:"); + Log.e(TAG, " The Xposed API classes are compiled into the module's APK."); + Log.e(TAG, " This may cause strange issues and must be fixed by the module developer."); + Log.e(TAG, " For details, see: http://api.xposed.info/using.html"); + return false; + } + } catch (ClassNotFoundException ignored) { + } + + try { + Field parentField = ClassLoader.class.getDeclaredField("parent"); + parentField.setAccessible(true); + parentField.set(mcl, XposedInit.class.getClassLoader()); + } catch (NoSuchFieldException | IllegalAccessException e) { + Log.e(TAG, " Cannot load module:"); + Log.e(TAG, " Classloader cannot change parent."); + return false; + } + + ZipFile zipFile = null; + InputStream is; + try { + zipFile = new ZipFile(apk); + ZipEntry zipEntry = zipFile.getEntry("assets/xposed_init"); + if (zipEntry == null) { + Log.e(TAG, " assets/xposed_init not found in the APK"); + closeSilently(zipFile); + return false; + } + is = zipFile.getInputStream(zipEntry); + } catch (IOException e) { + Log.e(TAG, " Cannot read assets/xposed_init in the APK", e); + closeSilently(zipFile); + return false; + } + + BufferedReader moduleClassesReader = new BufferedReader(new InputStreamReader(is)); + try { + String moduleClassName; + while ((moduleClassName = moduleClassesReader.readLine()) != null) { + moduleClassName = moduleClassName.trim(); + if (moduleClassName.isEmpty() || moduleClassName.startsWith("#")) + continue; + + try { + Log.i(TAG, " Loading class " + moduleClassName); + Class moduleClass = mcl.loadClass(moduleClassName); + + if (!IXposedMod.class.isAssignableFrom(moduleClass)) { + Log.e(TAG, " This class doesn't implement any sub-interface of IXposedMod, skipping it"); + continue; + } else if (disableResources && IXposedHookInitPackageResources.class.isAssignableFrom(moduleClass)) { + Log.e(TAG, " This class requires resource-related hooks (which are disabled), skipping it."); + continue; + } + + final Object moduleInstance = moduleClass.newInstance(); + if (XposedBridge.isZygote) { + if (moduleInstance instanceof IXposedHookZygoteInit) { + IXposedHookZygoteInit.StartupParam param = new IXposedHookZygoteInit.StartupParam(); + param.modulePath = apk; + param.startsSystemServer = startsSystemServer; + + XposedBridge.hookInitZygote(new IXposedHookZygoteInit.Wrapper( + (IXposedHookZygoteInit) moduleInstance, param)); + if (callInitZygote) { + ((IXposedHookZygoteInit) moduleInstance).initZygote(param); + } + } + + if (moduleInstance instanceof IXposedHookLoadPackage) + XposedBridge.hookLoadPackage(new IXposedHookLoadPackage.Wrapper( + (IXposedHookLoadPackage) moduleInstance, apk)); + + if (moduleInstance instanceof IXposedHookInitPackageResources) + XposedBridge.hookInitPackageResources(new IXposedHookInitPackageResources.Wrapper( + (IXposedHookInitPackageResources) moduleInstance, apk)); + } else { + if (moduleInstance instanceof IXposedHookCmdInit) { + IXposedHookCmdInit.StartupParam param = new IXposedHookCmdInit.StartupParam(); + param.modulePath = apk; + param.startClassName = startClassName; + ((IXposedHookCmdInit) moduleInstance).initCmdApp(param); + } + } + } catch (Throwable t) { + Log.e(TAG, " Failed to load class " + moduleClassName, t); + return false; + } + } + return true; + } catch (IOException e) { + Log.e(TAG, " Failed to load module from " + apk, e); + return false; + } finally { + closeSilently(is); + closeSilently(zipFile); + } + } + + public final static HashSet loadedPackagesInProcess = new HashSet<>(1); +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/annotation/ApiSensitive.java b/edxp-core/src/main/java/de/robv/android/xposed/annotation/ApiSensitive.java new file mode 100644 index 00000000..75466f60 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/annotation/ApiSensitive.java @@ -0,0 +1,17 @@ +package de.robv.android.xposed.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotation that indicates a element is sensitive to Android API level. + *

+ * Annotated elements' compatibility should be checked when adapting to new Android versions. + */ +@Retention(RetentionPolicy.SOURCE) +@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE}) +public @interface ApiSensitive { + Level value() default Level.HIGH; +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/annotation/Level.java b/edxp-core/src/main/java/de/robv/android/xposed/annotation/Level.java new file mode 100644 index 00000000..54d5869e --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/annotation/Level.java @@ -0,0 +1,9 @@ +package de.robv.android.xposed.annotation; + +public enum Level { + LOW, MIDDLE, HIGH; + + private Level() { + + } +} \ No newline at end of file diff --git a/edxp-core/src/main/java/de/robv/android/xposed/callbacks/IXUnhook.java b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/IXUnhook.java new file mode 100644 index 00000000..72766692 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/IXUnhook.java @@ -0,0 +1,25 @@ +package de.robv.android.xposed.callbacks; + +import de.robv.android.xposed.IXposedHookZygoteInit; + +/** + * Interface for objects that can be used to remove callbacks. + * + *

Just like hooking methods etc., unhooking applies only to the current process. + * In other process (or when the app is removed from memory and then restarted), the hook will still + * be active. The Zygote process (see {@link IXposedHookZygoteInit}) is an exception, the hook won't + * be inherited by any future processes forked from it in the future. + * + * @param The class of the callback. + */ +public interface IXUnhook { + /** + * Returns the callback that has been registered. + */ + T getCallback(); + + /** + * Removes the callback. + */ + void unhook(); +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_InitPackageResources.java b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_InitPackageResources.java new file mode 100644 index 00000000..33626b76 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_InitPackageResources.java @@ -0,0 +1,57 @@ +package de.robv.android.xposed.callbacks; + +import android.content.res.XResources; + +import de.robv.android.xposed.IXposedHookInitPackageResources; +import de.robv.android.xposed.XposedBridge.CopyOnWriteSortedSet; + +/** + * This class is only used for internal purposes, except for the {@link InitPackageResourcesParam} + * subclass. + */ +public abstract class XC_InitPackageResources extends XCallback implements IXposedHookInitPackageResources { + /** + * Creates a new callback with default priority. + * @hide + */ + @SuppressWarnings("deprecation") + public XC_InitPackageResources() { + super(); + } + + /** + * Creates a new callback with a specific priority. + * + * @param priority See {@link XCallback#priority}. + * @hide + */ + public XC_InitPackageResources(int priority) { + super(priority); + } + + /** + * Wraps information about the resources being initialized. + */ + public static final class InitPackageResourcesParam extends XCallback.Param { + /** @hide */ + public InitPackageResourcesParam(CopyOnWriteSortedSet callbacks) { + super(callbacks); + } + + /** The name of the package for which resources are being loaded. */ + public String packageName; + + /** + * Reference to the resources that can be used for calls to + * {@link XResources#setReplacement(String, String, String, Object)}. + */ + public XResources res; + } + + /** @hide */ + @Override + protected void call(Param param) throws Throwable { + if (param instanceof InitPackageResourcesParam) + handleInitPackageResources((InitPackageResourcesParam) param); + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_InitZygote.java b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_InitZygote.java new file mode 100644 index 00000000..60c05252 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_InitZygote.java @@ -0,0 +1,39 @@ +package de.robv.android.xposed.callbacks; + +import de.robv.android.xposed.IXposedHookZygoteInit; + +/** + * This class is only used for internal purposes, except for the {@link StartupParam} + * subclass. + */ +public abstract class XC_InitZygote extends XCallback implements IXposedHookZygoteInit { + + /** + * Creates a new callback with default priority. + * + * @hide + */ + @SuppressWarnings("deprecation") + public XC_InitZygote() { + super(); + } + + /** + * Creates a new callback with a specific priority. + * + * @param priority See {@link XCallback#priority}. + * @hide + */ + public XC_InitZygote(int priority) { + super(priority); + } + + /** + * @hide + */ + @Override + protected void call(Param param) throws Throwable { + if (param instanceof StartupParam) + initZygote((StartupParam) param); + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_LayoutInflated.java b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_LayoutInflated.java new file mode 100644 index 00000000..ff6ed3d4 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_LayoutInflated.java @@ -0,0 +1,99 @@ +package de.robv.android.xposed.callbacks; + +import android.content.res.XResources; +import android.content.res.XResources.ResourceNames; +import android.view.View; + +import de.robv.android.xposed.XposedBridge.CopyOnWriteSortedSet; + +/** + * Callback for hooking layouts. Such callbacks can be passed to {@link XResources#hookLayout} + * and its variants. + */ +public abstract class XC_LayoutInflated extends XCallback { + /** + * Creates a new callback with default priority. + */ + @SuppressWarnings("deprecation") + public XC_LayoutInflated() { + super(); + } + + /** + * Creates a new callback with a specific priority. + * + * @param priority See {@link XCallback#priority}. + */ + public XC_LayoutInflated(int priority) { + super(priority); + } + + /** + * Wraps information about the inflated layout. + */ + public static final class LayoutInflatedParam extends XCallback.Param { + /** @hide */ + public LayoutInflatedParam(CopyOnWriteSortedSet callbacks) { + super(callbacks); + } + + /** The view that has been created from the layout. */ + public View view; + + /** Container with the ID and name of the underlying resource. */ + public ResourceNames resNames; + + /** Directory from which the layout was actually loaded (e.g. "layout-sw600dp"). */ + public String variant; + + /** Resources containing the layout. */ + public XResources res; + } + + /** @hide */ + @Override + protected void call(Param param) throws Throwable { + if (param instanceof LayoutInflatedParam) + handleLayoutInflated((LayoutInflatedParam) param); + } + + /** + * This method is called when the hooked layout has been inflated. + * + * @param liparam Information about the layout and the inflated view. + * @throws Throwable Everything the callback throws is caught and logged. + */ + public abstract void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable; + + /** + * An object with which the callback can be removed. + */ + public class Unhook implements IXUnhook { + private final String resDir; + private final int id; + + /** @hide */ + public Unhook(String resDir, int id) { + this.resDir = resDir; + this.id = id; + } + + /** + * Returns the resource ID of the hooked layout. + */ + public int getId() { + return id; + } + + @Override + public XC_LayoutInflated getCallback() { + return XC_LayoutInflated.this; + } + + @Override + public void unhook() { + XResources.unhookLayout(resDir, id, XC_LayoutInflated.this); + } + + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_LoadPackage.java b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_LoadPackage.java new file mode 100644 index 00000000..03f3a1d6 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XC_LoadPackage.java @@ -0,0 +1,63 @@ +package de.robv.android.xposed.callbacks; + +import android.content.pm.ApplicationInfo; + +import de.robv.android.xposed.IXposedHookLoadPackage; +import de.robv.android.xposed.XposedBridge.CopyOnWriteSortedSet; + +/** + * This class is only used for internal purposes, except for the {@link LoadPackageParam} + * subclass. + */ +public abstract class XC_LoadPackage extends XCallback implements IXposedHookLoadPackage { + /** + * Creates a new callback with default priority. + * @hide + */ + @SuppressWarnings("deprecation") + public XC_LoadPackage() { + super(); + } + + /** + * Creates a new callback with a specific priority. + * + * @param priority See {@link XCallback#priority}. + * @hide + */ + public XC_LoadPackage(int priority) { + super(priority); + } + + /** + * Wraps information about the app being loaded. + */ + public static final class LoadPackageParam extends XCallback.Param { + /** @hide */ + public LoadPackageParam(CopyOnWriteSortedSet callbacks) { + super(callbacks); + } + + /** The name of the package being loaded. */ + public String packageName; + + /** The process in which the package is executed. */ + public String processName; + + /** The ClassLoader used for this package. */ + public ClassLoader classLoader; + + /** More information about the application being loaded. */ + public ApplicationInfo appInfo; + + /** Set to {@code true} if this is the first (and main) application for this process. */ + public boolean isFirstApplication; + } + + /** @hide */ + @Override + protected void call(Param param) throws Throwable { + if (param instanceof LoadPackageParam) + handleLoadPackage((LoadPackageParam) param); + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XCallback.java b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XCallback.java new file mode 100644 index 00000000..6e6663d2 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/XCallback.java @@ -0,0 +1,154 @@ +package de.robv.android.xposed.callbacks; + +import android.os.Bundle; + +import com.elderdrivers.riru.edxp.config.EdXpConfigGlobal; + +import java.io.Serializable; + +import de.robv.android.xposed.IModuleContext; +import de.robv.android.xposed.XposedBridge; +import de.robv.android.xposed.XposedBridge.CopyOnWriteSortedSet; + +/** + * Base class for Xposed callbacks. + * + * This class only keeps a priority for ordering multiple callbacks. + * The actual (abstract) callback methods are added by subclasses. + */ +public abstract class XCallback implements Comparable, IModuleContext { + /** + * Callback priority, higher number means earlier execution. + * + *

This is usually set to {@link #PRIORITY_DEFAULT}. However, in case a certain callback should + * be executed earlier or later a value between {@link #PRIORITY_HIGHEST} and {@link #PRIORITY_LOWEST} + * can be set instead. The values are just for orientation though, Xposed doesn't enforce any + * boundaries on the priority values. + */ + public final int priority; + + /** @deprecated This constructor can't be hidden for technical reasons. Nevertheless, don't use it! */ + @Deprecated + public XCallback() { + this.priority = PRIORITY_DEFAULT; + } + + /** @hide */ + public XCallback(int priority) { + this.priority = priority; + } + + /** + * Base class for Xposed callback parameters. + */ + public static abstract class Param { + /** @hide */ + public final Object[] callbacks; + private Bundle extra; + + /** @deprecated This constructor can't be hidden for technical reasons. Nevertheless, don't use it! */ + @Deprecated + protected Param() { + callbacks = null; + } + + /** @hide */ + protected Param(CopyOnWriteSortedSet callbacks) { + this.callbacks = callbacks.getSnapshot(); + } + + /** + * This can be used to store any data for the scope of the callback. + * + *

Use this instead of instance variables, as it has a clear reference to e.g. each + * separate call to a method, even when the same method is called recursively. + * + * @see #setObjectExtra + * @see #getObjectExtra + */ + public synchronized Bundle getExtra() { + if (extra == null) + extra = new Bundle(); + return extra; + } + + /** + * Returns an object stored with {@link #setObjectExtra}. + */ + public Object getObjectExtra(String key) { + Serializable o = getExtra().getSerializable(key); + if (o instanceof SerializeWrapper) + return ((SerializeWrapper) o).object; + return null; + } + + /** + * Stores any object for the scope of the callback. For data types that support it, use + * the {@link Bundle} returned by {@link #getExtra} instead. + */ + public void setObjectExtra(String key, Object o) { + getExtra().putSerializable(key, new SerializeWrapper(o)); + } + + private static class SerializeWrapper implements Serializable { + private static final long serialVersionUID = 1L; + private final Object object; + public SerializeWrapper(Object o) { + object = o; + } + } + } + + /** @hide */ + public static void callAll(Param param) { + + if (param instanceof XC_LoadPackage.LoadPackageParam) { + // deopt methods in system apps or priv-apps, this would be not necessary + // only if we found out how to recompile their apks + XC_LoadPackage.LoadPackageParam lpp = (XC_LoadPackage.LoadPackageParam) param; + EdXpConfigGlobal.getHookProvider().deoptMethods(lpp.packageName, lpp.classLoader); + } + + if (param.callbacks == null) + throw new IllegalStateException("This object was not created for use with callAll"); + + for (int i = 0; i < param.callbacks.length; i++) { + try { + ((XCallback) param.callbacks[i]).call(param); + } catch (Throwable t) { XposedBridge.log(t); } + } + } + + /** @hide */ + protected void call(Param param) throws Throwable {} + + @Override + public String getApkPath() { + return ""; + } + + /** @hide */ + @Override + public int compareTo(XCallback other) { + if (this == other) + return 0; + + // order descending by priority + if (other.priority != this.priority) + return other.priority - this.priority; + // then randomly + else if (System.identityHashCode(this) < System.identityHashCode(other)) + return -1; + else + return 1; + } + + /** The default priority, see {@link #priority}. */ + public static final int PRIORITY_DEFAULT = 50; + + /** Execute this callback late, see {@link #priority}. */ + public static final int PRIORITY_LOWEST = -10000; + + /** Execute this callback early, see {@link #priority}. */ + public static final int PRIORITY_HIGHEST = 10000; +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/callbacks/package-info.java b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/package-info.java new file mode 100644 index 00000000..3b00b7f5 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/callbacks/package-info.java @@ -0,0 +1,9 @@ +/** + * Contains the base classes for callbacks. + * + *

For historical reasons, {@link de.robv.android.xposed.XC_MethodHook} and + * {@link de.robv.android.xposed.XC_MethodReplacement} are directly in the + * {@code de.robv.android.xposed} package. + */ +package de.robv.android.xposed.callbacks; + diff --git a/edxp-core/src/main/java/de/robv/android/xposed/package-info.java b/edxp-core/src/main/java/de/robv/android/xposed/package-info.java new file mode 100644 index 00000000..c0fd7c56 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains the main classes of the Xposed framework. + */ +package de.robv.android.xposed; diff --git a/edxp-core/src/main/java/de/robv/android/xposed/services/BaseService.java b/edxp-core/src/main/java/de/robv/android/xposed/services/BaseService.java new file mode 100644 index 00000000..c0ccd186 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/services/BaseService.java @@ -0,0 +1,179 @@ +package de.robv.android.xposed.services; + +import java.io.ByteArrayInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import de.robv.android.xposed.SELinuxHelper; + +/** + * General definition of a file access service provided by the Xposed framework. + * + *

References to a concrete subclass should generally be retrieved from {@link SELinuxHelper}. + */ +public abstract class BaseService { + /** Flag for {@link #checkFileAccess}: Read access. */ + public static final int R_OK = 4; + /** Flag for {@link #checkFileAccess}: Write access. */ + public static final int W_OK = 2; + /** Flag for {@link #checkFileAccess}: Executable access. */ + public static final int X_OK = 1; + /** Flag for {@link #checkFileAccess}: File/directory exists. */ + public static final int F_OK = 0; + + /** + * Checks whether the services accesses files directly (instead of using IPC). + * + * @return {@code true} in case direct access is possible. + */ + public boolean hasDirectFileAccess() { + return false; + } + + /** + * Check whether a file is accessible. SELinux might enforce stricter checks. + * + * @param filename The absolute path of the file to check. + * @param mode The mode for POSIX's {@code access()} function. + * @return The result of the {@code access()} function. + */ + public abstract boolean checkFileAccess(String filename, int mode); + + /** + * Check whether a file exists. + * + * @param filename The absolute path of the file to check. + * @return The result of the {@code access()} function. + */ + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public boolean checkFileExists(String filename) { + return checkFileAccess(filename, F_OK); + } + + /** + * Determine the size and modification time of a file. + * + * @param filename The absolute path of the file to check. + * @return A {@link FileResult} object holding the result. + * @throws IOException In case an error occurred while retrieving the information. + */ + public abstract FileResult statFile(String filename) throws IOException; + + /** + * Determine the size time of a file. + * + * @param filename The absolute path of the file to check. + * @return The file size. + * @throws IOException In case an error occurred while retrieving the information. + */ + public long getFileSize(String filename) throws IOException { + return statFile(filename).size; + } + + /** + * Determine the size time of a file. + * + * @param filename The absolute path of the file to check. + * @return The file modification time. + * @throws IOException In case an error occurred while retrieving the information. + */ + public long getFileModificationTime(String filename) throws IOException { + return statFile(filename).mtime; + } + + /** + * Read a file into memory. + * + * @param filename The absolute path of the file to read. + * @return A {@code byte} array with the file content. + * @throws IOException In case an error occurred while reading the file. + */ + public abstract byte[] readFile(String filename) throws IOException; + + /** + * Read a file into memory, but only if it has changed since the last time. + * + * @param filename The absolute path of the file to read. + * @param previousSize File size of last read. + * @param previousTime File modification time of last read. + * @return A {@link FileResult} object holding the result. + *

The {@link FileResult#content} field might be {@code null} if the file + * is unmodified ({@code previousSize} and {@code previousTime} are still valid). + * @throws IOException In case an error occurred while reading the file. + */ + public abstract FileResult readFile(String filename, long previousSize, long previousTime) throws IOException; + + /** + * Read a file into memory, optionally only if it has changed since the last time. + * + * @param filename The absolute path of the file to read. + * @param offset Number of bytes to skip at the beginning of the file. + * @param length Number of bytes to read (0 means read to end of file). + * @param previousSize Optional: File size of last read. + * @param previousTime Optional: File modification time of last read. + * @return A {@link FileResult} object holding the result. + *

The {@link FileResult#content} field might be {@code null} if the file + * is unmodified ({@code previousSize} and {@code previousTime} are still valid). + * @throws IOException In case an error occurred while reading the file. + */ + public abstract FileResult readFile(String filename, int offset, int length, + long previousSize, long previousTime) throws IOException; + + /** + * Get a stream to the file content. + * Depending on the service, it may or may not be read completely into memory. + * + * @param filename The absolute path of the file to read. + * @return An {@link InputStream} to the file content. + * @throws IOException In case an error occurred while reading the file. + */ + public InputStream getFileInputStream(String filename) throws IOException { + return new ByteArrayInputStream(readFile(filename)); + } + + /** + * Get a stream to the file content, but only if it has changed since the last time. + * Depending on the service, it may or may not be read completely into memory. + * + * @param filename The absolute path of the file to read. + * @param previousSize Optional: File size of last read. + * @param previousTime Optional: File modification time of last read. + * @return A {@link FileResult} object holding the result. + *

The {@link FileResult#stream} field might be {@code null} if the file + * is unmodified ({@code previousSize} and {@code previousTime} are still valid). + * @throws IOException In case an error occurred while reading the file. + */ + public FileResult getFileInputStream(String filename, long previousSize, long previousTime) throws IOException { + FileResult result = readFile(filename, previousSize, previousTime); + if (result.content == null) + return result; + return new FileResult(new ByteArrayInputStream(result.content), result.size, result.mtime); + } + + + // ---------------------------------------------------------------------------- + /*package*/ BaseService() {} + + /*package*/ static void ensureAbsolutePath(String filename) { + if (!filename.startsWith("/")) { + throw new IllegalArgumentException("Only absolute filenames are allowed: " + filename); + } + } + + /*package*/ static void throwCommonIOException(int errno, String errorMsg, String filename, String defaultText) throws IOException { + switch (errno) { + case 1: // EPERM + case 13: // EACCES + throw new FileNotFoundException(errorMsg != null ? errorMsg : "Permission denied: " + filename); + case 2: // ENOENT + throw new FileNotFoundException(errorMsg != null ? errorMsg : "No such file or directory: " + filename); + case 12: // ENOMEM + throw new OutOfMemoryError(errorMsg); + case 21: // EISDIR + throw new FileNotFoundException(errorMsg != null ? errorMsg : "Is a directory: " + filename); + default: + throw new IOException(errorMsg != null ? errorMsg : "Error " + errno + defaultText + filename); + } + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/services/BinderService.java b/edxp-core/src/main/java/de/robv/android/xposed/services/BinderService.java new file mode 100644 index 00000000..1961f15e --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/services/BinderService.java @@ -0,0 +1,166 @@ +package de.robv.android.xposed.services; + +import android.os.IBinder; +import android.os.Parcel; +import android.os.RemoteException; +import android.os.ServiceManager; + +import java.io.IOException; + +/** @hide */ +public final class BinderService extends BaseService { + public static final int TARGET_APP = 0; + public static final int TARGET_SYSTEM = 1; + + /** + * Retrieve the binder service running in the specified context. + * @param target Either {@link #TARGET_APP} or {@link #TARGET_SYSTEM}. + * @return A reference to the service. + * @throws IllegalStateException In case the service doesn't exist (should never happen). + */ + public static BinderService getService(int target) { + if (target < 0 || target > sServices.length) { + throw new IllegalArgumentException("Invalid service target " + target); + } + synchronized (sServices) { + if (sServices[target] == null) { + sServices[target] = new BinderService(target); + } + return sServices[target]; + } + } + + @Override + public boolean checkFileAccess(String filename, int mode) { + ensureAbsolutePath(filename); + + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + data.writeInterfaceToken(INTERFACE_TOKEN); + data.writeString(filename); + data.writeInt(mode); + + try { + mRemote.transact(ACCESS_FILE_TRANSACTION, data, reply, 0); + } catch (RemoteException e) { + data.recycle(); + reply.recycle(); + return false; + } + + reply.readException(); + int result = reply.readInt(); + reply.recycle(); + data.recycle(); + return result == 0; + } + + @Override + public FileResult statFile(String filename) throws IOException { + ensureAbsolutePath(filename); + + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + data.writeInterfaceToken(INTERFACE_TOKEN); + data.writeString(filename); + + try { + mRemote.transact(STAT_FILE_TRANSACTION, data, reply, 0); + } catch (RemoteException e) { + data.recycle(); + reply.recycle(); + throw new IOException(e); + } + + reply.readException(); + int errno = reply.readInt(); + if (errno != 0) + throwCommonIOException(errno, null, filename, " while retrieving attributes for "); + + long size = reply.readLong(); + long time = reply.readLong(); + reply.recycle(); + data.recycle(); + return new FileResult(size, time); + } + + @Override + public byte[] readFile(String filename) throws IOException { + return readFile(filename, 0, 0, 0, 0).content; + } + + @Override + public FileResult readFile(String filename, long previousSize, long previousTime) throws IOException { + return readFile(filename, 0, 0, previousSize, previousTime); + } + + @Override + public FileResult readFile(String filename, int offset, int length, + long previousSize, long previousTime) throws IOException { + ensureAbsolutePath(filename); + + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + data.writeInterfaceToken(INTERFACE_TOKEN); + data.writeString(filename); + data.writeInt(offset); + data.writeInt(length); + data.writeLong(previousSize); + data.writeLong(previousTime); + + try { + mRemote.transact(READ_FILE_TRANSACTION, data, reply, 0); + } catch (RemoteException e) { + data.recycle(); + reply.recycle(); + throw new IOException(e); + } + + reply.readException(); + int errno = reply.readInt(); + String errorMsg = reply.readString(); + long size = reply.readLong(); + long time = reply.readLong(); + byte[] content = reply.createByteArray(); + reply.recycle(); + data.recycle(); + + switch (errno) { + case 0: + return new FileResult(content, size, time); + case 22: // EINVAL + if (errorMsg != null) { + IllegalArgumentException iae = new IllegalArgumentException(errorMsg); + if (offset == 0 && length == 0) + throw new IOException(iae); + else + throw iae; + } else { + throw new IllegalArgumentException("Offset " + offset + " / Length " + length + + " is out of range for " + filename + " with size " + size); + } + default: + throwCommonIOException(errno, errorMsg, filename, " while reading "); + throw new IllegalStateException(); // not reached + } + } + + + // ---------------------------------------------------------------------------- + private static final String INTERFACE_TOKEN = "de.robv.android.xposed.IXposedService"; + + private static final int ACCESS_FILE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 2; + private static final int STAT_FILE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 3; + private static final int READ_FILE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 4; + + private static final String[] SERVICE_NAMES = { "user.xposed.app", "user.xposed.system" }; + private static final BinderService[] sServices = new BinderService[2]; + private final IBinder mRemote; + + private BinderService(int target) { + IBinder binder = ServiceManager.getService(SERVICE_NAMES[target]); + if (binder == null) + throw new IllegalStateException("Service " + SERVICE_NAMES[target] + " does not exist"); + this.mRemote = binder; + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/services/DirectAccessService.java b/edxp-core/src/main/java/de/robv/android/xposed/services/DirectAccessService.java new file mode 100644 index 00000000..f2f7124b --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/services/DirectAccessService.java @@ -0,0 +1,113 @@ +package de.robv.android.xposed.services; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + +/** @hide */ +public final class DirectAccessService extends BaseService { + @Override + public boolean hasDirectFileAccess() { + return true; + } + + @SuppressWarnings("RedundantIfStatement") + @Override + public boolean checkFileAccess(String filename, int mode) { + File file = new File(filename); + if (mode == F_OK && !file.exists()) return false; + if ((mode & R_OK) != 0 && !file.canRead()) return false; + if ((mode & W_OK) != 0 && !file.canWrite()) return false; + if ((mode & X_OK) != 0 && !file.canExecute()) return false; + return true; + } + + @Override + public boolean checkFileExists(String filename) { + return new File(filename).exists(); + } + + @Override + public FileResult statFile(String filename) throws IOException { + File file = new File(filename); + return new FileResult(file.length(), file.lastModified()); + } + + @Override + public byte[] readFile(String filename) throws IOException { + File file = new File(filename); + byte content[] = new byte[(int)file.length()]; + FileInputStream fis = new FileInputStream(file); + fis.read(content); + fis.close(); + return content; + } + + @Override + public FileResult readFile(String filename, long previousSize, long previousTime) throws IOException { + File file = new File(filename); + long size = file.length(); + long time = file.lastModified(); + if (previousSize == size && previousTime == time) + return new FileResult(size, time); + return new FileResult(readFile(filename), size, time); + } + + @Override + public FileResult readFile(String filename, int offset, int length, long previousSize, long previousTime) throws IOException { + File file = new File(filename); + long size = file.length(); + long time = file.lastModified(); + if (previousSize == size && previousTime == time) + return new FileResult(size, time); + + // Shortcut for the simple case + if (offset <= 0 && length <= 0) + return new FileResult(readFile(filename), size, time); + + // Check range + if (offset > 0 && offset >= size) { + throw new IllegalArgumentException("Offset " + offset + " is out of range for " + filename); + } else if (offset < 0) { + offset = 0; + } + + if (length > 0 && (offset + length) > size) { + throw new IllegalArgumentException("Length " + length + " is out of range for " + filename); + } else if (length <= 0) { + length = (int) (size - offset); + } + + byte content[] = new byte[length]; + FileInputStream fis = new FileInputStream(file); + fis.skip(offset); + fis.read(content); + fis.close(); + return new FileResult(content, size, time); + } + + /** + * {@inheritDoc} + *

This implementation returns a BufferedInputStream instead of loading the file into memory. + */ + @Override + public InputStream getFileInputStream(String filename) throws IOException { + return new BufferedInputStream(new FileInputStream(filename), 16*1024); + } + + /** + * {@inheritDoc} + *

This implementation returns a BufferedInputStream instead of loading the file into memory. + */ + @Override + public FileResult getFileInputStream(String filename, long previousSize, long previousTime) throws IOException { + File file = new File(filename); + long size = file.length(); + long time = file.lastModified(); + if (previousSize == size && previousTime == time) + return new FileResult(size, time); + return new FileResult(new BufferedInputStream(new FileInputStream(filename), 16*1024), size, time); + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/services/FileResult.java b/edxp-core/src/main/java/de/robv/android/xposed/services/FileResult.java new file mode 100644 index 00000000..00da1dfa --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/services/FileResult.java @@ -0,0 +1,60 @@ +package de.robv.android.xposed.services; + +import java.io.InputStream; + +/** + * Holder for the result of a {@link BaseService#readFile} or {@link BaseService#statFile} call. + */ +public final class FileResult { + /** File content, might be {@code null} if the file wasn't read. */ + public final byte[] content; + /** File input stream, might be {@code null} if the file wasn't read. */ + public final InputStream stream; + /** File size. */ + public final long size; + /** File last modification time. */ + public final long mtime; + + /*package*/ FileResult(long size, long mtime) { + this.content = null; + this.stream = null; + this.size = size; + this.mtime = mtime; + } + + /*package*/ FileResult(byte[] content, long size, long mtime) { + this.content = content; + this.stream = null; + this.size = size; + this.mtime = mtime; + } + + /*package*/ FileResult(InputStream stream, long size, long mtime) { + this.content = null; + this.stream = stream; + this.size = size; + this.mtime = mtime; + } + + /** @hide */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder("{"); + if (content != null) { + sb.append("content.length: "); + sb.append(content.length); + sb.append(", "); + } + if (stream != null) { + sb.append("stream: "); + sb.append(stream.toString()); + sb.append(", "); + } + sb.append("size: "); + sb.append(size); + sb.append(", mtime: "); + sb.append(mtime); + sb.append("}"); + return sb.toString(); + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/services/ZygoteService.java b/edxp-core/src/main/java/de/robv/android/xposed/services/ZygoteService.java new file mode 100644 index 00000000..de1faa0d --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/services/ZygoteService.java @@ -0,0 +1,54 @@ +package de.robv.android.xposed.services; + +import java.io.IOException; +import java.util.Arrays; + +/** @hide */ +@SuppressWarnings("JniMissingFunction") +public final class ZygoteService extends BaseService { + @Override + public native boolean checkFileAccess(String filename, int mode); + + @Override + public native FileResult statFile(String filename) throws IOException; + + @Override + public native byte[] readFile(String filename) throws IOException; + + @Override + // Just for completeness, we don't expect this to be called often in Zygote. + public FileResult readFile(String filename, long previousSize, long previousTime) throws IOException { + FileResult stat = statFile(filename); + if (previousSize == stat.size && previousTime == stat.mtime) + return stat; + return new FileResult(readFile(filename), stat.size, stat.mtime); + } + + @Override + // Just for completeness, we don't expect this to be called often in Zygote. + public FileResult readFile(String filename, int offset, int length, long previousSize, long previousTime) throws IOException { + FileResult stat = statFile(filename); + if (previousSize == stat.size && previousTime == stat.mtime) + return stat; + + // Shortcut for the simple case + if (offset <= 0 && length <= 0) + return new FileResult(readFile(filename), stat.size, stat.mtime); + + // Check range + if (offset > 0 && offset >= stat.size) { + throw new IllegalArgumentException("offset " + offset + " >= size " + stat.size + " for " + filename); + } else if (offset < 0) { + offset = 0; + } + + if (length > 0 && (offset + length) > stat.size) { + throw new IllegalArgumentException("offset " + offset + " + length " + length + " > size " + stat.size + " for " + filename); + } else if (length <= 0) { + length = (int) (stat.size - offset); + } + + byte[] content = readFile(filename); + return new FileResult(Arrays.copyOfRange(content, offset, offset + length), stat.size, stat.mtime); + } +} diff --git a/edxp-core/src/main/java/de/robv/android/xposed/services/package-info.java b/edxp-core/src/main/java/de/robv/android/xposed/services/package-info.java new file mode 100644 index 00000000..270b32c4 --- /dev/null +++ b/edxp-core/src/main/java/de/robv/android/xposed/services/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains file access services provided by the Xposed framework. + */ +package de.robv.android.xposed.services; diff --git a/dalvikdx/src/main/java/external/com/android/dex/Annotation.java b/edxp-core/src/main/java/external/com/android/dex/Annotation.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/Annotation.java rename to edxp-core/src/main/java/external/com/android/dex/Annotation.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/CallSiteId.java b/edxp-core/src/main/java/external/com/android/dex/CallSiteId.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/CallSiteId.java rename to edxp-core/src/main/java/external/com/android/dex/CallSiteId.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/ClassData.java b/edxp-core/src/main/java/external/com/android/dex/ClassData.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/ClassData.java rename to edxp-core/src/main/java/external/com/android/dex/ClassData.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/ClassDef.java b/edxp-core/src/main/java/external/com/android/dex/ClassDef.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/ClassDef.java rename to edxp-core/src/main/java/external/com/android/dex/ClassDef.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/Code.java b/edxp-core/src/main/java/external/com/android/dex/Code.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/Code.java rename to edxp-core/src/main/java/external/com/android/dex/Code.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/Dex.java b/edxp-core/src/main/java/external/com/android/dex/Dex.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/Dex.java rename to edxp-core/src/main/java/external/com/android/dex/Dex.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/DexException.java b/edxp-core/src/main/java/external/com/android/dex/DexException.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/DexException.java rename to edxp-core/src/main/java/external/com/android/dex/DexException.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/DexFormat.java b/edxp-core/src/main/java/external/com/android/dex/DexFormat.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/DexFormat.java rename to edxp-core/src/main/java/external/com/android/dex/DexFormat.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/DexIndexOverflowException.java b/edxp-core/src/main/java/external/com/android/dex/DexIndexOverflowException.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/DexIndexOverflowException.java rename to edxp-core/src/main/java/external/com/android/dex/DexIndexOverflowException.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/EncodedValue.java b/edxp-core/src/main/java/external/com/android/dex/EncodedValue.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/EncodedValue.java rename to edxp-core/src/main/java/external/com/android/dex/EncodedValue.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/EncodedValueCodec.java b/edxp-core/src/main/java/external/com/android/dex/EncodedValueCodec.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/EncodedValueCodec.java rename to edxp-core/src/main/java/external/com/android/dex/EncodedValueCodec.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/EncodedValueReader.java b/edxp-core/src/main/java/external/com/android/dex/EncodedValueReader.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/EncodedValueReader.java rename to edxp-core/src/main/java/external/com/android/dex/EncodedValueReader.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/FieldId.java b/edxp-core/src/main/java/external/com/android/dex/FieldId.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/FieldId.java rename to edxp-core/src/main/java/external/com/android/dex/FieldId.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/Leb128.java b/edxp-core/src/main/java/external/com/android/dex/Leb128.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/Leb128.java rename to edxp-core/src/main/java/external/com/android/dex/Leb128.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/MethodHandle.java b/edxp-core/src/main/java/external/com/android/dex/MethodHandle.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/MethodHandle.java rename to edxp-core/src/main/java/external/com/android/dex/MethodHandle.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/MethodId.java b/edxp-core/src/main/java/external/com/android/dex/MethodId.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/MethodId.java rename to edxp-core/src/main/java/external/com/android/dex/MethodId.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/Mutf8.java b/edxp-core/src/main/java/external/com/android/dex/Mutf8.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/Mutf8.java rename to edxp-core/src/main/java/external/com/android/dex/Mutf8.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/ProtoId.java b/edxp-core/src/main/java/external/com/android/dex/ProtoId.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/ProtoId.java rename to edxp-core/src/main/java/external/com/android/dex/ProtoId.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/SizeOf.java b/edxp-core/src/main/java/external/com/android/dex/SizeOf.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/SizeOf.java rename to edxp-core/src/main/java/external/com/android/dex/SizeOf.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/TableOfContents.java b/edxp-core/src/main/java/external/com/android/dex/TableOfContents.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/TableOfContents.java rename to edxp-core/src/main/java/external/com/android/dex/TableOfContents.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/TypeList.java b/edxp-core/src/main/java/external/com/android/dex/TypeList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/TypeList.java rename to edxp-core/src/main/java/external/com/android/dex/TypeList.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/util/ByteArrayByteInput.java b/edxp-core/src/main/java/external/com/android/dex/util/ByteArrayByteInput.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/util/ByteArrayByteInput.java rename to edxp-core/src/main/java/external/com/android/dex/util/ByteArrayByteInput.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/util/ByteInput.java b/edxp-core/src/main/java/external/com/android/dex/util/ByteInput.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/util/ByteInput.java rename to edxp-core/src/main/java/external/com/android/dex/util/ByteInput.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/util/ByteOutput.java b/edxp-core/src/main/java/external/com/android/dex/util/ByteOutput.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/util/ByteOutput.java rename to edxp-core/src/main/java/external/com/android/dex/util/ByteOutput.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/util/ExceptionWithContext.java b/edxp-core/src/main/java/external/com/android/dex/util/ExceptionWithContext.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/util/ExceptionWithContext.java rename to edxp-core/src/main/java/external/com/android/dex/util/ExceptionWithContext.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/util/FileUtils.java b/edxp-core/src/main/java/external/com/android/dex/util/FileUtils.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/util/FileUtils.java rename to edxp-core/src/main/java/external/com/android/dex/util/FileUtils.java diff --git a/dalvikdx/src/main/java/external/com/android/dex/util/Unsigned.java b/edxp-core/src/main/java/external/com/android/dex/util/Unsigned.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dex/util/Unsigned.java rename to edxp-core/src/main/java/external/com/android/dex/util/Unsigned.java diff --git a/dexmaker/src/main/java/external/com/android/dx/AnnotationId.java b/edxp-core/src/main/java/external/com/android/dx/AnnotationId.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/AnnotationId.java rename to edxp-core/src/main/java/external/com/android/dx/AnnotationId.java diff --git a/dexmaker/src/main/java/external/com/android/dx/AppDataDirGuesser.java b/edxp-core/src/main/java/external/com/android/dx/AppDataDirGuesser.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/AppDataDirGuesser.java rename to edxp-core/src/main/java/external/com/android/dx/AppDataDirGuesser.java diff --git a/dexmaker/src/main/java/external/com/android/dx/BinaryOp.java b/edxp-core/src/main/java/external/com/android/dx/BinaryOp.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/BinaryOp.java rename to edxp-core/src/main/java/external/com/android/dx/BinaryOp.java diff --git a/dexmaker/src/main/java/external/com/android/dx/Code.java b/edxp-core/src/main/java/external/com/android/dx/Code.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/Code.java rename to edxp-core/src/main/java/external/com/android/dx/Code.java diff --git a/dexmaker/src/main/java/external/com/android/dx/Comparison.java b/edxp-core/src/main/java/external/com/android/dx/Comparison.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/Comparison.java rename to edxp-core/src/main/java/external/com/android/dx/Comparison.java diff --git a/dexmaker/src/main/java/external/com/android/dx/Constants.java b/edxp-core/src/main/java/external/com/android/dx/Constants.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/Constants.java rename to edxp-core/src/main/java/external/com/android/dx/Constants.java diff --git a/dexmaker/src/main/java/external/com/android/dx/DexMaker.java b/edxp-core/src/main/java/external/com/android/dx/DexMaker.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/DexMaker.java rename to edxp-core/src/main/java/external/com/android/dx/DexMaker.java diff --git a/dexmaker/src/main/java/external/com/android/dx/FieldId.java b/edxp-core/src/main/java/external/com/android/dx/FieldId.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/FieldId.java rename to edxp-core/src/main/java/external/com/android/dx/FieldId.java diff --git a/dexmaker/src/main/java/external/com/android/dx/Label.java b/edxp-core/src/main/java/external/com/android/dx/Label.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/Label.java rename to edxp-core/src/main/java/external/com/android/dx/Label.java diff --git a/dexmaker/src/main/java/external/com/android/dx/Local.java b/edxp-core/src/main/java/external/com/android/dx/Local.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/Local.java rename to edxp-core/src/main/java/external/com/android/dx/Local.java diff --git a/dexmaker/src/main/java/external/com/android/dx/MethodId.java b/edxp-core/src/main/java/external/com/android/dx/MethodId.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/MethodId.java rename to edxp-core/src/main/java/external/com/android/dx/MethodId.java diff --git a/dexmaker/src/main/java/external/com/android/dx/TypeId.java b/edxp-core/src/main/java/external/com/android/dx/TypeId.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/TypeId.java rename to edxp-core/src/main/java/external/com/android/dx/TypeId.java diff --git a/dexmaker/src/main/java/external/com/android/dx/TypeList.java b/edxp-core/src/main/java/external/com/android/dx/TypeList.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/TypeList.java rename to edxp-core/src/main/java/external/com/android/dx/TypeList.java diff --git a/dexmaker/src/main/java/external/com/android/dx/UnaryOp.java b/edxp-core/src/main/java/external/com/android/dx/UnaryOp.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/UnaryOp.java rename to edxp-core/src/main/java/external/com/android/dx/UnaryOp.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/Version.java b/edxp-core/src/main/java/external/com/android/dx/Version.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/Version.java rename to edxp-core/src/main/java/external/com/android/dx/Version.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttAnnotationDefault.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttAnnotationDefault.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttAnnotationDefault.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttAnnotationDefault.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttBootstrapMethods.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttBootstrapMethods.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttBootstrapMethods.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttBootstrapMethods.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttCode.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttCode.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttCode.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttCode.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttConstantValue.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttConstantValue.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttConstantValue.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttConstantValue.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttDeprecated.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttDeprecated.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttDeprecated.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttDeprecated.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttEnclosingMethod.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttEnclosingMethod.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttEnclosingMethod.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttEnclosingMethod.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttExceptions.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttExceptions.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttExceptions.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttExceptions.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttInnerClasses.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttInnerClasses.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttInnerClasses.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttInnerClasses.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttLineNumberTable.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttLineNumberTable.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttLineNumberTable.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttLineNumberTable.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttLocalVariableTable.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttLocalVariableTable.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttLocalVariableTable.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttLocalVariableTable.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttLocalVariableTypeTable.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttLocalVariableTypeTable.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttLocalVariableTypeTable.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttLocalVariableTypeTable.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeInvisibleAnnotations.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeInvisibleAnnotations.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeInvisibleAnnotations.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeInvisibleAnnotations.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeInvisibleParameterAnnotations.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeInvisibleParameterAnnotations.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeInvisibleParameterAnnotations.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeInvisibleParameterAnnotations.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeVisibleAnnotations.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeVisibleAnnotations.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeVisibleAnnotations.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeVisibleAnnotations.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeVisibleParameterAnnotations.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeVisibleParameterAnnotations.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeVisibleParameterAnnotations.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttRuntimeVisibleParameterAnnotations.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttSignature.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttSignature.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttSignature.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttSignature.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttSourceDebugExtension.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttSourceDebugExtension.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttSourceDebugExtension.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttSourceDebugExtension.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttSourceFile.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttSourceFile.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttSourceFile.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttSourceFile.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttSynthetic.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttSynthetic.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/AttSynthetic.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/AttSynthetic.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/BaseAnnotations.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/BaseAnnotations.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/BaseAnnotations.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/BaseAnnotations.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/BaseAttribute.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/BaseAttribute.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/BaseAttribute.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/BaseAttribute.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/BaseLocalVariables.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/BaseLocalVariables.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/BaseLocalVariables.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/BaseLocalVariables.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/BaseParameterAnnotations.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/BaseParameterAnnotations.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/BaseParameterAnnotations.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/BaseParameterAnnotations.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/InnerClassList.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/InnerClassList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/InnerClassList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/InnerClassList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/RawAttribute.java b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/RawAttribute.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/RawAttribute.java rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/RawAttribute.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/attrib/package.html b/edxp-core/src/main/java/external/com/android/dx/cf/attrib/package.html similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/attrib/package.html rename to edxp-core/src/main/java/external/com/android/dx/cf/attrib/package.html diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/BaseMachine.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/BaseMachine.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/BaseMachine.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/BaseMachine.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/BasicBlocker.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/BasicBlocker.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/BasicBlocker.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/BasicBlocker.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/BootstrapMethodArgumentsList.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/BootstrapMethodArgumentsList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/BootstrapMethodArgumentsList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/BootstrapMethodArgumentsList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/BootstrapMethodsList.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/BootstrapMethodsList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/BootstrapMethodsList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/BootstrapMethodsList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/ByteBlock.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/ByteBlock.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/ByteBlock.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/ByteBlock.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/ByteBlockList.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/ByteBlockList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/ByteBlockList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/ByteBlockList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/ByteCatchList.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/ByteCatchList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/ByteCatchList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/ByteCatchList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/ByteOps.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/ByteOps.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/ByteOps.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/ByteOps.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/BytecodeArray.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/BytecodeArray.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/BytecodeArray.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/BytecodeArray.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/ConcreteMethod.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/ConcreteMethod.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/ConcreteMethod.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/ConcreteMethod.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/ExecutionStack.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/ExecutionStack.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/ExecutionStack.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/ExecutionStack.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/Frame.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/Frame.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/Frame.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/Frame.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/LineNumberList.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/LineNumberList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/LineNumberList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/LineNumberList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/LocalVariableList.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/LocalVariableList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/LocalVariableList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/LocalVariableList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/LocalsArray.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/LocalsArray.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/LocalsArray.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/LocalsArray.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/LocalsArraySet.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/LocalsArraySet.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/LocalsArraySet.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/LocalsArraySet.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/Machine.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/Machine.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/Machine.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/Machine.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/Merger.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/Merger.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/Merger.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/Merger.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/OneLocalsArray.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/OneLocalsArray.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/OneLocalsArray.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/OneLocalsArray.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/ReturnAddress.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/ReturnAddress.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/ReturnAddress.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/ReturnAddress.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/Ropper.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/Ropper.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/Ropper.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/Ropper.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/RopperMachine.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/RopperMachine.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/RopperMachine.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/RopperMachine.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/SimException.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/SimException.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/SimException.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/SimException.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/Simulator.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/Simulator.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/Simulator.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/Simulator.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/SwitchList.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/SwitchList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/SwitchList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/SwitchList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/ValueAwareMachine.java b/edxp-core/src/main/java/external/com/android/dx/cf/code/ValueAwareMachine.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/ValueAwareMachine.java rename to edxp-core/src/main/java/external/com/android/dx/cf/code/ValueAwareMachine.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/code/package.html b/edxp-core/src/main/java/external/com/android/dx/cf/code/package.html similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/code/package.html rename to edxp-core/src/main/java/external/com/android/dx/cf/code/package.html diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/cst/ConstantPoolParser.java b/edxp-core/src/main/java/external/com/android/dx/cf/cst/ConstantPoolParser.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/cst/ConstantPoolParser.java rename to edxp-core/src/main/java/external/com/android/dx/cf/cst/ConstantPoolParser.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/cst/ConstantTags.java b/edxp-core/src/main/java/external/com/android/dx/cf/cst/ConstantTags.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/cst/ConstantTags.java rename to edxp-core/src/main/java/external/com/android/dx/cf/cst/ConstantTags.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/cst/MethodHandleKind.java b/edxp-core/src/main/java/external/com/android/dx/cf/cst/MethodHandleKind.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/cst/MethodHandleKind.java rename to edxp-core/src/main/java/external/com/android/dx/cf/cst/MethodHandleKind.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/AnnotationParser.java b/edxp-core/src/main/java/external/com/android/dx/cf/direct/AnnotationParser.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/AnnotationParser.java rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/AnnotationParser.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/AttributeFactory.java b/edxp-core/src/main/java/external/com/android/dx/cf/direct/AttributeFactory.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/AttributeFactory.java rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/AttributeFactory.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/AttributeListParser.java b/edxp-core/src/main/java/external/com/android/dx/cf/direct/AttributeListParser.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/AttributeListParser.java rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/AttributeListParser.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/ClassPathOpener.java b/edxp-core/src/main/java/external/com/android/dx/cf/direct/ClassPathOpener.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/ClassPathOpener.java rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/ClassPathOpener.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/CodeObserver.java b/edxp-core/src/main/java/external/com/android/dx/cf/direct/CodeObserver.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/CodeObserver.java rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/CodeObserver.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/DirectClassFile.java b/edxp-core/src/main/java/external/com/android/dx/cf/direct/DirectClassFile.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/DirectClassFile.java rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/DirectClassFile.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/FieldListParser.java b/edxp-core/src/main/java/external/com/android/dx/cf/direct/FieldListParser.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/FieldListParser.java rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/FieldListParser.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/MemberListParser.java b/edxp-core/src/main/java/external/com/android/dx/cf/direct/MemberListParser.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/MemberListParser.java rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/MemberListParser.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/MethodListParser.java b/edxp-core/src/main/java/external/com/android/dx/cf/direct/MethodListParser.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/MethodListParser.java rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/MethodListParser.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/StdAttributeFactory.java b/edxp-core/src/main/java/external/com/android/dx/cf/direct/StdAttributeFactory.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/StdAttributeFactory.java rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/StdAttributeFactory.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/direct/package.html b/edxp-core/src/main/java/external/com/android/dx/cf/direct/package.html similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/direct/package.html rename to edxp-core/src/main/java/external/com/android/dx/cf/direct/package.html diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/Attribute.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/Attribute.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/Attribute.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/Attribute.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/AttributeList.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/AttributeList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/AttributeList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/AttributeList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/ClassFile.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/ClassFile.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/ClassFile.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/ClassFile.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/Field.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/Field.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/Field.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/Field.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/FieldList.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/FieldList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/FieldList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/FieldList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/HasAttribute.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/HasAttribute.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/HasAttribute.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/HasAttribute.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/Member.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/Member.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/Member.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/Member.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/Method.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/Method.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/Method.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/Method.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/MethodList.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/MethodList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/MethodList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/MethodList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/ParseException.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/ParseException.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/ParseException.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/ParseException.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/ParseObserver.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/ParseObserver.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/ParseObserver.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/ParseObserver.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdAttributeList.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/StdAttributeList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdAttributeList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/StdAttributeList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdField.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/StdField.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdField.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/StdField.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdFieldList.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/StdFieldList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdFieldList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/StdFieldList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdMember.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/StdMember.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdMember.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/StdMember.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdMethod.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/StdMethod.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdMethod.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/StdMethod.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdMethodList.java b/edxp-core/src/main/java/external/com/android/dx/cf/iface/StdMethodList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/StdMethodList.java rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/StdMethodList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/cf/iface/package.html b/edxp-core/src/main/java/external/com/android/dx/cf/iface/package.html similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/cf/iface/package.html rename to edxp-core/src/main/java/external/com/android/dx/cf/iface/package.html diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/Main.java b/edxp-core/src/main/java/external/com/android/dx/command/Main.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/Main.java rename to edxp-core/src/main/java/external/com/android/dx/command/Main.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/UsageException.java b/edxp-core/src/main/java/external/com/android/dx/command/UsageException.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/UsageException.java rename to edxp-core/src/main/java/external/com/android/dx/command/UsageException.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/annotool/AnnotationLister.java b/edxp-core/src/main/java/external/com/android/dx/command/annotool/AnnotationLister.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/annotool/AnnotationLister.java rename to edxp-core/src/main/java/external/com/android/dx/command/annotool/AnnotationLister.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/annotool/Main.java b/edxp-core/src/main/java/external/com/android/dx/command/annotool/Main.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/annotool/Main.java rename to edxp-core/src/main/java/external/com/android/dx/command/annotool/Main.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/dexer/DxContext.java b/edxp-core/src/main/java/external/com/android/dx/command/dexer/DxContext.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/dexer/DxContext.java rename to edxp-core/src/main/java/external/com/android/dx/command/dexer/DxContext.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/dexer/Main.java b/edxp-core/src/main/java/external/com/android/dx/command/dexer/Main.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/dexer/Main.java rename to edxp-core/src/main/java/external/com/android/dx/command/dexer/Main.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/dump/Args.java b/edxp-core/src/main/java/external/com/android/dx/command/dump/Args.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/dump/Args.java rename to edxp-core/src/main/java/external/com/android/dx/command/dump/Args.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/dump/BaseDumper.java b/edxp-core/src/main/java/external/com/android/dx/command/dump/BaseDumper.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/dump/BaseDumper.java rename to edxp-core/src/main/java/external/com/android/dx/command/dump/BaseDumper.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/dump/BlockDumper.java b/edxp-core/src/main/java/external/com/android/dx/command/dump/BlockDumper.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/dump/BlockDumper.java rename to edxp-core/src/main/java/external/com/android/dx/command/dump/BlockDumper.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/dump/ClassDumper.java b/edxp-core/src/main/java/external/com/android/dx/command/dump/ClassDumper.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/dump/ClassDumper.java rename to edxp-core/src/main/java/external/com/android/dx/command/dump/ClassDumper.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/dump/DotDumper.java b/edxp-core/src/main/java/external/com/android/dx/command/dump/DotDumper.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/dump/DotDumper.java rename to edxp-core/src/main/java/external/com/android/dx/command/dump/DotDumper.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/dump/Main.java b/edxp-core/src/main/java/external/com/android/dx/command/dump/Main.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/dump/Main.java rename to edxp-core/src/main/java/external/com/android/dx/command/dump/Main.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/dump/SsaDumper.java b/edxp-core/src/main/java/external/com/android/dx/command/dump/SsaDumper.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/dump/SsaDumper.java rename to edxp-core/src/main/java/external/com/android/dx/command/dump/SsaDumper.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/findusages/FindUsages.java b/edxp-core/src/main/java/external/com/android/dx/command/findusages/FindUsages.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/findusages/FindUsages.java rename to edxp-core/src/main/java/external/com/android/dx/command/findusages/FindUsages.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/findusages/Main.java b/edxp-core/src/main/java/external/com/android/dx/command/findusages/Main.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/findusages/Main.java rename to edxp-core/src/main/java/external/com/android/dx/command/findusages/Main.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/grep/Grep.java b/edxp-core/src/main/java/external/com/android/dx/command/grep/Grep.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/grep/Grep.java rename to edxp-core/src/main/java/external/com/android/dx/command/grep/Grep.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/command/grep/Main.java b/edxp-core/src/main/java/external/com/android/dx/command/grep/Main.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/command/grep/Main.java rename to edxp-core/src/main/java/external/com/android/dx/command/grep/Main.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/DexOptions.java b/edxp-core/src/main/java/external/com/android/dx/dex/DexOptions.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/DexOptions.java rename to edxp-core/src/main/java/external/com/android/dx/dex/DexOptions.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/cf/AttributeTranslator.java b/edxp-core/src/main/java/external/com/android/dx/dex/cf/AttributeTranslator.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/cf/AttributeTranslator.java rename to edxp-core/src/main/java/external/com/android/dx/dex/cf/AttributeTranslator.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/cf/CfOptions.java b/edxp-core/src/main/java/external/com/android/dx/dex/cf/CfOptions.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/cf/CfOptions.java rename to edxp-core/src/main/java/external/com/android/dx/dex/cf/CfOptions.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/cf/CfTranslator.java b/edxp-core/src/main/java/external/com/android/dx/dex/cf/CfTranslator.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/cf/CfTranslator.java rename to edxp-core/src/main/java/external/com/android/dx/dex/cf/CfTranslator.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/cf/CodeStatistics.java b/edxp-core/src/main/java/external/com/android/dx/dex/cf/CodeStatistics.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/cf/CodeStatistics.java rename to edxp-core/src/main/java/external/com/android/dx/dex/cf/CodeStatistics.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/cf/OptimizerOptions.java b/edxp-core/src/main/java/external/com/android/dx/dex/cf/OptimizerOptions.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/cf/OptimizerOptions.java rename to edxp-core/src/main/java/external/com/android/dx/dex/cf/OptimizerOptions.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/cf/package.html b/edxp-core/src/main/java/external/com/android/dx/dex/cf/package.html similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/cf/package.html rename to edxp-core/src/main/java/external/com/android/dx/dex/cf/package.html diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/ArrayData.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/ArrayData.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/ArrayData.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/ArrayData.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/BlockAddresses.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/BlockAddresses.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/BlockAddresses.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/BlockAddresses.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/CatchBuilder.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/CatchBuilder.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/CatchBuilder.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/CatchBuilder.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/CatchHandlerList.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/CatchHandlerList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/CatchHandlerList.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/CatchHandlerList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/CatchTable.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/CatchTable.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/CatchTable.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/CatchTable.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/CodeAddress.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/CodeAddress.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/CodeAddress.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/CodeAddress.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/CstInsn.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/CstInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/CstInsn.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/CstInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/DalvCode.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/DalvCode.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/DalvCode.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/DalvCode.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/DalvInsn.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/DalvInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/DalvInsn.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/DalvInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/DalvInsnList.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/DalvInsnList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/DalvInsnList.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/DalvInsnList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/Dop.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/Dop.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/Dop.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/Dop.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/Dops.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/Dops.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/Dops.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/Dops.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/FixedSizeInsn.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/FixedSizeInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/FixedSizeInsn.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/FixedSizeInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/HighRegisterPrefix.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/HighRegisterPrefix.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/HighRegisterPrefix.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/HighRegisterPrefix.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/InsnFormat.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/InsnFormat.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/InsnFormat.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/InsnFormat.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/LocalList.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/LocalList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/LocalList.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/LocalList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/LocalSnapshot.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/LocalSnapshot.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/LocalSnapshot.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/LocalSnapshot.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/LocalStart.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/LocalStart.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/LocalStart.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/LocalStart.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/MultiCstInsn.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/MultiCstInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/MultiCstInsn.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/MultiCstInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/OddSpacer.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/OddSpacer.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/OddSpacer.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/OddSpacer.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/OutputCollector.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/OutputCollector.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/OutputCollector.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/OutputCollector.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/OutputFinisher.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/OutputFinisher.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/OutputFinisher.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/OutputFinisher.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/PositionList.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/PositionList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/PositionList.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/PositionList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/RopToDop.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/RopToDop.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/RopToDop.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/RopToDop.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/RopTranslator.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/RopTranslator.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/RopTranslator.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/RopTranslator.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/SimpleInsn.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/SimpleInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/SimpleInsn.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/SimpleInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/StdCatchBuilder.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/StdCatchBuilder.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/StdCatchBuilder.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/StdCatchBuilder.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/SwitchData.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/SwitchData.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/SwitchData.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/SwitchData.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/TargetInsn.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/TargetInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/TargetInsn.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/TargetInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/VariableSizeInsn.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/VariableSizeInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/VariableSizeInsn.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/VariableSizeInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/ZeroSizeInsn.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/ZeroSizeInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/ZeroSizeInsn.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/ZeroSizeInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form10t.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form10t.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form10t.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form10t.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form10x.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form10x.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form10x.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form10x.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form11n.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form11n.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form11n.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form11n.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form11x.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form11x.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form11x.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form11x.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form12x.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form12x.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form12x.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form12x.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form20t.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form20t.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form20t.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form20t.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form21c.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form21c.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form21c.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form21c.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form21h.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form21h.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form21h.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form21h.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form21s.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form21s.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form21s.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form21s.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form21t.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form21t.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form21t.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form21t.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form22b.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form22b.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form22b.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form22b.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form22c.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form22c.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form22c.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form22c.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form22s.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form22s.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form22s.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form22s.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form22t.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form22t.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form22t.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form22t.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form22x.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form22x.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form22x.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form22x.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form23x.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form23x.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form23x.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form23x.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form30t.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form30t.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form30t.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form30t.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form31c.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form31c.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form31c.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form31c.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form31i.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form31i.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form31i.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form31i.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form31t.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form31t.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form31t.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form31t.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form32x.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form32x.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form32x.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form32x.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form35c.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form35c.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form35c.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form35c.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form3rc.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form3rc.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form3rc.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form3rc.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form45cc.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form45cc.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form45cc.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form45cc.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form4rcc.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form4rcc.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form4rcc.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form4rcc.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form51l.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form51l.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/Form51l.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/Form51l.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/code/form/SpecialFormat.java b/edxp-core/src/main/java/external/com/android/dx/dex/code/form/SpecialFormat.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/code/form/SpecialFormat.java rename to edxp-core/src/main/java/external/com/android/dx/dex/code/form/SpecialFormat.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/AnnotationItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/AnnotationItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/AnnotationItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/AnnotationItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/AnnotationSetItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/AnnotationSetItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/AnnotationSetItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/AnnotationSetItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/AnnotationSetRefItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/AnnotationSetRefItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/AnnotationSetRefItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/AnnotationSetRefItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/AnnotationUtils.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/AnnotationUtils.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/AnnotationUtils.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/AnnotationUtils.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/AnnotationsDirectoryItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/AnnotationsDirectoryItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/AnnotationsDirectoryItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/AnnotationsDirectoryItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/CallSiteIdItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/CallSiteIdItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/CallSiteIdItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/CallSiteIdItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/CallSiteIdsSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/CallSiteIdsSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/CallSiteIdsSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/CallSiteIdsSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/CallSiteItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/CallSiteItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/CallSiteItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/CallSiteItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/CatchStructs.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/CatchStructs.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/CatchStructs.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/CatchStructs.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/ClassDataItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/ClassDataItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/ClassDataItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/ClassDataItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/ClassDefItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/ClassDefItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/ClassDefItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/ClassDefItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/ClassDefsSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/ClassDefsSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/ClassDefsSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/ClassDefsSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/CodeItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/CodeItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/CodeItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/CodeItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/DebugInfoConstants.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/DebugInfoConstants.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/DebugInfoConstants.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/DebugInfoConstants.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/DebugInfoDecoder.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/DebugInfoDecoder.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/DebugInfoDecoder.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/DebugInfoDecoder.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/DebugInfoEncoder.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/DebugInfoEncoder.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/DebugInfoEncoder.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/DebugInfoEncoder.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/DebugInfoItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/DebugInfoItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/DebugInfoItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/DebugInfoItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/DexFile.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/DexFile.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/DexFile.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/DexFile.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/EncodedArrayItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/EncodedArrayItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/EncodedArrayItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/EncodedArrayItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/EncodedField.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/EncodedField.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/EncodedField.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/EncodedField.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/EncodedMember.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/EncodedMember.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/EncodedMember.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/EncodedMember.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/EncodedMethod.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/EncodedMethod.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/EncodedMethod.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/EncodedMethod.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/FieldAnnotationStruct.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/FieldAnnotationStruct.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/FieldAnnotationStruct.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/FieldAnnotationStruct.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/FieldIdItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/FieldIdItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/FieldIdItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/FieldIdItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/FieldIdsSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/FieldIdsSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/FieldIdsSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/FieldIdsSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/HeaderItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/HeaderItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/HeaderItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/HeaderItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/HeaderSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/HeaderSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/HeaderSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/HeaderSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/IdItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/IdItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/IdItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/IdItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/IndexedItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/IndexedItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/IndexedItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/IndexedItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/Item.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/Item.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/Item.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/Item.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/ItemType.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/ItemType.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/ItemType.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/ItemType.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/MapItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/MapItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/MapItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/MapItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/MemberIdItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/MemberIdItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/MemberIdItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/MemberIdItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/MemberIdsSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/MemberIdsSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/MemberIdsSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/MemberIdsSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/MethodAnnotationStruct.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/MethodAnnotationStruct.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/MethodAnnotationStruct.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/MethodAnnotationStruct.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/MethodHandleItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/MethodHandleItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/MethodHandleItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/MethodHandleItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/MethodHandlesSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/MethodHandlesSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/MethodHandlesSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/MethodHandlesSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/MethodIdItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/MethodIdItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/MethodIdItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/MethodIdItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/MethodIdsSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/MethodIdsSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/MethodIdsSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/MethodIdsSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/MixedItemSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/MixedItemSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/MixedItemSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/MixedItemSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/OffsettedItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/OffsettedItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/OffsettedItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/OffsettedItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/ParameterAnnotationStruct.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/ParameterAnnotationStruct.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/ParameterAnnotationStruct.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/ParameterAnnotationStruct.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/ProtoIdItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/ProtoIdItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/ProtoIdItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/ProtoIdItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/ProtoIdsSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/ProtoIdsSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/ProtoIdsSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/ProtoIdsSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/Section.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/Section.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/Section.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/Section.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/Statistics.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/Statistics.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/Statistics.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/Statistics.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/StringDataItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/StringDataItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/StringDataItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/StringDataItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/StringIdItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/StringIdItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/StringIdItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/StringIdItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/StringIdsSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/StringIdsSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/StringIdsSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/StringIdsSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/TypeIdItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/TypeIdItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/TypeIdItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/TypeIdItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/TypeIdsSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/TypeIdsSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/TypeIdsSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/TypeIdsSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/TypeListItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/TypeListItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/TypeListItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/TypeListItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/UniformItemSection.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/UniformItemSection.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/UniformItemSection.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/UniformItemSection.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/UniformListItem.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/UniformListItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/UniformListItem.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/UniformListItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/dex/file/ValueEncoder.java b/edxp-core/src/main/java/external/com/android/dx/dex/file/ValueEncoder.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/dex/file/ValueEncoder.java rename to edxp-core/src/main/java/external/com/android/dx/dex/file/ValueEncoder.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/CodeReader.java b/edxp-core/src/main/java/external/com/android/dx/io/CodeReader.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/CodeReader.java rename to edxp-core/src/main/java/external/com/android/dx/io/CodeReader.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/DexIndexPrinter.java b/edxp-core/src/main/java/external/com/android/dx/io/DexIndexPrinter.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/DexIndexPrinter.java rename to edxp-core/src/main/java/external/com/android/dx/io/DexIndexPrinter.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/IndexType.java b/edxp-core/src/main/java/external/com/android/dx/io/IndexType.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/IndexType.java rename to edxp-core/src/main/java/external/com/android/dx/io/IndexType.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/OpcodeInfo.java b/edxp-core/src/main/java/external/com/android/dx/io/OpcodeInfo.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/OpcodeInfo.java rename to edxp-core/src/main/java/external/com/android/dx/io/OpcodeInfo.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/Opcodes.java b/edxp-core/src/main/java/external/com/android/dx/io/Opcodes.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/Opcodes.java rename to edxp-core/src/main/java/external/com/android/dx/io/Opcodes.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/AddressMap.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/AddressMap.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/AddressMap.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/AddressMap.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/BaseCodeCursor.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/BaseCodeCursor.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/BaseCodeCursor.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/BaseCodeCursor.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/CodeCursor.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/CodeCursor.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/CodeCursor.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/CodeCursor.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/CodeInput.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/CodeInput.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/CodeInput.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/CodeInput.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/CodeOutput.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/CodeOutput.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/CodeOutput.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/CodeOutput.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/DecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/DecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/DecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/DecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/FillArrayDataPayloadDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/FillArrayDataPayloadDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/FillArrayDataPayloadDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/FillArrayDataPayloadDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/FiveRegisterDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/FiveRegisterDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/FiveRegisterDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/FiveRegisterDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/FourRegisterDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/FourRegisterDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/FourRegisterDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/FourRegisterDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/InstructionCodec.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/InstructionCodec.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/InstructionCodec.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/InstructionCodec.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/InvokePolymorphicDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/InvokePolymorphicDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/InvokePolymorphicDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/InvokePolymorphicDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/InvokePolymorphicRangeDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/InvokePolymorphicRangeDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/InvokePolymorphicRangeDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/InvokePolymorphicRangeDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/OneRegisterDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/OneRegisterDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/OneRegisterDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/OneRegisterDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/PackedSwitchPayloadDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/PackedSwitchPayloadDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/PackedSwitchPayloadDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/PackedSwitchPayloadDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/RegisterRangeDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/RegisterRangeDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/RegisterRangeDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/RegisterRangeDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/ShortArrayCodeInput.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/ShortArrayCodeInput.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/ShortArrayCodeInput.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/ShortArrayCodeInput.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/ShortArrayCodeOutput.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/ShortArrayCodeOutput.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/ShortArrayCodeOutput.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/ShortArrayCodeOutput.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/SparseSwitchPayloadDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/SparseSwitchPayloadDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/SparseSwitchPayloadDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/SparseSwitchPayloadDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/ThreeRegisterDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/ThreeRegisterDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/ThreeRegisterDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/ThreeRegisterDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/TwoRegisterDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/TwoRegisterDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/TwoRegisterDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/TwoRegisterDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/io/instructions/ZeroRegisterDecodedInstruction.java b/edxp-core/src/main/java/external/com/android/dx/io/instructions/ZeroRegisterDecodedInstruction.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/io/instructions/ZeroRegisterDecodedInstruction.java rename to edxp-core/src/main/java/external/com/android/dx/io/instructions/ZeroRegisterDecodedInstruction.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/merge/CollisionPolicy.java b/edxp-core/src/main/java/external/com/android/dx/merge/CollisionPolicy.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/merge/CollisionPolicy.java rename to edxp-core/src/main/java/external/com/android/dx/merge/CollisionPolicy.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/merge/DexMerger.java b/edxp-core/src/main/java/external/com/android/dx/merge/DexMerger.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/merge/DexMerger.java rename to edxp-core/src/main/java/external/com/android/dx/merge/DexMerger.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/merge/IndexMap.java b/edxp-core/src/main/java/external/com/android/dx/merge/IndexMap.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/merge/IndexMap.java rename to edxp-core/src/main/java/external/com/android/dx/merge/IndexMap.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/merge/InstructionTransformer.java b/edxp-core/src/main/java/external/com/android/dx/merge/InstructionTransformer.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/merge/InstructionTransformer.java rename to edxp-core/src/main/java/external/com/android/dx/merge/InstructionTransformer.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/merge/SortableType.java b/edxp-core/src/main/java/external/com/android/dx/merge/SortableType.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/merge/SortableType.java rename to edxp-core/src/main/java/external/com/android/dx/merge/SortableType.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/annotation/Annotation.java b/edxp-core/src/main/java/external/com/android/dx/rop/annotation/Annotation.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/annotation/Annotation.java rename to edxp-core/src/main/java/external/com/android/dx/rop/annotation/Annotation.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/annotation/AnnotationVisibility.java b/edxp-core/src/main/java/external/com/android/dx/rop/annotation/AnnotationVisibility.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/annotation/AnnotationVisibility.java rename to edxp-core/src/main/java/external/com/android/dx/rop/annotation/AnnotationVisibility.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/annotation/Annotations.java b/edxp-core/src/main/java/external/com/android/dx/rop/annotation/Annotations.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/annotation/Annotations.java rename to edxp-core/src/main/java/external/com/android/dx/rop/annotation/Annotations.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/annotation/AnnotationsList.java b/edxp-core/src/main/java/external/com/android/dx/rop/annotation/AnnotationsList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/annotation/AnnotationsList.java rename to edxp-core/src/main/java/external/com/android/dx/rop/annotation/AnnotationsList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/annotation/NameValuePair.java b/edxp-core/src/main/java/external/com/android/dx/rop/annotation/NameValuePair.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/annotation/NameValuePair.java rename to edxp-core/src/main/java/external/com/android/dx/rop/annotation/NameValuePair.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/AccessFlags.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/AccessFlags.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/AccessFlags.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/AccessFlags.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/BasicBlock.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/BasicBlock.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/BasicBlock.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/BasicBlock.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/BasicBlockList.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/BasicBlockList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/BasicBlockList.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/BasicBlockList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/ConservativeTranslationAdvice.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/ConservativeTranslationAdvice.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/ConservativeTranslationAdvice.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/ConservativeTranslationAdvice.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/CstInsn.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/CstInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/CstInsn.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/CstInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/DexTranslationAdvice.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/DexTranslationAdvice.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/DexTranslationAdvice.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/DexTranslationAdvice.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/Exceptions.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/Exceptions.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/Exceptions.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/Exceptions.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/FillArrayDataInsn.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/FillArrayDataInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/FillArrayDataInsn.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/FillArrayDataInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/Insn.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/Insn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/Insn.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/Insn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/InsnList.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/InsnList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/InsnList.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/InsnList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/InvokePolymorphicInsn.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/InvokePolymorphicInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/InvokePolymorphicInsn.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/InvokePolymorphicInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/LocalItem.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/LocalItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/LocalItem.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/LocalItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/LocalVariableExtractor.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/LocalVariableExtractor.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/LocalVariableExtractor.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/LocalVariableExtractor.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/LocalVariableInfo.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/LocalVariableInfo.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/LocalVariableInfo.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/LocalVariableInfo.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/PlainCstInsn.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/PlainCstInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/PlainCstInsn.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/PlainCstInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/PlainInsn.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/PlainInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/PlainInsn.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/PlainInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/RegOps.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/RegOps.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/RegOps.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/RegOps.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/RegisterSpec.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/RegisterSpec.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/RegisterSpec.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/RegisterSpec.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/RegisterSpecList.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/RegisterSpecList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/RegisterSpecList.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/RegisterSpecList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/RegisterSpecSet.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/RegisterSpecSet.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/RegisterSpecSet.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/RegisterSpecSet.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/Rop.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/Rop.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/Rop.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/Rop.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/RopMethod.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/RopMethod.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/RopMethod.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/RopMethod.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/Rops.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/Rops.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/Rops.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/Rops.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/SourcePosition.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/SourcePosition.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/SourcePosition.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/SourcePosition.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/SwitchInsn.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/SwitchInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/SwitchInsn.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/SwitchInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/ThrowingCstInsn.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/ThrowingCstInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/ThrowingCstInsn.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/ThrowingCstInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/ThrowingInsn.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/ThrowingInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/ThrowingInsn.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/ThrowingInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/TranslationAdvice.java b/edxp-core/src/main/java/external/com/android/dx/rop/code/TranslationAdvice.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/TranslationAdvice.java rename to edxp-core/src/main/java/external/com/android/dx/rop/code/TranslationAdvice.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/code/package.html b/edxp-core/src/main/java/external/com/android/dx/rop/code/package.html similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/code/package.html rename to edxp-core/src/main/java/external/com/android/dx/rop/code/package.html diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/Constant.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/Constant.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/Constant.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/Constant.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/ConstantPool.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/ConstantPool.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/ConstantPool.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/ConstantPool.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstAnnotation.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstAnnotation.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstAnnotation.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstAnnotation.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstArray.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstArray.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstArray.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstArray.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstBaseMethodRef.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstBaseMethodRef.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstBaseMethodRef.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstBaseMethodRef.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstBoolean.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstBoolean.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstBoolean.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstBoolean.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstByte.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstByte.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstByte.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstByte.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstCallSite.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstCallSite.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstCallSite.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstCallSite.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstCallSiteRef.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstCallSiteRef.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstCallSiteRef.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstCallSiteRef.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstChar.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstChar.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstChar.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstChar.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstDouble.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstDouble.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstDouble.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstDouble.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstEnumRef.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstEnumRef.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstEnumRef.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstEnumRef.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstFieldRef.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstFieldRef.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstFieldRef.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstFieldRef.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstFloat.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstFloat.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstFloat.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstFloat.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstInteger.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstInteger.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstInteger.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstInteger.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstInterfaceMethodRef.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstInterfaceMethodRef.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstInterfaceMethodRef.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstInterfaceMethodRef.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstInvokeDynamic.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstInvokeDynamic.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstInvokeDynamic.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstInvokeDynamic.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstKnownNull.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstKnownNull.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstKnownNull.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstKnownNull.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstLiteral32.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstLiteral32.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstLiteral32.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstLiteral32.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstLiteral64.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstLiteral64.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstLiteral64.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstLiteral64.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstLiteralBits.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstLiteralBits.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstLiteralBits.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstLiteralBits.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstLong.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstLong.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstLong.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstLong.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstMemberRef.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstMemberRef.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstMemberRef.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstMemberRef.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstMethodHandle.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstMethodHandle.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstMethodHandle.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstMethodHandle.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstMethodRef.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstMethodRef.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstMethodRef.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstMethodRef.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstNat.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstNat.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstNat.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstNat.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstProtoRef.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstProtoRef.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstProtoRef.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstProtoRef.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstShort.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstShort.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstShort.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstShort.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstString.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstString.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstString.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstString.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstType.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/CstType.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/CstType.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/CstType.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/StdConstantPool.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/StdConstantPool.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/StdConstantPool.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/StdConstantPool.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/TypedConstant.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/TypedConstant.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/TypedConstant.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/TypedConstant.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/Zeroes.java b/edxp-core/src/main/java/external/com/android/dx/rop/cst/Zeroes.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/Zeroes.java rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/Zeroes.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/cst/package.html b/edxp-core/src/main/java/external/com/android/dx/rop/cst/package.html similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/cst/package.html rename to edxp-core/src/main/java/external/com/android/dx/rop/cst/package.html diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/package-info.java b/edxp-core/src/main/java/external/com/android/dx/rop/package-info.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/package-info.java rename to edxp-core/src/main/java/external/com/android/dx/rop/package-info.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/type/Prototype.java b/edxp-core/src/main/java/external/com/android/dx/rop/type/Prototype.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/type/Prototype.java rename to edxp-core/src/main/java/external/com/android/dx/rop/type/Prototype.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/type/StdTypeList.java b/edxp-core/src/main/java/external/com/android/dx/rop/type/StdTypeList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/type/StdTypeList.java rename to edxp-core/src/main/java/external/com/android/dx/rop/type/StdTypeList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/type/Type.java b/edxp-core/src/main/java/external/com/android/dx/rop/type/Type.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/type/Type.java rename to edxp-core/src/main/java/external/com/android/dx/rop/type/Type.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/type/TypeBearer.java b/edxp-core/src/main/java/external/com/android/dx/rop/type/TypeBearer.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/type/TypeBearer.java rename to edxp-core/src/main/java/external/com/android/dx/rop/type/TypeBearer.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/type/TypeList.java b/edxp-core/src/main/java/external/com/android/dx/rop/type/TypeList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/type/TypeList.java rename to edxp-core/src/main/java/external/com/android/dx/rop/type/TypeList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/rop/type/package.html b/edxp-core/src/main/java/external/com/android/dx/rop/type/package.html similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/rop/type/package.html rename to edxp-core/src/main/java/external/com/android/dx/rop/type/package.html diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/BasicRegisterMapper.java b/edxp-core/src/main/java/external/com/android/dx/ssa/BasicRegisterMapper.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/BasicRegisterMapper.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/BasicRegisterMapper.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/ConstCollector.java b/edxp-core/src/main/java/external/com/android/dx/ssa/ConstCollector.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/ConstCollector.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/ConstCollector.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/DeadCodeRemover.java b/edxp-core/src/main/java/external/com/android/dx/ssa/DeadCodeRemover.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/DeadCodeRemover.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/DeadCodeRemover.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/DomFront.java b/edxp-core/src/main/java/external/com/android/dx/ssa/DomFront.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/DomFront.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/DomFront.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/Dominators.java b/edxp-core/src/main/java/external/com/android/dx/ssa/Dominators.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/Dominators.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/Dominators.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/EscapeAnalysis.java b/edxp-core/src/main/java/external/com/android/dx/ssa/EscapeAnalysis.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/EscapeAnalysis.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/EscapeAnalysis.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/InterferenceRegisterMapper.java b/edxp-core/src/main/java/external/com/android/dx/ssa/InterferenceRegisterMapper.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/InterferenceRegisterMapper.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/InterferenceRegisterMapper.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/LiteralOpUpgrader.java b/edxp-core/src/main/java/external/com/android/dx/ssa/LiteralOpUpgrader.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/LiteralOpUpgrader.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/LiteralOpUpgrader.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/LocalVariableExtractor.java b/edxp-core/src/main/java/external/com/android/dx/ssa/LocalVariableExtractor.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/LocalVariableExtractor.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/LocalVariableExtractor.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/LocalVariableInfo.java b/edxp-core/src/main/java/external/com/android/dx/ssa/LocalVariableInfo.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/LocalVariableInfo.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/LocalVariableInfo.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/MoveParamCombiner.java b/edxp-core/src/main/java/external/com/android/dx/ssa/MoveParamCombiner.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/MoveParamCombiner.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/MoveParamCombiner.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/NormalSsaInsn.java b/edxp-core/src/main/java/external/com/android/dx/ssa/NormalSsaInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/NormalSsaInsn.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/NormalSsaInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/Optimizer.java b/edxp-core/src/main/java/external/com/android/dx/ssa/Optimizer.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/Optimizer.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/Optimizer.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/PhiInsn.java b/edxp-core/src/main/java/external/com/android/dx/ssa/PhiInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/PhiInsn.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/PhiInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/PhiTypeResolver.java b/edxp-core/src/main/java/external/com/android/dx/ssa/PhiTypeResolver.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/PhiTypeResolver.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/PhiTypeResolver.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/RegisterMapper.java b/edxp-core/src/main/java/external/com/android/dx/ssa/RegisterMapper.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/RegisterMapper.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/RegisterMapper.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/SCCP.java b/edxp-core/src/main/java/external/com/android/dx/ssa/SCCP.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/SCCP.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/SCCP.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/SetFactory.java b/edxp-core/src/main/java/external/com/android/dx/ssa/SetFactory.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/SetFactory.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/SetFactory.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/SsaBasicBlock.java b/edxp-core/src/main/java/external/com/android/dx/ssa/SsaBasicBlock.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/SsaBasicBlock.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/SsaBasicBlock.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/SsaConverter.java b/edxp-core/src/main/java/external/com/android/dx/ssa/SsaConverter.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/SsaConverter.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/SsaConverter.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/SsaInsn.java b/edxp-core/src/main/java/external/com/android/dx/ssa/SsaInsn.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/SsaInsn.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/SsaInsn.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/SsaMethod.java b/edxp-core/src/main/java/external/com/android/dx/ssa/SsaMethod.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/SsaMethod.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/SsaMethod.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/SsaRenamer.java b/edxp-core/src/main/java/external/com/android/dx/ssa/SsaRenamer.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/SsaRenamer.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/SsaRenamer.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/back/FirstFitAllocator.java b/edxp-core/src/main/java/external/com/android/dx/ssa/back/FirstFitAllocator.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/back/FirstFitAllocator.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/back/FirstFitAllocator.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/back/FirstFitLocalCombiningAllocator.java b/edxp-core/src/main/java/external/com/android/dx/ssa/back/FirstFitLocalCombiningAllocator.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/back/FirstFitLocalCombiningAllocator.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/back/FirstFitLocalCombiningAllocator.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/back/IdenticalBlockCombiner.java b/edxp-core/src/main/java/external/com/android/dx/ssa/back/IdenticalBlockCombiner.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/back/IdenticalBlockCombiner.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/back/IdenticalBlockCombiner.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/back/InterferenceGraph.java b/edxp-core/src/main/java/external/com/android/dx/ssa/back/InterferenceGraph.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/back/InterferenceGraph.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/back/InterferenceGraph.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/back/LivenessAnalyzer.java b/edxp-core/src/main/java/external/com/android/dx/ssa/back/LivenessAnalyzer.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/back/LivenessAnalyzer.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/back/LivenessAnalyzer.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/back/NullRegisterAllocator.java b/edxp-core/src/main/java/external/com/android/dx/ssa/back/NullRegisterAllocator.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/back/NullRegisterAllocator.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/back/NullRegisterAllocator.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/back/RegisterAllocator.java b/edxp-core/src/main/java/external/com/android/dx/ssa/back/RegisterAllocator.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/back/RegisterAllocator.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/back/RegisterAllocator.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/back/SsaToRop.java b/edxp-core/src/main/java/external/com/android/dx/ssa/back/SsaToRop.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/back/SsaToRop.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/back/SsaToRop.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/ssa/package-info.java b/edxp-core/src/main/java/external/com/android/dx/ssa/package-info.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/ssa/package-info.java rename to edxp-core/src/main/java/external/com/android/dx/ssa/package-info.java diff --git a/dexmaker/src/main/java/external/com/android/dx/stock/ProxyBuilder.java b/edxp-core/src/main/java/external/com/android/dx/stock/ProxyBuilder.java similarity index 100% rename from dexmaker/src/main/java/external/com/android/dx/stock/ProxyBuilder.java rename to edxp-core/src/main/java/external/com/android/dx/stock/ProxyBuilder.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/AnnotatedOutput.java b/edxp-core/src/main/java/external/com/android/dx/util/AnnotatedOutput.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/AnnotatedOutput.java rename to edxp-core/src/main/java/external/com/android/dx/util/AnnotatedOutput.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/BitIntSet.java b/edxp-core/src/main/java/external/com/android/dx/util/BitIntSet.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/BitIntSet.java rename to edxp-core/src/main/java/external/com/android/dx/util/BitIntSet.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/Bits.java b/edxp-core/src/main/java/external/com/android/dx/util/Bits.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/Bits.java rename to edxp-core/src/main/java/external/com/android/dx/util/Bits.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/ByteArray.java b/edxp-core/src/main/java/external/com/android/dx/util/ByteArray.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/ByteArray.java rename to edxp-core/src/main/java/external/com/android/dx/util/ByteArray.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/ByteArrayAnnotatedOutput.java b/edxp-core/src/main/java/external/com/android/dx/util/ByteArrayAnnotatedOutput.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/ByteArrayAnnotatedOutput.java rename to edxp-core/src/main/java/external/com/android/dx/util/ByteArrayAnnotatedOutput.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/FixedSizeList.java b/edxp-core/src/main/java/external/com/android/dx/util/FixedSizeList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/FixedSizeList.java rename to edxp-core/src/main/java/external/com/android/dx/util/FixedSizeList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/Hex.java b/edxp-core/src/main/java/external/com/android/dx/util/Hex.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/Hex.java rename to edxp-core/src/main/java/external/com/android/dx/util/Hex.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/HexParser.java b/edxp-core/src/main/java/external/com/android/dx/util/HexParser.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/HexParser.java rename to edxp-core/src/main/java/external/com/android/dx/util/HexParser.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/IndentingWriter.java b/edxp-core/src/main/java/external/com/android/dx/util/IndentingWriter.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/IndentingWriter.java rename to edxp-core/src/main/java/external/com/android/dx/util/IndentingWriter.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/IntIterator.java b/edxp-core/src/main/java/external/com/android/dx/util/IntIterator.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/IntIterator.java rename to edxp-core/src/main/java/external/com/android/dx/util/IntIterator.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/IntList.java b/edxp-core/src/main/java/external/com/android/dx/util/IntList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/IntList.java rename to edxp-core/src/main/java/external/com/android/dx/util/IntList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/IntSet.java b/edxp-core/src/main/java/external/com/android/dx/util/IntSet.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/IntSet.java rename to edxp-core/src/main/java/external/com/android/dx/util/IntSet.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/LabeledItem.java b/edxp-core/src/main/java/external/com/android/dx/util/LabeledItem.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/LabeledItem.java rename to edxp-core/src/main/java/external/com/android/dx/util/LabeledItem.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/LabeledList.java b/edxp-core/src/main/java/external/com/android/dx/util/LabeledList.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/LabeledList.java rename to edxp-core/src/main/java/external/com/android/dx/util/LabeledList.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/ListIntSet.java b/edxp-core/src/main/java/external/com/android/dx/util/ListIntSet.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/ListIntSet.java rename to edxp-core/src/main/java/external/com/android/dx/util/ListIntSet.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/MutabilityControl.java b/edxp-core/src/main/java/external/com/android/dx/util/MutabilityControl.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/MutabilityControl.java rename to edxp-core/src/main/java/external/com/android/dx/util/MutabilityControl.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/MutabilityException.java b/edxp-core/src/main/java/external/com/android/dx/util/MutabilityException.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/MutabilityException.java rename to edxp-core/src/main/java/external/com/android/dx/util/MutabilityException.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/Output.java b/edxp-core/src/main/java/external/com/android/dx/util/Output.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/Output.java rename to edxp-core/src/main/java/external/com/android/dx/util/Output.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/ToHuman.java b/edxp-core/src/main/java/external/com/android/dx/util/ToHuman.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/ToHuman.java rename to edxp-core/src/main/java/external/com/android/dx/util/ToHuman.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/TwoColumnOutput.java b/edxp-core/src/main/java/external/com/android/dx/util/TwoColumnOutput.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/TwoColumnOutput.java rename to edxp-core/src/main/java/external/com/android/dx/util/TwoColumnOutput.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/Warning.java b/edxp-core/src/main/java/external/com/android/dx/util/Warning.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/Warning.java rename to edxp-core/src/main/java/external/com/android/dx/util/Warning.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/Writers.java b/edxp-core/src/main/java/external/com/android/dx/util/Writers.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/Writers.java rename to edxp-core/src/main/java/external/com/android/dx/util/Writers.java diff --git a/dalvikdx/src/main/java/external/com/android/dx/util/package.html b/edxp-core/src/main/java/external/com/android/dx/util/package.html similarity index 100% rename from dalvikdx/src/main/java/external/com/android/dx/util/package.html rename to edxp-core/src/main/java/external/com/android/dx/util/package.html diff --git a/dalvikdx/src/main/java/external/com/android/multidex/ArchivePathElement.java b/edxp-core/src/main/java/external/com/android/multidex/ArchivePathElement.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/multidex/ArchivePathElement.java rename to edxp-core/src/main/java/external/com/android/multidex/ArchivePathElement.java diff --git a/dalvikdx/src/main/java/external/com/android/multidex/ClassPathElement.java b/edxp-core/src/main/java/external/com/android/multidex/ClassPathElement.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/multidex/ClassPathElement.java rename to edxp-core/src/main/java/external/com/android/multidex/ClassPathElement.java diff --git a/dalvikdx/src/main/java/external/com/android/multidex/ClassReferenceListBuilder.java b/edxp-core/src/main/java/external/com/android/multidex/ClassReferenceListBuilder.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/multidex/ClassReferenceListBuilder.java rename to edxp-core/src/main/java/external/com/android/multidex/ClassReferenceListBuilder.java diff --git a/dalvikdx/src/main/java/external/com/android/multidex/FolderPathElement.java b/edxp-core/src/main/java/external/com/android/multidex/FolderPathElement.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/multidex/FolderPathElement.java rename to edxp-core/src/main/java/external/com/android/multidex/FolderPathElement.java diff --git a/dalvikdx/src/main/java/external/com/android/multidex/MainDexListBuilder.java b/edxp-core/src/main/java/external/com/android/multidex/MainDexListBuilder.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/multidex/MainDexListBuilder.java rename to edxp-core/src/main/java/external/com/android/multidex/MainDexListBuilder.java diff --git a/dalvikdx/src/main/java/external/com/android/multidex/Path.java b/edxp-core/src/main/java/external/com/android/multidex/Path.java similarity index 100% rename from dalvikdx/src/main/java/external/com/android/multidex/Path.java rename to edxp-core/src/main/java/external/com/android/multidex/Path.java diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/ArrayUtils.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/ArrayUtils.java new file mode 100644 index 00000000..1db7dc97 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/ArrayUtils.java @@ -0,0 +1,5797 @@ +/* + * 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.reflect.Array; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + + +import external.org.apache.commons.lang3.builder.EqualsBuilder; +import external.org.apache.commons.lang3.builder.HashCodeBuilder; +import external.org.apache.commons.lang3.builder.ToStringBuilder; +import external.org.apache.commons.lang3.builder.ToStringStyle; +import external.org.apache.commons.lang3.mutable.MutableInt; + +/** + *

Operations on arrays, primitive arrays (like {@code int[]}) and + * primitive wrapper arrays (like {@code Integer[]}).

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will not be thrown for a {@code null} + * array input. However, an Object array that contains a {@code null} + * element may throw an exception. Each method documents its behaviour.

+ * + *

#ThreadSafe#

+ * @since 2.0 + * @version $Id: ArrayUtils.java 1154216 2011-08-05 13:57:16Z mbenson $ + */ +public class ArrayUtils { + + /** + * An empty immutable {@code Object} array. + */ + public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; + /** + * An empty immutable {@code Class} array. + */ + public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; + /** + * An empty immutable {@code String} array. + */ + public static final String[] EMPTY_STRING_ARRAY = new String[0]; + /** + * An empty immutable {@code long} array. + */ + public static final long[] EMPTY_LONG_ARRAY = new long[0]; + /** + * An empty immutable {@code Long} array. + */ + public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0]; + /** + * An empty immutable {@code int} array. + */ + public static final int[] EMPTY_INT_ARRAY = new int[0]; + /** + * An empty immutable {@code Integer} array. + */ + public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0]; + /** + * An empty immutable {@code short} array. + */ + public static final short[] EMPTY_SHORT_ARRAY = new short[0]; + /** + * An empty immutable {@code Short} array. + */ + public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0]; + /** + * An empty immutable {@code byte} array. + */ + public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; + /** + * An empty immutable {@code Byte} array. + */ + public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0]; + /** + * An empty immutable {@code double} array. + */ + public static final double[] EMPTY_DOUBLE_ARRAY = new double[0]; + /** + * An empty immutable {@code Double} array. + */ + public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0]; + /** + * An empty immutable {@code float} array. + */ + public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; + /** + * An empty immutable {@code Float} array. + */ + public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0]; + /** + * An empty immutable {@code boolean} array. + */ + public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; + /** + * An empty immutable {@code Boolean} array. + */ + public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0]; + /** + * An empty immutable {@code char} array. + */ + public static final char[] EMPTY_CHAR_ARRAY = new char[0]; + /** + * An empty immutable {@code Character} array. + */ + public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0]; + + /** + * The index value when an element is not found in a list or array: {@code -1}. + * This value is returned by methods in this class and can also be used in comparisons with values returned by + * various method from {@link java.util.List}. + */ + public static final int INDEX_NOT_FOUND = -1; + + /** + *

ArrayUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

+ * + *

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

+ */ + public ArrayUtils() { + super(); + } + + + // NOTE: Cannot use {@code} to enclose text which includes {}, but is OK + + + // Basic methods handling multi-dimensional arrays + //----------------------------------------------------------------------- + /** + *

Outputs an array as a String, treating {@code null} as an empty array.

+ * + *

Multi-dimensional arrays are handled correctly, including + * multi-dimensional primitive arrays.

+ * + *

The format is that of Java source code, for example {a,b}.

+ * + * @param array the array to get a toString for, may be {@code null} + * @return a String representation of the array, '{}' if null array input + */ + public static String toString(Object array) { + return toString(array, "{}"); + } + + /** + *

Outputs an array as a String handling {@code null}s.

+ * + *

Multi-dimensional arrays are handled correctly, including + * multi-dimensional primitive arrays.

+ * + *

The format is that of Java source code, for example {a,b}.

+ * + * @param array the array to get a toString for, may be {@code null} + * @param stringIfNull the String to return if the array is {@code null} + * @return a String representation of the array + */ + public static String toString(Object array, String stringIfNull) { + if (array == null) { + return stringIfNull; + } + return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); + } + + /** + *

Get a hash code for an array handling multi-dimensional arrays correctly.

+ * + *

Multi-dimensional primitive arrays are also handled correctly by this method.

+ * + * @param array the array to get a hash code for, {@code null} returns zero + * @return a hash code for the array + */ + public static int hashCode(Object array) { + return new HashCodeBuilder().append(array).toHashCode(); + } + + /** + *

Compares two arrays, using equals(), handling multi-dimensional arrays + * correctly.

+ * + *

Multi-dimensional primitive arrays are also handled correctly by this method.

+ * + * @param array1 the left hand array to compare, may be {@code null} + * @param array2 the right hand array to compare, may be {@code null} + * @return {@code true} if the arrays are equal + */ + public static boolean isEquals(Object array1, Object array2) { + return new EqualsBuilder().append(array1, array2).isEquals(); + } + + // To map + //----------------------------------------------------------------------- + /** + *

Converts the given array into a {@link java.util.Map}. Each element of the array + * must be either a {@link java.util.Map.Entry} or an Array, containing at least two + * elements, where the first element is used as key and the second as + * value.

+ * + *

This method can be used to initialize:

+ *
+     * // Create a Map mapping colors.
+     * Map colorMap = MapUtils.toMap(new String[][] {{
+     *     {"RED", "#FF0000"},
+     *     {"GREEN", "#00FF00"},
+     *     {"BLUE", "#0000FF"}});
+     * 
+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array an array whose elements are either a {@link java.util.Map.Entry} or + * an Array containing at least two elements, may be {@code null} + * @return a {@code Map} that was created from the array + * @throws IllegalArgumentException if one element of this Array is + * itself an Array containing less then two elements + * @throws IllegalArgumentException if the array contains elements other + * than {@link java.util.Map.Entry} and an Array + */ + public static Map toMap(Object[] array) { + if (array == null) { + return null; + } + final Map map = new HashMap((int) (array.length * 1.5)); + for (int i = 0; i < array.length; i++) { + Object object = array[i]; + if (object instanceof Map.Entry) { + Map.Entry entry = (Map.Entry) object; + map.put(entry.getKey(), entry.getValue()); + } else if (object instanceof Object[]) { + Object[] entry = (Object[]) object; + if (entry.length < 2) { + throw new IllegalArgumentException("Array element " + i + ", '" + + object + + "', has a length less than 2"); + } + map.put(entry[0], entry[1]); + } else { + throw new IllegalArgumentException("Array element " + i + ", '" + + object + + "', is neither of type Map.Entry nor an Array"); + } + } + return map; + } + + // Generic array + //----------------------------------------------------------------------- + /** + *

Create a type-safe generic array.

+ * + *

The Java language does not allow an array to be created from a generic type:

+ * + *
+    public static <T> T[] createAnArray(int size) {
+        return new T[size]; // compiler error here
+    }
+    public static <T> T[] createAnArray(int size) {
+        return (T[])new Object[size]; // ClassCastException at runtime
+    }
+     * 
+ * + *

Therefore new arrays of generic types can be created with this method. + * For example, an array of Strings can be created:

+ * + *
+    String[] array = ArrayUtils.toArray("1", "2");
+    String[] emptyArray = ArrayUtils.<String>toArray();
+     * 
+ * + *

The method is typically used in scenarios, where the caller itself uses generic types + * that have to be combined into an array.

+ * + *

Note, this method makes only sense to provide arguments of the same type so that the + * compiler can deduce the type of the array itself. While it is possible to select the + * type explicitly like in + * Number[] array = ArrayUtils.<Number>toArray(Integer.valueOf(42), Double.valueOf(Math.PI)), + * there is no real advantage when compared to + * new Number[] {Integer.valueOf(42), Double.valueOf(Math.PI)}.

+ * + * @param the array's element type + * @param items the varargs array items, null allowed + * @return the array, not null unless a null array is passed in + * @since 3.0 + */ + public static T[] toArray(final T... items) { + return items; + } + + // Clone + //----------------------------------------------------------------------- + /** + *

Shallow clones an array returning a typecast result and handling + * {@code null}.

+ * + *

The objects in the array are not cloned, thus there is no special + * handling for multi-dimensional arrays.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param the component type of the array + * @param array the array to shallow clone, may be {@code null} + * @return the cloned array, {@code null} if {@code null} input + */ + public static T[] clone(T[] array) { + if (array == null) { + return null; + } + return array.clone(); + } + + /** + *

Clones an array returning a typecast result and handling + * {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array the array to clone, may be {@code null} + * @return the cloned array, {@code null} if {@code null} input + */ + public static long[] clone(long[] array) { + if (array == null) { + return null; + } + return array.clone(); + } + + /** + *

Clones an array returning a typecast result and handling + * {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array the array to clone, may be {@code null} + * @return the cloned array, {@code null} if {@code null} input + */ + public static int[] clone(int[] array) { + if (array == null) { + return null; + } + return array.clone(); + } + + /** + *

Clones an array returning a typecast result and handling + * {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array the array to clone, may be {@code null} + * @return the cloned array, {@code null} if {@code null} input + */ + public static short[] clone(short[] array) { + if (array == null) { + return null; + } + return array.clone(); + } + + /** + *

Clones an array returning a typecast result and handling + * {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array the array to clone, may be {@code null} + * @return the cloned array, {@code null} if {@code null} input + */ + public static char[] clone(char[] array) { + if (array == null) { + return null; + } + return array.clone(); + } + + /** + *

Clones an array returning a typecast result and handling + * {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array the array to clone, may be {@code null} + * @return the cloned array, {@code null} if {@code null} input + */ + public static byte[] clone(byte[] array) { + if (array == null) { + return null; + } + return array.clone(); + } + + /** + *

Clones an array returning a typecast result and handling + * {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array the array to clone, may be {@code null} + * @return the cloned array, {@code null} if {@code null} input + */ + public static double[] clone(double[] array) { + if (array == null) { + return null; + } + return array.clone(); + } + + /** + *

Clones an array returning a typecast result and handling + * {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array the array to clone, may be {@code null} + * @return the cloned array, {@code null} if {@code null} input + */ + public static float[] clone(float[] array) { + if (array == null) { + return null; + } + return array.clone(); + } + + /** + *

Clones an array returning a typecast result and handling + * {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array the array to clone, may be {@code null} + * @return the cloned array, {@code null} if {@code null} input + */ + public static boolean[] clone(boolean[] array) { + if (array == null) { + return null; + } + return array.clone(); + } + + // nullToEmpty + //----------------------------------------------------------------------- + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static Object[] nullToEmpty(Object[] array) { + if (array == null || array.length == 0) { + return EMPTY_OBJECT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static String[] nullToEmpty(String[] array) { + if (array == null || array.length == 0) { + return EMPTY_STRING_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static long[] nullToEmpty(long[] array) { + if (array == null || array.length == 0) { + return EMPTY_LONG_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static int[] nullToEmpty(int[] array) { + if (array == null || array.length == 0) { + return EMPTY_INT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static short[] nullToEmpty(short[] array) { + if (array == null || array.length == 0) { + return EMPTY_SHORT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static char[] nullToEmpty(char[] array) { + if (array == null || array.length == 0) { + return EMPTY_CHAR_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static byte[] nullToEmpty(byte[] array) { + if (array == null || array.length == 0) { + return EMPTY_BYTE_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static double[] nullToEmpty(double[] array) { + if (array == null || array.length == 0) { + return EMPTY_DOUBLE_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static float[] nullToEmpty(float[] array) { + if (array == null || array.length == 0) { + return EMPTY_FLOAT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static boolean[] nullToEmpty(boolean[] array) { + if (array == null || array.length == 0) { + return EMPTY_BOOLEAN_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static Long[] nullToEmpty(Long[] array) { + if (array == null || array.length == 0) { + return EMPTY_LONG_OBJECT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static Integer[] nullToEmpty(Integer[] array) { + if (array == null || array.length == 0) { + return EMPTY_INTEGER_OBJECT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static Short[] nullToEmpty(Short[] array) { + if (array == null || array.length == 0) { + return EMPTY_SHORT_OBJECT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static Character[] nullToEmpty(Character[] array) { + if (array == null || array.length == 0) { + return EMPTY_CHARACTER_OBJECT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static Byte[] nullToEmpty(Byte[] array) { + if (array == null || array.length == 0) { + return EMPTY_BYTE_OBJECT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static Double[] nullToEmpty(Double[] array) { + if (array == null || array.length == 0) { + return EMPTY_DOUBLE_OBJECT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static Float[] nullToEmpty(Float[] array) { + if (array == null || array.length == 0) { + return EMPTY_FLOAT_OBJECT_ARRAY; + } + return array; + } + + /** + *

Defensive programming technique to change a {@code null} + * reference to an empty one.

+ * + *

This method returns an empty array for a {@code null} input array.

+ * + *

As a memory optimizing technique an empty array passed in will be overridden with + * the empty {@code public static} references in this class.

+ * + * @param array the array to check for {@code null} or empty + * @return the same array, {@code public static} empty array if {@code null} or empty input + * @since 2.5 + */ + public static Boolean[] nullToEmpty(Boolean[] array) { + if (array == null || array.length == 0) { + return EMPTY_BOOLEAN_OBJECT_ARRAY; + } + return array; + } + + // Subarrays + //----------------------------------------------------------------------- + /** + *

Produces a new array containing the elements between + * the start and end indices.

+ * + *

The start index is inclusive, the end index exclusive. + * Null array input produces null output.

+ * + *

The component type of the subarray is always the same as + * that of the input array. Thus, if the input is an array of type + * {@code Date}, the following usage is envisaged:

+ * + *
+     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);
+     * 
+ * + * @param the component type of the array + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static T[] subarray(T[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + Class type = array.getClass().getComponentType(); + if (newSize <= 0) { + @SuppressWarnings("unchecked") // OK, because array is of type T + final T[] emptyArray = (T[]) Array.newInstance(type, 0); + return emptyArray; + } + @SuppressWarnings("unchecked") // OK, because array is of type T + T[] subarray = (T[]) Array.newInstance(type, newSize); + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *

Produces a new {@code long} array containing the elements + * between the start and end indices.

+ * + *

The start index is inclusive, the end index exclusive. + * Null array input produces null output.

+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static long[] subarray(long[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_LONG_ARRAY; + } + + long[] subarray = new long[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *

Produces a new {@code int} array containing the elements + * between the start and end indices.

+ * + *

The start index is inclusive, the end index exclusive. + * Null array input produces null output.

+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static int[] subarray(int[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_INT_ARRAY; + } + + int[] subarray = new int[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *

Produces a new {@code short} array containing the elements + * between the start and end indices.

+ * + *

The start index is inclusive, the end index exclusive. + * Null array input produces null output.

+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static short[] subarray(short[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_SHORT_ARRAY; + } + + short[] subarray = new short[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *

Produces a new {@code char} array containing the elements + * between the start and end indices.

+ * + *

The start index is inclusive, the end index exclusive. + * Null array input produces null output.

+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static char[] subarray(char[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_CHAR_ARRAY; + } + + char[] subarray = new char[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *

Produces a new {@code byte} array containing the elements + * between the start and end indices.

+ * + *

The start index is inclusive, the end index exclusive. + * Null array input produces null output.

+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_BYTE_ARRAY; + } + + byte[] subarray = new byte[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *

Produces a new {@code double} array containing the elements + * between the start and end indices.

+ * + *

The start index is inclusive, the end index exclusive. + * Null array input produces null output.

+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static double[] subarray(double[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_DOUBLE_ARRAY; + } + + double[] subarray = new double[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *

Produces a new {@code float} array containing the elements + * between the start and end indices.

+ * + *

The start index is inclusive, the end index exclusive. + * Null array input produces null output.

+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static float[] subarray(float[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_FLOAT_ARRAY; + } + + float[] subarray = new float[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + /** + *

Produces a new {@code boolean} array containing the elements + * between the start and end indices.

+ * + *

The start index is inclusive, the end index exclusive. + * Null array input produces null output.

+ * + * @param array the array + * @param startIndexInclusive the starting index. Undervalue (<0) + * is promoted to 0, overvalue (>array.length) results + * in an empty array. + * @param endIndexExclusive elements up to endIndex-1 are present in the + * returned subarray. Undervalue (< startIndex) produces + * empty array, overvalue (>array.length) is demoted to + * array length. + * @return a new array containing the elements between + * the start and end indices. + * @since 2.1 + */ + public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) { + if (array == null) { + return null; + } + if (startIndexInclusive < 0) { + startIndexInclusive = 0; + } + if (endIndexExclusive > array.length) { + endIndexExclusive = array.length; + } + int newSize = endIndexExclusive - startIndexInclusive; + if (newSize <= 0) { + return EMPTY_BOOLEAN_ARRAY; + } + + boolean[] subarray = new boolean[newSize]; + System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); + return subarray; + } + + // Is same length + //----------------------------------------------------------------------- + /** + *

Checks whether two arrays are the same length, treating + * {@code null} arrays as length {@code 0}. + * + *

Any multi-dimensional aspects of the arrays are ignored.

+ * + * @param array1 the first array, may be {@code null} + * @param array2 the second array, may be {@code null} + * @return {@code true} if length of arrays matches, treating + * {@code null} as an empty array + */ + public static boolean isSameLength(Object[] array1, Object[] array2) { + if ((array1 == null && array2 != null && array2.length > 0) || + (array2 == null && array1 != null && array1.length > 0) || + (array1 != null && array2 != null && array1.length != array2.length)) { + return false; + } + return true; + } + + /** + *

Checks whether two arrays are the same length, treating + * {@code null} arrays as length {@code 0}.

+ * + * @param array1 the first array, may be {@code null} + * @param array2 the second array, may be {@code null} + * @return {@code true} if length of arrays matches, treating + * {@code null} as an empty array + */ + public static boolean isSameLength(long[] array1, long[] array2) { + if ((array1 == null && array2 != null && array2.length > 0) || + (array2 == null && array1 != null && array1.length > 0) || + (array1 != null && array2 != null && array1.length != array2.length)) { + return false; + } + return true; + } + + /** + *

Checks whether two arrays are the same length, treating + * {@code null} arrays as length {@code 0}.

+ * + * @param array1 the first array, may be {@code null} + * @param array2 the second array, may be {@code null} + * @return {@code true} if length of arrays matches, treating + * {@code null} as an empty array + */ + public static boolean isSameLength(int[] array1, int[] array2) { + if ((array1 == null && array2 != null && array2.length > 0) || + (array2 == null && array1 != null && array1.length > 0) || + (array1 != null && array2 != null && array1.length != array2.length)) { + return false; + } + return true; + } + + /** + *

Checks whether two arrays are the same length, treating + * {@code null} arrays as length {@code 0}.

+ * + * @param array1 the first array, may be {@code null} + * @param array2 the second array, may be {@code null} + * @return {@code true} if length of arrays matches, treating + * {@code null} as an empty array + */ + public static boolean isSameLength(short[] array1, short[] array2) { + if ((array1 == null && array2 != null && array2.length > 0) || + (array2 == null && array1 != null && array1.length > 0) || + (array1 != null && array2 != null && array1.length != array2.length)) { + return false; + } + return true; + } + + /** + *

Checks whether two arrays are the same length, treating + * {@code null} arrays as length {@code 0}.

+ * + * @param array1 the first array, may be {@code null} + * @param array2 the second array, may be {@code null} + * @return {@code true} if length of arrays matches, treating + * {@code null} as an empty array + */ + public static boolean isSameLength(char[] array1, char[] array2) { + if ((array1 == null && array2 != null && array2.length > 0) || + (array2 == null && array1 != null && array1.length > 0) || + (array1 != null && array2 != null && array1.length != array2.length)) { + return false; + } + return true; + } + + /** + *

Checks whether two arrays are the same length, treating + * {@code null} arrays as length {@code 0}.

+ * + * @param array1 the first array, may be {@code null} + * @param array2 the second array, may be {@code null} + * @return {@code true} if length of arrays matches, treating + * {@code null} as an empty array + */ + public static boolean isSameLength(byte[] array1, byte[] array2) { + if ((array1 == null && array2 != null && array2.length > 0) || + (array2 == null && array1 != null && array1.length > 0) || + (array1 != null && array2 != null && array1.length != array2.length)) { + return false; + } + return true; + } + + /** + *

Checks whether two arrays are the same length, treating + * {@code null} arrays as length {@code 0}.

+ * + * @param array1 the first array, may be {@code null} + * @param array2 the second array, may be {@code null} + * @return {@code true} if length of arrays matches, treating + * {@code null} as an empty array + */ + public static boolean isSameLength(double[] array1, double[] array2) { + if ((array1 == null && array2 != null && array2.length > 0) || + (array2 == null && array1 != null && array1.length > 0) || + (array1 != null && array2 != null && array1.length != array2.length)) { + return false; + } + return true; + } + + /** + *

Checks whether two arrays are the same length, treating + * {@code null} arrays as length {@code 0}.

+ * + * @param array1 the first array, may be {@code null} + * @param array2 the second array, may be {@code null} + * @return {@code true} if length of arrays matches, treating + * {@code null} as an empty array + */ + public static boolean isSameLength(float[] array1, float[] array2) { + if ((array1 == null && array2 != null && array2.length > 0) || + (array2 == null && array1 != null && array1.length > 0) || + (array1 != null && array2 != null && array1.length != array2.length)) { + return false; + } + return true; + } + + /** + *

Checks whether two arrays are the same length, treating + * {@code null} arrays as length {@code 0}.

+ * + * @param array1 the first array, may be {@code null} + * @param array2 the second array, may be {@code null} + * @return {@code true} if length of arrays matches, treating + * {@code null} as an empty array + */ + public static boolean isSameLength(boolean[] array1, boolean[] array2) { + if ((array1 == null && array2 != null && array2.length > 0) || + (array2 == null && array1 != null && array1.length > 0) || + (array1 != null && array2 != null && array1.length != array2.length)) { + return false; + } + return true; + } + + //----------------------------------------------------------------------- + /** + *

Returns the length of the specified array. + * This method can deal with {@code Object} arrays and with primitive arrays.

+ * + *

If the input array is {@code null}, {@code 0} is returned.

+ * + *
+     * ArrayUtils.getLength(null)            = 0
+     * ArrayUtils.getLength([])              = 0
+     * ArrayUtils.getLength([null])          = 1
+     * ArrayUtils.getLength([true, false])   = 2
+     * ArrayUtils.getLength([1, 2, 3])       = 3
+     * ArrayUtils.getLength(["a", "b", "c"]) = 3
+     * 
+ * + * @param array the array to retrieve the length from, may be null + * @return The length of the array, or {@code 0} if the array is {@code null} + * @throws IllegalArgumentException if the object arguement is not an array. + * @since 2.1 + */ + public static int getLength(Object array) { + if (array == null) { + return 0; + } + return Array.getLength(array); + } + + /** + *

Checks whether two arrays are the same type taking into account + * multi-dimensional arrays.

+ * + * @param array1 the first array, must not be {@code null} + * @param array2 the second array, must not be {@code null} + * @return {@code true} if type of arrays matches + * @throws IllegalArgumentException if either array is {@code null} + */ + public static boolean isSameType(Object array1, Object array2) { + if (array1 == null || array2 == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + return array1.getClass().getName().equals(array2.getClass().getName()); + } + + // Reverse + //----------------------------------------------------------------------- + /** + *

Reverses the order of the given array.

+ * + *

There is no special handling for multi-dimensional arrays.

+ * + *

This method does nothing for a {@code null} input array.

+ * + * @param array the array to reverse, may be {@code null} + */ + public static void reverse(Object[] array) { + if (array == null) { + return; + } + int i = 0; + int j = array.length - 1; + Object tmp; + while (j > i) { + tmp = array[j]; + array[j] = array[i]; + array[i] = tmp; + j--; + i++; + } + } + + /** + *

Reverses the order of the given array.

+ * + *

This method does nothing for a {@code null} input array.

+ * + * @param array the array to reverse, may be {@code null} + */ + public static void reverse(long[] array) { + if (array == null) { + return; + } + int i = 0; + int j = array.length - 1; + long tmp; + while (j > i) { + tmp = array[j]; + array[j] = array[i]; + array[i] = tmp; + j--; + i++; + } + } + + /** + *

Reverses the order of the given array.

+ * + *

This method does nothing for a {@code null} input array.

+ * + * @param array the array to reverse, may be {@code null} + */ + public static void reverse(int[] array) { + if (array == null) { + return; + } + int i = 0; + int j = array.length - 1; + int tmp; + while (j > i) { + tmp = array[j]; + array[j] = array[i]; + array[i] = tmp; + j--; + i++; + } + } + + /** + *

Reverses the order of the given array.

+ * + *

This method does nothing for a {@code null} input array.

+ * + * @param array the array to reverse, may be {@code null} + */ + public static void reverse(short[] array) { + if (array == null) { + return; + } + int i = 0; + int j = array.length - 1; + short tmp; + while (j > i) { + tmp = array[j]; + array[j] = array[i]; + array[i] = tmp; + j--; + i++; + } + } + + /** + *

Reverses the order of the given array.

+ * + *

This method does nothing for a {@code null} input array.

+ * + * @param array the array to reverse, may be {@code null} + */ + public static void reverse(char[] array) { + if (array == null) { + return; + } + int i = 0; + int j = array.length - 1; + char tmp; + while (j > i) { + tmp = array[j]; + array[j] = array[i]; + array[i] = tmp; + j--; + i++; + } + } + + /** + *

Reverses the order of the given array.

+ * + *

This method does nothing for a {@code null} input array.

+ * + * @param array the array to reverse, may be {@code null} + */ + public static void reverse(byte[] array) { + if (array == null) { + return; + } + int i = 0; + int j = array.length - 1; + byte tmp; + while (j > i) { + tmp = array[j]; + array[j] = array[i]; + array[i] = tmp; + j--; + i++; + } + } + + /** + *

Reverses the order of the given array.

+ * + *

This method does nothing for a {@code null} input array.

+ * + * @param array the array to reverse, may be {@code null} + */ + public static void reverse(double[] array) { + if (array == null) { + return; + } + int i = 0; + int j = array.length - 1; + double tmp; + while (j > i) { + tmp = array[j]; + array[j] = array[i]; + array[i] = tmp; + j--; + i++; + } + } + + /** + *

Reverses the order of the given array.

+ * + *

This method does nothing for a {@code null} input array.

+ * + * @param array the array to reverse, may be {@code null} + */ + public static void reverse(float[] array) { + if (array == null) { + return; + } + int i = 0; + int j = array.length - 1; + float tmp; + while (j > i) { + tmp = array[j]; + array[j] = array[i]; + array[i] = tmp; + j--; + i++; + } + } + + /** + *

Reverses the order of the given array.

+ * + *

This method does nothing for a {@code null} input array.

+ * + * @param array the array to reverse, may be {@code null} + */ + public static void reverse(boolean[] array) { + if (array == null) { + return; + } + int i = 0; + int j = array.length - 1; + boolean tmp; + while (j > i) { + tmp = array[j]; + array[j] = array[i]; + array[i] = tmp; + j--; + i++; + } + } + + // IndexOf search + // ---------------------------------------------------------------------- + + // Object IndexOf + //----------------------------------------------------------------------- + /** + *

Finds the index of the given object in the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param objectToFind the object to find, may be {@code null} + * @return the index of the object within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(Object[] array, Object objectToFind) { + return indexOf(array, objectToFind, 0); + } + + /** + *

Finds the index of the given object in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex is treated as zero. A startIndex larger than the array + * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).

+ * + * @param array the array to search through for the object, may be {@code null} + * @param objectToFind the object to find, may be {@code null} + * @param startIndex the index to start searching at + * @return the index of the object within the array starting at the index, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(Object[] array, Object objectToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + startIndex = 0; + } + if (objectToFind == null) { + for (int i = startIndex; i < array.length; i++) { + if (array[i] == null) { + return i; + } + } + } else if (array.getClass().getComponentType().isInstance(objectToFind)) { + for (int i = startIndex; i < array.length; i++) { + if (objectToFind.equals(array[i])) { + return i; + } + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the last index of the given object within the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to travers backwords looking for the object, may be {@code null} + * @param objectToFind the object to find, may be {@code null} + * @return the last index of the object within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(Object[] array, Object objectToFind) { + return lastIndexOf(array, objectToFind, Integer.MAX_VALUE); + } + + /** + *

Finds the last index of the given object in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than + * the array length will search from the end of the array.

+ * + * @param array the array to traverse for looking for the object, may be {@code null} + * @param objectToFind the object to find, may be {@code null} + * @param startIndex the start index to travers backwards from + * @return the last index of the object within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(Object[] array, Object objectToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + return INDEX_NOT_FOUND; + } else if (startIndex >= array.length) { + startIndex = array.length - 1; + } + if (objectToFind == null) { + for (int i = startIndex; i >= 0; i--) { + if (array[i] == null) { + return i; + } + } + } else if (array.getClass().getComponentType().isInstance(objectToFind)) { + for (int i = startIndex; i >= 0; i--) { + if (objectToFind.equals(array[i])) { + return i; + } + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Checks if the object is in the given array.

+ * + *

The method returns {@code false} if a {@code null} array is passed in.

+ * + * @param array the array to search through + * @param objectToFind the object to find + * @return {@code true} if the array contains the object + */ + public static boolean contains(Object[] array, Object objectToFind) { + return indexOf(array, objectToFind) != INDEX_NOT_FOUND; + } + + // long IndexOf + //----------------------------------------------------------------------- + /** + *

Finds the index of the given value in the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(long[] array, long valueToFind) { + return indexOf(array, valueToFind, 0); + } + + /** + *

Finds the index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex is treated as zero. A startIndex larger than the array + * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the index to start searching at + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(long[] array, long valueToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + startIndex = 0; + } + for (int i = startIndex; i < array.length; i++) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the last index of the given value within the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to travers backwords looking for the object, may be {@code null} + * @param valueToFind the object to find + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(long[] array, long valueToFind) { + return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); + } + + /** + *

Finds the last index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the + * array length will search from the end of the array.

+ * + * @param array the array to traverse for looking for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the start index to travers backwards from + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(long[] array, long valueToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + return INDEX_NOT_FOUND; + } else if (startIndex >= array.length) { + startIndex = array.length - 1; + } + for (int i = startIndex; i >= 0; i--) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Checks if the value is in the given array.

+ * + *

The method returns {@code false} if a {@code null} array is passed in.

+ * + * @param array the array to search through + * @param valueToFind the value to find + * @return {@code true} if the array contains the object + */ + public static boolean contains(long[] array, long valueToFind) { + return indexOf(array, valueToFind) != INDEX_NOT_FOUND; + } + + // int IndexOf + //----------------------------------------------------------------------- + /** + *

Finds the index of the given value in the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(int[] array, int valueToFind) { + return indexOf(array, valueToFind, 0); + } + + /** + *

Finds the index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex is treated as zero. A startIndex larger than the array + * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the index to start searching at + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(int[] array, int valueToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + startIndex = 0; + } + for (int i = startIndex; i < array.length; i++) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the last index of the given value within the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to travers backwords looking for the object, may be {@code null} + * @param valueToFind the object to find + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(int[] array, int valueToFind) { + return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); + } + + /** + *

Finds the last index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the + * array length will search from the end of the array.

+ * + * @param array the array to traverse for looking for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the start index to travers backwards from + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(int[] array, int valueToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + return INDEX_NOT_FOUND; + } else if (startIndex >= array.length) { + startIndex = array.length - 1; + } + for (int i = startIndex; i >= 0; i--) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Checks if the value is in the given array.

+ * + *

The method returns {@code false} if a {@code null} array is passed in.

+ * + * @param array the array to search through + * @param valueToFind the value to find + * @return {@code true} if the array contains the object + */ + public static boolean contains(int[] array, int valueToFind) { + return indexOf(array, valueToFind) != INDEX_NOT_FOUND; + } + + // short IndexOf + //----------------------------------------------------------------------- + /** + *

Finds the index of the given value in the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(short[] array, short valueToFind) { + return indexOf(array, valueToFind, 0); + } + + /** + *

Finds the index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex is treated as zero. A startIndex larger than the array + * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the index to start searching at + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(short[] array, short valueToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + startIndex = 0; + } + for (int i = startIndex; i < array.length; i++) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the last index of the given value within the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to travers backwords looking for the object, may be {@code null} + * @param valueToFind the object to find + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(short[] array, short valueToFind) { + return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); + } + + /** + *

Finds the last index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the + * array length will search from the end of the array.

+ * + * @param array the array to traverse for looking for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the start index to travers backwards from + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(short[] array, short valueToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + return INDEX_NOT_FOUND; + } else if (startIndex >= array.length) { + startIndex = array.length - 1; + } + for (int i = startIndex; i >= 0; i--) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Checks if the value is in the given array.

+ * + *

The method returns {@code false} if a {@code null} array is passed in.

+ * + * @param array the array to search through + * @param valueToFind the value to find + * @return {@code true} if the array contains the object + */ + public static boolean contains(short[] array, short valueToFind) { + return indexOf(array, valueToFind) != INDEX_NOT_FOUND; + } + + // char IndexOf + //----------------------------------------------------------------------- + /** + *

Finds the index of the given value in the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + * @since 2.1 + */ + public static int indexOf(char[] array, char valueToFind) { + return indexOf(array, valueToFind, 0); + } + + /** + *

Finds the index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex is treated as zero. A startIndex larger than the array + * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the index to start searching at + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + * @since 2.1 + */ + public static int indexOf(char[] array, char valueToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + startIndex = 0; + } + for (int i = startIndex; i < array.length; i++) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the last index of the given value within the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to travers backwords looking for the object, may be {@code null} + * @param valueToFind the object to find + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + * @since 2.1 + */ + public static int lastIndexOf(char[] array, char valueToFind) { + return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); + } + + /** + *

Finds the last index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the + * array length will search from the end of the array.

+ * + * @param array the array to traverse for looking for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the start index to travers backwards from + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + * @since 2.1 + */ + public static int lastIndexOf(char[] array, char valueToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + return INDEX_NOT_FOUND; + } else if (startIndex >= array.length) { + startIndex = array.length - 1; + } + for (int i = startIndex; i >= 0; i--) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Checks if the value is in the given array.

+ * + *

The method returns {@code false} if a {@code null} array is passed in.

+ * + * @param array the array to search through + * @param valueToFind the value to find + * @return {@code true} if the array contains the object + * @since 2.1 + */ + public static boolean contains(char[] array, char valueToFind) { + return indexOf(array, valueToFind) != INDEX_NOT_FOUND; + } + + // byte IndexOf + //----------------------------------------------------------------------- + /** + *

Finds the index of the given value in the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(byte[] array, byte valueToFind) { + return indexOf(array, valueToFind, 0); + } + + /** + *

Finds the index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex is treated as zero. A startIndex larger than the array + * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the index to start searching at + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(byte[] array, byte valueToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + startIndex = 0; + } + for (int i = startIndex; i < array.length; i++) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the last index of the given value within the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to travers backwords looking for the object, may be {@code null} + * @param valueToFind the object to find + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(byte[] array, byte valueToFind) { + return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); + } + + /** + *

Finds the last index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the + * array length will search from the end of the array.

+ * + * @param array the array to traverse for looking for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the start index to travers backwards from + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(byte[] array, byte valueToFind, int startIndex) { + if (array == null) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + return INDEX_NOT_FOUND; + } else if (startIndex >= array.length) { + startIndex = array.length - 1; + } + for (int i = startIndex; i >= 0; i--) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Checks if the value is in the given array.

+ * + *

The method returns {@code false} if a {@code null} array is passed in.

+ * + * @param array the array to search through + * @param valueToFind the value to find + * @return {@code true} if the array contains the object + */ + public static boolean contains(byte[] array, byte valueToFind) { + return indexOf(array, valueToFind) != INDEX_NOT_FOUND; + } + + // double IndexOf + //----------------------------------------------------------------------- + /** + *

Finds the index of the given value in the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(double[] array, double valueToFind) { + return indexOf(array, valueToFind, 0); + } + + /** + *

Finds the index of the given value within a given tolerance in the array. + * This method will return the index of the first value which falls between the region + * defined by valueToFind - tolerance and valueToFind + tolerance.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param tolerance tolerance of the search + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(double[] array, double valueToFind, double tolerance) { + return indexOf(array, valueToFind, 0, tolerance); + } + + /** + *

Finds the index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex is treated as zero. A startIndex larger than the array + * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the index to start searching at + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(double[] array, double valueToFind, int startIndex) { + if (ArrayUtils.isEmpty(array)) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + startIndex = 0; + } + for (int i = startIndex; i < array.length; i++) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the index of the given value in the array starting at the given index. + * This method will return the index of the first value which falls between the region + * defined by valueToFind - tolerance and valueToFind + tolerance.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex is treated as zero. A startIndex larger than the array + * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the index to start searching at + * @param tolerance tolerance of the search + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(double[] array, double valueToFind, int startIndex, double tolerance) { + if (ArrayUtils.isEmpty(array)) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + startIndex = 0; + } + double min = valueToFind - tolerance; + double max = valueToFind + tolerance; + for (int i = startIndex; i < array.length; i++) { + if (array[i] >= min && array[i] <= max) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the last index of the given value within the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to travers backwords looking for the object, may be {@code null} + * @param valueToFind the object to find + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(double[] array, double valueToFind) { + return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); + } + + /** + *

Finds the last index of the given value within a given tolerance in the array. + * This method will return the index of the last value which falls between the region + * defined by valueToFind - tolerance and valueToFind + tolerance.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param tolerance tolerance of the search + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(double[] array, double valueToFind, double tolerance) { + return lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance); + } + + /** + *

Finds the last index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the + * array length will search from the end of the array.

+ * + * @param array the array to traverse for looking for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the start index to travers backwards from + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(double[] array, double valueToFind, int startIndex) { + if (ArrayUtils.isEmpty(array)) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + return INDEX_NOT_FOUND; + } else if (startIndex >= array.length) { + startIndex = array.length - 1; + } + for (int i = startIndex; i >= 0; i--) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the last index of the given value in the array starting at the given index. + * This method will return the index of the last value which falls between the region + * defined by valueToFind - tolerance and valueToFind + tolerance.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the + * array length will search from the end of the array.

+ * + * @param array the array to traverse for looking for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the start index to travers backwards from + * @param tolerance search for value within plus/minus this amount + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(double[] array, double valueToFind, int startIndex, double tolerance) { + if (ArrayUtils.isEmpty(array)) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + return INDEX_NOT_FOUND; + } else if (startIndex >= array.length) { + startIndex = array.length - 1; + } + double min = valueToFind - tolerance; + double max = valueToFind + tolerance; + for (int i = startIndex; i >= 0; i--) { + if (array[i] >= min && array[i] <= max) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Checks if the value is in the given array.

+ * + *

The method returns {@code false} if a {@code null} array is passed in.

+ * + * @param array the array to search through + * @param valueToFind the value to find + * @return {@code true} if the array contains the object + */ + public static boolean contains(double[] array, double valueToFind) { + return indexOf(array, valueToFind) != INDEX_NOT_FOUND; + } + + /** + *

Checks if a value falling within the given tolerance is in the + * given array. If the array contains a value within the inclusive range + * defined by (value - tolerance) to (value + tolerance).

+ * + *

The method returns {@code false} if a {@code null} array + * is passed in.

+ * + * @param array the array to search + * @param valueToFind the value to find + * @param tolerance the array contains the tolerance of the search + * @return true if value falling within tolerance is in array + */ + public static boolean contains(double[] array, double valueToFind, double tolerance) { + return indexOf(array, valueToFind, 0, tolerance) != INDEX_NOT_FOUND; + } + + // float IndexOf + //----------------------------------------------------------------------- + /** + *

Finds the index of the given value in the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(float[] array, float valueToFind) { + return indexOf(array, valueToFind, 0); + } + + /** + *

Finds the index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex is treated as zero. A startIndex larger than the array + * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the index to start searching at + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(float[] array, float valueToFind, int startIndex) { + if (ArrayUtils.isEmpty(array)) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + startIndex = 0; + } + for (int i = startIndex; i < array.length; i++) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the last index of the given value within the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to travers backwords looking for the object, may be {@code null} + * @param valueToFind the object to find + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(float[] array, float valueToFind) { + return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); + } + + /** + *

Finds the last index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the + * array length will search from the end of the array.

+ * + * @param array the array to traverse for looking for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the start index to travers backwards from + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(float[] array, float valueToFind, int startIndex) { + if (ArrayUtils.isEmpty(array)) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + return INDEX_NOT_FOUND; + } else if (startIndex >= array.length) { + startIndex = array.length - 1; + } + for (int i = startIndex; i >= 0; i--) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Checks if the value is in the given array.

+ * + *

The method returns {@code false} if a {@code null} array is passed in.

+ * + * @param array the array to search through + * @param valueToFind the value to find + * @return {@code true} if the array contains the object + */ + public static boolean contains(float[] array, float valueToFind) { + return indexOf(array, valueToFind) != INDEX_NOT_FOUND; + } + + // boolean IndexOf + //----------------------------------------------------------------------- + /** + *

Finds the index of the given value in the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int indexOf(boolean[] array, boolean valueToFind) { + return indexOf(array, valueToFind, 0); + } + + /** + *

Finds the index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex is treated as zero. A startIndex larger than the array + * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).

+ * + * @param array the array to search through for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the index to start searching at + * @return the index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} + * array input + */ + public static int indexOf(boolean[] array, boolean valueToFind, int startIndex) { + if (ArrayUtils.isEmpty(array)) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + startIndex = 0; + } + for (int i = startIndex; i < array.length; i++) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Finds the last index of the given value within the array.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) if + * {@code null} array input.

+ * + * @param array the array to travers backwords looking for the object, may be {@code null} + * @param valueToFind the object to find + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(boolean[] array, boolean valueToFind) { + return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); + } + + /** + *

Finds the last index of the given value in the array starting at the given index.

+ * + *

This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.

+ * + *

A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than + * the array length will search from the end of the array.

+ * + * @param array the array to traverse for looking for the object, may be {@code null} + * @param valueToFind the value to find + * @param startIndex the start index to travers backwards from + * @return the last index of the value within the array, + * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input + */ + public static int lastIndexOf(boolean[] array, boolean valueToFind, int startIndex) { + if (ArrayUtils.isEmpty(array)) { + return INDEX_NOT_FOUND; + } + if (startIndex < 0) { + return INDEX_NOT_FOUND; + } else if (startIndex >= array.length) { + startIndex = array.length - 1; + } + for (int i = startIndex; i >= 0; i--) { + if (valueToFind == array[i]) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Checks if the value is in the given array.

+ * + *

The method returns {@code false} if a {@code null} array is passed in.

+ * + * @param array the array to search through + * @param valueToFind the value to find + * @return {@code true} if the array contains the object + */ + public static boolean contains(boolean[] array, boolean valueToFind) { + return indexOf(array, valueToFind) != INDEX_NOT_FOUND; + } + + // Primitive/Object array converters + // ---------------------------------------------------------------------- + + // Character array converters + // ---------------------------------------------------------------------- + /** + *

Converts an array of object Characters to primitives.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Character} array, may be {@code null} + * @return a {@code char} array, {@code null} if null array input + * @throws NullPointerException if array content is {@code null} + */ + public static char[] toPrimitive(Character[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_CHAR_ARRAY; + } + final char[] result = new char[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[i].charValue(); + } + return result; + } + + /** + *

Converts an array of object Character to primitives handling {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Character} array, may be {@code null} + * @param valueForNull the value to insert if {@code null} found + * @return a {@code char} array, {@code null} if null array input + */ + public static char[] toPrimitive(Character[] array, char valueForNull) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_CHAR_ARRAY; + } + final char[] result = new char[array.length]; + for (int i = 0; i < array.length; i++) { + Character b = array[i]; + result[i] = (b == null ? valueForNull : b.charValue()); + } + return result; + } + + /** + *

Converts an array of primitive chars to objects.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code char} array + * @return a {@code Character} array, {@code null} if null array input + */ + public static Character[] toObject(char[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_CHARACTER_OBJECT_ARRAY; + } + final Character[] result = new Character[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = Character.valueOf(array[i]); + } + return result; + } + + // Long array converters + // ---------------------------------------------------------------------- + /** + *

Converts an array of object Longs to primitives.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Long} array, may be {@code null} + * @return a {@code long} array, {@code null} if null array input + * @throws NullPointerException if array content is {@code null} + */ + public static long[] toPrimitive(Long[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_LONG_ARRAY; + } + final long[] result = new long[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[i].longValue(); + } + return result; + } + + /** + *

Converts an array of object Long to primitives handling {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Long} array, may be {@code null} + * @param valueForNull the value to insert if {@code null} found + * @return a {@code long} array, {@code null} if null array input + */ + public static long[] toPrimitive(Long[] array, long valueForNull) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_LONG_ARRAY; + } + final long[] result = new long[array.length]; + for (int i = 0; i < array.length; i++) { + Long b = array[i]; + result[i] = (b == null ? valueForNull : b.longValue()); + } + return result; + } + + /** + *

Converts an array of primitive longs to objects.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code long} array + * @return a {@code Long} array, {@code null} if null array input + */ + public static Long[] toObject(long[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_LONG_OBJECT_ARRAY; + } + final Long[] result = new Long[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = Long.valueOf(array[i]); + } + return result; + } + + // Int array converters + // ---------------------------------------------------------------------- + /** + *

Converts an array of object Integers to primitives.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Integer} array, may be {@code null} + * @return an {@code int} array, {@code null} if null array input + * @throws NullPointerException if array content is {@code null} + */ + public static int[] toPrimitive(Integer[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_INT_ARRAY; + } + final int[] result = new int[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[i].intValue(); + } + return result; + } + + /** + *

Converts an array of object Integer to primitives handling {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Integer} array, may be {@code null} + * @param valueForNull the value to insert if {@code null} found + * @return an {@code int} array, {@code null} if null array input + */ + public static int[] toPrimitive(Integer[] array, int valueForNull) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_INT_ARRAY; + } + final int[] result = new int[array.length]; + for (int i = 0; i < array.length; i++) { + Integer b = array[i]; + result[i] = (b == null ? valueForNull : b.intValue()); + } + return result; + } + + /** + *

Converts an array of primitive ints to objects.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array an {@code int} array + * @return an {@code Integer} array, {@code null} if null array input + */ + public static Integer[] toObject(int[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_INTEGER_OBJECT_ARRAY; + } + final Integer[] result = new Integer[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = Integer.valueOf(array[i]); + } + return result; + } + + // Short array converters + // ---------------------------------------------------------------------- + /** + *

Converts an array of object Shorts to primitives.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Short} array, may be {@code null} + * @return a {@code byte} array, {@code null} if null array input + * @throws NullPointerException if array content is {@code null} + */ + public static short[] toPrimitive(Short[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_SHORT_ARRAY; + } + final short[] result = new short[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[i].shortValue(); + } + return result; + } + + /** + *

Converts an array of object Short to primitives handling {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Short} array, may be {@code null} + * @param valueForNull the value to insert if {@code null} found + * @return a {@code byte} array, {@code null} if null array input + */ + public static short[] toPrimitive(Short[] array, short valueForNull) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_SHORT_ARRAY; + } + final short[] result = new short[array.length]; + for (int i = 0; i < array.length; i++) { + Short b = array[i]; + result[i] = (b == null ? valueForNull : b.shortValue()); + } + return result; + } + + /** + *

Converts an array of primitive shorts to objects.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code short} array + * @return a {@code Short} array, {@code null} if null array input + */ + public static Short[] toObject(short[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_SHORT_OBJECT_ARRAY; + } + final Short[] result = new Short[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = Short.valueOf(array[i]); + } + return result; + } + + // Byte array converters + // ---------------------------------------------------------------------- + /** + *

Converts an array of object Bytes to primitives.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Byte} array, may be {@code null} + * @return a {@code byte} array, {@code null} if null array input + * @throws NullPointerException if array content is {@code null} + */ + public static byte[] toPrimitive(Byte[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_BYTE_ARRAY; + } + final byte[] result = new byte[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[i].byteValue(); + } + return result; + } + + /** + *

Converts an array of object Bytes to primitives handling {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Byte} array, may be {@code null} + * @param valueForNull the value to insert if {@code null} found + * @return a {@code byte} array, {@code null} if null array input + */ + public static byte[] toPrimitive(Byte[] array, byte valueForNull) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_BYTE_ARRAY; + } + final byte[] result = new byte[array.length]; + for (int i = 0; i < array.length; i++) { + Byte b = array[i]; + result[i] = (b == null ? valueForNull : b.byteValue()); + } + return result; + } + + /** + *

Converts an array of primitive bytes to objects.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code byte} array + * @return a {@code Byte} array, {@code null} if null array input + */ + public static Byte[] toObject(byte[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_BYTE_OBJECT_ARRAY; + } + final Byte[] result = new Byte[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = Byte.valueOf(array[i]); + } + return result; + } + + // Double array converters + // ---------------------------------------------------------------------- + /** + *

Converts an array of object Doubles to primitives.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Double} array, may be {@code null} + * @return a {@code double} array, {@code null} if null array input + * @throws NullPointerException if array content is {@code null} + */ + public static double[] toPrimitive(Double[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_DOUBLE_ARRAY; + } + final double[] result = new double[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[i].doubleValue(); + } + return result; + } + + /** + *

Converts an array of object Doubles to primitives handling {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Double} array, may be {@code null} + * @param valueForNull the value to insert if {@code null} found + * @return a {@code double} array, {@code null} if null array input + */ + public static double[] toPrimitive(Double[] array, double valueForNull) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_DOUBLE_ARRAY; + } + final double[] result = new double[array.length]; + for (int i = 0; i < array.length; i++) { + Double b = array[i]; + result[i] = (b == null ? valueForNull : b.doubleValue()); + } + return result; + } + + /** + *

Converts an array of primitive doubles to objects.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code double} array + * @return a {@code Double} array, {@code null} if null array input + */ + public static Double[] toObject(double[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_DOUBLE_OBJECT_ARRAY; + } + final Double[] result = new Double[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = Double.valueOf(array[i]); + } + return result; + } + + // Float array converters + // ---------------------------------------------------------------------- + /** + *

Converts an array of object Floats to primitives.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Float} array, may be {@code null} + * @return a {@code float} array, {@code null} if null array input + * @throws NullPointerException if array content is {@code null} + */ + public static float[] toPrimitive(Float[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_FLOAT_ARRAY; + } + final float[] result = new float[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[i].floatValue(); + } + return result; + } + + /** + *

Converts an array of object Floats to primitives handling {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Float} array, may be {@code null} + * @param valueForNull the value to insert if {@code null} found + * @return a {@code float} array, {@code null} if null array input + */ + public static float[] toPrimitive(Float[] array, float valueForNull) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_FLOAT_ARRAY; + } + final float[] result = new float[array.length]; + for (int i = 0; i < array.length; i++) { + Float b = array[i]; + result[i] = (b == null ? valueForNull : b.floatValue()); + } + return result; + } + + /** + *

Converts an array of primitive floats to objects.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code float} array + * @return a {@code Float} array, {@code null} if null array input + */ + public static Float[] toObject(float[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_FLOAT_OBJECT_ARRAY; + } + final Float[] result = new Float[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = Float.valueOf(array[i]); + } + return result; + } + + // Boolean array converters + // ---------------------------------------------------------------------- + /** + *

Converts an array of object Booleans to primitives.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Boolean} array, may be {@code null} + * @return a {@code boolean} array, {@code null} if null array input + * @throws NullPointerException if array content is {@code null} + */ + public static boolean[] toPrimitive(Boolean[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_BOOLEAN_ARRAY; + } + final boolean[] result = new boolean[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[i].booleanValue(); + } + return result; + } + + /** + *

Converts an array of object Booleans to primitives handling {@code null}.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code Boolean} array, may be {@code null} + * @param valueForNull the value to insert if {@code null} found + * @return a {@code boolean} array, {@code null} if null array input + */ + public static boolean[] toPrimitive(Boolean[] array, boolean valueForNull) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_BOOLEAN_ARRAY; + } + final boolean[] result = new boolean[array.length]; + for (int i = 0; i < array.length; i++) { + Boolean b = array[i]; + result[i] = (b == null ? valueForNull : b.booleanValue()); + } + return result; + } + + /** + *

Converts an array of primitive booleans to objects.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array a {@code boolean} array + * @return a {@code Boolean} array, {@code null} if null array input + */ + public static Boolean[] toObject(boolean[] array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return EMPTY_BOOLEAN_OBJECT_ARRAY; + } + final Boolean[] result = new Boolean[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = (array[i] ? Boolean.TRUE : Boolean.FALSE); + } + return result; + } + + // ---------------------------------------------------------------------- + /** + *

Checks if an array of Objects is empty or {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is empty or {@code null} + * @since 2.1 + */ + public static boolean isEmpty(Object[] array) { + return array == null || array.length == 0; + } + + /** + *

Checks if an array of primitive longs is empty or {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is empty or {@code null} + * @since 2.1 + */ + public static boolean isEmpty(long[] array) { + return array == null || array.length == 0; + } + + /** + *

Checks if an array of primitive ints is empty or {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is empty or {@code null} + * @since 2.1 + */ + public static boolean isEmpty(int[] array) { + return array == null || array.length == 0; + } + + /** + *

Checks if an array of primitive shorts is empty or {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is empty or {@code null} + * @since 2.1 + */ + public static boolean isEmpty(short[] array) { + return array == null || array.length == 0; + } + + /** + *

Checks if an array of primitive chars is empty or {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is empty or {@code null} + * @since 2.1 + */ + public static boolean isEmpty(char[] array) { + return array == null || array.length == 0; + } + + /** + *

Checks if an array of primitive bytes is empty or {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is empty or {@code null} + * @since 2.1 + */ + public static boolean isEmpty(byte[] array) { + return array == null || array.length == 0; + } + + /** + *

Checks if an array of primitive doubles is empty or {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is empty or {@code null} + * @since 2.1 + */ + public static boolean isEmpty(double[] array) { + return array == null || array.length == 0; + } + + /** + *

Checks if an array of primitive floats is empty or {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is empty or {@code null} + * @since 2.1 + */ + public static boolean isEmpty(float[] array) { + return array == null || array.length == 0; + } + + /** + *

Checks if an array of primitive booleans is empty or {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is empty or {@code null} + * @since 2.1 + */ + public static boolean isEmpty(boolean[] array) { + return array == null || array.length == 0; + } + + // ---------------------------------------------------------------------- + /** + *

Checks if an array of Objects is not empty or not {@code null}.

+ * + * @param the component type of the array + * @param array the array to test + * @return {@code true} if the array is not empty or not {@code null} + * @since 2.5 + */ + public static boolean isNotEmpty(T[] array) { + return (array != null && array.length != 0); + } + + /** + *

Checks if an array of primitive longs is not empty or not {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is not empty or not {@code null} + * @since 2.5 + */ + public static boolean isNotEmpty(long[] array) { + return (array != null && array.length != 0); + } + + /** + *

Checks if an array of primitive ints is not empty or not {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is not empty or not {@code null} + * @since 2.5 + */ + public static boolean isNotEmpty(int[] array) { + return (array != null && array.length != 0); + } + + /** + *

Checks if an array of primitive shorts is not empty or not {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is not empty or not {@code null} + * @since 2.5 + */ + public static boolean isNotEmpty(short[] array) { + return (array != null && array.length != 0); + } + + /** + *

Checks if an array of primitive chars is not empty or not {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is not empty or not {@code null} + * @since 2.5 + */ + public static boolean isNotEmpty(char[] array) { + return (array != null && array.length != 0); + } + + /** + *

Checks if an array of primitive bytes is not empty or not {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is not empty or not {@code null} + * @since 2.5 + */ + public static boolean isNotEmpty(byte[] array) { + return (array != null && array.length != 0); + } + + /** + *

Checks if an array of primitive doubles is not empty or not {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is not empty or not {@code null} + * @since 2.5 + */ + public static boolean isNotEmpty(double[] array) { + return (array != null && array.length != 0); + } + + /** + *

Checks if an array of primitive floats is not empty or not {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is not empty or not {@code null} + * @since 2.5 + */ + public static boolean isNotEmpty(float[] array) { + return (array != null && array.length != 0); + } + + /** + *

Checks if an array of primitive booleans is not empty or not {@code null}.

+ * + * @param array the array to test + * @return {@code true} if the array is not empty or not {@code null} + * @since 2.5 + */ + public static boolean isNotEmpty(boolean[] array) { + return (array != null && array.length != 0); + } + + /** + *

Adds all the elements of the given arrays into a new array.

+ *

The new array contains all of the element of {@code array1} followed + * by all of the elements {@code array2}. When an array is returned, it is always + * a new array.

+ * + *
+     * ArrayUtils.addAll(null, null)     = null
+     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
+     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
+     * ArrayUtils.addAll([], [])         = []
+     * ArrayUtils.addAll([null], [null]) = [null, null]
+     * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
+     * 
+ * + * @param the component type of the array + * @param array1 the first array whose elements are added to the new array, may be {@code null} + * @param array2 the second array whose elements are added to the new array, may be {@code null} + * @return The new array, {@code null} if both arrays are {@code null}. + * The type of the new array is the type of the first array, + * unless the first array is null, in which case the type is the same as the second array. + * @since 2.1 + * @throws IllegalArgumentException if the array types are incompatible + */ + public static T[] addAll(T[] array1, T... array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + final Class type1 = array1.getClass().getComponentType(); + @SuppressWarnings("unchecked") // OK, because array is of type T + T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length); + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + try { + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + } catch (ArrayStoreException ase) { + // Check if problem was due to incompatible types + /* + * We do this here, rather than before the copy because: + * - it would be a wasted check most of the time + * - safer, in case check turns out to be too strict + */ + final Class type2 = array2.getClass().getComponentType(); + if (!type1.isAssignableFrom(type2)){ + throw new IllegalArgumentException("Cannot store "+type2.getName()+" in an array of " + +type1.getName(), ase); + } + throw ase; // No, so rethrow original + } + return joinedArray; + } + + /** + *

Adds all the elements of the given arrays into a new array.

+ *

The new array contains all of the element of {@code array1} followed + * by all of the elements {@code array2}. When an array is returned, it is always + * a new array.

+ * + *
+     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
+     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
+     * ArrayUtils.addAll([], [])         = []
+     * 
+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new boolean[] array. + * @since 2.1 + */ + public static boolean[] addAll(boolean[] array1, boolean... array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + boolean[] joinedArray = new boolean[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *

Adds all the elements of the given arrays into a new array.

+ *

The new array contains all of the element of {@code array1} followed + * by all of the elements {@code array2}. When an array is returned, it is always + * a new array.

+ * + *
+     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
+     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
+     * ArrayUtils.addAll([], [])         = []
+     * 
+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new char[] array. + * @since 2.1 + */ + public static char[] addAll(char[] array1, char... array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + char[] joinedArray = new char[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *

Adds all the elements of the given arrays into a new array.

+ *

The new array contains all of the element of {@code array1} followed + * by all of the elements {@code array2}. When an array is returned, it is always + * a new array.

+ * + *
+     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
+     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
+     * ArrayUtils.addAll([], [])         = []
+     * 
+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new byte[] array. + * @since 2.1 + */ + public static byte[] addAll(byte[] array1, byte... array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + byte[] joinedArray = new byte[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *

Adds all the elements of the given arrays into a new array.

+ *

The new array contains all of the element of {@code array1} followed + * by all of the elements {@code array2}. When an array is returned, it is always + * a new array.

+ * + *
+     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
+     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
+     * ArrayUtils.addAll([], [])         = []
+     * 
+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new short[] array. + * @since 2.1 + */ + public static short[] addAll(short[] array1, short... array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + short[] joinedArray = new short[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *

Adds all the elements of the given arrays into a new array.

+ *

The new array contains all of the element of {@code array1} followed + * by all of the elements {@code array2}. When an array is returned, it is always + * a new array.

+ * + *
+     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
+     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
+     * ArrayUtils.addAll([], [])         = []
+     * 
+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new int[] array. + * @since 2.1 + */ + public static int[] addAll(int[] array1, int... array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + int[] joinedArray = new int[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *

Adds all the elements of the given arrays into a new array.

+ *

The new array contains all of the element of {@code array1} followed + * by all of the elements {@code array2}. When an array is returned, it is always + * a new array.

+ * + *
+     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
+     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
+     * ArrayUtils.addAll([], [])         = []
+     * 
+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new long[] array. + * @since 2.1 + */ + public static long[] addAll(long[] array1, long... array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + long[] joinedArray = new long[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *

Adds all the elements of the given arrays into a new array.

+ *

The new array contains all of the element of {@code array1} followed + * by all of the elements {@code array2}. When an array is returned, it is always + * a new array.

+ * + *
+     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
+     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
+     * ArrayUtils.addAll([], [])         = []
+     * 
+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new float[] array. + * @since 2.1 + */ + public static float[] addAll(float[] array1, float... array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + float[] joinedArray = new float[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *

Adds all the elements of the given arrays into a new array.

+ *

The new array contains all of the element of {@code array1} followed + * by all of the elements {@code array2}. When an array is returned, it is always + * a new array.

+ * + *
+     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
+     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
+     * ArrayUtils.addAll([], [])         = []
+     * 
+ * + * @param array1 the first array whose elements are added to the new array. + * @param array2 the second array whose elements are added to the new array. + * @return The new double[] array. + * @since 2.1 + */ + public static double[] addAll(double[] array1, double... array2) { + if (array1 == null) { + return clone(array2); + } else if (array2 == null) { + return clone(array1); + } + double[] joinedArray = new double[array1.length + array2.length]; + System.arraycopy(array1, 0, joinedArray, 0, array1.length); + System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); + return joinedArray; + } + + /** + *

Copies the given array and adds the given element at the end of the new array.

+ * + *

The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element, unless the element itself is null, + * in which case the return type is Object[]

+ * + *
+     * ArrayUtils.add(null, null)      = [null]
+     * ArrayUtils.add(null, "a")       = ["a"]
+     * ArrayUtils.add(["a"], null)     = ["a", null]
+     * ArrayUtils.add(["a"], "b")      = ["a", "b"]
+     * ArrayUtils.add(["a", "b"], "c") = ["a", "b", "c"]
+     * 
+ * + * @param the component type of the array + * @param array the array to "add" the element to, may be {@code null} + * @param element the object to add, may be {@code null} + * @return A new array containing the existing elements plus the new element + * The returned array type will be that of the input array (unless null), + * in which case it will have the same type as the element. + * If both are null, an IllegalArgumentException is thrown + * @since 2.1 + * @throws IllegalArgumentException if both arguments are null + */ + public static T[] add(T[] array, T element) { + Class type; + if (array != null){ + type = array.getClass(); + } else if (element != null) { + type = element.getClass(); + } else { + throw new IllegalArgumentException("Arguments cannot both be null"); + } + @SuppressWarnings("unchecked") // type must be T + T[] newArray = (T[]) copyArrayGrow1(array, type); + newArray[newArray.length - 1] = element; + return newArray; + } + + /** + *

Copies the given array and adds the given element at the end of the new array.

+ * + *

The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, true)          = [true]
+     * ArrayUtils.add([true], false)       = [true, false]
+     * ArrayUtils.add([true, false], true) = [true, false, true]
+     * 
+ * + * @param array the array to copy and add the element to, may be {@code null} + * @param element the object to add at the last index of the new array + * @return A new array containing the existing elements plus the new element + * @since 2.1 + */ + public static boolean[] add(boolean[] array, boolean element) { + boolean[] newArray = (boolean[])copyArrayGrow1(array, Boolean.TYPE); + newArray[newArray.length - 1] = element; + return newArray; + } + + /** + *

Copies the given array and adds the given element at the end of the new array.

+ * + *

The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, 0)   = [0]
+     * ArrayUtils.add([1], 0)    = [1, 0]
+     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+     * 
+ * + * @param array the array to copy and add the element to, may be {@code null} + * @param element the object to add at the last index of the new array + * @return A new array containing the existing elements plus the new element + * @since 2.1 + */ + public static byte[] add(byte[] array, byte element) { + byte[] newArray = (byte[])copyArrayGrow1(array, Byte.TYPE); + newArray[newArray.length - 1] = element; + return newArray; + } + + /** + *

Copies the given array and adds the given element at the end of the new array.

+ * + *

The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, '0')       = ['0']
+     * ArrayUtils.add(['1'], '0')      = ['1', '0']
+     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']
+     * 
+ * + * @param array the array to copy and add the element to, may be {@code null} + * @param element the object to add at the last index of the new array + * @return A new array containing the existing elements plus the new element + * @since 2.1 + */ + public static char[] add(char[] array, char element) { + char[] newArray = (char[])copyArrayGrow1(array, Character.TYPE); + newArray[newArray.length - 1] = element; + return newArray; + } + + /** + *

Copies the given array and adds the given element at the end of the new array.

+ * + *

The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, 0)   = [0]
+     * ArrayUtils.add([1], 0)    = [1, 0]
+     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+     * 
+ * + * @param array the array to copy and add the element to, may be {@code null} + * @param element the object to add at the last index of the new array + * @return A new array containing the existing elements plus the new element + * @since 2.1 + */ + public static double[] add(double[] array, double element) { + double[] newArray = (double[])copyArrayGrow1(array, Double.TYPE); + newArray[newArray.length - 1] = element; + return newArray; + } + + /** + *

Copies the given array and adds the given element at the end of the new array.

+ * + *

The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, 0)   = [0]
+     * ArrayUtils.add([1], 0)    = [1, 0]
+     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+     * 
+ * + * @param array the array to copy and add the element to, may be {@code null} + * @param element the object to add at the last index of the new array + * @return A new array containing the existing elements plus the new element + * @since 2.1 + */ + public static float[] add(float[] array, float element) { + float[] newArray = (float[])copyArrayGrow1(array, Float.TYPE); + newArray[newArray.length - 1] = element; + return newArray; + } + + /** + *

Copies the given array and adds the given element at the end of the new array.

+ * + *

The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, 0)   = [0]
+     * ArrayUtils.add([1], 0)    = [1, 0]
+     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+     * 
+ * + * @param array the array to copy and add the element to, may be {@code null} + * @param element the object to add at the last index of the new array + * @return A new array containing the existing elements plus the new element + * @since 2.1 + */ + public static int[] add(int[] array, int element) { + int[] newArray = (int[])copyArrayGrow1(array, Integer.TYPE); + newArray[newArray.length - 1] = element; + return newArray; + } + + /** + *

Copies the given array and adds the given element at the end of the new array.

+ * + *

The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, 0)   = [0]
+     * ArrayUtils.add([1], 0)    = [1, 0]
+     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+     * 
+ * + * @param array the array to copy and add the element to, may be {@code null} + * @param element the object to add at the last index of the new array + * @return A new array containing the existing elements plus the new element + * @since 2.1 + */ + public static long[] add(long[] array, long element) { + long[] newArray = (long[])copyArrayGrow1(array, Long.TYPE); + newArray[newArray.length - 1] = element; + return newArray; + } + + /** + *

Copies the given array and adds the given element at the end of the new array.

+ * + *

The new array contains the same elements of the input + * array plus the given element in the last position. The component type of + * the new array is the same as that of the input array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, 0)   = [0]
+     * ArrayUtils.add([1], 0)    = [1, 0]
+     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
+     * 
+ * + * @param array the array to copy and add the element to, may be {@code null} + * @param element the object to add at the last index of the new array + * @return A new array containing the existing elements plus the new element + * @since 2.1 + */ + public static short[] add(short[] array, short element) { + short[] newArray = (short[])copyArrayGrow1(array, Short.TYPE); + newArray[newArray.length - 1] = element; + return newArray; + } + + /** + * Returns a copy of the given array of size 1 greater than the argument. + * The last value of the array is left to the default value. + * + * @param array The array to copy, must not be {@code null}. + * @param newArrayComponentType If {@code array} is {@code null}, create a + * size 1 array of this type. + * @return A new copy of the array of size 1 greater than the input. + */ + private static Object copyArrayGrow1(Object array, Class newArrayComponentType) { + if (array != null) { + int arrayLength = Array.getLength(array); + Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1); + System.arraycopy(array, 0, newArray, 0, arrayLength); + return newArray; + } + return Array.newInstance(newArrayComponentType, 1); + } + + /** + *

Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).

+ * + *

This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, 0, null)      = [null]
+     * ArrayUtils.add(null, 0, "a")       = ["a"]
+     * ArrayUtils.add(["a"], 1, null)     = ["a", null]
+     * ArrayUtils.add(["a"], 1, "b")      = ["a", "b"]
+     * ArrayUtils.add(["a", "b"], 3, "c") = ["a", "b", "c"]
+     * 
+ * + * @param the component type of the array + * @param array the array to add the element to, may be {@code null} + * @param index the position of the new object + * @param element the object to add + * @return A new array containing the existing elements and the new element + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index > array.length). + * @throws IllegalArgumentException if both array and element are null + */ + public static T[] add(T[] array, int index, T element) { + Class clss = null; + if (array != null) { + clss = array.getClass().getComponentType(); + } else if (element != null) { + clss = element.getClass(); + } else { + throw new IllegalArgumentException("Array and element cannot both be null"); + } + @SuppressWarnings("unchecked") // the add method creates an array of type clss, which is type T + final T[] newArray = (T[]) add(array, index, element, clss); + return newArray; + } + + /** + *

Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).

+ * + *

This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, 0, true)          = [true]
+     * ArrayUtils.add([true], 0, false)       = [false, true]
+     * ArrayUtils.add([false], 1, true)       = [false, true]
+     * ArrayUtils.add([true, false], 1, true) = [true, true, false]
+     * 
+ * + * @param array the array to add the element to, may be {@code null} + * @param index the position of the new object + * @param element the object to add + * @return A new array containing the existing elements and the new element + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index > array.length). + */ + public static boolean[] add(boolean[] array, int index, boolean element) { + return (boolean[]) add(array, index, Boolean.valueOf(element), Boolean.TYPE); + } + + /** + *

Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).

+ * + *

This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add(null, 0, 'a')            = ['a']
+     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']
+     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']
+     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']
+     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']
+     * 
+ * + * @param array the array to add the element to, may be {@code null} + * @param index the position of the new object + * @param element the object to add + * @return A new array containing the existing elements and the new element + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index > array.length). + */ + public static char[] add(char[] array, int index, char element) { + return (char[]) add(array, index, Character.valueOf(element), Character.TYPE); + } + + /** + *

Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).

+ * + *

This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add([1], 0, 2)         = [2, 1]
+     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]
+     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]
+     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]
+     * 
+ * + * @param array the array to add the element to, may be {@code null} + * @param index the position of the new object + * @param element the object to add + * @return A new array containing the existing elements and the new element + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index > array.length). + */ + public static byte[] add(byte[] array, int index, byte element) { + return (byte[]) add(array, index, Byte.valueOf(element), Byte.TYPE); + } + + /** + *

Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).

+ * + *

This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add([1], 0, 2)         = [2, 1]
+     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]
+     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]
+     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]
+     * 
+ * + * @param array the array to add the element to, may be {@code null} + * @param index the position of the new object + * @param element the object to add + * @return A new array containing the existing elements and the new element + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index > array.length). + */ + public static short[] add(short[] array, int index, short element) { + return (short[]) add(array, index, Short.valueOf(element), Short.TYPE); + } + + /** + *

Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).

+ * + *

This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add([1], 0, 2)         = [2, 1]
+     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]
+     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]
+     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]
+     * 
+ * + * @param array the array to add the element to, may be {@code null} + * @param index the position of the new object + * @param element the object to add + * @return A new array containing the existing elements and the new element + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index > array.length). + */ + public static int[] add(int[] array, int index, int element) { + return (int[]) add(array, index, Integer.valueOf(element), Integer.TYPE); + } + + /** + *

Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).

+ * + *

This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]
+     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]
+     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]
+     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]
+     * 
+ * + * @param array the array to add the element to, may be {@code null} + * @param index the position of the new object + * @param element the object to add + * @return A new array containing the existing elements and the new element + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index > array.length). + */ + public static long[] add(long[] array, int index, long element) { + return (long[]) add(array, index, Long.valueOf(element), Long.TYPE); + } + + /** + *

Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).

+ * + *

This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]
+     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]
+     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]
+     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]
+     * 
+ * + * @param array the array to add the element to, may be {@code null} + * @param index the position of the new object + * @param element the object to add + * @return A new array containing the existing elements and the new element + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index > array.length). + */ + public static float[] add(float[] array, int index, float element) { + return (float[]) add(array, index, Float.valueOf(element), Float.TYPE); + } + + /** + *

Inserts the specified element at the specified position in the array. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices).

+ * + *

This method returns a new array with the same elements of the input + * array plus the given element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, a new one element array is returned + * whose component type is the same as the element.

+ * + *
+     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]
+     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]
+     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]
+     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]
+     * 
+ * + * @param array the array to add the element to, may be {@code null} + * @param index the position of the new object + * @param element the object to add + * @return A new array containing the existing elements and the new element + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index > array.length). + */ + public static double[] add(double[] array, int index, double element) { + return (double[]) add(array, index, Double.valueOf(element), Double.TYPE); + } + + /** + * Underlying implementation of add(array, index, element) methods. + * The last parameter is the class, which may not equal element.getClass + * for primitives. + * + * @param array the array to add the element to, may be {@code null} + * @param index the position of the new object + * @param element the object to add + * @param clss the type of the element being added + * @return A new array containing the existing elements and the new element + */ + private static Object add(Object array, int index, Object element, Class clss) { + if (array == null) { + if (index != 0) { + throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0"); + } + Object joinedArray = Array.newInstance(clss, 1); + Array.set(joinedArray, 0, element); + return joinedArray; + } + int length = Array.getLength(array); + if (index > length || index < 0) { + throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); + } + Object result = Array.newInstance(clss, length + 1); + System.arraycopy(array, 0, result, 0, index); + Array.set(result, index, element); + if (index < length) { + System.arraycopy(array, index, result, index + 1, length - index); + } + return result; + } + + /** + *

Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (subtracts one from + * their indices).

+ * + *

This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.remove(["a"], 0)           = []
+     * ArrayUtils.remove(["a", "b"], 0)      = ["b"]
+     * ArrayUtils.remove(["a", "b"], 1)      = ["a"]
+     * ArrayUtils.remove(["a", "b", "c"], 1) = ["a", "c"]
+     * 
+ * + * @param the component type of the array + * @param array the array to remove the element from, may not be {@code null} + * @param index the position of the element to be removed + * @return A new array containing the existing elements except the element + * at the specified position. + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 2.1 + */ + @SuppressWarnings("unchecked") // remove() always creates an array of the same type as its input + public static T[] remove(T[] array, int index) { + return (T[]) remove((Object) array, index); + } + + /** + *

Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (subtracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.

+ * + *

This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *
+     * ArrayUtils.removeElement(null, "a")            = null
+     * ArrayUtils.removeElement([], "a")              = []
+     * ArrayUtils.removeElement(["a"], "b")           = ["a"]
+     * ArrayUtils.removeElement(["a", "b"], "a")      = ["b"]
+     * ArrayUtils.removeElement(["a", "b", "a"], "a") = ["b", "a"]
+     * 
+ * + * @param the component type of the array + * @param array the array to remove the element from, may be {@code null} + * @param element the element to be removed + * @return A new array containing the existing elements except the first + * occurrence of the specified element. + * @since 2.1 + */ + public static T[] removeElement(T[] array, Object element) { + int index = indexOf(array, element); + if (index == INDEX_NOT_FOUND) { + return clone(array); + } + return remove(array, index); + } + + /** + *

Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (subtracts one from + * their indices).

+ * + *

This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.remove([true], 0)              = []
+     * ArrayUtils.remove([true, false], 0)       = [false]
+     * ArrayUtils.remove([true, false], 1)       = [true]
+     * ArrayUtils.remove([true, true, false], 1) = [true, false]
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param index the position of the element to be removed + * @return A new array containing the existing elements except the element + * at the specified position. + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 2.1 + */ + public static boolean[] remove(boolean[] array, int index) { + return (boolean[]) remove((Object) array, index); + } + + /** + *

Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (subtracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.

+ * + *

This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *
+     * ArrayUtils.removeElement(null, true)                = null
+     * ArrayUtils.removeElement([], true)                  = []
+     * ArrayUtils.removeElement([true], false)             = [true]
+     * ArrayUtils.removeElement([true, false], false)      = [true]
+     * ArrayUtils.removeElement([true, false, true], true) = [false, true]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param element the element to be removed + * @return A new array containing the existing elements except the first + * occurrence of the specified element. + * @since 2.1 + */ + public static boolean[] removeElement(boolean[] array, boolean element) { + int index = indexOf(array, element); + if (index == INDEX_NOT_FOUND) { + return clone(array); + } + return remove(array, index); + } + + /** + *

Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (subtracts one from + * their indices).

+ * + *

This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.remove([1], 0)          = []
+     * ArrayUtils.remove([1, 0], 0)       = [0]
+     * ArrayUtils.remove([1, 0], 1)       = [1]
+     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param index the position of the element to be removed + * @return A new array containing the existing elements except the element + * at the specified position. + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 2.1 + */ + public static byte[] remove(byte[] array, int index) { + return (byte[]) remove((Object) array, index); + } + + /** + *

Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (subtracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.

+ * + *

This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *
+     * ArrayUtils.removeElement(null, 1)        = null
+     * ArrayUtils.removeElement([], 1)          = []
+     * ArrayUtils.removeElement([1], 0)         = [1]
+     * ArrayUtils.removeElement([1, 0], 0)      = [1]
+     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param element the element to be removed + * @return A new array containing the existing elements except the first + * occurrence of the specified element. + * @since 2.1 + */ + public static byte[] removeElement(byte[] array, byte element) { + int index = indexOf(array, element); + if (index == INDEX_NOT_FOUND) { + return clone(array); + } + return remove(array, index); + } + + /** + *

Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (subtracts one from + * their indices).

+ * + *

This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.remove(['a'], 0)           = []
+     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']
+     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']
+     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param index the position of the element to be removed + * @return A new array containing the existing elements except the element + * at the specified position. + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 2.1 + */ + public static char[] remove(char[] array, int index) { + return (char[]) remove((Object) array, index); + } + + /** + *

Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (subtracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.

+ * + *

This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *
+     * ArrayUtils.removeElement(null, 'a')            = null
+     * ArrayUtils.removeElement([], 'a')              = []
+     * ArrayUtils.removeElement(['a'], 'b')           = ['a']
+     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']
+     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param element the element to be removed + * @return A new array containing the existing elements except the first + * occurrence of the specified element. + * @since 2.1 + */ + public static char[] removeElement(char[] array, char element) { + int index = indexOf(array, element); + if (index == INDEX_NOT_FOUND) { + return clone(array); + } + return remove(array, index); + } + + /** + *

Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (subtracts one from + * their indices).

+ * + *

This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.remove([1.1], 0)           = []
+     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]
+     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]
+     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param index the position of the element to be removed + * @return A new array containing the existing elements except the element + * at the specified position. + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 2.1 + */ + public static double[] remove(double[] array, int index) { + return (double[]) remove((Object) array, index); + } + + /** + *

Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (subtracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.

+ * + *

This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *
+     * ArrayUtils.removeElement(null, 1.1)            = null
+     * ArrayUtils.removeElement([], 1.1)              = []
+     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]
+     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]
+     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param element the element to be removed + * @return A new array containing the existing elements except the first + * occurrence of the specified element. + * @since 2.1 + */ + public static double[] removeElement(double[] array, double element) { + int index = indexOf(array, element); + if (index == INDEX_NOT_FOUND) { + return clone(array); + } + return remove(array, index); + } + + /** + *

Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (subtracts one from + * their indices).

+ * + *

This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.remove([1.1], 0)           = []
+     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]
+     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]
+     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param index the position of the element to be removed + * @return A new array containing the existing elements except the element + * at the specified position. + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 2.1 + */ + public static float[] remove(float[] array, int index) { + return (float[]) remove((Object) array, index); + } + + /** + *

Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (subtracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.

+ * + *

This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *
+     * ArrayUtils.removeElement(null, 1.1)            = null
+     * ArrayUtils.removeElement([], 1.1)              = []
+     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]
+     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]
+     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param element the element to be removed + * @return A new array containing the existing elements except the first + * occurrence of the specified element. + * @since 2.1 + */ + public static float[] removeElement(float[] array, float element) { + int index = indexOf(array, element); + if (index == INDEX_NOT_FOUND) { + return clone(array); + } + return remove(array, index); + } + + /** + *

Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (subtracts one from + * their indices).

+ * + *

This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.remove([1], 0)         = []
+     * ArrayUtils.remove([2, 6], 0)      = [6]
+     * ArrayUtils.remove([2, 6], 1)      = [2]
+     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param index the position of the element to be removed + * @return A new array containing the existing elements except the element + * at the specified position. + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 2.1 + */ + public static int[] remove(int[] array, int index) { + return (int[]) remove((Object) array, index); + } + + /** + *

Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (subtracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.

+ * + *

This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *
+     * ArrayUtils.removeElement(null, 1)      = null
+     * ArrayUtils.removeElement([], 1)        = []
+     * ArrayUtils.removeElement([1], 2)       = [1]
+     * ArrayUtils.removeElement([1, 3], 1)    = [3]
+     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param element the element to be removed + * @return A new array containing the existing elements except the first + * occurrence of the specified element. + * @since 2.1 + */ + public static int[] removeElement(int[] array, int element) { + int index = indexOf(array, element); + if (index == INDEX_NOT_FOUND) { + return clone(array); + } + return remove(array, index); + } + + /** + *

Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (subtracts one from + * their indices).

+ * + *

This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.remove([1], 0)         = []
+     * ArrayUtils.remove([2, 6], 0)      = [6]
+     * ArrayUtils.remove([2, 6], 1)      = [2]
+     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param index the position of the element to be removed + * @return A new array containing the existing elements except the element + * at the specified position. + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 2.1 + */ + public static long[] remove(long[] array, int index) { + return (long[]) remove((Object) array, index); + } + + /** + *

Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (subtracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.

+ * + *

This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *
+     * ArrayUtils.removeElement(null, 1)      = null
+     * ArrayUtils.removeElement([], 1)        = []
+     * ArrayUtils.removeElement([1], 2)       = [1]
+     * ArrayUtils.removeElement([1, 3], 1)    = [3]
+     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param element the element to be removed + * @return A new array containing the existing elements except the first + * occurrence of the specified element. + * @since 2.1 + */ + public static long[] removeElement(long[] array, long element) { + int index = indexOf(array, element); + if (index == INDEX_NOT_FOUND) { + return clone(array); + } + return remove(array, index); + } + + /** + *

Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (subtracts one from + * their indices).

+ * + *

This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.remove([1], 0)         = []
+     * ArrayUtils.remove([2, 6], 0)      = [6]
+     * ArrayUtils.remove([2, 6], 1)      = [2]
+     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param index the position of the element to be removed + * @return A new array containing the existing elements except the element + * at the specified position. + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 2.1 + */ + public static short[] remove(short[] array, int index) { + return (short[]) remove((Object) array, index); + } + + /** + *

Removes the first occurrence of the specified element from the + * specified array. All subsequent elements are shifted to the left + * (subtracts one from their indices). If the array doesn't contains + * such an element, no elements are removed from the array.

+ * + *

This method returns a new array with the same elements of the input + * array except the first occurrence of the specified element. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *
+     * ArrayUtils.removeElement(null, 1)      = null
+     * ArrayUtils.removeElement([], 1)        = []
+     * ArrayUtils.removeElement([1], 2)       = [1]
+     * ArrayUtils.removeElement([1, 3], 1)    = [3]
+     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param element the element to be removed + * @return A new array containing the existing elements except the first + * occurrence of the specified element. + * @since 2.1 + */ + public static short[] removeElement(short[] array, short element) { + int index = indexOf(array, element); + if (index == INDEX_NOT_FOUND) { + return clone(array); + } + return remove(array, index); + } + + /** + *

Removes the element at the specified position from the specified array. + * All subsequent elements are shifted to the left (subtracts one from + * their indices).

+ * + *

This method returns a new array with the same elements of the input + * array except the element on the specified position. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + * @param array the array to remove the element from, may not be {@code null} + * @param index the position of the element to be removed + * @return A new array containing the existing elements except the element + * at the specified position. + * @throws IndexOutOfBoundsException if the index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 2.1 + */ + private static Object remove(Object array, int index) { + int length = getLength(array); + if (index < 0 || index >= length) { + throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); + } + + Object result = Array.newInstance(array.getClass().getComponentType(), length - 1); + System.arraycopy(array, 0, result, 0, index); + if (index < length - 1) { + System.arraycopy(array, index + 1, result, index, length - index - 1); + } + + return result; + } + + /** + *

Removes the elements at the specified positions from the specified array. + * All remaining elements are shifted to the left.

+ * + *

This method returns a new array with the same elements of the input + * array except those at the specified positions. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.removeAll(["a", "b", "c"], 0, 2) = ["b"]
+     * ArrayUtils.removeAll(["a", "b", "c"], 1, 2) = ["a"]
+     * 
+ * + * @param the component type of the array + * @param array the array to remove the element from, may not be {@code null} + * @param indices the positions of the elements to be removed + * @return A new array containing the existing elements except those + * at the specified positions. + * @throws IndexOutOfBoundsException if any index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 3.0.1 + */ + @SuppressWarnings("unchecked") + // removeAll() always creates an array of the same type as its input + public static T[] removeAll(T[] array, int... indices) { + return (T[]) removeAll((Object) array, clone(indices)); + } + + /** + *

Removes occurrences of specified elements, in specified quantities, + * from the specified array. All subsequent elements are shifted left. + * For any element-to-be-removed specified in greater quantities than + * contained in the original array, no change occurs beyond the + * removal of the existing matching items.

+ * + *

This method returns a new array with the same elements of the input + * array except for the earliest-encountered occurrences of the specified + * elements. The component type of the returned array is always the same + * as that of the input array.

+ * + *
+     * ArrayUtils.removeElements(null, "a", "b")            = null
+     * ArrayUtils.removeElements([], "a", "b")              = []
+     * ArrayUtils.removeElements(["a"], "b", "c")           = ["a"]
+     * ArrayUtils.removeElements(["a", "b"], "a", "c")      = ["b"]
+     * ArrayUtils.removeElements(["a", "b", "a"], "a")      = ["b", "a"]
+     * ArrayUtils.removeElements(["a", "b", "a"], "a", "a") = ["b"]
+     * 
+ * + * @param the component type of the array + * @param array the array to remove the element from, may be {@code null} + * @param values the elements to be removed + * @return A new array containing the existing elements except the + * earliest-encountered occurrences of the specified elements. + * @since 3.0.1 + */ + public static T[] removeElements(T[] array, T... values) { + if (isEmpty(array) || isEmpty(values)) { + return clone(array); + } + HashMap occurrences = new HashMap(values.length); + for (T v : values) { + MutableInt count = occurrences.get(v); + if (count == null) { + occurrences.put(v, new MutableInt(1)); + } else { + count.increment(); + } + } + HashSet toRemove = new HashSet(); + for (Map.Entry e : occurrences.entrySet()) { + T v = e.getKey(); + int found = 0; + for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) { + found = indexOf(array, v, found); + if (found < 0) { + break; + } + toRemove.add(found++); + } + } + return removeAll(array, extractIndices(toRemove)); + } + + /** + *

Removes the elements at the specified positions from the specified array. + * All remaining elements are shifted to the left.

+ * + *

This method returns a new array with the same elements of the input + * array except those at the specified positions. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.removeAll([1], 0)             = []
+     * ArrayUtils.removeAll([2, 6], 0)          = [6]
+     * ArrayUtils.removeAll([2, 6], 0, 1)       = []
+     * ArrayUtils.removeAll([2, 6, 3], 1, 2)    = [2]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 2)    = [6]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param indices the positions of the elements to be removed + * @return A new array containing the existing elements except those + * at the specified positions. + * @throws IndexOutOfBoundsException if any index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 3.0.1 + */ + public static byte[] removeAll(byte[] array, int... indices) { + return (byte[]) removeAll((Object) array, clone(indices)); + } + + /** + *

Removes occurrences of specified elements, in specified quantities, + * from the specified array. All subsequent elements are shifted left. + * For any element-to-be-removed specified in greater quantities than + * contained in the original array, no change occurs beyond the + * removal of the existing matching items.

+ * + *

This method returns a new array with the same elements of the input + * array except for the earliest-encountered occurrences of the specified + * elements. The component type of the returned array is always the same + * as that of the input array.

+ * + *
+     * ArrayUtils.removeElements(null, 1, 2)      = null
+     * ArrayUtils.removeElements([], 1, 2)        = []
+     * ArrayUtils.removeElements([1], 2, 3)       = [1]
+     * ArrayUtils.removeElements([1, 3], 1, 2)    = [3]
+     * ArrayUtils.removeElements([1, 3, 1], 1)    = [3, 1]
+     * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param values the elements to be removed + * @return A new array containing the existing elements except the + * earliest-encountered occurrences of the specified elements. + * @since 3.0.1 + */ + public static byte[] removeElements(byte[] array, byte... values) { + if (isEmpty(array) || isEmpty(values)) { + return clone(array); + } + HashMap occurrences = new HashMap(values.length); + for (byte v : values) { + Byte boxed = Byte.valueOf(v); + MutableInt count = occurrences.get(boxed); + if (count == null) { + occurrences.put(boxed, new MutableInt(1)); + } else { + count.increment(); + } + } + HashSet toRemove = new HashSet(); + for (Map.Entry e : occurrences.entrySet()) { + Byte v = e.getKey(); + int found = 0; + for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) { + found = indexOf(array, v.byteValue(), found); + if (found < 0) { + break; + } + toRemove.add(found++); + } + } + return removeAll(array, extractIndices(toRemove)); + } + + /** + *

Removes the elements at the specified positions from the specified array. + * All remaining elements are shifted to the left.

+ * + *

This method returns a new array with the same elements of the input + * array except those at the specified positions. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.removeAll([1], 0)             = []
+     * ArrayUtils.removeAll([2, 6], 0)          = [6]
+     * ArrayUtils.removeAll([2, 6], 0, 1)       = []
+     * ArrayUtils.removeAll([2, 6, 3], 1, 2)    = [2]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 2)    = [6]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param indices the positions of the elements to be removed + * @return A new array containing the existing elements except those + * at the specified positions. + * @throws IndexOutOfBoundsException if any index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 3.0.1 + */ + public static short[] removeAll(short[] array, int... indices) { + return (short[]) removeAll((Object) array, clone(indices)); + } + + /** + *

Removes occurrences of specified elements, in specified quantities, + * from the specified array. All subsequent elements are shifted left. + * For any element-to-be-removed specified in greater quantities than + * contained in the original array, no change occurs beyond the + * removal of the existing matching items.

+ * + *

This method returns a new array with the same elements of the input + * array except for the earliest-encountered occurrences of the specified + * elements. The component type of the returned array is always the same + * as that of the input array.

+ * + *
+     * ArrayUtils.removeElements(null, 1, 2)      = null
+     * ArrayUtils.removeElements([], 1, 2)        = []
+     * ArrayUtils.removeElements([1], 2, 3)       = [1]
+     * ArrayUtils.removeElements([1, 3], 1, 2)    = [3]
+     * ArrayUtils.removeElements([1, 3, 1], 1)    = [3, 1]
+     * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param values the elements to be removed + * @return A new array containing the existing elements except the + * earliest-encountered occurrences of the specified elements. + * @since 3.0.1 + */ + public static short[] removeElements(short[] array, short... values) { + if (isEmpty(array) || isEmpty(values)) { + return clone(array); + } + HashMap occurrences = new HashMap(values.length); + for (short v : values) { + Short boxed = Short.valueOf(v); + MutableInt count = occurrences.get(boxed); + if (count == null) { + occurrences.put(boxed, new MutableInt(1)); + } else { + count.increment(); + } + } + HashSet toRemove = new HashSet(); + for (Map.Entry e : occurrences.entrySet()) { + Short v = e.getKey(); + int found = 0; + for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) { + found = indexOf(array, v.shortValue(), found); + if (found < 0) { + break; + } + toRemove.add(found++); + } + } + return removeAll(array, extractIndices(toRemove)); + } + + /** + *

Removes the elements at the specified positions from the specified array. + * All remaining elements are shifted to the left.

+ * + *

This method returns a new array with the same elements of the input + * array except those at the specified positions. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.removeAll([1], 0)             = []
+     * ArrayUtils.removeAll([2, 6], 0)          = [6]
+     * ArrayUtils.removeAll([2, 6], 0, 1)       = []
+     * ArrayUtils.removeAll([2, 6, 3], 1, 2)    = [2]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 2)    = [6]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param indices the positions of the elements to be removed + * @return A new array containing the existing elements except those + * at the specified positions. + * @throws IndexOutOfBoundsException if any index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 3.0.1 + */ + public static int[] removeAll(int[] array, int... indices) { + return (int[]) removeAll((Object) array, clone(indices)); + } + + /** + *

Removes occurrences of specified elements, in specified quantities, + * from the specified array. All subsequent elements are shifted left. + * For any element-to-be-removed specified in greater quantities than + * contained in the original array, no change occurs beyond the + * removal of the existing matching items.

+ * + *

This method returns a new array with the same elements of the input + * array except for the earliest-encountered occurrences of the specified + * elements. The component type of the returned array is always the same + * as that of the input array.

+ * + *
+     * ArrayUtils.removeElements(null, 1, 2)      = null
+     * ArrayUtils.removeElements([], 1, 2)        = []
+     * ArrayUtils.removeElements([1], 2, 3)       = [1]
+     * ArrayUtils.removeElements([1, 3], 1, 2)    = [3]
+     * ArrayUtils.removeElements([1, 3, 1], 1)    = [3, 1]
+     * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param values the elements to be removed + * @return A new array containing the existing elements except the + * earliest-encountered occurrences of the specified elements. + * @since 3.0.1 + */ + public static int[] removeElements(int[] array, int... values) { + if (isEmpty(array) || isEmpty(values)) { + return clone(array); + } + HashMap occurrences = new HashMap(values.length); + for (int v : values) { + Integer boxed = Integer.valueOf(v); + MutableInt count = occurrences.get(boxed); + if (count == null) { + occurrences.put(boxed, new MutableInt(1)); + } else { + count.increment(); + } + } + HashSet toRemove = new HashSet(); + for (Map.Entry e : occurrences.entrySet()) { + Integer v = e.getKey(); + int found = 0; + for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) { + found = indexOf(array, v.intValue(), found); + if (found < 0) { + break; + } + toRemove.add(found++); + } + } + return removeAll(array, extractIndices(toRemove)); + } + + /** + *

Removes the elements at the specified positions from the specified array. + * All remaining elements are shifted to the left.

+ * + *

This method returns a new array with the same elements of the input + * array except those at the specified positions. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.removeAll([1], 0)             = []
+     * ArrayUtils.removeAll([2, 6], 0)          = [6]
+     * ArrayUtils.removeAll([2, 6], 0, 1)       = []
+     * ArrayUtils.removeAll([2, 6, 3], 1, 2)    = [2]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 2)    = [6]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param indices the positions of the elements to be removed + * @return A new array containing the existing elements except those + * at the specified positions. + * @throws IndexOutOfBoundsException if any index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 3.0.1 + */ + public static char[] removeAll(char[] array, int... indices) { + return (char[]) removeAll((Object) array, clone(indices)); + } + + /** + *

Removes occurrences of specified elements, in specified quantities, + * from the specified array. All subsequent elements are shifted left. + * For any element-to-be-removed specified in greater quantities than + * contained in the original array, no change occurs beyond the + * removal of the existing matching items.

+ * + *

This method returns a new array with the same elements of the input + * array except for the earliest-encountered occurrences of the specified + * elements. The component type of the returned array is always the same + * as that of the input array.

+ * + *
+     * ArrayUtils.removeElements(null, 1, 2)      = null
+     * ArrayUtils.removeElements([], 1, 2)        = []
+     * ArrayUtils.removeElements([1], 2, 3)       = [1]
+     * ArrayUtils.removeElements([1, 3], 1, 2)    = [3]
+     * ArrayUtils.removeElements([1, 3, 1], 1)    = [3, 1]
+     * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param values the elements to be removed + * @return A new array containing the existing elements except the + * earliest-encountered occurrences of the specified elements. + * @since 3.0.1 + */ + public static char[] removeElements(char[] array, char... values) { + if (isEmpty(array) || isEmpty(values)) { + return clone(array); + } + HashMap occurrences = new HashMap(values.length); + for (char v : values) { + Character boxed = Character.valueOf(v); + MutableInt count = occurrences.get(boxed); + if (count == null) { + occurrences.put(boxed, new MutableInt(1)); + } else { + count.increment(); + } + } + HashSet toRemove = new HashSet(); + for (Map.Entry e : occurrences.entrySet()) { + Character v = e.getKey(); + int found = 0; + for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) { + found = indexOf(array, v.charValue(), found); + if (found < 0) { + break; + } + toRemove.add(found++); + } + } + return removeAll(array, extractIndices(toRemove)); + } + + /** + *

Removes the elements at the specified positions from the specified array. + * All remaining elements are shifted to the left.

+ * + *

This method returns a new array with the same elements of the input + * array except those at the specified positions. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.removeAll([1], 0)             = []
+     * ArrayUtils.removeAll([2, 6], 0)          = [6]
+     * ArrayUtils.removeAll([2, 6], 0, 1)       = []
+     * ArrayUtils.removeAll([2, 6, 3], 1, 2)    = [2]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 2)    = [6]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param indices the positions of the elements to be removed + * @return A new array containing the existing elements except those + * at the specified positions. + * @throws IndexOutOfBoundsException if any index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 3.0.1 + */ + public static long[] removeAll(long[] array, int... indices) { + return (long[]) removeAll((Object) array, clone(indices)); + } + + /** + *

Removes occurrences of specified elements, in specified quantities, + * from the specified array. All subsequent elements are shifted left. + * For any element-to-be-removed specified in greater quantities than + * contained in the original array, no change occurs beyond the + * removal of the existing matching items.

+ * + *

This method returns a new array with the same elements of the input + * array except for the earliest-encountered occurrences of the specified + * elements. The component type of the returned array is always the same + * as that of the input array.

+ * + *
+     * ArrayUtils.removeElements(null, 1, 2)      = null
+     * ArrayUtils.removeElements([], 1, 2)        = []
+     * ArrayUtils.removeElements([1], 2, 3)       = [1]
+     * ArrayUtils.removeElements([1, 3], 1, 2)    = [3]
+     * ArrayUtils.removeElements([1, 3, 1], 1)    = [3, 1]
+     * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param values the elements to be removed + * @return A new array containing the existing elements except the + * earliest-encountered occurrences of the specified elements. + * @since 3.0.1 + */ + public static long[] removeElements(long[] array, long... values) { + if (isEmpty(array) || isEmpty(values)) { + return clone(array); + } + HashMap occurrences = new HashMap(values.length); + for (long v : values) { + Long boxed = Long.valueOf(v); + MutableInt count = occurrences.get(boxed); + if (count == null) { + occurrences.put(boxed, new MutableInt(1)); + } else { + count.increment(); + } + } + HashSet toRemove = new HashSet(); + for (Map.Entry e : occurrences.entrySet()) { + Long v = e.getKey(); + int found = 0; + for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) { + found = indexOf(array, v.longValue(), found); + if (found < 0) { + break; + } + toRemove.add(found++); + } + } + return removeAll(array, extractIndices(toRemove)); + } + + /** + *

Removes the elements at the specified positions from the specified array. + * All remaining elements are shifted to the left.

+ * + *

This method returns a new array with the same elements of the input + * array except those at the specified positions. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.removeAll([1], 0)             = []
+     * ArrayUtils.removeAll([2, 6], 0)          = [6]
+     * ArrayUtils.removeAll([2, 6], 0, 1)       = []
+     * ArrayUtils.removeAll([2, 6, 3], 1, 2)    = [2]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 2)    = [6]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param indices the positions of the elements to be removed + * @return A new array containing the existing elements except those + * at the specified positions. + * @throws IndexOutOfBoundsException if any index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 3.0.1 + */ + public static float[] removeAll(float[] array, int... indices) { + return (float[]) removeAll((Object) array, clone(indices)); + } + + /** + *

Removes occurrences of specified elements, in specified quantities, + * from the specified array. All subsequent elements are shifted left. + * For any element-to-be-removed specified in greater quantities than + * contained in the original array, no change occurs beyond the + * removal of the existing matching items.

+ * + *

This method returns a new array with the same elements of the input + * array except for the earliest-encountered occurrences of the specified + * elements. The component type of the returned array is always the same + * as that of the input array.

+ * + *
+     * ArrayUtils.removeElements(null, 1, 2)      = null
+     * ArrayUtils.removeElements([], 1, 2)        = []
+     * ArrayUtils.removeElements([1], 2, 3)       = [1]
+     * ArrayUtils.removeElements([1, 3], 1, 2)    = [3]
+     * ArrayUtils.removeElements([1, 3, 1], 1)    = [3, 1]
+     * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param values the elements to be removed + * @return A new array containing the existing elements except the + * earliest-encountered occurrences of the specified elements. + * @since 3.0.1 + */ + public static float[] removeElements(float[] array, float... values) { + if (isEmpty(array) || isEmpty(values)) { + return clone(array); + } + HashMap occurrences = new HashMap(values.length); + for (float v : values) { + Float boxed = Float.valueOf(v); + MutableInt count = occurrences.get(boxed); + if (count == null) { + occurrences.put(boxed, new MutableInt(1)); + } else { + count.increment(); + } + } + HashSet toRemove = new HashSet(); + for (Map.Entry e : occurrences.entrySet()) { + Float v = e.getKey(); + int found = 0; + for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) { + found = indexOf(array, v.floatValue(), found); + if (found < 0) { + break; + } + toRemove.add(found++); + } + } + return removeAll(array, extractIndices(toRemove)); + } + + /** + *

Removes the elements at the specified positions from the specified array. + * All remaining elements are shifted to the left.

+ * + *

This method returns a new array with the same elements of the input + * array except those at the specified positions. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.removeAll([1], 0)             = []
+     * ArrayUtils.removeAll([2, 6], 0)          = [6]
+     * ArrayUtils.removeAll([2, 6], 0, 1)       = []
+     * ArrayUtils.removeAll([2, 6, 3], 1, 2)    = [2]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 2)    = [6]
+     * ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param indices the positions of the elements to be removed + * @return A new array containing the existing elements except those + * at the specified positions. + * @throws IndexOutOfBoundsException if any index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 3.0.1 + */ + public static double[] removeAll(double[] array, int... indices) { + return (double[]) removeAll((Object) array, clone(indices)); + } + + /** + *

Removes occurrences of specified elements, in specified quantities, + * from the specified array. All subsequent elements are shifted left. + * For any element-to-be-removed specified in greater quantities than + * contained in the original array, no change occurs beyond the + * removal of the existing matching items.

+ * + *

This method returns a new array with the same elements of the input + * array except for the earliest-encountered occurrences of the specified + * elements. The component type of the returned array is always the same + * as that of the input array.

+ * + *
+     * ArrayUtils.removeElements(null, 1, 2)      = null
+     * ArrayUtils.removeElements([], 1, 2)        = []
+     * ArrayUtils.removeElements([1], 2, 3)       = [1]
+     * ArrayUtils.removeElements([1, 3], 1, 2)    = [3]
+     * ArrayUtils.removeElements([1, 3, 1], 1)    = [3, 1]
+     * ArrayUtils.removeElements([1, 3, 1], 1, 1) = [3]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param values the elements to be removed + * @return A new array containing the existing elements except the + * earliest-encountered occurrences of the specified elements. + * @since 3.0.1 + */ + public static double[] removeElements(double[] array, double... values) { + if (isEmpty(array) || isEmpty(values)) { + return clone(array); + } + HashMap occurrences = new HashMap(values.length); + for (double v : values) { + Double boxed = Double.valueOf(v); + MutableInt count = occurrences.get(boxed); + if (count == null) { + occurrences.put(boxed, new MutableInt(1)); + } else { + count.increment(); + } + } + HashSet toRemove = new HashSet(); + for (Map.Entry e : occurrences.entrySet()) { + Double v = e.getKey(); + int found = 0; + for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) { + found = indexOf(array, v.doubleValue(), found); + if (found < 0) { + break; + } + toRemove.add(found++); + } + } + return removeAll(array, extractIndices(toRemove)); + } + + /** + *

Removes the elements at the specified positions from the specified array. + * All remaining elements are shifted to the left.

+ * + *

This method returns a new array with the same elements of the input + * array except those at the specified positions. The component + * type of the returned array is always the same as that of the input + * array.

+ * + *

If the input array is {@code null}, an IndexOutOfBoundsException + * will be thrown, because in that case no valid index can be specified.

+ * + *
+     * ArrayUtils.removeAll([true, false, true], 0, 2) = [false]
+     * ArrayUtils.removeAll([true, false, true], 1, 2) = [true]
+     * 
+ * + * @param array the array to remove the element from, may not be {@code null} + * @param indices the positions of the elements to be removed + * @return A new array containing the existing elements except those + * at the specified positions. + * @throws IndexOutOfBoundsException if any index is out of range + * (index < 0 || index >= array.length), or if the array is {@code null}. + * @since 3.0.1 + */ + public static boolean[] removeAll(boolean[] array, int... indices) { + return (boolean[]) removeAll((Object) array, clone(indices)); + } + + /** + *

Removes occurrences of specified elements, in specified quantities, + * from the specified array. All subsequent elements are shifted left. + * For any element-to-be-removed specified in greater quantities than + * contained in the original array, no change occurs beyond the + * removal of the existing matching items.

+ * + *

This method returns a new array with the same elements of the input + * array except for the earliest-encountered occurrences of the specified + * elements. The component type of the returned array is always the same + * as that of the input array.

+ * + *
+     * ArrayUtils.removeElements(null, true, false)               = null
+     * ArrayUtils.removeElements([], true, false)                 = []
+     * ArrayUtils.removeElements([true], false, false)            = [true]
+     * ArrayUtils.removeElements([true, false], true, true)       = [false]
+     * ArrayUtils.removeElements([true, false, true], true)       = [false, true]
+     * ArrayUtils.removeElements([true, false, true], true, true) = [false]
+     * 
+ * + * @param array the array to remove the element from, may be {@code null} + * @param values the elements to be removed + * @return A new array containing the existing elements except the + * earliest-encountered occurrences of the specified elements. + * @since 3.0.1 + */ + public static boolean[] removeElements(boolean[] array, boolean... values) { + if (isEmpty(array) || isEmpty(values)) { + return clone(array); + } + HashMap occurrences = new HashMap(values.length); + for (boolean v : values) { + Boolean boxed = Boolean.valueOf(v); + MutableInt count = occurrences.get(boxed); + if (count == null) { + occurrences.put(boxed, new MutableInt(1)); + } else { + count.increment(); + } + } + HashSet toRemove = new HashSet(); + for (Map.Entry e : occurrences.entrySet()) { + Boolean v = e.getKey(); + int found = 0; + for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) { + found = indexOf(array, v.booleanValue(), found); + if (found < 0) { + break; + } + toRemove.add(found++); + } + } + return removeAll(array, extractIndices(toRemove)); + } + + /** + * Removes multiple array elements specified by index. + * @param array source + * @param indices to remove, WILL BE SORTED--so only clones of user-owned arrays! + * @return new array of same type minus elements specified by unique values of {@code indices} + * @since 3.0.1 + */ + private static Object removeAll(Object array, int... indices) { + int length = getLength(array); + int diff = 0; + + if (isNotEmpty(indices)) { + Arrays.sort(indices); + + int i = indices.length; + int prevIndex = length; + while (--i >= 0) { + int index = indices[i]; + if (index < 0 || index >= length) { + throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); + } + if (index >= prevIndex) { + continue; + } + diff++; + prevIndex = index; + } + } + Object result = Array.newInstance(array.getClass().getComponentType(), length - diff); + if (diff < length) { + int end = length; + int dest = length - diff; + for (int i = indices.length - 1; i >= 0; i--) { + int index = indices[i]; + if (end - index > 1) { + int cp = end - index - 1; + dest -= cp; + System.arraycopy(array, index + 1, result, dest, cp); + } + end = index; + } + if (end > 0) { + System.arraycopy(array, 0, result, 0, end); + } + } + return result; + } + + /** + * Extract a set of Integer indices into an int[]. + * @param coll {@code HashSet} of {@code Integer} + * @return int[] + * @since 3.0.1 + */ + private static int[] extractIndices(HashSet coll) { + int[] result = new int[coll.size()]; + int i = 0; + for (Integer index : coll) { + result[i++] = index.intValue(); + } + return result; + } +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/CharSequenceUtils.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/CharSequenceUtils.java new file mode 100644 index 00000000..8e090f57 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/CharSequenceUtils.java @@ -0,0 +1,197 @@ +/* + * 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 {@link java.lang.CharSequence} that are + * {@code null} safe.

+ * + * @see java.lang.CharSequence + * @since 3.0 + * @version $Id: CharSequenceUtils.java 1199894 2011-11-09 17:53:59Z ggregory $ + */ +public class CharSequenceUtils { + + /** + *

{@code CharSequenceUtils} instances should NOT be constructed in + * standard programming.

+ * + *

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

+ */ + public CharSequenceUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Returns a new {@code CharSequence} that is a subsequence of this + * sequence starting with the {@code char} value at the specified index.

+ * + *

This provides the {@code CharSequence} equivalent to {@link String#substring(int)}. + * The length (in {@code char}) of the returned sequence is {@code length() - start}, + * so if {@code start == end} then an empty sequence is returned.

+ * + * @param cs the specified subsequence, null returns null + * @param start the start index, inclusive, valid + * @return a new subsequence, may be null + * @throws IndexOutOfBoundsException if {@code start} is negative or if + * {@code start} is greater than {@code length()} + */ + public static CharSequence subSequence(CharSequence cs, int start) { + return cs == null ? null : cs.subSequence(start, cs.length()); + } + + //----------------------------------------------------------------------- + /** + *

Finds the first index in the {@code CharSequence} that matches the + * specified character.

+ * + * @param cs the {@code CharSequence} to be processed, not null + * @param searchChar the char to be searched for + * @param start the start index, negative starts at the string start + * @return the index where the search char was found, -1 if not found + */ + static int indexOf(CharSequence cs, int searchChar, int start) { + if (cs instanceof String) { + return ((String) cs).indexOf(searchChar, start); + } else { + int sz = cs.length(); + if (start < 0) { + start = 0; + } + for (int i = start; i < sz; i++) { + if (cs.charAt(i) == searchChar) { + return i; + } + } + return -1; + } + } + + /** + * Used by the indexOf(CharSequence methods) as a green implementation of indexOf. + * + * @param cs the {@code CharSequence} to be processed + * @param searchChar the {@code CharSequence} to be searched for + * @param start the start index + * @return the index where the search sequence was found + */ + static int indexOf(CharSequence cs, CharSequence searchChar, int start) { + return cs.toString().indexOf(searchChar.toString(), start); +// if (cs instanceof String && searchChar instanceof String) { +// // TODO: Do we assume searchChar is usually relatively small; +// // If so then calling toString() on it is better than reverting to +// // the green implementation in the else block +// return ((String) cs).indexOf((String) searchChar, start); +// } else { +// // TODO: Implement rather than convert to String +// return cs.toString().indexOf(searchChar.toString(), start); +// } + } + + /** + *

Finds the last index in the {@code CharSequence} that matches the + * specified character.

+ * + * @param cs the {@code CharSequence} to be processed + * @param searchChar the char to be searched for + * @param start the start index, negative returns -1, beyond length starts at end + * @return the index where the search char was found, -1 if not found + */ + static int lastIndexOf(CharSequence cs, int searchChar, int start) { + if (cs instanceof String) { + return ((String) cs).lastIndexOf(searchChar, start); + } else { + int sz = cs.length(); + if (start < 0) { + return -1; + } + if (start >= sz) { + start = sz - 1; + } + for (int i = start; i >= 0; --i) { + if (cs.charAt(i) == searchChar) { + return i; + } + } + return -1; + } + } + + /** + * Used by the lastIndexOf(CharSequence methods) as a green implementation of lastIndexOf + * + * @param cs the {@code CharSequence} to be processed + * @param searchChar the {@code CharSequence} to be searched for + * @param start the start index + * @return the index where the search sequence was found + */ + static int lastIndexOf(CharSequence cs, CharSequence searchChar, int start) { + return cs.toString().lastIndexOf(searchChar.toString(), start); +// if (cs instanceof String && searchChar instanceof String) { +// // TODO: Do we assume searchChar is usually relatively small; +// // If so then calling toString() on it is better than reverting to +// // the green implementation in the else block +// return ((String) cs).lastIndexOf((String) searchChar, start); +// } else { +// // TODO: Implement rather than convert to String +// return cs.toString().lastIndexOf(searchChar.toString(), start); +// } + } + + /** + * Green implementation of toCharArray. + * + * @param cs the {@code CharSequence} to be processed + * @return the resulting char array + */ + static char[] toCharArray(CharSequence cs) { + if (cs instanceof String) { + return ((String) cs).toCharArray(); + } else { + int sz = cs.length(); + char[] array = new char[cs.length()]; + for (int i = 0; i < sz; i++) { + array[i] = cs.charAt(i); + } + return array; + } + } + + /** + * Green implementation of regionMatches. + * + * @param cs the {@code CharSequence} to be processed + * @param ignoreCase whether or not to be case insensitive + * @param thisStart the index to start on the {@code cs} CharSequence + * @param substring the {@code CharSequence} to be looked for + * @param start the index to start on the {@code substring} CharSequence + * @param length character length of the region + * @return whether the region matched + */ + static boolean regionMatches(CharSequence cs, boolean ignoreCase, int thisStart, + CharSequence substring, int start, int length) { + if (cs instanceof String && substring instanceof String) { + return ((String) cs).regionMatches(ignoreCase, thisStart, (String) substring, start, length); + } else { + // TODO: Implement rather than convert to String + return cs.toString().regionMatches(ignoreCase, thisStart, substring.toString(), start, length); + } + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/CharUtils.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/CharUtils.java new file mode 100644 index 00000000..d176a824 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/CharUtils.java @@ -0,0 +1,539 @@ +/* + * 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 char primitives and Character 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.1 + * @version $Id: CharUtils.java 1158279 2011-08-16 14:06:45Z ggregory $ + */ +public class CharUtils { + + private static final String[] CHAR_STRING_ARRAY = new String[128]; + + /** + * {@code \u000a} linefeed LF ('\n'). + * + * @see JLF: Escape Sequences + * for Character and String Literals + * @since 2.2 + */ + public static final char LF = '\n'; + + /** + * {@code \u000d} carriage return CR ('\r'). + * + * @see JLF: Escape Sequences + * for Character and String Literals + * @since 2.2 + */ + public static final char CR = '\r'; + + + static { + for (char c = 0; c < CHAR_STRING_ARRAY.length; c++) { + CHAR_STRING_ARRAY[c] = String.valueOf(c); + } + } + + /** + *

{@code CharUtils} instances should NOT be constructed in standard programming. + * Instead, the class should be used as {@code CharUtils.toString('c');}.

+ * + *

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

+ */ + public CharUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Converts the character to a Character.

+ * + *

For ASCII 7 bit characters, this uses a cache that will return the + * same Character object each time.

+ * + *
+     *   CharUtils.toCharacterObject(' ')  = ' '
+     *   CharUtils.toCharacterObject('A')  = 'A'
+     * 
+ * + * @deprecated Java 5 introduced {@link Character#valueOf(char)} which caches chars 0 through 127. + * @param ch the character to convert + * @return a Character of the specified character + */ + @Deprecated + public static Character toCharacterObject(char ch) { + return Character.valueOf(ch); + } + + /** + *

Converts the String to a Character using the first character, returning + * null for empty Strings.

+ * + *

For ASCII 7 bit characters, this uses a cache that will return the + * same Character object each time.

+ * + *
+     *   CharUtils.toCharacterObject(null) = null
+     *   CharUtils.toCharacterObject("")   = null
+     *   CharUtils.toCharacterObject("A")  = 'A'
+     *   CharUtils.toCharacterObject("BA") = 'B'
+     * 
+ * + * @param str the character to convert + * @return the Character value of the first letter of the String + */ + public static Character toCharacterObject(String str) { + if (StringUtils.isEmpty(str)) { + return null; + } + return Character.valueOf(str.charAt(0)); + } + + //----------------------------------------------------------------------- + /** + *

Converts the Character to a char throwing an exception for {@code null}.

+ * + *
+     *   CharUtils.toChar(' ')  = ' '
+     *   CharUtils.toChar('A')  = 'A'
+     *   CharUtils.toChar(null) throws IllegalArgumentException
+     * 
+ * + * @param ch the character to convert + * @return the char value of the Character + * @throws IllegalArgumentException if the Character is null + */ + public static char toChar(Character ch) { + if (ch == null) { + throw new IllegalArgumentException("The Character must not be null"); + } + return ch.charValue(); + } + + /** + *

Converts the Character to a char handling {@code null}.

+ * + *
+     *   CharUtils.toChar(null, 'X') = 'X'
+     *   CharUtils.toChar(' ', 'X')  = ' '
+     *   CharUtils.toChar('A', 'X')  = 'A'
+     * 
+ * + * @param ch the character to convert + * @param defaultValue the value to use if the Character is null + * @return the char value of the Character or the default if null + */ + public static char toChar(Character ch, char defaultValue) { + if (ch == null) { + return defaultValue; + } + return ch.charValue(); + } + + //----------------------------------------------------------------------- + /** + *

Converts the String to a char using the first character, throwing + * an exception on empty Strings.

+ * + *
+     *   CharUtils.toChar("A")  = 'A'
+     *   CharUtils.toChar("BA") = 'B'
+     *   CharUtils.toChar(null) throws IllegalArgumentException
+     *   CharUtils.toChar("")   throws IllegalArgumentException
+     * 
+ * + * @param str the character to convert + * @return the char value of the first letter of the String + * @throws IllegalArgumentException if the String is empty + */ + public static char toChar(String str) { + if (StringUtils.isEmpty(str)) { + throw new IllegalArgumentException("The String must not be empty"); + } + return str.charAt(0); + } + + /** + *

Converts the String to a char using the first character, defaulting + * the value on empty Strings.

+ * + *
+     *   CharUtils.toChar(null, 'X') = 'X'
+     *   CharUtils.toChar("", 'X')   = 'X'
+     *   CharUtils.toChar("A", 'X')  = 'A'
+     *   CharUtils.toChar("BA", 'X') = 'B'
+     * 
+ * + * @param str the character to convert + * @param defaultValue the value to use if the Character is null + * @return the char value of the first letter of the String or the default if null + */ + public static char toChar(String str, char defaultValue) { + if (StringUtils.isEmpty(str)) { + return defaultValue; + } + return str.charAt(0); + } + + //----------------------------------------------------------------------- + /** + *

Converts the character to the Integer it represents, throwing an + * exception if the character is not numeric.

+ * + *

This method coverts the char '1' to the int 1 and so on.

+ * + *
+     *   CharUtils.toIntValue('3')  = 3
+     *   CharUtils.toIntValue('A')  throws IllegalArgumentException
+     * 
+ * + * @param ch the character to convert + * @return the int value of the character + * @throws IllegalArgumentException if the character is not ASCII numeric + */ + public static int toIntValue(char ch) { + if (isAsciiNumeric(ch) == false) { + throw new IllegalArgumentException("The character " + ch + " is not in the range '0' - '9'"); + } + return ch - 48; + } + + /** + *

Converts the character to the Integer it represents, throwing an + * exception if the character is not numeric.

+ * + *

This method coverts the char '1' to the int 1 and so on.

+ * + *
+     *   CharUtils.toIntValue('3', -1)  = 3
+     *   CharUtils.toIntValue('A', -1)  = -1
+     * 
+ * + * @param ch the character to convert + * @param defaultValue the default value to use if the character is not numeric + * @return the int value of the character + */ + public static int toIntValue(char ch, int defaultValue) { + if (isAsciiNumeric(ch) == false) { + return defaultValue; + } + return ch - 48; + } + + /** + *

Converts the character to the Integer it represents, throwing an + * exception if the character is not numeric.

+ * + *

This method coverts the char '1' to the int 1 and so on.

+ * + *
+     *   CharUtils.toIntValue('3')  = 3
+     *   CharUtils.toIntValue(null) throws IllegalArgumentException
+     *   CharUtils.toIntValue('A')  throws IllegalArgumentException
+     * 
+ * + * @param ch the character to convert, not null + * @return the int value of the character + * @throws IllegalArgumentException if the Character is not ASCII numeric or is null + */ + public static int toIntValue(Character ch) { + if (ch == null) { + throw new IllegalArgumentException("The character must not be null"); + } + return toIntValue(ch.charValue()); + } + + /** + *

Converts the character to the Integer it represents, throwing an + * exception if the character is not numeric.

+ * + *

This method coverts the char '1' to the int 1 and so on.

+ * + *
+     *   CharUtils.toIntValue(null, -1) = -1
+     *   CharUtils.toIntValue('3', -1)  = 3
+     *   CharUtils.toIntValue('A', -1)  = -1
+     * 
+ * + * @param ch the character to convert + * @param defaultValue the default value to use if the character is not numeric + * @return the int value of the character + */ + public static int toIntValue(Character ch, int defaultValue) { + if (ch == null) { + return defaultValue; + } + return toIntValue(ch.charValue(), defaultValue); + } + + //----------------------------------------------------------------------- + /** + *

Converts the character to a String that contains the one character.

+ * + *

For ASCII 7 bit characters, this uses a cache that will return the + * same String object each time.

+ * + *
+     *   CharUtils.toString(' ')  = " "
+     *   CharUtils.toString('A')  = "A"
+     * 
+ * + * @param ch the character to convert + * @return a String containing the one specified character + */ + public static String toString(char ch) { + if (ch < 128) { + return CHAR_STRING_ARRAY[ch]; + } + return new String(new char[] {ch}); + } + + /** + *

Converts the character to a String that contains the one character.

+ * + *

For ASCII 7 bit characters, this uses a cache that will return the + * same String object each time.

+ * + *

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

+ * + *
+     *   CharUtils.toString(null) = null
+     *   CharUtils.toString(' ')  = " "
+     *   CharUtils.toString('A')  = "A"
+     * 
+ * + * @param ch the character to convert + * @return a String containing the one specified character + */ + public static String toString(Character ch) { + if (ch == null) { + return null; + } + return toString(ch.charValue()); + } + + //-------------------------------------------------------------------------- + /** + *

Converts the string to the Unicode format '\u0020'.

+ * + *

This format is the Java source code format.

+ * + *
+     *   CharUtils.unicodeEscaped(' ') = "\u0020"
+     *   CharUtils.unicodeEscaped('A') = "\u0041"
+     * 
+ * + * @param ch the character to convert + * @return the escaped Unicode string + */ + public static String unicodeEscaped(char ch) { + if (ch < 0x10) { + return "\\u000" + Integer.toHexString(ch); + } else if (ch < 0x100) { + return "\\u00" + Integer.toHexString(ch); + } else if (ch < 0x1000) { + return "\\u0" + Integer.toHexString(ch); + } + return "\\u" + Integer.toHexString(ch); + } + + /** + *

Converts the string to the Unicode format '\u0020'.

+ * + *

This format is the Java source code format.

+ * + *

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

+ * + *
+     *   CharUtils.unicodeEscaped(null) = null
+     *   CharUtils.unicodeEscaped(' ')  = "\u0020"
+     *   CharUtils.unicodeEscaped('A')  = "\u0041"
+     * 
+ * + * @param ch the character to convert, may be null + * @return the escaped Unicode string, null if null input + */ + public static String unicodeEscaped(Character ch) { + if (ch == null) { + return null; + } + return unicodeEscaped(ch.charValue()); + } + + //-------------------------------------------------------------------------- + /** + *

Checks whether the character is ASCII 7 bit.

+ * + *
+     *   CharUtils.isAscii('a')  = true
+     *   CharUtils.isAscii('A')  = true
+     *   CharUtils.isAscii('3')  = true
+     *   CharUtils.isAscii('-')  = true
+     *   CharUtils.isAscii('\n') = true
+     *   CharUtils.isAscii('©') = false
+     * 
+ * + * @param ch the character to check + * @return true if less than 128 + */ + public static boolean isAscii(char ch) { + return ch < 128; + } + + /** + *

Checks whether the character is ASCII 7 bit printable.

+ * + *
+     *   CharUtils.isAsciiPrintable('a')  = true
+     *   CharUtils.isAsciiPrintable('A')  = true
+     *   CharUtils.isAsciiPrintable('3')  = true
+     *   CharUtils.isAsciiPrintable('-')  = true
+     *   CharUtils.isAsciiPrintable('\n') = false
+     *   CharUtils.isAsciiPrintable('©') = false
+     * 
+ * + * @param ch the character to check + * @return true if between 32 and 126 inclusive + */ + public static boolean isAsciiPrintable(char ch) { + return ch >= 32 && ch < 127; + } + + /** + *

Checks whether the character is ASCII 7 bit control.

+ * + *
+     *   CharUtils.isAsciiControl('a')  = false
+     *   CharUtils.isAsciiControl('A')  = false
+     *   CharUtils.isAsciiControl('3')  = false
+     *   CharUtils.isAsciiControl('-')  = false
+     *   CharUtils.isAsciiControl('\n') = true
+     *   CharUtils.isAsciiControl('©') = false
+     * 
+ * + * @param ch the character to check + * @return true if less than 32 or equals 127 + */ + public static boolean isAsciiControl(char ch) { + return ch < 32 || ch == 127; + } + + /** + *

Checks whether the character is ASCII 7 bit alphabetic.

+ * + *
+     *   CharUtils.isAsciiAlpha('a')  = true
+     *   CharUtils.isAsciiAlpha('A')  = true
+     *   CharUtils.isAsciiAlpha('3')  = false
+     *   CharUtils.isAsciiAlpha('-')  = false
+     *   CharUtils.isAsciiAlpha('\n') = false
+     *   CharUtils.isAsciiAlpha('©') = false
+     * 
+ * + * @param ch the character to check + * @return true if between 65 and 90 or 97 and 122 inclusive + */ + public static boolean isAsciiAlpha(char ch) { + return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); + } + + /** + *

Checks whether the character is ASCII 7 bit alphabetic upper case.

+ * + *
+     *   CharUtils.isAsciiAlphaUpper('a')  = false
+     *   CharUtils.isAsciiAlphaUpper('A')  = true
+     *   CharUtils.isAsciiAlphaUpper('3')  = false
+     *   CharUtils.isAsciiAlphaUpper('-')  = false
+     *   CharUtils.isAsciiAlphaUpper('\n') = false
+     *   CharUtils.isAsciiAlphaUpper('©') = false
+     * 
+ * + * @param ch the character to check + * @return true if between 65 and 90 inclusive + */ + public static boolean isAsciiAlphaUpper(char ch) { + return ch >= 'A' && ch <= 'Z'; + } + + /** + *

Checks whether the character is ASCII 7 bit alphabetic lower case.

+ * + *
+     *   CharUtils.isAsciiAlphaLower('a')  = true
+     *   CharUtils.isAsciiAlphaLower('A')  = false
+     *   CharUtils.isAsciiAlphaLower('3')  = false
+     *   CharUtils.isAsciiAlphaLower('-')  = false
+     *   CharUtils.isAsciiAlphaLower('\n') = false
+     *   CharUtils.isAsciiAlphaLower('©') = false
+     * 
+ * + * @param ch the character to check + * @return true if between 97 and 122 inclusive + */ + public static boolean isAsciiAlphaLower(char ch) { + return ch >= 'a' && ch <= 'z'; + } + + /** + *

Checks whether the character is ASCII 7 bit numeric.

+ * + *
+     *   CharUtils.isAsciiNumeric('a')  = false
+     *   CharUtils.isAsciiNumeric('A')  = false
+     *   CharUtils.isAsciiNumeric('3')  = true
+     *   CharUtils.isAsciiNumeric('-')  = false
+     *   CharUtils.isAsciiNumeric('\n') = false
+     *   CharUtils.isAsciiNumeric('©') = false
+     * 
+ * + * @param ch the character to check + * @return true if between 48 and 57 inclusive + */ + public static boolean isAsciiNumeric(char ch) { + return ch >= '0' && ch <= '9'; + } + + /** + *

Checks whether the character is ASCII 7 bit numeric.

+ * + *
+     *   CharUtils.isAsciiAlphanumeric('a')  = true
+     *   CharUtils.isAsciiAlphanumeric('A')  = true
+     *   CharUtils.isAsciiAlphanumeric('3')  = true
+     *   CharUtils.isAsciiAlphanumeric('-')  = false
+     *   CharUtils.isAsciiAlphanumeric('\n') = false
+     *   CharUtils.isAsciiAlphanumeric('©') = false
+     * 
+ * + * @param ch the character to check + * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive + */ + public static boolean isAsciiAlphanumeric(char ch) { + return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'); + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/ClassUtils.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/ClassUtils.java new file mode 100644 index 00000000..183d1d11 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/ClassUtils.java @@ -0,0 +1,1135 @@ +/* + * 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.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; + + +/** + *

Operates on classes without using reflection.

+ * + *

This class handles invalid {@code null} inputs as best it can. + * Each method documents its behaviour in more detail.

+ * + *

The notion of a {@code canonical name} includes the human + * readable name for the type, for example {@code int[]}. The + * non-canonical method variants work with the JVM names, such as + * {@code [I}.

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

The package separator character: '.' == {@value}.

+ */ + public static final char PACKAGE_SEPARATOR_CHAR = '.'; + + /** + *

The package separator String: {@code "."}.

+ */ + public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR); + + /** + *

The inner class separator character: '$' == {@value}.

+ */ + public static final char INNER_CLASS_SEPARATOR_CHAR = '$'; + + /** + *

The inner class separator String: {@code "$"}.

+ */ + public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR); + + /** + * Maps primitive {@code Class}es to their corresponding wrapper {@code Class}. + */ + private static final Map, Class> primitiveWrapperMap = new HashMap, Class>(); + static { + primitiveWrapperMap.put(Boolean.TYPE, Boolean.class); + primitiveWrapperMap.put(Byte.TYPE, Byte.class); + primitiveWrapperMap.put(Character.TYPE, Character.class); + primitiveWrapperMap.put(Short.TYPE, Short.class); + primitiveWrapperMap.put(Integer.TYPE, Integer.class); + primitiveWrapperMap.put(Long.TYPE, Long.class); + primitiveWrapperMap.put(Double.TYPE, Double.class); + primitiveWrapperMap.put(Float.TYPE, Float.class); + primitiveWrapperMap.put(Void.TYPE, Void.TYPE); + } + + /** + * Maps wrapper {@code Class}es to their corresponding primitive types. + */ + private static final Map, Class> wrapperPrimitiveMap = new HashMap, Class>(); + static { + for (Class primitiveClass : primitiveWrapperMap.keySet()) { + Class wrapperClass = primitiveWrapperMap.get(primitiveClass); + if (!primitiveClass.equals(wrapperClass)) { + wrapperPrimitiveMap.put(wrapperClass, primitiveClass); + } + } + } + + /** + * Maps a primitive class name to its corresponding abbreviation used in array class names. + */ + private static final Map abbreviationMap = new HashMap(); + + /** + * Maps an abbreviation used in array class names to corresponding primitive class name. + */ + private static final Map reverseAbbreviationMap = new HashMap(); + + /** + * Add primitive type abbreviation to maps of abbreviations. + * + * @param primitive Canonical name of primitive type + * @param abbreviation Corresponding abbreviation of primitive type + */ + private static void addAbbreviation(String primitive, String abbreviation) { + abbreviationMap.put(primitive, abbreviation); + reverseAbbreviationMap.put(abbreviation, primitive); + } + + /** + * Feed abbreviation maps + */ + static { + addAbbreviation("int", "I"); + addAbbreviation("boolean", "Z"); + addAbbreviation("float", "F"); + addAbbreviation("long", "J"); + addAbbreviation("short", "S"); + addAbbreviation("byte", "B"); + addAbbreviation("double", "D"); + addAbbreviation("char", "C"); + } + + /** + *

ClassUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as + * {@code ClassUtils.getShortClassName(cls)}.

+ * + *

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

+ */ + public ClassUtils() { + super(); + } + + // Short class name + // ---------------------------------------------------------------------- + /** + *

Gets the class name minus the package name for an {@code Object}.

+ * + * @param object the class to get the short name for, may be null + * @param valueIfNull the value to return if null + * @return the class name of the object without the package name, or the null value + */ + public static String getShortClassName(Object object, String valueIfNull) { + if (object == null) { + return valueIfNull; + } + return getShortClassName(object.getClass()); + } + + /** + *

Gets the class name minus the package name from a {@code Class}.

+ * + *

Consider using the Java 5 API {@link Class#getSimpleName()} instead. + * The one known difference is that this code will return {@code "Map.Entry"} while + * the {@code java.lang.Class} variant will simply return {@code "Entry"}.

+ * + * @param cls the class to get the short name for. + * @return the class name without the package name or an empty string + */ + public static String getShortClassName(Class cls) { + if (cls == null) { + return StringUtils.EMPTY; + } + return getShortClassName(cls.getName()); + } + + /** + *

Gets the class name minus the package name from a String.

+ * + *

The string passed in is assumed to be a class name - it is not checked.

+ + *

Note that this method differs from Class.getSimpleName() in that this will + * return {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply + * return {@code "Entry"}.

+ * + * @param className the className to get the short name for + * @return the class name of the class without the package name or an empty string + */ + public static String getShortClassName(String className) { + if (className == null) { + return StringUtils.EMPTY; + } + if (className.length() == 0) { + return StringUtils.EMPTY; + } + + StringBuilder arrayPrefix = new StringBuilder(); + + // Handle array encoding + if (className.startsWith("[")) { + while (className.charAt(0) == '[') { + className = className.substring(1); + arrayPrefix.append("[]"); + } + // Strip Object type encoding + if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') { + className = className.substring(1, className.length() - 1); + } + } + + if (reverseAbbreviationMap.containsKey(className)) { + className = reverseAbbreviationMap.get(className); + } + + int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); + int innerIdx = className.indexOf( + INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1); + String out = className.substring(lastDotIdx + 1); + if (innerIdx != -1) { + out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR); + } + return out + arrayPrefix; + } + + /** + *

Null-safe version of aClass.getSimpleName()

+ * + * @param cls the class for which to get the simple name. + * @return the simple class name. + * @since 3.0 + * @see Class#getSimpleName() + */ + public static String getSimpleName(Class cls) { + if (cls == null) { + return StringUtils.EMPTY; + } + return cls.getSimpleName(); + } + + /** + *

Null-safe version of aClass.getSimpleName()

+ * + * @param object the object for which to get the simple class name. + * @param valueIfNull the value to return if object is null + * @return the simple class name. + * @since 3.0 + * @see Class#getSimpleName() + */ + public static String getSimpleName(Object object, String valueIfNull) { + if (object == null) { + return valueIfNull; + } + return getSimpleName(object.getClass()); + } + + // Package name + // ---------------------------------------------------------------------- + /** + *

Gets the package name of an {@code Object}.

+ * + * @param object the class to get the package name for, may be null + * @param valueIfNull the value to return if null + * @return the package name of the object, or the null value + */ + public static String getPackageName(Object object, String valueIfNull) { + if (object == null) { + return valueIfNull; + } + return getPackageName(object.getClass()); + } + + /** + *

Gets the package name of a {@code Class}.

+ * + * @param cls the class to get the package name for, may be {@code null}. + * @return the package name or an empty string + */ + public static String getPackageName(Class cls) { + if (cls == null) { + return StringUtils.EMPTY; + } + return getPackageName(cls.getName()); + } + + /** + *

Gets the package name from a {@code String}.

+ * + *

The string passed in is assumed to be a class name - it is not checked.

+ *

If the class is unpackaged, return an empty string.

+ * + * @param className the className to get the package name for, may be {@code null} + * @return the package name or an empty string + */ + public static String getPackageName(String className) { + if (className == null || className.length() == 0) { + return StringUtils.EMPTY; + } + + // Strip array encoding + while (className.charAt(0) == '[') { + className = className.substring(1); + } + // Strip Object type encoding + if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') { + className = className.substring(1); + } + + int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); + if (i == -1) { + return StringUtils.EMPTY; + } + return className.substring(0, i); + } + + // Superclasses/Superinterfaces + // ---------------------------------------------------------------------- + /** + *

Gets a {@code List} of superclasses for the given class.

+ * + * @param cls the class to look up, may be {@code null} + * @return the {@code List} of superclasses in order going up from this one + * {@code null} if null input + */ + public static List> getAllSuperclasses(Class cls) { + if (cls == null) { + return null; + } + List> classes = new ArrayList>(); + Class superclass = cls.getSuperclass(); + while (superclass != null) { + classes.add(superclass); + superclass = superclass.getSuperclass(); + } + return classes; + } + + /** + *

Gets a {@code List} of all interfaces implemented by the given + * class and its superclasses.

+ * + *

The order is determined by looking through each interface in turn as + * declared in the source file and following its hierarchy up. Then each + * superclass is considered in the same way. Later duplicates are ignored, + * so the order is maintained.

+ * + * @param cls the class to look up, may be {@code null} + * @return the {@code List} of interfaces in order, + * {@code null} if null input + */ + public static List> getAllInterfaces(Class cls) { + if (cls == null) { + return null; + } + + LinkedHashSet> interfacesFound = new LinkedHashSet>(); + getAllInterfaces(cls, interfacesFound); + + return new ArrayList>(interfacesFound); + } + + /** + * Get the interfaces for the specified class. + * + * @param cls the class to look up, may be {@code null} + * @param interfacesFound the {@code Set} of interfaces for the class + */ + private static void getAllInterfaces(Class cls, HashSet> interfacesFound) { + while (cls != null) { + Class[] interfaces = cls.getInterfaces(); + + for (Class i : interfaces) { + if (interfacesFound.add(i)) { + getAllInterfaces(i, interfacesFound); + } + } + + cls = cls.getSuperclass(); + } + } + + // Convert list + // ---------------------------------------------------------------------- + /** + *

Given a {@code List} of class names, this method converts them into classes.

+ * + *

A new {@code List} is returned. If the class name cannot be found, {@code null} + * is stored in the {@code List}. If the class name in the {@code List} is + * {@code null}, {@code null} is stored in the output {@code List}.

+ * + * @param classNames the classNames to change + * @return a {@code List} of Class objects corresponding to the class names, + * {@code null} if null input + * @throws ClassCastException if classNames contains a non String entry + */ + public static List> convertClassNamesToClasses(List classNames) { + if (classNames == null) { + return null; + } + List> classes = new ArrayList>(classNames.size()); + for (String className : classNames) { + try { + classes.add(Class.forName(className)); + } catch (Exception ex) { + classes.add(null); + } + } + return classes; + } + + /** + *

Given a {@code List} of {@code Class} objects, this method converts + * them into class names.

+ * + *

A new {@code List} is returned. {@code null} objects will be copied into + * the returned list as {@code null}.

+ * + * @param classes the classes to change + * @return a {@code List} of class names corresponding to the Class objects, + * {@code null} if null input + * @throws ClassCastException if {@code classes} contains a non-{@code Class} entry + */ + public static List convertClassesToClassNames(List> classes) { + if (classes == null) { + return null; + } + List classNames = new ArrayList(classes.size()); + for (Class cls : classes) { + if (cls == null) { + classNames.add(null); + } else { + classNames.add(cls.getName()); + } + } + return classNames; + } + + // Is assignable + // ---------------------------------------------------------------------- + /** + *

Checks if an array of Classes can be assigned to another array of Classes.

+ * + *

This method calls {@link #isAssignable(Class, Class) isAssignable} for each + * Class pair in the input arrays. It can be used to check if a set of arguments + * (the first parameter) are suitably compatible with a set of method parameter types + * (the second parameter).

+ * + *

Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this + * method takes into account widenings of primitive classes and + * {@code null}s.

+ * + *

Primitive widenings allow an int to be assigned to a {@code long}, + * {@code float} or {@code double}. This method returns the correct + * result for these cases.

+ * + *

{@code Null} may be assigned to any reference type. This method will + * return {@code true} if {@code null} is passed in and the toClass is + * non-primitive.

+ * + *

Specifically, this method tests whether the type represented by the + * specified {@code Class} parameter can be converted to the type + * represented by this {@code Class} object via an identity conversion + * widening primitive or widening reference conversion. See + * The Java Language Specification, + * sections 5.1.1, 5.1.2 and 5.1.4 for details.

+ * + *

Since Lang 3.0, this method will default behavior for + * calculating assignability between primitive and wrapper types corresponding + * to the running Java version; i.e. autoboxing will be the default + * behavior in VMs running Java versions >= 1.5.

+ * + * @param classArray the array of Classes to check, may be {@code null} + * @param toClassArray the array of Classes to try to assign into, may be {@code null} + * @return {@code true} if assignment possible + */ + public static boolean isAssignable(Class[] classArray, Class... toClassArray) { + return isAssignable(classArray, toClassArray, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5)); + } + + /** + *

Checks if an array of Classes can be assigned to another array of Classes.

+ * + *

This method calls {@link #isAssignable(Class, Class) isAssignable} for each + * Class pair in the input arrays. It can be used to check if a set of arguments + * (the first parameter) are suitably compatible with a set of method parameter types + * (the second parameter).

+ * + *

Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this + * method takes into account widenings of primitive classes and + * {@code null}s.

+ * + *

Primitive widenings allow an int to be assigned to a {@code long}, + * {@code float} or {@code double}. This method returns the correct + * result for these cases.

+ * + *

{@code Null} may be assigned to any reference type. This method will + * return {@code true} if {@code null} is passed in and the toClass is + * non-primitive.

+ * + *

Specifically, this method tests whether the type represented by the + * specified {@code Class} parameter can be converted to the type + * represented by this {@code Class} object via an identity conversion + * widening primitive or widening reference conversion. See + * The Java Language Specification, + * sections 5.1.1, 5.1.2 and 5.1.4 for details.

+ * + * @param classArray the array of Classes to check, may be {@code null} + * @param toClassArray the array of Classes to try to assign into, may be {@code null} + * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers + * @return {@code true} if assignment possible + */ + public static boolean isAssignable(Class[] classArray, Class[] toClassArray, boolean autoboxing) { + if (ArrayUtils.isSameLength(classArray, toClassArray) == false) { + return false; + } + if (classArray == null) { + classArray = ArrayUtils.EMPTY_CLASS_ARRAY; + } + if (toClassArray == null) { + toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY; + } + for (int i = 0; i < classArray.length; i++) { + if (isAssignable(classArray[i], toClassArray[i], autoboxing) == false) { + return false; + } + } + return true; + } + + /** + * Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, + * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}). + * + * @param type + * The class to query or null. + * @return true if the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, + * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}). + * @since 3.1 + */ + public static boolean isPrimitiveOrWrapper(Class type) { + if (type == null) { + return false; + } + return type.isPrimitive() || isPrimitiveWrapper(type); + } + + /** + * Returns whether the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short}, + * {@link Integer}, {@link Long}, {@link Double}, {@link Float}). + * + * @param type + * The class to query or null. + * @return true if the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short}, + * {@link Integer}, {@link Long}, {@link Double}, {@link Float}). + * @since 3.1 + */ + public static boolean isPrimitiveWrapper(Class type) { + return wrapperPrimitiveMap.containsKey(type); + } + + /** + *

Checks if one {@code Class} can be assigned to a variable of + * another {@code Class}.

+ * + *

Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, + * this method takes into account widenings of primitive classes and + * {@code null}s.

+ * + *

Primitive widenings allow an int to be assigned to a long, float or + * double. This method returns the correct result for these cases.

+ * + *

{@code Null} may be assigned to any reference type. This method + * will return {@code true} if {@code null} is passed in and the + * toClass is non-primitive.

+ * + *

Specifically, this method tests whether the type represented by the + * specified {@code Class} parameter can be converted to the type + * represented by this {@code Class} object via an identity conversion + * widening primitive or widening reference conversion. See + * The Java Language Specification, + * sections 5.1.1, 5.1.2 and 5.1.4 for details.

+ * + *

Since Lang 3.0, this method will default behavior for + * calculating assignability between primitive and wrapper types corresponding + * to the running Java version; i.e. autoboxing will be the default + * behavior in VMs running Java versions >= 1.5.

+ * + * @param cls the Class to check, may be null + * @param toClass the Class to try to assign into, returns false if null + * @return {@code true} if assignment possible + */ + public static boolean isAssignable(Class cls, Class toClass) { + return isAssignable(cls, toClass, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5)); + } + + /** + *

Checks if one {@code Class} can be assigned to a variable of + * another {@code Class}.

+ * + *

Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, + * this method takes into account widenings of primitive classes and + * {@code null}s.

+ * + *

Primitive widenings allow an int to be assigned to a long, float or + * double. This method returns the correct result for these cases.

+ * + *

{@code Null} may be assigned to any reference type. This method + * will return {@code true} if {@code null} is passed in and the + * toClass is non-primitive.

+ * + *

Specifically, this method tests whether the type represented by the + * specified {@code Class} parameter can be converted to the type + * represented by this {@code Class} object via an identity conversion + * widening primitive or widening reference conversion. See + * The Java Language Specification, + * sections 5.1.1, 5.1.2 and 5.1.4 for details.

+ * + * @param cls the Class to check, may be null + * @param toClass the Class to try to assign into, returns false if null + * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers + * @return {@code true} if assignment possible + */ + public static boolean isAssignable(Class cls, Class toClass, boolean autoboxing) { + if (toClass == null) { + return false; + } + // have to check for null, as isAssignableFrom doesn't + if (cls == null) { + return !toClass.isPrimitive(); + } + //autoboxing: + if (autoboxing) { + if (cls.isPrimitive() && !toClass.isPrimitive()) { + cls = primitiveToWrapper(cls); + if (cls == null) { + return false; + } + } + if (toClass.isPrimitive() && !cls.isPrimitive()) { + cls = wrapperToPrimitive(cls); + if (cls == null) { + return false; + } + } + } + if (cls.equals(toClass)) { + return true; + } + if (cls.isPrimitive()) { + if (toClass.isPrimitive() == false) { + return false; + } + if (Integer.TYPE.equals(cls)) { + return Long.TYPE.equals(toClass) + || Float.TYPE.equals(toClass) + || Double.TYPE.equals(toClass); + } + if (Long.TYPE.equals(cls)) { + return Float.TYPE.equals(toClass) + || Double.TYPE.equals(toClass); + } + if (Boolean.TYPE.equals(cls)) { + return false; + } + if (Double.TYPE.equals(cls)) { + return false; + } + if (Float.TYPE.equals(cls)) { + return Double.TYPE.equals(toClass); + } + if (Character.TYPE.equals(cls)) { + return Integer.TYPE.equals(toClass) + || Long.TYPE.equals(toClass) + || Float.TYPE.equals(toClass) + || Double.TYPE.equals(toClass); + } + if (Short.TYPE.equals(cls)) { + return Integer.TYPE.equals(toClass) + || Long.TYPE.equals(toClass) + || Float.TYPE.equals(toClass) + || Double.TYPE.equals(toClass); + } + if (Byte.TYPE.equals(cls)) { + return Short.TYPE.equals(toClass) + || Integer.TYPE.equals(toClass) + || Long.TYPE.equals(toClass) + || Float.TYPE.equals(toClass) + || Double.TYPE.equals(toClass); + } + // should never get here + return false; + } + return toClass.isAssignableFrom(cls); + } + + /** + *

Converts the specified primitive Class object to its corresponding + * wrapper Class object.

+ * + *

NOTE: From v2.2, this method handles {@code Void.TYPE}, + * returning {@code Void.TYPE}.

+ * + * @param cls the class to convert, may be null + * @return the wrapper class for {@code cls} or {@code cls} if + * {@code cls} is not a primitive. {@code null} if null input. + * @since 2.1 + */ + public static Class primitiveToWrapper(Class cls) { + Class convertedClass = cls; + if (cls != null && cls.isPrimitive()) { + convertedClass = primitiveWrapperMap.get(cls); + } + return convertedClass; + } + + /** + *

Converts the specified array of primitive Class objects to an array of + * its corresponding wrapper Class objects.

+ * + * @param classes the class array to convert, may be null or empty + * @return an array which contains for each given class, the wrapper class or + * the original class if class is not a primitive. {@code null} if null input. + * Empty array if an empty array passed in. + * @since 2.1 + */ + public static Class[] primitivesToWrappers(Class... classes) { + if (classes == null) { + return null; + } + + if (classes.length == 0) { + return classes; + } + + Class[] convertedClasses = new Class[classes.length]; + for (int i = 0; i < classes.length; i++) { + convertedClasses[i] = primitiveToWrapper(classes[i]); + } + return convertedClasses; + } + + /** + *

Converts the specified wrapper class to its corresponding primitive + * class.

+ * + *

This method is the counter part of {@code primitiveToWrapper()}. + * If the passed in class is a wrapper class for a primitive type, this + * primitive type will be returned (e.g. {@code Integer.TYPE} for + * {@code Integer.class}). For other classes, or if the parameter is + * null, the return value is null.

+ * + * @param cls the class to convert, may be null + * @return the corresponding primitive type if {@code cls} is a + * wrapper class, null otherwise + * @see #primitiveToWrapper(Class) + * @since 2.4 + */ + public static Class wrapperToPrimitive(Class cls) { + return wrapperPrimitiveMap.get(cls); + } + + /** + *

Converts the specified array of wrapper Class objects to an array of + * its corresponding primitive Class objects.

+ * + *

This method invokes {@code wrapperToPrimitive()} for each element + * of the passed in array.

+ * + * @param classes the class array to convert, may be null or empty + * @return an array which contains for each given class, the primitive class or + * null if the original class is not a wrapper class. {@code null} if null input. + * Empty array if an empty array passed in. + * @see #wrapperToPrimitive(Class) + * @since 2.4 + */ + public static Class[] wrappersToPrimitives(Class... classes) { + if (classes == null) { + return null; + } + + if (classes.length == 0) { + return classes; + } + + Class[] convertedClasses = new Class[classes.length]; + for (int i = 0; i < classes.length; i++) { + convertedClasses[i] = wrapperToPrimitive(classes[i]); + } + return convertedClasses; + } + + // Inner class + // ---------------------------------------------------------------------- + /** + *

Is the specified class an inner class or static nested class.

+ * + * @param cls the class to check, may be null + * @return {@code true} if the class is an inner or static nested class, + * false if not or {@code null} + */ + public static boolean isInnerClass(Class cls) { + return cls != null && cls.getEnclosingClass() != null; + } + + // Class loading + // ---------------------------------------------------------------------- + /** + * Returns the class represented by {@code className} using the + * {@code classLoader}. This implementation supports the syntaxes + * "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}", + * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}". + * + * @param classLoader the class loader to use to load the class + * @param className the class name + * @param initialize whether the class must be initialized + * @return the class represented by {@code className} using the {@code classLoader} + * @throws ClassNotFoundException if the class is not found + */ + public static Class getClass( + ClassLoader classLoader, String className, boolean initialize) throws ClassNotFoundException { + try { + Class clazz; + if (abbreviationMap.containsKey(className)) { + String clsName = "[" + abbreviationMap.get(className); + clazz = Class.forName(clsName, initialize, classLoader).getComponentType(); + } else { + clazz = Class.forName(toCanonicalName(className), initialize, classLoader); + } + return clazz; + } catch (ClassNotFoundException ex) { + // allow path separators (.) as inner class name separators + int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); + + if (lastDotIndex != -1) { + try { + return getClass(classLoader, className.substring(0, lastDotIndex) + + INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1), + initialize); + } catch (ClassNotFoundException ex2) { // NOPMD + // ignore exception + } + } + + throw ex; + } + } + + /** + * Returns the (initialized) class represented by {@code className} + * using the {@code classLoader}. This implementation supports + * the syntaxes "{@code java.util.Map.Entry[]}", + * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}", + * and "{@code [Ljava.util.Map$Entry;}". + * + * @param classLoader the class loader to use to load the class + * @param className the class name + * @return the class represented by {@code className} using the {@code classLoader} + * @throws ClassNotFoundException if the class is not found + */ + public static Class getClass(ClassLoader classLoader, String className) throws ClassNotFoundException { + return getClass(classLoader, className, true); + } + + /** + * Returns the (initialized) class represented by {@code className} + * using the current thread's context class loader. This implementation + * supports the syntaxes "{@code java.util.Map.Entry[]}", + * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}", + * and "{@code [Ljava.util.Map$Entry;}". + * + * @param className the class name + * @return the class represented by {@code className} using the current thread's context class loader + * @throws ClassNotFoundException if the class is not found + */ + public static Class getClass(String className) throws ClassNotFoundException { + return getClass(className, true); + } + + /** + * Returns the class represented by {@code className} using the + * current thread's context class loader. This implementation supports the + * syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}", + * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}". + * + * @param className the class name + * @param initialize whether the class must be initialized + * @return the class represented by {@code className} using the current thread's context class loader + * @throws ClassNotFoundException if the class is not found + */ + public static Class getClass(String className, boolean initialize) throws ClassNotFoundException { + ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); + ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL; + return getClass(loader, className, initialize); + } + + // Public method + // ---------------------------------------------------------------------- + /** + *

Returns the desired Method much like {@code Class.getMethod}, however + * it ensures that the returned Method is from a public class or interface and not + * from an anonymous inner class. This means that the Method is invokable and + * doesn't fall foul of Java bug + * 4071957). + * + *

Set set = Collections.unmodifiableSet(...);
+     *  Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty",  new Class[0]);
+     *  Object result = method.invoke(set, new Object[]);
+ *

+ * + * @param cls the class to check, not null + * @param methodName the name of the method + * @param parameterTypes the list of parameters + * @return the method + * @throws NullPointerException if the class is null + * @throws SecurityException if a a security violation occured + * @throws NoSuchMethodException if the method is not found in the given class + * or if the metothod doen't conform with the requirements + */ + public static Method getPublicMethod(Class cls, String methodName, Class... parameterTypes) + throws SecurityException, NoSuchMethodException { + + Method declaredMethod = cls.getMethod(methodName, parameterTypes); + if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) { + return declaredMethod; + } + + List> candidateClasses = new ArrayList>(); + candidateClasses.addAll(getAllInterfaces(cls)); + candidateClasses.addAll(getAllSuperclasses(cls)); + + for (Class candidateClass : candidateClasses) { + if (!Modifier.isPublic(candidateClass.getModifiers())) { + continue; + } + Method candidateMethod; + try { + candidateMethod = candidateClass.getMethod(methodName, parameterTypes); + } catch (NoSuchMethodException ex) { + continue; + } + if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) { + return candidateMethod; + } + } + + throw new NoSuchMethodException("Can't find a public method for " + + methodName + " " + ArrayUtils.toString(parameterTypes)); + } + + // ---------------------------------------------------------------------- + /** + * Converts a class name to a JLS style class name. + * + * @param className the class name + * @return the converted name + */ + private static String toCanonicalName(String className) { + className = StringUtils.deleteWhitespace(className); + if (className == null) { + throw new NullPointerException("className must not be null."); + } else if (className.endsWith("[]")) { + StringBuilder classNameBuffer = new StringBuilder(); + while (className.endsWith("[]")) { + className = className.substring(0, className.length() - 2); + classNameBuffer.append("["); + } + String abbreviation = abbreviationMap.get(className); + if (abbreviation != null) { + classNameBuffer.append(abbreviation); + } else { + classNameBuffer.append("L").append(className).append(";"); + } + className = classNameBuffer.toString(); + } + return className; + } + + /** + *

Converts an array of {@code Object} in to an array of {@code Class} objects. + * If any of these objects is null, a null element will be inserted into the array.

+ * + *

This method returns {@code null} for a {@code null} input array.

+ * + * @param array an {@code Object} array + * @return a {@code Class} array, {@code null} if null array input + * @since 2.4 + */ + public static Class[] toClass(Object... array) { + if (array == null) { + return null; + } else if (array.length == 0) { + return ArrayUtils.EMPTY_CLASS_ARRAY; + } + Class[] classes = new Class[array.length]; + for (int i = 0; i < array.length; i++) { + classes[i] = array[i] == null ? null : array[i].getClass(); + } + return classes; + } + + // Short canonical name + // ---------------------------------------------------------------------- + /** + *

Gets the canonical name minus the package name for an {@code Object}.

+ * + * @param object the class to get the short name for, may be null + * @param valueIfNull the value to return if null + * @return the canonical name of the object without the package name, or the null value + * @since 2.4 + */ + public static String getShortCanonicalName(Object object, String valueIfNull) { + if (object == null) { + return valueIfNull; + } + return getShortCanonicalName(object.getClass().getName()); + } + + /** + *

Gets the canonical name minus the package name from a {@code Class}.

+ * + * @param cls the class to get the short name for. + * @return the canonical name without the package name or an empty string + * @since 2.4 + */ + public static String getShortCanonicalName(Class cls) { + if (cls == null) { + return StringUtils.EMPTY; + } + return getShortCanonicalName(cls.getName()); + } + + /** + *

Gets the canonical name minus the package name from a String.

+ * + *

The string passed in is assumed to be a canonical name - it is not checked.

+ * + * @param canonicalName the class name to get the short name for + * @return the canonical name of the class without the package name or an empty string + * @since 2.4 + */ + public static String getShortCanonicalName(String canonicalName) { + return ClassUtils.getShortClassName(getCanonicalName(canonicalName)); + } + + // Package name + // ---------------------------------------------------------------------- + /** + *

Gets the package name from the canonical name of an {@code Object}.

+ * + * @param object the class to get the package name for, may be null + * @param valueIfNull the value to return if null + * @return the package name of the object, or the null value + * @since 2.4 + */ + public static String getPackageCanonicalName(Object object, String valueIfNull) { + if (object == null) { + return valueIfNull; + } + return getPackageCanonicalName(object.getClass().getName()); + } + + /** + *

Gets the package name from the canonical name of a {@code Class}.

+ * + * @param cls the class to get the package name for, may be {@code null}. + * @return the package name or an empty string + * @since 2.4 + */ + public static String getPackageCanonicalName(Class cls) { + if (cls == null) { + return StringUtils.EMPTY; + } + return getPackageCanonicalName(cls.getName()); + } + + /** + *

Gets the package name from the canonical name.

+ * + *

The string passed in is assumed to be a canonical name - it is not checked.

+ *

If the class is unpackaged, return an empty string.

+ * + * @param canonicalName the canonical name to get the package name for, may be {@code null} + * @return the package name or an empty string + * @since 2.4 + */ + public static String getPackageCanonicalName(String canonicalName) { + return ClassUtils.getPackageName(getCanonicalName(canonicalName)); + } + + /** + *

Converts a given name of class into canonical format. + * If name of class is not a name of array class it returns + * unchanged name.

+ *

Example: + *

    + *
  • {@code getCanonicalName("[I") = "int[]"}
  • + *
  • {@code getCanonicalName("[Ljava.lang.String;") = "java.lang.String[]"}
  • + *
  • {@code getCanonicalName("java.lang.String") = "java.lang.String"}
  • + *
+ *

+ * + * @param className the name of class + * @return canonical form of class name + * @since 2.4 + */ + private static String getCanonicalName(String className) { + className = StringUtils.deleteWhitespace(className); + if (className == null) { + return null; + } else { + int dim = 0; + while (className.startsWith("[")) { + dim++; + className = className.substring(1); + } + if (dim < 1) { + return className; + } else { + if (className.startsWith("L")) { + className = className.substring( + 1, + className.endsWith(";") + ? className.length() - 1 + : className.length()); + } else { + if (className.length() > 0) { + className = reverseAbbreviationMap.get(className.substring(0, 1)); + } + } + StringBuilder canonicalClassNameBuffer = new StringBuilder(className); + for (int i = 0; i < dim; i++) { + canonicalClassNameBuffer.append("[]"); + } + return canonicalClassNameBuffer.toString(); + } + } + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/JavaVersion.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/JavaVersion.java new file mode 100644 index 00000000..6e2b6fea --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/JavaVersion.java @@ -0,0 +1,168 @@ +/* + * 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; + +/** + *

An enum representing all the versions of the Java specification. + * This is intended to mirror available values from the + * java.specification.version System property.

+ * + * @since 3.0 + * @version $Id: $ + */ +public enum JavaVersion { + + /** + * The Java version reported by Android. This is not an official Java version number. + */ + JAVA_0_9(1.5f, "0.9"), + + /** + * Java 1.1. + */ + JAVA_1_1(1.1f, "1.1"), + + /** + * Java 1.2. + */ + JAVA_1_2(1.2f, "1.2"), + + /** + * Java 1.3. + */ + JAVA_1_3(1.3f, "1.3"), + + /** + * Java 1.4. + */ + JAVA_1_4(1.4f, "1.4"), + + /** + * Java 1.5. + */ + JAVA_1_5(1.5f, "1.5"), + + /** + * Java 1.6. + */ + JAVA_1_6(1.6f, "1.6"), + + /** + * Java 1.7. + */ + JAVA_1_7(1.7f, "1.7"), + + /** + * Java 1.8. + */ + JAVA_1_8(1.8f, "1.8"); + + /** + * The float value. + */ + private float value; + /** + * The standard name. + */ + private String name; + + /** + * Constructor. + * + * @param value the float value + * @param name the standard name, not null + */ + JavaVersion(final float value, final String name) { + this.value = value; + this.name = name; + } + + //----------------------------------------------------------------------- + /** + *

Whether this version of Java is at least the version of Java passed in.

+ * + *

For example:
+ * {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}

+ * + * @param requiredVersion the version to check against, not null + * @return true if this version is equal to or greater than the specified version + */ + public boolean atLeast(JavaVersion requiredVersion) { + return this.value >= requiredVersion.value; + } + + /** + * Transforms the given string with a Java version number to the + * corresponding constant of this enumeration class. This method is used + * internally. + * + * @param nom the Java version as string + * @return the corresponding enumeration constant or null if the + * version is unknown + */ + // helper for static importing + static JavaVersion getJavaVersion(final String nom) { + return get(nom); + } + + /** + * Transforms the given string with a Java version number to the + * corresponding constant of this enumeration class. This method is used + * internally. + * + * @param nom the Java version as string + * @return the corresponding enumeration constant or null if the + * version is unknown + */ + static JavaVersion get(final String nom) { + if ("0.9".equals(nom)) { + return JAVA_0_9; + } else if ("1.1".equals(nom)) { + return JAVA_1_1; + } else if ("1.2".equals(nom)) { + return JAVA_1_2; + } else if ("1.3".equals(nom)) { + return JAVA_1_3; + } else if ("1.4".equals(nom)) { + return JAVA_1_4; + } else if ("1.5".equals(nom)) { + return JAVA_1_5; + } else if ("1.6".equals(nom)) { + return JAVA_1_6; + } else if ("1.7".equals(nom)) { + return JAVA_1_7; + } else if ("1.8".equals(nom)) { + return JAVA_1_8; + } else { + return null; + } + } + + //----------------------------------------------------------------------- + /** + *

The string value is overridden to return the standard name.

+ * + *

For example, "1.5".

+ * + * @return the name, not null + */ + @Override + public String toString() { + return name; + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/LICENSE.txt b/edxp-core/src/main/java/external/org/apache/commons/lang3/LICENSE.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/MODIFICATIONS.txt b/edxp-core/src/main/java/external/org/apache/commons/lang3/MODIFICATIONS.txt new file mode 100644 index 00000000..d6f4e370 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/MODIFICATIONS.txt @@ -0,0 +1,44 @@ +This is the original source code of the Apache Commons Lang library version 3.1 +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 +- 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/edxp-core/src/main/java/external/org/apache/commons/lang3/NOTICE.txt b/edxp-core/src/main/java/external/org/apache/commons/lang3/NOTICE.txt new file mode 100644 index 00000000..2f0ca384 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/NOTICE.txt @@ -0,0 +1,8 @@ +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()) diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/ObjectUtils.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/ObjectUtils.java new file mode 100644 index 00000000..d8e85a8c --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/ObjectUtils.java @@ -0,0 +1,609 @@ +/* + * 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.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + + +import external.org.apache.commons.lang3.exception.CloneFailedException; +import external.org.apache.commons.lang3.mutable.MutableInt; + +/** + *

Operations on {@code Object}.

+ * + *

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

+ * + *

#ThreadSafe#

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

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

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

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(T object, T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(T... values) { + if (values != null) { + for (T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + */ + public static boolean equals(Object object1, Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(Object object1, Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + */ + public static int hashCode(Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + */ + public static int hashCodeMulti(Object... objects) { + int hash = 1; + if (objects != null) { + for (Object object : objects) { + hash = hash * 31 + ObjectUtils.hashCode(object); + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(Object object) { + if (object == null) { + return null; + } + StringBuffer buffer = new StringBuffer(); + identityToString(buffer, object); + return buffer.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(StringBuffer buffer, Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or nullStr if {@code null} input + * @since 2.0 + */ + public static String toString(Object obj) { + return obj == null ? "" : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or nullStr if {@code null} input + * @since 2.0 + */ + public static String toString(Object obj, String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(T... values) { + T result = null; + if (values != null) { + for (T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(T... values) { + T result = null; + if (values != null) { + for (T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(T c1, T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(T c1, T c2, boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(Comparator comparator, T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(T... items) { + if (ArrayUtils.isNotEmpty(items)) { + HashMap occurrences = new HashMap(items.length); + for (T t : items) { + MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (Map.Entry e : occurrences.entrySet()) { + int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/RELEASE-NOTES.txt b/edxp-core/src/main/java/external/org/apache/commons/lang3/RELEASE-NOTES.txt new file mode 100644 index 00000000..e0ec1336 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/RELEASE-NOTES.txt @@ -0,0 +1,40 @@ +$Id: RELEASE-NOTES.txt 1199820 2011-11-09 16:14:52Z bayard $ + + Commons Lang Package + Version 3.1 + Release Notes + + +INTRODUCTION: + +This document contains the release notes for the 3.1 version of Apache Commons Lang. +Commons Lang is a set of utility functions and reusable components that should be of use in any +Java environment. + +Lang 3.0 and onwards now targets Java 5.0, making use of features that arrived with Java 5.0 such as generics, +variable arguments, autoboxing, concurrency and formatted output. + +For the advice on upgrading from 2.x to 3.x, see the following page: + + http://commons.apache.org/lang/article3_0.html + +CHANGES IN 3.1 +================ + + [LANG-760] Add API StringUtils.toString(byte[] intput, String charsetName) + [LANG-756] Add APIs ClassUtils.isPrimitiveWrapper(Class) and isPrimitiveOrWrapper(Class) + [LANG-758] Add an example with whitespace in StringUtils.defaultIfEmpty + [LANG-752] Fix createLong() so it behaves like createInteger() + [LANG-751] Include the actual type in the Validate.isInstance and isAssignableFrom exception messages + [LANG-748] Deprecating chomp(String, String) + [LANG-736] CharUtils static final array CHAR_STRING is not needed to compute CHAR_STRING_ARRAY + [LANG-695] SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system + +BUG FIXES IN 3.1 +================== + + [LANG-749] Incorrect Bundle-SymbolicName in Manifest + [LANG-746] NumberUtils does not handle upper-case hex: 0X and -0X + [LANG-744] StringUtils throws java.security.AccessControlException on Google App Engine + [LANG-741] Ant build has wrong component.name + [LANG-698] Document that the Mutable numbers don't work as expected with String.format diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/StringUtils.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/StringUtils.java new file mode 100644 index 00000000..68032566 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/StringUtils.java @@ -0,0 +1,6582 @@ +/* + * 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.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.regex.Pattern; + +/** + *

Operations on {@link java.lang.String} that are + * {@code null} safe.

+ * + *
    + *
  • IsEmpty/IsBlank + * - checks if a String contains text
  • + *
  • Trim/Strip + * - removes leading and trailing whitespace
  • + *
  • Equals + * - compares two strings null-safe
  • + *
  • startsWith + * - check if a String starts with a prefix null-safe
  • + *
  • endsWith + * - check if a String ends with a suffix null-safe
  • + *
  • IndexOf/LastIndexOf/Contains + * - null-safe index-of checks + *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut + * - index-of any of a set of Strings
  • + *
  • ContainsOnly/ContainsNone/ContainsAny + * - does String contains only/none/any of these characters
  • + *
  • Substring/Left/Right/Mid + * - null-safe substring extractions
  • + *
  • SubstringBefore/SubstringAfter/SubstringBetween + * - substring extraction relative to other strings
  • + *
  • Split/Join + * - splits a String into an array of substrings and vice versa
  • + *
  • Remove/Delete + * - removes part of a String
  • + *
  • Replace/Overlay + * - Searches a String and replaces one String with another
  • + *
  • Chomp/Chop + * - removes the last part of a String
  • + *
  • LeftPad/RightPad/Center/Repeat + * - pads a String
  • + *
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize + * - changes the case of a String
  • + *
  • CountMatches + * - counts the number of occurrences of one String in another
  • + *
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable + * - checks the characters in a String
  • + *
  • DefaultString + * - protects against a null input String
  • + *
  • Reverse/ReverseDelimited + * - reverses a String
  • + *
  • Abbreviate + * - abbreviates a string using ellipsis
  • + *
  • Difference + * - compares Strings and reports on their differences
  • + *
  • LevenshteinDistance + * - the number of changes needed to change one String into another
  • + *
+ * + *

The {@code StringUtils} class defines certain words related to + * String handling.

+ * + *
    + *
  • null - {@code null}
  • + *
  • empty - a zero-length string ({@code ""})
  • + *
  • space - the space character ({@code ' '}, char 32)
  • + *
  • whitespace - the characters defined by {@link Character#isWhitespace(char)}
  • + *
  • trim - the characters <= 32 as in {@link String#trim()}
  • + *
+ * + *

{@code StringUtils} handles {@code null} input Strings quietly. + * That is to say that a {@code null} input will return {@code null}. + * Where a {@code boolean} or {@code int} is being returned + * details vary by method.

+ * + *

A side effect of the {@code null} handling is that a + * {@code NullPointerException} should be considered a bug in + * {@code StringUtils}.

+ * + *

Methods in this class give sample code to explain their operation. + * The symbol {@code *} is used to indicate any input including {@code null}.

+ * + *

#ThreadSafe#

+ * @see java.lang.String + * @since 1.0 + * @version $Id: StringUtils.java 1199894 2011-11-09 17:53:59Z ggregory $ + */ +//@Immutable +public class StringUtils { + // Performance testing notes (JDK 1.4, Jul03, scolebourne) + // Whitespace: + // Character.isWhitespace() is faster than WHITESPACE.indexOf() + // where WHITESPACE is a string of all whitespace characters + // + // Character access: + // String.charAt(n) versus toCharArray(), then array[n] + // String.charAt(n) is about 15% worse for a 10K string + // They are about equal for a length 50 string + // String.charAt(n) is about 4 times better for a length 3 string + // String.charAt(n) is best bet overall + // + // Append: + // String.concat about twice as fast as StringBuffer.append + // (not sure who tested this) + + /** + * The empty String {@code ""}. + * @since 2.0 + */ + public static final String EMPTY = ""; + + /** + * Represents a failed index search. + * @since 2.1 + */ + public static final int INDEX_NOT_FOUND = -1; + + /** + *

The maximum size to which the padding constant(s) can expand.

+ */ + private static final int PAD_LIMIT = 8192; + + /** + * A regex pattern for recognizing blocks of whitespace characters. + */ + private static final Pattern WHITESPACE_BLOCK = Pattern.compile("\\s+"); + + /** + *

{@code StringUtils} instances should NOT be constructed in + * standard programming. Instead, the class should be used as + * {@code StringUtils.trim(" foo ");}.

+ * + *

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

+ */ + public StringUtils() { + super(); + } + + // Empty checks + //----------------------------------------------------------------------- + /** + *

Checks if a CharSequence is empty ("") or null.

+ * + *
+     * StringUtils.isEmpty(null)      = true
+     * StringUtils.isEmpty("")        = true
+     * StringUtils.isEmpty(" ")       = false
+     * StringUtils.isEmpty("bob")     = false
+     * StringUtils.isEmpty("  bob  ") = false
+     * 
+ * + *

NOTE: This method changed in Lang version 2.0. + * It no longer trims the CharSequence. + * That functionality is available in isBlank().

+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if the CharSequence is empty or null + * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) + */ + public static boolean isEmpty(CharSequence cs) { + return cs == null || cs.length() == 0; + } + + /** + *

Checks if a CharSequence is not empty ("") and not null.

+ * + *
+     * StringUtils.isNotEmpty(null)      = false
+     * StringUtils.isNotEmpty("")        = false
+     * StringUtils.isNotEmpty(" ")       = true
+     * StringUtils.isNotEmpty("bob")     = true
+     * StringUtils.isNotEmpty("  bob  ") = true
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if the CharSequence is not empty and not null + * @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence) + */ + public static boolean isNotEmpty(CharSequence cs) { + return !StringUtils.isEmpty(cs); + } + + /** + *

Checks if a CharSequence is whitespace, empty ("") or null.

+ * + *
+     * StringUtils.isBlank(null)      = true
+     * StringUtils.isBlank("")        = true
+     * StringUtils.isBlank(" ")       = true
+     * StringUtils.isBlank("bob")     = false
+     * StringUtils.isBlank("  bob  ") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if the CharSequence is null, empty or whitespace + * @since 2.0 + * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence) + */ + public static boolean isBlank(CharSequence cs) { + int strLen; + if (cs == null || (strLen = cs.length()) == 0) { + return true; + } + for (int i = 0; i < strLen; i++) { + if (Character.isWhitespace(cs.charAt(i)) == false) { + return false; + } + } + return true; + } + + /** + *

Checks if a CharSequence is not empty (""), not null and not whitespace only.

+ * + *
+     * StringUtils.isNotBlank(null)      = false
+     * StringUtils.isNotBlank("")        = false
+     * StringUtils.isNotBlank(" ")       = false
+     * StringUtils.isNotBlank("bob")     = true
+     * StringUtils.isNotBlank("  bob  ") = true
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if the CharSequence is + * not empty and not null and not whitespace + * @since 2.0 + * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence) + */ + public static boolean isNotBlank(CharSequence cs) { + return !StringUtils.isBlank(cs); + } + + // Trim + //----------------------------------------------------------------------- + /** + *

Removes control characters (char <= 32) from both + * ends of this String, handling {@code null} by returning + * {@code null}.

+ * + *

The String is trimmed using {@link String#trim()}. + * Trim removes start and end characters <= 32. + * To strip whitespace use {@link #strip(String)}.

+ * + *

To trim your choice of characters, use the + * {@link #strip(String, String)} methods.

+ * + *
+     * StringUtils.trim(null)          = null
+     * StringUtils.trim("")            = ""
+     * StringUtils.trim("     ")       = ""
+     * StringUtils.trim("abc")         = "abc"
+     * StringUtils.trim("    abc    ") = "abc"
+     * 
+ * + * @param str the String to be trimmed, may be null + * @return the trimmed string, {@code null} if null String input + */ + public static String trim(String str) { + return str == null ? null : str.trim(); + } + + /** + *

Removes control characters (char <= 32) from both + * ends of this String returning {@code null} if the String is + * empty ("") after the trim or if it is {@code null}. + * + *

The String is trimmed using {@link String#trim()}. + * Trim removes start and end characters <= 32. + * To strip whitespace use {@link #stripToNull(String)}.

+ * + *
+     * StringUtils.trimToNull(null)          = null
+     * StringUtils.trimToNull("")            = null
+     * StringUtils.trimToNull("     ")       = null
+     * StringUtils.trimToNull("abc")         = "abc"
+     * StringUtils.trimToNull("    abc    ") = "abc"
+     * 
+ * + * @param str the String to be trimmed, may be null + * @return the trimmed String, + * {@code null} if only chars <= 32, empty or null String input + * @since 2.0 + */ + public static String trimToNull(String str) { + String ts = trim(str); + return isEmpty(ts) ? null : ts; + } + + /** + *

Removes control characters (char <= 32) from both + * ends of this String returning an empty String ("") if the String + * is empty ("") after the trim or if it is {@code null}. + * + *

The String is trimmed using {@link String#trim()}. + * Trim removes start and end characters <= 32. + * To strip whitespace use {@link #stripToEmpty(String)}.

+ * + *
+     * StringUtils.trimToEmpty(null)          = ""
+     * StringUtils.trimToEmpty("")            = ""
+     * StringUtils.trimToEmpty("     ")       = ""
+     * StringUtils.trimToEmpty("abc")         = "abc"
+     * StringUtils.trimToEmpty("    abc    ") = "abc"
+     * 
+ * + * @param str the String to be trimmed, may be null + * @return the trimmed String, or an empty String if {@code null} input + * @since 2.0 + */ + public static String trimToEmpty(String str) { + return str == null ? EMPTY : str.trim(); + } + + // Stripping + //----------------------------------------------------------------------- + /** + *

Strips whitespace from the start and end of a String.

+ * + *

This is similar to {@link #trim(String)} but removes whitespace. + * Whitespace is defined by {@link Character#isWhitespace(char)}.

+ * + *

A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.strip(null)     = null
+     * StringUtils.strip("")       = ""
+     * StringUtils.strip("   ")    = ""
+     * StringUtils.strip("abc")    = "abc"
+     * StringUtils.strip("  abc")  = "abc"
+     * StringUtils.strip("abc  ")  = "abc"
+     * StringUtils.strip(" abc ")  = "abc"
+     * StringUtils.strip(" ab c ") = "ab c"
+     * 
+ * + * @param str the String to remove whitespace from, may be null + * @return the stripped String, {@code null} if null String input + */ + public static String strip(String str) { + return strip(str, null); + } + + /** + *

Strips whitespace from the start and end of a String returning + * {@code null} if the String is empty ("") after the strip.

+ * + *

This is similar to {@link #trimToNull(String)} but removes whitespace. + * Whitespace is defined by {@link Character#isWhitespace(char)}.

+ * + *
+     * StringUtils.stripToNull(null)     = null
+     * StringUtils.stripToNull("")       = null
+     * StringUtils.stripToNull("   ")    = null
+     * StringUtils.stripToNull("abc")    = "abc"
+     * StringUtils.stripToNull("  abc")  = "abc"
+     * StringUtils.stripToNull("abc  ")  = "abc"
+     * StringUtils.stripToNull(" abc ")  = "abc"
+     * StringUtils.stripToNull(" ab c ") = "ab c"
+     * 
+ * + * @param str the String to be stripped, may be null + * @return the stripped String, + * {@code null} if whitespace, empty or null String input + * @since 2.0 + */ + public static String stripToNull(String str) { + if (str == null) { + return null; + } + str = strip(str, null); + return str.length() == 0 ? null : str; + } + + /** + *

Strips whitespace from the start and end of a String returning + * an empty String if {@code null} input.

+ * + *

This is similar to {@link #trimToEmpty(String)} but removes whitespace. + * Whitespace is defined by {@link Character#isWhitespace(char)}.

+ * + *
+     * StringUtils.stripToEmpty(null)     = ""
+     * StringUtils.stripToEmpty("")       = ""
+     * StringUtils.stripToEmpty("   ")    = ""
+     * StringUtils.stripToEmpty("abc")    = "abc"
+     * StringUtils.stripToEmpty("  abc")  = "abc"
+     * StringUtils.stripToEmpty("abc  ")  = "abc"
+     * StringUtils.stripToEmpty(" abc ")  = "abc"
+     * StringUtils.stripToEmpty(" ab c ") = "ab c"
+     * 
+ * + * @param str the String to be stripped, may be null + * @return the trimmed String, or an empty String if {@code null} input + * @since 2.0 + */ + public static String stripToEmpty(String str) { + return str == null ? EMPTY : strip(str, null); + } + + /** + *

Strips any of a set of characters from the start and end of a String. + * This is similar to {@link String#trim()} but allows the characters + * to be stripped to be controlled.

+ * + *

A {@code null} input String returns {@code null}. + * An empty string ("") input returns the empty string.

+ * + *

If the stripChars String is {@code null}, whitespace is + * stripped as defined by {@link Character#isWhitespace(char)}. + * Alternatively use {@link #strip(String)}.

+ * + *
+     * StringUtils.strip(null, *)          = null
+     * StringUtils.strip("", *)            = ""
+     * StringUtils.strip("abc", null)      = "abc"
+     * StringUtils.strip("  abc", null)    = "abc"
+     * StringUtils.strip("abc  ", null)    = "abc"
+     * StringUtils.strip(" abc ", null)    = "abc"
+     * StringUtils.strip("  abcyx", "xyz") = "  abc"
+     * 
+ * + * @param str the String to remove characters from, may be null + * @param stripChars the characters to remove, null treated as whitespace + * @return the stripped String, {@code null} if null String input + */ + public static String strip(String str, String stripChars) { + if (isEmpty(str)) { + return str; + } + str = stripStart(str, stripChars); + return stripEnd(str, stripChars); + } + + /** + *

Strips any of a set of characters from the start of a String.

+ * + *

A {@code null} input String returns {@code null}. + * An empty string ("") input returns the empty string.

+ * + *

If the stripChars String is {@code null}, whitespace is + * stripped as defined by {@link Character#isWhitespace(char)}.

+ * + *
+     * StringUtils.stripStart(null, *)          = null
+     * StringUtils.stripStart("", *)            = ""
+     * StringUtils.stripStart("abc", "")        = "abc"
+     * StringUtils.stripStart("abc", null)      = "abc"
+     * StringUtils.stripStart("  abc", null)    = "abc"
+     * StringUtils.stripStart("abc  ", null)    = "abc  "
+     * StringUtils.stripStart(" abc ", null)    = "abc "
+     * StringUtils.stripStart("yxabc  ", "xyz") = "abc  "
+     * 
+ * + * @param str the String to remove characters from, may be null + * @param stripChars the characters to remove, null treated as whitespace + * @return the stripped String, {@code null} if null String input + */ + public static String stripStart(String str, String stripChars) { + int strLen; + if (str == null || (strLen = str.length()) == 0) { + return str; + } + int start = 0; + if (stripChars == null) { + while (start != strLen && Character.isWhitespace(str.charAt(start))) { + start++; + } + } else if (stripChars.length() == 0) { + return str; + } else { + while (start != strLen && stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND) { + start++; + } + } + return str.substring(start); + } + + /** + *

Strips any of a set of characters from the end of a String.

+ * + *

A {@code null} input String returns {@code null}. + * An empty string ("") input returns the empty string.

+ * + *

If the stripChars String is {@code null}, whitespace is + * stripped as defined by {@link Character#isWhitespace(char)}.

+ * + *
+     * StringUtils.stripEnd(null, *)          = null
+     * StringUtils.stripEnd("", *)            = ""
+     * StringUtils.stripEnd("abc", "")        = "abc"
+     * StringUtils.stripEnd("abc", null)      = "abc"
+     * StringUtils.stripEnd("  abc", null)    = "  abc"
+     * StringUtils.stripEnd("abc  ", null)    = "abc"
+     * StringUtils.stripEnd(" abc ", null)    = " abc"
+     * StringUtils.stripEnd("  abcyx", "xyz") = "  abc"
+     * StringUtils.stripEnd("120.00", ".0")   = "12"
+     * 
+ * + * @param str the String to remove characters from, may be null + * @param stripChars the set of characters to remove, null treated as whitespace + * @return the stripped String, {@code null} if null String input + */ + public static String stripEnd(String str, String stripChars) { + int end; + if (str == null || (end = str.length()) == 0) { + return str; + } + + if (stripChars == null) { + while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) { + end--; + } + } else if (stripChars.length() == 0) { + return str; + } else { + while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) { + end--; + } + } + return str.substring(0, end); + } + + // StripAll + //----------------------------------------------------------------------- + /** + *

Strips whitespace from the start and end of every String in an array. + * Whitespace is defined by {@link Character#isWhitespace(char)}.

+ * + *

A new array is returned each time, except for length zero. + * A {@code null} array will return {@code null}. + * An empty array will return itself. + * A {@code null} array entry will be ignored.

+ * + *
+     * StringUtils.stripAll(null)             = null
+     * StringUtils.stripAll([])               = []
+     * StringUtils.stripAll(["abc", "  abc"]) = ["abc", "abc"]
+     * StringUtils.stripAll(["abc  ", null])  = ["abc", null]
+     * 
+ * + * @param strs the array to remove whitespace from, may be null + * @return the stripped Strings, {@code null} if null array input + */ + public static String[] stripAll(String... strs) { + return stripAll(strs, null); + } + + /** + *

Strips any of a set of characters from the start and end of every + * String in an array.

+ * Whitespace is defined by {@link Character#isWhitespace(char)}.

+ * + *

A new array is returned each time, except for length zero. + * A {@code null} array will return {@code null}. + * An empty array will return itself. + * A {@code null} array entry will be ignored. + * A {@code null} stripChars will strip whitespace as defined by + * {@link Character#isWhitespace(char)}.

+ * + *
+     * StringUtils.stripAll(null, *)                = null
+     * StringUtils.stripAll([], *)                  = []
+     * StringUtils.stripAll(["abc", "  abc"], null) = ["abc", "abc"]
+     * StringUtils.stripAll(["abc  ", null], null)  = ["abc", null]
+     * StringUtils.stripAll(["abc  ", null], "yz")  = ["abc  ", null]
+     * StringUtils.stripAll(["yabcz", null], "yz")  = ["abc", null]
+     * 
+ * + * @param strs the array to remove characters from, may be null + * @param stripChars the characters to remove, null treated as whitespace + * @return the stripped Strings, {@code null} if null array input + */ + public static String[] stripAll(String[] strs, String stripChars) { + int strsLen; + if (strs == null || (strsLen = strs.length) == 0) { + return strs; + } + String[] newArr = new String[strsLen]; + for (int i = 0; i < strsLen; i++) { + newArr[i] = strip(strs[i], stripChars); + } + return newArr; + } + + /** + *

Removes diacritics (~= accents) from a string. The case will not be altered.

+ *

For instance, 'à' will be replaced by 'a'.

+ *

Note that ligatures will be left as is.

+ * + *

This method will use the first available implementation of: + * Java 6's {@link java.text.Normalizer}, Java 1.3–1.5's {@code sun.text.Normalizer}

+ * + *
+     * StringUtils.stripAccents(null)                = null
+     * StringUtils.stripAccents("")                  = ""
+     * StringUtils.stripAccents("control")           = "control"
+     * StringUtils.stripAccents("éclair")     = "eclair"
+     * 
+ * + * @param input String to be stripped + * @return input text with diacritics removed + * + * @since 3.0 + */ + // See also Lucene's ASCIIFoldingFilter (Lucene 2.9) that replaces accented characters by their unaccented equivalent (and uncommitted bug fix: https://issues.apache.org/jira/browse/LUCENE-1343?focusedCommentId=12858907&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_12858907). + public static String stripAccents(String input) { + if(input == null) { + return null; + } + try { + String result = null; + if (InitStripAccents.java6NormalizeMethod != null) { + result = removeAccentsJava6(input); + } else if (InitStripAccents.sunDecomposeMethod != null) { + result = removeAccentsSUN(input); + } else { + throw new UnsupportedOperationException( + "The stripAccents(CharSequence) method requires at least" + +" Java6, but got: "+InitStripAccents.java6Exception + +"; or a Sun JVM: "+InitStripAccents.sunException); + } + // Note that none of the above methods correctly remove ligatures... + return result; + } catch(IllegalArgumentException iae) { + throw new RuntimeException("IllegalArgumentException occurred", iae); + } catch(IllegalAccessException iae) { + throw new RuntimeException("IllegalAccessException occurred", iae); + } catch(InvocationTargetException ite) { + throw new RuntimeException("InvocationTargetException occurred", ite); + } catch(SecurityException se) { + throw new RuntimeException("SecurityException occurred", se); + } + } + + /** + * Use {@code java.text.Normalizer#normalize(CharSequence, Normalizer.Form)} + * (but be careful, this class exists in Java 1.3, with an entirely different meaning!) + * + * @param text the text to be processed + * @return the processed string + * @throws IllegalAccessException may be thrown by a reflection call + * @throws InvocationTargetException if a reflection call throws an exception + * @throws IllegalStateException if the {@code Normalizer} class is not available + */ + private static String removeAccentsJava6(CharSequence text) + throws IllegalAccessException, InvocationTargetException { + /* + String decomposed = java.text.Normalizer.normalize(CharSequence, Normalizer.Form.NFD); + return java6Pattern.matcher(decomposed).replaceAll("");//$NON-NLS-1$ + */ + if (InitStripAccents.java6NormalizeMethod == null || InitStripAccents.java6NormalizerFormNFD == null) { + throw new IllegalStateException("java.text.Normalizer is not available", InitStripAccents.java6Exception); + } + String result; + result = (String) InitStripAccents.java6NormalizeMethod.invoke(null, new Object[] {text, InitStripAccents.java6NormalizerFormNFD}); + result = InitStripAccents.java6Pattern.matcher(result).replaceAll("");//$NON-NLS-1$ + return result; + } + + /** + * Use {@code sun.text.Normalizer#decompose(String, boolean, int)} + * + * @param text the text to be processed + * @return the processed string + * @throws IllegalAccessException may be thrown by a reflection call + * @throws InvocationTargetException if a reflection call throws an exception + * @throws IllegalStateException if the {@code Normalizer} class is not available + */ + private static String removeAccentsSUN(CharSequence text) + throws IllegalAccessException, InvocationTargetException { + /* + String decomposed = sun.text.Normalizer.decompose(text, false, 0); + return sunPattern.matcher(decomposed).replaceAll("");//$NON-NLS-1$ + */ + if (InitStripAccents.sunDecomposeMethod == null) { + throw new IllegalStateException("sun.text.Normalizer is not available", InitStripAccents.sunException); + } + String result; + result = (String) InitStripAccents.sunDecomposeMethod.invoke(null, new Object[] {text, Boolean.FALSE, Integer.valueOf(0)}); + result = InitStripAccents.sunPattern.matcher(result).replaceAll("");//$NON-NLS-1$ + return result; + } + + // IOD container for stripAccent() initialisation + private static class InitStripAccents { + // SUN internal, Java 1.3 -> Java 5 + private static final Throwable sunException; + private static final Method sunDecomposeMethod; + private static final Pattern sunPattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");//$NON-NLS-1$ + // Java 6+ + private static final Throwable java6Exception; + private static final Method java6NormalizeMethod; + private static final Object java6NormalizerFormNFD; + private static final Pattern java6Pattern = sunPattern; + + static { + // Set up defaults for final static fields + Object _java6NormalizerFormNFD = null; + Method _java6NormalizeMethod = null; + Method _sunDecomposeMethod = null; + Throwable _java6Exception = null; + Throwable _sunException = null; + try { + // java.text.Normalizer.normalize(CharSequence, Normalizer.Form.NFD); + // Be careful not to get Java 1.3 java.text.Normalizer! + Class normalizerFormClass = Thread.currentThread().getContextClassLoader() + .loadClass("java.text.Normalizer$Form");//$NON-NLS-1$ + _java6NormalizerFormNFD = normalizerFormClass.getField("NFD").get(null);//$NON-NLS-1$ + Class normalizerClass = Thread.currentThread().getContextClassLoader() + .loadClass("java.text.Normalizer");//$NON-NLS-1$ + _java6NormalizeMethod = normalizerClass.getMethod("normalize",//$NON-NLS-1$ + new Class[] {CharSequence.class, normalizerFormClass});//$NON-NLS-1$ + } catch (Exception e1) { + // Only check for Sun method if Java 6 method is not available + _java6Exception = e1; + try { + // sun.text.Normalizer.decompose(text, false, 0); + Class normalizerClass = Thread.currentThread().getContextClassLoader() + .loadClass("sun.text.Normalizer");//$NON-NLS-1$ + _sunDecomposeMethod = normalizerClass.getMethod("decompose",//$NON-NLS-1$ + new Class[] {String.class, Boolean.TYPE, Integer.TYPE});//$NON-NLS-1$ + } catch (Exception e2) { + _sunException = e2; + } + } + + // Set up final static fields + java6Exception = _java6Exception; + java6NormalizerFormNFD = _java6NormalizerFormNFD; + java6NormalizeMethod = _java6NormalizeMethod; + sunException = _sunException; + sunDecomposeMethod = _sunDecomposeMethod; + } + } + + // Equals + //----------------------------------------------------------------------- + /** + *

Compares two CharSequences, returning {@code true} if they are equal.

+ * + *

{@code null}s are handled without exceptions. Two {@code null} + * references are considered to be equal. The comparison is case sensitive.

+ * + *
+     * StringUtils.equals(null, null)   = true
+     * StringUtils.equals(null, "abc")  = false
+     * StringUtils.equals("abc", null)  = false
+     * StringUtils.equals("abc", "abc") = true
+     * StringUtils.equals("abc", "ABC") = false
+     * 
+ * + * @see java.lang.String#equals(Object) + * @param cs1 the first CharSequence, may be null + * @param cs2 the second CharSequence, may be null + * @return {@code true} if the CharSequences are equal, case sensitive, or + * both {@code null} + * @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence) + */ + public static boolean equals(CharSequence cs1, CharSequence cs2) { + return cs1 == null ? cs2 == null : cs1.equals(cs2); + } + + /** + *

Compares two CharSequences, returning {@code true} if they are equal ignoring + * the case.

+ * + *

{@code null}s are handled without exceptions. Two {@code null} + * references are considered equal. Comparison is case insensitive.

+ * + *
+     * StringUtils.equalsIgnoreCase(null, null)   = true
+     * StringUtils.equalsIgnoreCase(null, "abc")  = false
+     * StringUtils.equalsIgnoreCase("abc", null)  = false
+     * StringUtils.equalsIgnoreCase("abc", "abc") = true
+     * StringUtils.equalsIgnoreCase("abc", "ABC") = true
+     * 
+ * + * @param str1 the first CharSequence, may be null + * @param str2 the second CharSequence, may be null + * @return {@code true} if the CharSequence are equal, case insensitive, or + * both {@code null} + * @since 3.0 Changed signature from equalsIgnoreCase(String, String) to equalsIgnoreCase(CharSequence, CharSequence) + */ + public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2) { + if (str1 == null || str2 == null) { + return str1 == str2; + } else { + return CharSequenceUtils.regionMatches(str1, true, 0, str2, 0, Math.max(str1.length(), str2.length())); + } + } + + // IndexOf + //----------------------------------------------------------------------- + /** + *

Finds the first index within a CharSequence, handling {@code null}. + * This method uses {@link String#indexOf(int, int)} if possible.

+ * + *

A {@code null} or empty ("") CharSequence will return {@code INDEX_NOT_FOUND (-1)}.

+ * + *
+     * StringUtils.indexOf(null, *)         = -1
+     * StringUtils.indexOf("", *)           = -1
+     * StringUtils.indexOf("aabaabaa", 'a') = 0
+     * StringUtils.indexOf("aabaabaa", 'b') = 2
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchChar the character to find + * @return the first index of the search character, + * -1 if no match or {@code null} string input + * @since 2.0 + * @since 3.0 Changed signature from indexOf(String, int) to indexOf(CharSequence, int) + */ + public static int indexOf(CharSequence seq, int searchChar) { + if (isEmpty(seq)) { + return INDEX_NOT_FOUND; + } + return CharSequenceUtils.indexOf(seq, searchChar, 0); + } + + /** + *

Finds the first index within a CharSequence from a start position, + * handling {@code null}. + * This method uses {@link String#indexOf(int, int)} if possible.

+ * + *

A {@code null} or empty ("") CharSequence will return {@code (INDEX_NOT_FOUND) -1}. + * A negative start position is treated as zero. + * A start position greater than the string length returns {@code -1}.

+ * + *
+     * StringUtils.indexOf(null, *, *)          = -1
+     * StringUtils.indexOf("", *, *)            = -1
+     * StringUtils.indexOf("aabaabaa", 'b', 0)  = 2
+     * StringUtils.indexOf("aabaabaa", 'b', 3)  = 5
+     * StringUtils.indexOf("aabaabaa", 'b', 9)  = -1
+     * StringUtils.indexOf("aabaabaa", 'b', -1) = 2
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchChar the character to find + * @param startPos the start position, negative treated as zero + * @return the first index of the search character, + * -1 if no match or {@code null} string input + * @since 2.0 + * @since 3.0 Changed signature from indexOf(String, int, int) to indexOf(CharSequence, int, int) + */ + public static int indexOf(CharSequence seq, int searchChar, int startPos) { + if (isEmpty(seq)) { + return INDEX_NOT_FOUND; + } + return CharSequenceUtils.indexOf(seq, searchChar, startPos); + } + + /** + *

Finds the first index within a CharSequence, handling {@code null}. + * This method uses {@link String#indexOf(String, int)} if possible.

+ * + *

A {@code null} CharSequence will return {@code -1}.

+ * + *
+     * StringUtils.indexOf(null, *)          = -1
+     * StringUtils.indexOf(*, null)          = -1
+     * StringUtils.indexOf("", "")           = 0
+     * StringUtils.indexOf("", *)            = -1 (except when * = "")
+     * StringUtils.indexOf("aabaabaa", "a")  = 0
+     * StringUtils.indexOf("aabaabaa", "b")  = 2
+     * StringUtils.indexOf("aabaabaa", "ab") = 1
+     * StringUtils.indexOf("aabaabaa", "")   = 0
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchSeq the CharSequence to find, may be null + * @return the first index of the search CharSequence, + * -1 if no match or {@code null} string input + * @since 2.0 + * @since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence) + */ + public static int indexOf(CharSequence seq, CharSequence searchSeq) { + if (seq == null || searchSeq == null) { + return INDEX_NOT_FOUND; + } + return CharSequenceUtils.indexOf(seq, searchSeq, 0); + } + + /** + *

Finds the first index within a CharSequence, handling {@code null}. + * This method uses {@link String#indexOf(String, int)} if possible.

+ * + *

A {@code null} CharSequence will return {@code -1}. + * A negative start position is treated as zero. + * An empty ("") search CharSequence always matches. + * A start position greater than the string length only matches + * an empty search CharSequence.

+ * + *
+     * StringUtils.indexOf(null, *, *)          = -1
+     * StringUtils.indexOf(*, null, *)          = -1
+     * StringUtils.indexOf("", "", 0)           = 0
+     * StringUtils.indexOf("", *, 0)            = -1 (except when * = "")
+     * StringUtils.indexOf("aabaabaa", "a", 0)  = 0
+     * StringUtils.indexOf("aabaabaa", "b", 0)  = 2
+     * StringUtils.indexOf("aabaabaa", "ab", 0) = 1
+     * StringUtils.indexOf("aabaabaa", "b", 3)  = 5
+     * StringUtils.indexOf("aabaabaa", "b", 9)  = -1
+     * StringUtils.indexOf("aabaabaa", "b", -1) = 2
+     * StringUtils.indexOf("aabaabaa", "", 2)   = 2
+     * StringUtils.indexOf("abc", "", 9)        = 3
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchSeq the CharSequence to find, may be null + * @param startPos the start position, negative treated as zero + * @return the first index of the search CharSequence, + * -1 if no match or {@code null} string input + * @since 2.0 + * @since 3.0 Changed signature from indexOf(String, String, int) to indexOf(CharSequence, CharSequence, int) + */ + public static int indexOf(CharSequence seq, CharSequence searchSeq, int startPos) { + if (seq == null || searchSeq == null) { + return INDEX_NOT_FOUND; + } + return CharSequenceUtils.indexOf(seq, searchSeq, startPos); + } + + /** + *

Finds the n-th index within a CharSequence, handling {@code null}. + * This method uses {@link String#indexOf(String)} if possible.

+ * + *

A {@code null} CharSequence will return {@code -1}.

+ * + *
+     * StringUtils.ordinalIndexOf(null, *, *)          = -1
+     * StringUtils.ordinalIndexOf(*, null, *)          = -1
+     * StringUtils.ordinalIndexOf("", "", *)           = 0
+     * StringUtils.ordinalIndexOf("aabaabaa", "a", 1)  = 0
+     * StringUtils.ordinalIndexOf("aabaabaa", "a", 2)  = 1
+     * StringUtils.ordinalIndexOf("aabaabaa", "b", 1)  = 2
+     * StringUtils.ordinalIndexOf("aabaabaa", "b", 2)  = 5
+     * StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
+     * StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
+     * StringUtils.ordinalIndexOf("aabaabaa", "", 1)   = 0
+     * StringUtils.ordinalIndexOf("aabaabaa", "", 2)   = 0
+     * 
+ * + *

Note that 'head(CharSequence str, int n)' may be implemented as:

+ * + *
+     *   str.substring(0, lastOrdinalIndexOf(str, "\n", n))
+     * 
+ * + * @param str the CharSequence to check, may be null + * @param searchStr the CharSequence to find, may be null + * @param ordinal the n-th {@code searchStr} to find + * @return the n-th index of the search CharSequence, + * {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input + * @since 2.1 + * @since 3.0 Changed signature from ordinalIndexOf(String, String, int) to ordinalIndexOf(CharSequence, CharSequence, int) + */ + public static int ordinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal) { + return ordinalIndexOf(str, searchStr, ordinal, false); + } + + /** + *

Finds the n-th index within a String, handling {@code null}. + * This method uses {@link String#indexOf(String)} if possible.

+ * + *

A {@code null} CharSequence will return {@code -1}.

+ * + * @param str the CharSequence to check, may be null + * @param searchStr the CharSequence to find, may be null + * @param ordinal the n-th {@code searchStr} to find + * @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf() + * @return the n-th index of the search CharSequence, + * {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input + */ + // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int) + private static int ordinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal, boolean lastIndex) { + if (str == null || searchStr == null || ordinal <= 0) { + return INDEX_NOT_FOUND; + } + if (searchStr.length() == 0) { + return lastIndex ? str.length() : 0; + } + int found = 0; + int index = lastIndex ? str.length() : INDEX_NOT_FOUND; + do { + if (lastIndex) { + index = CharSequenceUtils.lastIndexOf(str, searchStr, index - 1); + } else { + index = CharSequenceUtils.indexOf(str, searchStr, index + 1); + } + if (index < 0) { + return index; + } + found++; + } while (found < ordinal); + return index; + } + + /** + *

Case in-sensitive find of the first index within a CharSequence.

+ * + *

A {@code null} CharSequence will return {@code -1}. + * A negative start position is treated as zero. + * An empty ("") search CharSequence always matches. + * A start position greater than the string length only matches + * an empty search CharSequence.

+ * + *
+     * StringUtils.indexOfIgnoreCase(null, *)          = -1
+     * StringUtils.indexOfIgnoreCase(*, null)          = -1
+     * StringUtils.indexOfIgnoreCase("", "")           = 0
+     * StringUtils.indexOfIgnoreCase("aabaabaa", "a")  = 0
+     * StringUtils.indexOfIgnoreCase("aabaabaa", "b")  = 2
+     * StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1
+     * 
+ * + * @param str the CharSequence to check, may be null + * @param searchStr the CharSequence to find, may be null + * @return the first index of the search CharSequence, + * -1 if no match or {@code null} string input + * @since 2.5 + * @since 3.0 Changed signature from indexOfIgnoreCase(String, String) to indexOfIgnoreCase(CharSequence, CharSequence) + */ + public static int indexOfIgnoreCase(CharSequence str, CharSequence searchStr) { + return indexOfIgnoreCase(str, searchStr, 0); + } + + /** + *

Case in-sensitive find of the first index within a CharSequence + * from the specified position.

+ * + *

A {@code null} CharSequence will return {@code -1}. + * A negative start position is treated as zero. + * An empty ("") search CharSequence always matches. + * A start position greater than the string length only matches + * an empty search CharSequence.

+ * + *
+     * StringUtils.indexOfIgnoreCase(null, *, *)          = -1
+     * StringUtils.indexOfIgnoreCase(*, null, *)          = -1
+     * StringUtils.indexOfIgnoreCase("", "", 0)           = 0
+     * StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0)  = 0
+     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0)  = 2
+     * StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
+     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3)  = 5
+     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9)  = -1
+     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
+     * StringUtils.indexOfIgnoreCase("aabaabaa", "", 2)   = 2
+     * StringUtils.indexOfIgnoreCase("abc", "", 9)        = 3
+     * 
+ * + * @param str the CharSequence to check, may be null + * @param searchStr the CharSequence to find, may be null + * @param startPos the start position, negative treated as zero + * @return the first index of the search CharSequence, + * -1 if no match or {@code null} string input + * @since 2.5 + * @since 3.0 Changed signature from indexOfIgnoreCase(String, String, int) to indexOfIgnoreCase(CharSequence, CharSequence, int) + */ + public static int indexOfIgnoreCase(CharSequence str, CharSequence searchStr, int startPos) { + if (str == null || searchStr == null) { + return INDEX_NOT_FOUND; + } + if (startPos < 0) { + startPos = 0; + } + int endLimit = str.length() - searchStr.length() + 1; + if (startPos > endLimit) { + return INDEX_NOT_FOUND; + } + if (searchStr.length() == 0) { + return startPos; + } + for (int i = startPos; i < endLimit; i++) { + if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + // LastIndexOf + //----------------------------------------------------------------------- + /** + *

Finds the last index within a CharSequence, handling {@code null}. + * This method uses {@link String#lastIndexOf(int)} if possible.

+ * + *

A {@code null} or empty ("") CharSequence will return {@code -1}.

+ * + *
+     * StringUtils.lastIndexOf(null, *)         = -1
+     * StringUtils.lastIndexOf("", *)           = -1
+     * StringUtils.lastIndexOf("aabaabaa", 'a') = 7
+     * StringUtils.lastIndexOf("aabaabaa", 'b') = 5
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchChar the character to find + * @return the last index of the search character, + * -1 if no match or {@code null} string input + * @since 2.0 + * @since 3.0 Changed signature from lastIndexOf(String, int) to lastIndexOf(CharSequence, int) + */ + public static int lastIndexOf(CharSequence seq, int searchChar) { + if (isEmpty(seq)) { + return INDEX_NOT_FOUND; + } + return CharSequenceUtils.lastIndexOf(seq, searchChar, seq.length()); + } + + /** + *

Finds the last index within a CharSequence from a start position, + * handling {@code null}. + * This method uses {@link String#lastIndexOf(int, int)} if possible.

+ * + *

A {@code null} or empty ("") CharSequence will return {@code -1}. + * A negative start position returns {@code -1}. + * A start position greater than the string length searches the whole string.

+ * + *
+     * StringUtils.lastIndexOf(null, *, *)          = -1
+     * StringUtils.lastIndexOf("", *,  *)           = -1
+     * StringUtils.lastIndexOf("aabaabaa", 'b', 8)  = 5
+     * StringUtils.lastIndexOf("aabaabaa", 'b', 4)  = 2
+     * StringUtils.lastIndexOf("aabaabaa", 'b', 0)  = -1
+     * StringUtils.lastIndexOf("aabaabaa", 'b', 9)  = 5
+     * StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
+     * StringUtils.lastIndexOf("aabaabaa", 'a', 0)  = 0
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchChar the character to find + * @param startPos the start position + * @return the last index of the search character, + * -1 if no match or {@code null} string input + * @since 2.0 + * @since 3.0 Changed signature from lastIndexOf(String, int, int) to lastIndexOf(CharSequence, int, int) + */ + public static int lastIndexOf(CharSequence seq, int searchChar, int startPos) { + if (isEmpty(seq)) { + return INDEX_NOT_FOUND; + } + return CharSequenceUtils.lastIndexOf(seq, searchChar, startPos); + } + + /** + *

Finds the last index within a CharSequence, handling {@code null}. + * This method uses {@link String#lastIndexOf(String)} if possible.

+ * + *

A {@code null} CharSequence will return {@code -1}.

+ * + *
+     * StringUtils.lastIndexOf(null, *)          = -1
+     * StringUtils.lastIndexOf(*, null)          = -1
+     * StringUtils.lastIndexOf("", "")           = 0
+     * StringUtils.lastIndexOf("aabaabaa", "a")  = 7
+     * StringUtils.lastIndexOf("aabaabaa", "b")  = 5
+     * StringUtils.lastIndexOf("aabaabaa", "ab") = 4
+     * StringUtils.lastIndexOf("aabaabaa", "")   = 8
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchSeq the CharSequence to find, may be null + * @return the last index of the search String, + * -1 if no match or {@code null} string input + * @since 2.0 + * @since 3.0 Changed signature from lastIndexOf(String, String) to lastIndexOf(CharSequence, CharSequence) + */ + public static int lastIndexOf(CharSequence seq, CharSequence searchSeq) { + if (seq == null || searchSeq == null) { + return INDEX_NOT_FOUND; + } + return CharSequenceUtils.lastIndexOf(seq, searchSeq, seq.length()); + } + + /** + *

Finds the n-th last index within a String, handling {@code null}. + * This method uses {@link String#lastIndexOf(String)}.

+ * + *

A {@code null} String will return {@code -1}.

+ * + *
+     * StringUtils.lastOrdinalIndexOf(null, *, *)          = -1
+     * StringUtils.lastOrdinalIndexOf(*, null, *)          = -1
+     * StringUtils.lastOrdinalIndexOf("", "", *)           = 0
+     * StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1)  = 7
+     * StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2)  = 6
+     * StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1)  = 5
+     * StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2)  = 2
+     * StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4
+     * StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1
+     * StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1)   = 8
+     * StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2)   = 8
+     * 
+ * + *

Note that 'tail(CharSequence str, int n)' may be implemented as:

+ * + *
+     *   str.substring(lastOrdinalIndexOf(str, "\n", n) + 1)
+     * 
+ * + * @param str the CharSequence to check, may be null + * @param searchStr the CharSequence to find, may be null + * @param ordinal the n-th last {@code searchStr} to find + * @return the n-th last index of the search CharSequence, + * {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input + * @since 2.5 + * @since 3.0 Changed signature from lastOrdinalIndexOf(String, String, int) to lastOrdinalIndexOf(CharSequence, CharSequence, int) + */ + public static int lastOrdinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal) { + return ordinalIndexOf(str, searchStr, ordinal, true); + } + + /** + *

Finds the first index within a CharSequence, handling {@code null}. + * This method uses {@link String#lastIndexOf(String, int)} if possible.

+ * + *

A {@code null} CharSequence will return {@code -1}. + * A negative start position returns {@code -1}. + * An empty ("") search CharSequence always matches unless the start position is negative. + * A start position greater than the string length searches the whole string.

+ * + *
+     * StringUtils.lastIndexOf(null, *, *)          = -1
+     * StringUtils.lastIndexOf(*, null, *)          = -1
+     * StringUtils.lastIndexOf("aabaabaa", "a", 8)  = 7
+     * StringUtils.lastIndexOf("aabaabaa", "b", 8)  = 5
+     * StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
+     * StringUtils.lastIndexOf("aabaabaa", "b", 9)  = 5
+     * StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
+     * StringUtils.lastIndexOf("aabaabaa", "a", 0)  = 0
+     * StringUtils.lastIndexOf("aabaabaa", "b", 0)  = -1
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchSeq the CharSequence to find, may be null + * @param startPos the start position, negative treated as zero + * @return the first index of the search CharSequence, + * -1 if no match or {@code null} string input + * @since 2.0 + * @since 3.0 Changed signature from lastIndexOf(String, String, int) to lastIndexOf(CharSequence, CharSequence, int) + */ + public static int lastIndexOf(CharSequence seq, CharSequence searchSeq, int startPos) { + if (seq == null || searchSeq == null) { + return INDEX_NOT_FOUND; + } + return CharSequenceUtils.lastIndexOf(seq, searchSeq, startPos); + } + + /** + *

Case in-sensitive find of the last index within a CharSequence.

+ * + *

A {@code null} CharSequence will return {@code -1}. + * A negative start position returns {@code -1}. + * An empty ("") search CharSequence always matches unless the start position is negative. + * A start position greater than the string length searches the whole string.

+ * + *
+     * StringUtils.lastIndexOfIgnoreCase(null, *)          = -1
+     * StringUtils.lastIndexOfIgnoreCase(*, null)          = -1
+     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A")  = 7
+     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B")  = 5
+     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4
+     * 
+ * + * @param str the CharSequence to check, may be null + * @param searchStr the CharSequence to find, may be null + * @return the first index of the search CharSequence, + * -1 if no match or {@code null} string input + * @since 2.5 + * @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String) to lastIndexOfIgnoreCase(CharSequence, CharSequence) + */ + public static int lastIndexOfIgnoreCase(CharSequence str, CharSequence searchStr) { + if (str == null || searchStr == null) { + return INDEX_NOT_FOUND; + } + return lastIndexOfIgnoreCase(str, searchStr, str.length()); + } + + /** + *

Case in-sensitive find of the last index within a CharSequence + * from the specified position.

+ * + *

A {@code null} CharSequence will return {@code -1}. + * A negative start position returns {@code -1}. + * An empty ("") search CharSequence always matches unless the start position is negative. + * A start position greater than the string length searches the whole string.

+ * + *
+     * StringUtils.lastIndexOfIgnoreCase(null, *, *)          = -1
+     * StringUtils.lastIndexOfIgnoreCase(*, null, *)          = -1
+     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8)  = 7
+     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8)  = 5
+     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4
+     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9)  = 5
+     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1
+     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0)  = 0
+     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0)  = -1
+     * 
+ * + * @param str the CharSequence to check, may be null + * @param searchStr the CharSequence to find, may be null + * @param startPos the start position + * @return the first index of the search CharSequence, + * -1 if no match or {@code null} input + * @since 2.5 + * @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String, int) to lastIndexOfIgnoreCase(CharSequence, CharSequence, int) + */ + public static int lastIndexOfIgnoreCase(CharSequence str, CharSequence searchStr, int startPos) { + if (str == null || searchStr == null) { + return INDEX_NOT_FOUND; + } + if (startPos > str.length() - searchStr.length()) { + startPos = str.length() - searchStr.length(); + } + if (startPos < 0) { + return INDEX_NOT_FOUND; + } + if (searchStr.length() == 0) { + return startPos; + } + + for (int i = startPos; i >= 0; i--) { + if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + // Contains + //----------------------------------------------------------------------- + /** + *

Checks if CharSequence contains a search character, handling {@code null}. + * This method uses {@link String#indexOf(int)} if possible.

+ * + *

A {@code null} or empty ("") CharSequence will return {@code false}.

+ * + *
+     * StringUtils.contains(null, *)    = false
+     * StringUtils.contains("", *)      = false
+     * StringUtils.contains("abc", 'a') = true
+     * StringUtils.contains("abc", 'z') = false
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchChar the character to find + * @return true if the CharSequence contains the search character, + * false if not or {@code null} string input + * @since 2.0 + * @since 3.0 Changed signature from contains(String, int) to contains(CharSequence, int) + */ + public static boolean contains(CharSequence seq, int searchChar) { + if (isEmpty(seq)) { + return false; + } + return CharSequenceUtils.indexOf(seq, searchChar, 0) >= 0; + } + + /** + *

Checks if CharSequence contains a search CharSequence, handling {@code null}. + * This method uses {@link String#indexOf(String)} if possible.

+ * + *

A {@code null} CharSequence will return {@code false}.

+ * + *
+     * StringUtils.contains(null, *)     = false
+     * StringUtils.contains(*, null)     = false
+     * StringUtils.contains("", "")      = true
+     * StringUtils.contains("abc", "")   = true
+     * StringUtils.contains("abc", "a")  = true
+     * StringUtils.contains("abc", "z")  = false
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchSeq the CharSequence to find, may be null + * @return true if the CharSequence contains the search CharSequence, + * false if not or {@code null} string input + * @since 2.0 + * @since 3.0 Changed signature from contains(String, String) to contains(CharSequence, CharSequence) + */ + public static boolean contains(CharSequence seq, CharSequence searchSeq) { + if (seq == null || searchSeq == null) { + return false; + } + return CharSequenceUtils.indexOf(seq, searchSeq, 0) >= 0; + } + + /** + *

Checks if CharSequence contains a search CharSequence irrespective of case, + * handling {@code null}. Case-insensitivity is defined as by + * {@link String#equalsIgnoreCase(String)}. + * + *

A {@code null} CharSequence will return {@code false}.

+ * + *
+     * StringUtils.contains(null, *) = false
+     * StringUtils.contains(*, null) = false
+     * StringUtils.contains("", "") = true
+     * StringUtils.contains("abc", "") = true
+     * StringUtils.contains("abc", "a") = true
+     * StringUtils.contains("abc", "z") = false
+     * StringUtils.contains("abc", "A") = true
+     * StringUtils.contains("abc", "Z") = false
+     * 
+ * + * @param str the CharSequence to check, may be null + * @param searchStr the CharSequence to find, may be null + * @return true if the CharSequence contains the search CharSequence irrespective of + * case or false if not or {@code null} string input + * @since 3.0 Changed signature from containsIgnoreCase(String, String) to containsIgnoreCase(CharSequence, CharSequence) + */ + public static boolean containsIgnoreCase(CharSequence str, CharSequence searchStr) { + if (str == null || searchStr == null) { + return false; + } + int len = searchStr.length(); + int max = str.length() - len; + for (int i = 0; i <= max; i++) { + if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) { + return true; + } + } + return false; + } + + /** + * Check whether the given CharSequence contains any whitespace characters. + * @param seq the CharSequence to check (may be {@code null}) + * @return {@code true} if the CharSequence is not empty and + * contains at least 1 whitespace character + * @see java.lang.Character#isWhitespace + * @since 3.0 + */ + // From org.springframework.util.StringUtils, under Apache License 2.0 + public static boolean containsWhitespace(CharSequence seq) { + if (isEmpty(seq)) { + return false; + } + int strLen = seq.length(); + for (int i = 0; i < strLen; i++) { + if (Character.isWhitespace(seq.charAt(i))) { + return true; + } + } + return false; + } + + // IndexOfAny chars + //----------------------------------------------------------------------- + /** + *

Search a CharSequence to find the first index of any + * character in the given set of characters.

+ * + *

A {@code null} String will return {@code -1}. + * A {@code null} or zero length search array will return {@code -1}.

+ * + *
+     * StringUtils.indexOfAny(null, *)                = -1
+     * StringUtils.indexOfAny("", *)                  = -1
+     * StringUtils.indexOfAny(*, null)                = -1
+     * StringUtils.indexOfAny(*, [])                  = -1
+     * StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
+     * StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
+     * StringUtils.indexOfAny("aba", ['z'])           = -1
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @param searchChars the chars to search for, may be null + * @return the index of any of the chars, -1 if no match or null input + * @since 2.0 + * @since 3.0 Changed signature from indexOfAny(String, char[]) to indexOfAny(CharSequence, char...) + */ + public static int indexOfAny(CharSequence cs, char... searchChars) { + if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { + return INDEX_NOT_FOUND; + } + int csLen = cs.length(); + int csLast = csLen - 1; + int searchLen = searchChars.length; + int searchLast = searchLen - 1; + for (int i = 0; i < csLen; i++) { + char ch = cs.charAt(i); + for (int j = 0; j < searchLen; j++) { + if (searchChars[j] == ch) { + if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) { + // ch is a supplementary character + if (searchChars[j + 1] == cs.charAt(i + 1)) { + return i; + } + } else { + return i; + } + } + } + } + return INDEX_NOT_FOUND; + } + + /** + *

Search a CharSequence to find the first index of any + * character in the given set of characters.

+ * + *

A {@code null} String will return {@code -1}. + * A {@code null} search string will return {@code -1}.

+ * + *
+     * StringUtils.indexOfAny(null, *)            = -1
+     * StringUtils.indexOfAny("", *)              = -1
+     * StringUtils.indexOfAny(*, null)            = -1
+     * StringUtils.indexOfAny(*, "")              = -1
+     * StringUtils.indexOfAny("zzabyycdxx", "za") = 0
+     * StringUtils.indexOfAny("zzabyycdxx", "by") = 3
+     * StringUtils.indexOfAny("aba","z")          = -1
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @param searchChars the chars to search for, may be null + * @return the index of any of the chars, -1 if no match or null input + * @since 2.0 + * @since 3.0 Changed signature from indexOfAny(String, String) to indexOfAny(CharSequence, String) + */ + public static int indexOfAny(CharSequence cs, String searchChars) { + if (isEmpty(cs) || isEmpty(searchChars)) { + return INDEX_NOT_FOUND; + } + return indexOfAny(cs, searchChars.toCharArray()); + } + + // ContainsAny + //----------------------------------------------------------------------- + /** + *

Checks if the CharSequence contains any character in the given + * set of characters.

+ * + *

A {@code null} CharSequence will return {@code false}. + * A {@code null} or zero length search array will return {@code false}.

+ * + *
+     * StringUtils.containsAny(null, *)                = false
+     * StringUtils.containsAny("", *)                  = false
+     * StringUtils.containsAny(*, null)                = false
+     * StringUtils.containsAny(*, [])                  = false
+     * StringUtils.containsAny("zzabyycdxx",['z','a']) = true
+     * StringUtils.containsAny("zzabyycdxx",['b','y']) = true
+     * StringUtils.containsAny("aba", ['z'])           = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @param searchChars the chars to search for, may be null + * @return the {@code true} if any of the chars are found, + * {@code false} if no match or null input + * @since 2.4 + * @since 3.0 Changed signature from containsAny(String, char[]) to containsAny(CharSequence, char...) + */ + public static boolean containsAny(CharSequence cs, char... searchChars) { + if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { + return false; + } + int csLength = cs.length(); + int searchLength = searchChars.length; + int csLast = csLength - 1; + int searchLast = searchLength - 1; + for (int i = 0; i < csLength; i++) { + char ch = cs.charAt(i); + for (int j = 0; j < searchLength; j++) { + if (searchChars[j] == ch) { + if (Character.isHighSurrogate(ch)) { + if (j == searchLast) { + // missing low surrogate, fine, like String.indexOf(String) + return true; + } + if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) { + return true; + } + } else { + // ch is in the Basic Multilingual Plane + return true; + } + } + } + } + return false; + } + + /** + *

+ * Checks if the CharSequence contains any character in the given set of characters. + *

+ * + *

+ * A {@code null} CharSequence will return {@code false}. A {@code null} search CharSequence will return + * {@code false}. + *

+ * + *
+     * StringUtils.containsAny(null, *)            = false
+     * StringUtils.containsAny("", *)              = false
+     * StringUtils.containsAny(*, null)            = false
+     * StringUtils.containsAny(*, "")              = false
+     * StringUtils.containsAny("zzabyycdxx", "za") = true
+     * StringUtils.containsAny("zzabyycdxx", "by") = true
+     * StringUtils.containsAny("aba","z")          = false
+     * 
+ * + * @param cs + * the CharSequence to check, may be null + * @param searchChars + * the chars to search for, may be null + * @return the {@code true} if any of the chars are found, {@code false} if no match or null input + * @since 2.4 + * @since 3.0 Changed signature from containsAny(String, String) to containsAny(CharSequence, CharSequence) + */ + public static boolean containsAny(CharSequence cs, CharSequence searchChars) { + if (searchChars == null) { + return false; + } + return containsAny(cs, CharSequenceUtils.toCharArray(searchChars)); + } + + // IndexOfAnyBut chars + //----------------------------------------------------------------------- + /** + *

Searches a CharSequence to find the first index of any + * character not in the given set of characters.

+ * + *

A {@code null} CharSequence will return {@code -1}. + * A {@code null} or zero length search array will return {@code -1}.

+ * + *
+     * StringUtils.indexOfAnyBut(null, *)                              = -1
+     * StringUtils.indexOfAnyBut("", *)                                = -1
+     * StringUtils.indexOfAnyBut(*, null)                              = -1
+     * StringUtils.indexOfAnyBut(*, [])                                = -1
+     * StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z', 'a'} ) = 3
+     * StringUtils.indexOfAnyBut("aba", new char[] {'z'} )             = 0
+     * StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'} )        = -1
+
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @param searchChars the chars to search for, may be null + * @return the index of any of the chars, -1 if no match or null input + * @since 2.0 + * @since 3.0 Changed signature from indexOfAnyBut(String, char[]) to indexOfAnyBut(CharSequence, char...) + */ + public static int indexOfAnyBut(CharSequence cs, char... searchChars) { + if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { + return INDEX_NOT_FOUND; + } + int csLen = cs.length(); + int csLast = csLen - 1; + int searchLen = searchChars.length; + int searchLast = searchLen - 1; + outer: + for (int i = 0; i < csLen; i++) { + char ch = cs.charAt(i); + for (int j = 0; j < searchLen; j++) { + if (searchChars[j] == ch) { + if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) { + if (searchChars[j + 1] == cs.charAt(i + 1)) { + continue outer; + } + } else { + continue outer; + } + } + } + return i; + } + return INDEX_NOT_FOUND; + } + + /** + *

Search a CharSequence to find the first index of any + * character not in the given set of characters.

+ * + *

A {@code null} CharSequence will return {@code -1}. + * A {@code null} or empty search string will return {@code -1}.

+ * + *
+     * StringUtils.indexOfAnyBut(null, *)            = -1
+     * StringUtils.indexOfAnyBut("", *)              = -1
+     * StringUtils.indexOfAnyBut(*, null)            = -1
+     * StringUtils.indexOfAnyBut(*, "")              = -1
+     * StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
+     * StringUtils.indexOfAnyBut("zzabyycdxx", "")   = -1
+     * StringUtils.indexOfAnyBut("aba","ab")         = -1
+     * 
+ * + * @param seq the CharSequence to check, may be null + * @param searchChars the chars to search for, may be null + * @return the index of any of the chars, -1 if no match or null input + * @since 2.0 + * @since 3.0 Changed signature from indexOfAnyBut(String, String) to indexOfAnyBut(CharSequence, CharSequence) + */ + public static int indexOfAnyBut(CharSequence seq, CharSequence searchChars) { + if (isEmpty(seq) || isEmpty(searchChars)) { + return INDEX_NOT_FOUND; + } + int strLen = seq.length(); + for (int i = 0; i < strLen; i++) { + char ch = seq.charAt(i); + boolean chFound = CharSequenceUtils.indexOf(searchChars, ch, 0) >= 0; + if (i + 1 < strLen && Character.isHighSurrogate(ch)) { + char ch2 = seq.charAt(i + 1); + if (chFound && CharSequenceUtils.indexOf(searchChars, ch2, 0) < 0) { + return i; + } + } else { + if (!chFound) { + return i; + } + } + } + return INDEX_NOT_FOUND; + } + + // ContainsOnly + //----------------------------------------------------------------------- + /** + *

Checks if the CharSequence contains only certain characters.

+ * + *

A {@code null} CharSequence will return {@code false}. + * A {@code null} valid character array will return {@code false}. + * An empty CharSequence (length()=0) always returns {@code true}.

+ * + *
+     * StringUtils.containsOnly(null, *)       = false
+     * StringUtils.containsOnly(*, null)       = false
+     * StringUtils.containsOnly("", *)         = true
+     * StringUtils.containsOnly("ab", '')      = false
+     * StringUtils.containsOnly("abab", 'abc') = true
+     * StringUtils.containsOnly("ab1", 'abc')  = false
+     * StringUtils.containsOnly("abz", 'abc')  = false
+     * 
+ * + * @param cs the String to check, may be null + * @param valid an array of valid chars, may be null + * @return true if it only contains valid chars and is non-null + * @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...) + */ + public static boolean containsOnly(CharSequence cs, char... valid) { + // All these pre-checks are to maintain API with an older version + if (valid == null || cs == null) { + return false; + } + if (cs.length() == 0) { + return true; + } + if (valid.length == 0) { + return false; + } + return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND; + } + + /** + *

Checks if the CharSequence contains only certain characters.

+ * + *

A {@code null} CharSequence will return {@code false}. + * A {@code null} valid character String will return {@code false}. + * An empty String (length()=0) always returns {@code true}.

+ * + *
+     * StringUtils.containsOnly(null, *)       = false
+     * StringUtils.containsOnly(*, null)       = false
+     * StringUtils.containsOnly("", *)         = true
+     * StringUtils.containsOnly("ab", "")      = false
+     * StringUtils.containsOnly("abab", "abc") = true
+     * StringUtils.containsOnly("ab1", "abc")  = false
+     * StringUtils.containsOnly("abz", "abc")  = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @param validChars a String of valid chars, may be null + * @return true if it only contains valid chars and is non-null + * @since 2.0 + * @since 3.0 Changed signature from containsOnly(String, String) to containsOnly(CharSequence, String) + */ + public static boolean containsOnly(CharSequence cs, String validChars) { + if (cs == null || validChars == null) { + return false; + } + return containsOnly(cs, validChars.toCharArray()); + } + + // ContainsNone + //----------------------------------------------------------------------- + /** + *

Checks that the CharSequence does not contain certain characters.

+ * + *

A {@code null} CharSequence will return {@code true}. + * A {@code null} invalid character array will return {@code true}. + * An empty CharSequence (length()=0) always returns true.

+ * + *
+     * StringUtils.containsNone(null, *)       = true
+     * StringUtils.containsNone(*, null)       = true
+     * StringUtils.containsNone("", *)         = true
+     * StringUtils.containsNone("ab", '')      = true
+     * StringUtils.containsNone("abab", 'xyz') = true
+     * StringUtils.containsNone("ab1", 'xyz')  = true
+     * StringUtils.containsNone("abz", 'xyz')  = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @param searchChars an array of invalid chars, may be null + * @return true if it contains none of the invalid chars, or is null + * @since 2.0 + * @since 3.0 Changed signature from containsNone(String, char[]) to containsNone(CharSequence, char...) + */ + public static boolean containsNone(CharSequence cs, char... searchChars) { + if (cs == null || searchChars == null) { + return true; + } + int csLen = cs.length(); + int csLast = csLen - 1; + int searchLen = searchChars.length; + int searchLast = searchLen - 1; + for (int i = 0; i < csLen; i++) { + char ch = cs.charAt(i); + for (int j = 0; j < searchLen; j++) { + if (searchChars[j] == ch) { + if (Character.isHighSurrogate(ch)) { + if (j == searchLast) { + // missing low surrogate, fine, like String.indexOf(String) + return false; + } + if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) { + return false; + } + } else { + // ch is in the Basic Multilingual Plane + return false; + } + } + } + } + return true; + } + + /** + *

Checks that the CharSequence does not contain certain characters.

+ * + *

A {@code null} CharSequence will return {@code true}. + * A {@code null} invalid character array will return {@code true}. + * An empty String ("") always returns true.

+ * + *
+     * StringUtils.containsNone(null, *)       = true
+     * StringUtils.containsNone(*, null)       = true
+     * StringUtils.containsNone("", *)         = true
+     * StringUtils.containsNone("ab", "")      = true
+     * StringUtils.containsNone("abab", "xyz") = true
+     * StringUtils.containsNone("ab1", "xyz")  = true
+     * StringUtils.containsNone("abz", "xyz")  = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @param invalidChars a String of invalid chars, may be null + * @return true if it contains none of the invalid chars, or is null + * @since 2.0 + * @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String) + */ + public static boolean containsNone(CharSequence cs, String invalidChars) { + if (cs == null || invalidChars == null) { + return true; + } + return containsNone(cs, invalidChars.toCharArray()); + } + + // IndexOfAny strings + //----------------------------------------------------------------------- + /** + *

Find the first index of any of a set of potential substrings.

+ * + *

A {@code null} CharSequence will return {@code -1}. + * A {@code null} or zero length search array will return {@code -1}. + * A {@code null} search array entry will be ignored, but a search + * array containing "" will return {@code 0} if {@code str} is not + * null. This method uses {@link String#indexOf(String)} if possible.

+ * + *
+     * StringUtils.indexOfAny(null, *)                     = -1
+     * StringUtils.indexOfAny(*, null)                     = -1
+     * StringUtils.indexOfAny(*, [])                       = -1
+     * StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"])   = 2
+     * StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"])   = 2
+     * StringUtils.indexOfAny("zzabyycdxx", ["mn","op"])   = -1
+     * StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
+     * StringUtils.indexOfAny("zzabyycdxx", [""])          = 0
+     * StringUtils.indexOfAny("", [""])                    = 0
+     * StringUtils.indexOfAny("", ["a"])                   = -1
+     * 
+ * + * @param str the CharSequence to check, may be null + * @param searchStrs the CharSequences to search for, may be null + * @return the first index of any of the searchStrs in str, -1 if no match + * @since 3.0 Changed signature from indexOfAny(String, String[]) to indexOfAny(CharSequence, CharSequence...) + */ + public static int indexOfAny(CharSequence str, CharSequence... searchStrs) { + if (str == null || searchStrs == null) { + return INDEX_NOT_FOUND; + } + int sz = searchStrs.length; + + // String's can't have a MAX_VALUEth index. + int ret = Integer.MAX_VALUE; + + int tmp = 0; + for (int i = 0; i < sz; i++) { + CharSequence search = searchStrs[i]; + if (search == null) { + continue; + } + tmp = CharSequenceUtils.indexOf(str, search, 0); + if (tmp == INDEX_NOT_FOUND) { + continue; + } + + if (tmp < ret) { + ret = tmp; + } + } + + return ret == Integer.MAX_VALUE ? INDEX_NOT_FOUND : ret; + } + + /** + *

Find the latest index of any of a set of potential substrings.

+ * + *

A {@code null} CharSequence will return {@code -1}. + * A {@code null} search array will return {@code -1}. + * A {@code null} or zero length search array entry will be ignored, + * but a search array containing "" will return the length of {@code str} + * if {@code str} is not null. This method uses {@link String#indexOf(String)} if possible

+ * + *
+     * StringUtils.lastIndexOfAny(null, *)                   = -1
+     * StringUtils.lastIndexOfAny(*, null)                   = -1
+     * StringUtils.lastIndexOfAny(*, [])                     = -1
+     * StringUtils.lastIndexOfAny(*, [null])                 = -1
+     * StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
+     * StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
+     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
+     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
+     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""])   = 10
+     * 
+ * + * @param str the CharSequence to check, may be null + * @param searchStrs the CharSequences to search for, may be null + * @return the last index of any of the CharSequences, -1 if no match + * @since 3.0 Changed signature from lastIndexOfAny(String, String[]) to lastIndexOfAny(CharSequence, CharSequence) + */ + public static int lastIndexOfAny(CharSequence str, CharSequence... searchStrs) { + if (str == null || searchStrs == null) { + return INDEX_NOT_FOUND; + } + int sz = searchStrs.length; + int ret = INDEX_NOT_FOUND; + int tmp = 0; + for (int i = 0; i < sz; i++) { + CharSequence search = searchStrs[i]; + if (search == null) { + continue; + } + tmp = CharSequenceUtils.lastIndexOf(str, search, str.length()); + if (tmp > ret) { + ret = tmp; + } + } + return ret; + } + + // Substring + //----------------------------------------------------------------------- + /** + *

Gets a substring from the specified String avoiding exceptions.

+ * + *

A negative start position can be used to start {@code n} + * characters from the end of the String.

+ * + *

A {@code null} String will return {@code null}. + * An empty ("") String will return "".

+ * + *
+     * StringUtils.substring(null, *)   = null
+     * StringUtils.substring("", *)     = ""
+     * StringUtils.substring("abc", 0)  = "abc"
+     * StringUtils.substring("abc", 2)  = "c"
+     * StringUtils.substring("abc", 4)  = ""
+     * StringUtils.substring("abc", -2) = "bc"
+     * StringUtils.substring("abc", -4) = "abc"
+     * 
+ * + * @param str the String to get the substring from, may be null + * @param start the position to start from, negative means + * count back from the end of the String by this many characters + * @return substring from start position, {@code null} if null String input + */ + public static String substring(String str, int start) { + if (str == null) { + return null; + } + + // handle negatives, which means last n characters + if (start < 0) { + start = str.length() + start; // remember start is negative + } + + if (start < 0) { + start = 0; + } + if (start > str.length()) { + return EMPTY; + } + + return str.substring(start); + } + + /** + *

Gets a substring from the specified String avoiding exceptions.

+ * + *

A negative start position can be used to start/end {@code n} + * characters from the end of the String.

+ * + *

The returned substring starts with the character in the {@code start} + * position and ends before the {@code end} position. All position counting is + * zero-based -- i.e., to start at the beginning of the string use + * {@code start = 0}. Negative start and end positions can be used to + * specify offsets relative to the end of the String.

+ * + *

If {@code start} is not strictly to the left of {@code end}, "" + * is returned.

+ * + *
+     * StringUtils.substring(null, *, *)    = null
+     * StringUtils.substring("", * ,  *)    = "";
+     * StringUtils.substring("abc", 0, 2)   = "ab"
+     * StringUtils.substring("abc", 2, 0)   = ""
+     * StringUtils.substring("abc", 2, 4)   = "c"
+     * StringUtils.substring("abc", 4, 6)   = ""
+     * StringUtils.substring("abc", 2, 2)   = ""
+     * StringUtils.substring("abc", -2, -1) = "b"
+     * StringUtils.substring("abc", -4, 2)  = "ab"
+     * 
+ * + * @param str the String to get the substring from, may be null + * @param start the position to start from, negative means + * count back from the end of the String by this many characters + * @param end the position to end at (exclusive), negative means + * count back from the end of the String by this many characters + * @return substring from start position to end position, + * {@code null} if null String input + */ + public static String substring(String str, int start, int end) { + if (str == null) { + return null; + } + + // handle negatives + if (end < 0) { + end = str.length() + end; // remember end is negative + } + if (start < 0) { + start = str.length() + start; // remember start is negative + } + + // check length next + if (end > str.length()) { + end = str.length(); + } + + // if start is greater than end, return "" + if (start > end) { + return EMPTY; + } + + if (start < 0) { + start = 0; + } + if (end < 0) { + end = 0; + } + + return str.substring(start, end); + } + + // Left/Right/Mid + //----------------------------------------------------------------------- + /** + *

Gets the leftmost {@code len} characters of a String.

+ * + *

If {@code len} characters are not available, or the + * String is {@code null}, the String will be returned without + * an exception. An empty String is returned if len is negative.

+ * + *
+     * StringUtils.left(null, *)    = null
+     * StringUtils.left(*, -ve)     = ""
+     * StringUtils.left("", *)      = ""
+     * StringUtils.left("abc", 0)   = ""
+     * StringUtils.left("abc", 2)   = "ab"
+     * StringUtils.left("abc", 4)   = "abc"
+     * 
+ * + * @param str the String to get the leftmost characters from, may be null + * @param len the length of the required String + * @return the leftmost characters, {@code null} if null String input + */ + public static String left(String str, int len) { + if (str == null) { + return null; + } + if (len < 0) { + return EMPTY; + } + if (str.length() <= len) { + return str; + } + return str.substring(0, len); + } + + /** + *

Gets the rightmost {@code len} characters of a String.

+ * + *

If {@code len} characters are not available, or the String + * is {@code null}, the String will be returned without an + * an exception. An empty String is returned if len is negative.

+ * + *
+     * StringUtils.right(null, *)    = null
+     * StringUtils.right(*, -ve)     = ""
+     * StringUtils.right("", *)      = ""
+     * StringUtils.right("abc", 0)   = ""
+     * StringUtils.right("abc", 2)   = "bc"
+     * StringUtils.right("abc", 4)   = "abc"
+     * 
+ * + * @param str the String to get the rightmost characters from, may be null + * @param len the length of the required String + * @return the rightmost characters, {@code null} if null String input + */ + public static String right(String str, int len) { + if (str == null) { + return null; + } + if (len < 0) { + return EMPTY; + } + if (str.length() <= len) { + return str; + } + return str.substring(str.length() - len); + } + + /** + *

Gets {@code len} characters from the middle of a String.

+ * + *

If {@code len} characters are not available, the remainder + * of the String will be returned without an exception. If the + * String is {@code null}, {@code null} will be returned. + * An empty String is returned if len is negative or exceeds the + * length of {@code str}.

+ * + *
+     * StringUtils.mid(null, *, *)    = null
+     * StringUtils.mid(*, *, -ve)     = ""
+     * StringUtils.mid("", 0, *)      = ""
+     * StringUtils.mid("abc", 0, 2)   = "ab"
+     * StringUtils.mid("abc", 0, 4)   = "abc"
+     * StringUtils.mid("abc", 2, 4)   = "c"
+     * StringUtils.mid("abc", 4, 2)   = ""
+     * StringUtils.mid("abc", -2, 2)  = "ab"
+     * 
+ * + * @param str the String to get the characters from, may be null + * @param pos the position to start from, negative treated as zero + * @param len the length of the required String + * @return the middle characters, {@code null} if null String input + */ + public static String mid(String str, int pos, int len) { + if (str == null) { + return null; + } + if (len < 0 || pos > str.length()) { + return EMPTY; + } + if (pos < 0) { + pos = 0; + } + if (str.length() <= pos + len) { + return str.substring(pos); + } + return str.substring(pos, pos + len); + } + + // SubStringAfter/SubStringBefore + //----------------------------------------------------------------------- + /** + *

Gets the substring before the first occurrence of a separator. + * The separator is not returned.

+ * + *

A {@code null} string input will return {@code null}. + * An empty ("") string input will return the empty string. + * A {@code null} separator will return the input string.

+ * + *

If nothing is found, the string input is returned.

+ * + *
+     * StringUtils.substringBefore(null, *)      = null
+     * StringUtils.substringBefore("", *)        = ""
+     * StringUtils.substringBefore("abc", "a")   = ""
+     * StringUtils.substringBefore("abcba", "b") = "a"
+     * StringUtils.substringBefore("abc", "c")   = "ab"
+     * StringUtils.substringBefore("abc", "d")   = "abc"
+     * StringUtils.substringBefore("abc", "")    = ""
+     * StringUtils.substringBefore("abc", null)  = "abc"
+     * 
+ * + * @param str the String to get a substring from, may be null + * @param separator the String to search for, may be null + * @return the substring before the first occurrence of the separator, + * {@code null} if null String input + * @since 2.0 + */ + public static String substringBefore(String str, String separator) { + if (isEmpty(str) || separator == null) { + return str; + } + if (separator.length() == 0) { + return EMPTY; + } + int pos = str.indexOf(separator); + if (pos == INDEX_NOT_FOUND) { + return str; + } + return str.substring(0, pos); + } + + /** + *

Gets the substring after the first occurrence of a separator. + * The separator is not returned.

+ * + *

A {@code null} string input will return {@code null}. + * An empty ("") string input will return the empty string. + * A {@code null} separator will return the empty string if the + * input string is not {@code null}.

+ * + *

If nothing is found, the empty string is returned.

+ * + *
+     * StringUtils.substringAfter(null, *)      = null
+     * StringUtils.substringAfter("", *)        = ""
+     * StringUtils.substringAfter(*, null)      = ""
+     * StringUtils.substringAfter("abc", "a")   = "bc"
+     * StringUtils.substringAfter("abcba", "b") = "cba"
+     * StringUtils.substringAfter("abc", "c")   = ""
+     * StringUtils.substringAfter("abc", "d")   = ""
+     * StringUtils.substringAfter("abc", "")    = "abc"
+     * 
+ * + * @param str the String to get a substring from, may be null + * @param separator the String to search for, may be null + * @return the substring after the first occurrence of the separator, + * {@code null} if null String input + * @since 2.0 + */ + public static String substringAfter(String str, String separator) { + if (isEmpty(str)) { + return str; + } + if (separator == null) { + return EMPTY; + } + int pos = str.indexOf(separator); + if (pos == INDEX_NOT_FOUND) { + return EMPTY; + } + return str.substring(pos + separator.length()); + } + + /** + *

Gets the substring before the last occurrence of a separator. + * The separator is not returned.

+ * + *

A {@code null} string input will return {@code null}. + * An empty ("") string input will return the empty string. + * An empty or {@code null} separator will return the input string.

+ * + *

If nothing is found, the string input is returned.

+ * + *
+     * StringUtils.substringBeforeLast(null, *)      = null
+     * StringUtils.substringBeforeLast("", *)        = ""
+     * StringUtils.substringBeforeLast("abcba", "b") = "abc"
+     * StringUtils.substringBeforeLast("abc", "c")   = "ab"
+     * StringUtils.substringBeforeLast("a", "a")     = ""
+     * StringUtils.substringBeforeLast("a", "z")     = "a"
+     * StringUtils.substringBeforeLast("a", null)    = "a"
+     * StringUtils.substringBeforeLast("a", "")      = "a"
+     * 
+ * + * @param str the String to get a substring from, may be null + * @param separator the String to search for, may be null + * @return the substring before the last occurrence of the separator, + * {@code null} if null String input + * @since 2.0 + */ + public static String substringBeforeLast(String str, String separator) { + if (isEmpty(str) || isEmpty(separator)) { + return str; + } + int pos = str.lastIndexOf(separator); + if (pos == INDEX_NOT_FOUND) { + return str; + } + return str.substring(0, pos); + } + + /** + *

Gets the substring after the last occurrence of a separator. + * The separator is not returned.

+ * + *

A {@code null} string input will return {@code null}. + * An empty ("") string input will return the empty string. + * An empty or {@code null} separator will return the empty string if + * the input string is not {@code null}.

+ * + *

If nothing is found, the empty string is returned.

+ * + *
+     * StringUtils.substringAfterLast(null, *)      = null
+     * StringUtils.substringAfterLast("", *)        = ""
+     * StringUtils.substringAfterLast(*, "")        = ""
+     * StringUtils.substringAfterLast(*, null)      = ""
+     * StringUtils.substringAfterLast("abc", "a")   = "bc"
+     * StringUtils.substringAfterLast("abcba", "b") = "a"
+     * StringUtils.substringAfterLast("abc", "c")   = ""
+     * StringUtils.substringAfterLast("a", "a")     = ""
+     * StringUtils.substringAfterLast("a", "z")     = ""
+     * 
+ * + * @param str the String to get a substring from, may be null + * @param separator the String to search for, may be null + * @return the substring after the last occurrence of the separator, + * {@code null} if null String input + * @since 2.0 + */ + public static String substringAfterLast(String str, String separator) { + if (isEmpty(str)) { + return str; + } + if (isEmpty(separator)) { + return EMPTY; + } + int pos = str.lastIndexOf(separator); + if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) { + return EMPTY; + } + return str.substring(pos + separator.length()); + } + + // Substring between + //----------------------------------------------------------------------- + /** + *

Gets the String that is nested in between two instances of the + * same String.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} tag returns {@code null}.

+ * + *
+     * StringUtils.substringBetween(null, *)            = null
+     * StringUtils.substringBetween("", "")             = ""
+     * StringUtils.substringBetween("", "tag")          = null
+     * StringUtils.substringBetween("tagabctag", null)  = null
+     * StringUtils.substringBetween("tagabctag", "")    = ""
+     * StringUtils.substringBetween("tagabctag", "tag") = "abc"
+     * 
+ * + * @param str the String containing the substring, may be null + * @param tag the String before and after the substring, may be null + * @return the substring, {@code null} if no match + * @since 2.0 + */ + public static String substringBetween(String str, String tag) { + return substringBetween(str, tag, tag); + } + + /** + *

Gets the String that is nested in between two Strings. + * Only the first match is returned.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} open/close returns {@code null} (no match). + * An empty ("") open and close returns an empty string.

+ * + *
+     * StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
+     * StringUtils.substringBetween(null, *, *)          = null
+     * StringUtils.substringBetween(*, null, *)          = null
+     * StringUtils.substringBetween(*, *, null)          = null
+     * StringUtils.substringBetween("", "", "")          = ""
+     * StringUtils.substringBetween("", "", "]")         = null
+     * StringUtils.substringBetween("", "[", "]")        = null
+     * StringUtils.substringBetween("yabcz", "", "")     = ""
+     * StringUtils.substringBetween("yabcz", "y", "z")   = "abc"
+     * StringUtils.substringBetween("yabczyabcz", "y", "z")   = "abc"
+     * 
+ * + * @param str the String containing the substring, may be null + * @param open the String before the substring, may be null + * @param close the String after the substring, may be null + * @return the substring, {@code null} if no match + * @since 2.0 + */ + public static String substringBetween(String str, String open, String close) { + if (str == null || open == null || close == null) { + return null; + } + int start = str.indexOf(open); + if (start != INDEX_NOT_FOUND) { + int end = str.indexOf(close, start + open.length()); + if (end != INDEX_NOT_FOUND) { + return str.substring(start + open.length(), end); + } + } + return null; + } + + /** + *

Searches a String for substrings delimited by a start and end tag, + * returning all matching substrings in an array.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} open/close returns {@code null} (no match). + * An empty ("") open/close returns {@code null} (no match).

+ * + *
+     * StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
+     * StringUtils.substringsBetween(null, *, *)            = null
+     * StringUtils.substringsBetween(*, null, *)            = null
+     * StringUtils.substringsBetween(*, *, null)            = null
+     * StringUtils.substringsBetween("", "[", "]")          = []
+     * 
+ * + * @param str the String containing the substrings, null returns null, empty returns empty + * @param open the String identifying the start of the substring, empty returns null + * @param close the String identifying the end of the substring, empty returns null + * @return a String Array of substrings, or {@code null} if no match + * @since 2.3 + */ + public static String[] substringsBetween(String str, String open, String close) { + if (str == null || isEmpty(open) || isEmpty(close)) { + return null; + } + int strLen = str.length(); + if (strLen == 0) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + int closeLen = close.length(); + int openLen = open.length(); + List list = new ArrayList(); + int pos = 0; + while (pos < strLen - closeLen) { + int start = str.indexOf(open, pos); + if (start < 0) { + break; + } + start += openLen; + int end = str.indexOf(close, start); + if (end < 0) { + break; + } + list.add(str.substring(start, end)); + pos = end + closeLen; + } + if (list.isEmpty()) { + return null; + } + return list.toArray(new String [list.size()]); + } + + // Nested extraction + //----------------------------------------------------------------------- + + // Splitting + //----------------------------------------------------------------------- + /** + *

Splits the provided text into an array, using whitespace as the + * separator. + * Whitespace is defined by {@link Character#isWhitespace(char)}.

+ * + *

The separator is not included in the returned String array. + * Adjacent separators are treated as one separator. + * For more control over the split use the StrTokenizer class.

+ * + *

A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.split(null)       = null
+     * StringUtils.split("")         = []
+     * StringUtils.split("abc def")  = ["abc", "def"]
+     * StringUtils.split("abc  def") = ["abc", "def"]
+     * StringUtils.split(" abc ")    = ["abc"]
+     * 
+ * + * @param str the String to parse, may be null + * @return an array of parsed Strings, {@code null} if null String input + */ + public static String[] split(String str) { + return split(str, null, -1); + } + + /** + *

Splits the provided text into an array, separator specified. + * This is an alternative to using StringTokenizer.

+ * + *

The separator is not included in the returned String array. + * Adjacent separators are treated as one separator. + * For more control over the split use the StrTokenizer class.

+ * + *

A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.split(null, *)         = null
+     * StringUtils.split("", *)           = []
+     * StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
+     * StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
+     * StringUtils.split("a:b:c", '.')    = ["a:b:c"]
+     * StringUtils.split("a b c", ' ')    = ["a", "b", "c"]
+     * 
+ * + * @param str the String to parse, may be null + * @param separatorChar the character used as the delimiter + * @return an array of parsed Strings, {@code null} if null String input + * @since 2.0 + */ + public static String[] split(String str, char separatorChar) { + return splitWorker(str, separatorChar, false); + } + + /** + *

Splits the provided text into an array, separators specified. + * This is an alternative to using StringTokenizer.

+ * + *

The separator is not included in the returned String array. + * Adjacent separators are treated as one separator. + * For more control over the split use the StrTokenizer class.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} separatorChars splits on whitespace.

+ * + *
+     * StringUtils.split(null, *)         = null
+     * StringUtils.split("", *)           = []
+     * StringUtils.split("abc def", null) = ["abc", "def"]
+     * StringUtils.split("abc def", " ")  = ["abc", "def"]
+     * StringUtils.split("abc  def", " ") = ["abc", "def"]
+     * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
+     * 
+ * + * @param str the String to parse, may be null + * @param separatorChars the characters used as the delimiters, + * {@code null} splits on whitespace + * @return an array of parsed Strings, {@code null} if null String input + */ + public static String[] split(String str, String separatorChars) { + return splitWorker(str, separatorChars, -1, false); + } + + /** + *

Splits the provided text into an array with a maximum length, + * separators specified.

+ * + *

The separator is not included in the returned String array. + * Adjacent separators are treated as one separator.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} separatorChars splits on whitespace.

+ * + *

If more than {@code max} delimited substrings are found, the last + * returned string includes all characters after the first {@code max - 1} + * returned strings (including separator characters).

+ * + *
+     * StringUtils.split(null, *, *)            = null
+     * StringUtils.split("", *, *)              = []
+     * StringUtils.split("ab de fg", null, 0)   = ["ab", "cd", "ef"]
+     * StringUtils.split("ab   de fg", null, 0) = ["ab", "cd", "ef"]
+     * StringUtils.split("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
+     * StringUtils.split("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
+     * 
+ * + * @param str the String to parse, may be null + * @param separatorChars the characters used as the delimiters, + * {@code null} splits on whitespace + * @param max the maximum number of elements to include in the + * array. A zero or negative value implies no limit + * @return an array of parsed Strings, {@code null} if null String input + */ + public static String[] split(String str, String separatorChars, int max) { + return splitWorker(str, separatorChars, max, false); + } + + /** + *

Splits the provided text into an array, separator string specified.

+ * + *

The separator(s) will not be included in the returned String array. + * Adjacent separators are treated as one separator.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} separator splits on whitespace.

+ * + *
+     * StringUtils.splitByWholeSeparator(null, *)               = null
+     * StringUtils.splitByWholeSeparator("", *)                 = []
+     * StringUtils.splitByWholeSeparator("ab de fg", null)      = ["ab", "de", "fg"]
+     * StringUtils.splitByWholeSeparator("ab   de fg", null)    = ["ab", "de", "fg"]
+     * StringUtils.splitByWholeSeparator("ab:cd:ef", ":")       = ["ab", "cd", "ef"]
+     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
+     * 
+ * + * @param str the String to parse, may be null + * @param separator String containing the String to be used as a delimiter, + * {@code null} splits on whitespace + * @return an array of parsed Strings, {@code null} if null String was input + */ + public static String[] splitByWholeSeparator(String str, String separator) { + return splitByWholeSeparatorWorker( str, separator, -1, false ) ; + } + + /** + *

Splits the provided text into an array, separator string specified. + * Returns a maximum of {@code max} substrings.

+ * + *

The separator(s) will not be included in the returned String array. + * Adjacent separators are treated as one separator.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} separator splits on whitespace.

+ * + *
+     * StringUtils.splitByWholeSeparator(null, *, *)               = null
+     * StringUtils.splitByWholeSeparator("", *, *)                 = []
+     * StringUtils.splitByWholeSeparator("ab de fg", null, 0)      = ["ab", "de", "fg"]
+     * StringUtils.splitByWholeSeparator("ab   de fg", null, 0)    = ["ab", "de", "fg"]
+     * StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2)       = ["ab", "cd:ef"]
+     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
+     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
+     * 
+ * + * @param str the String to parse, may be null + * @param separator String containing the String to be used as a delimiter, + * {@code null} splits on whitespace + * @param max the maximum number of elements to include in the returned + * array. A zero or negative value implies no limit. + * @return an array of parsed Strings, {@code null} if null String was input + */ + public static String[] splitByWholeSeparator( String str, String separator, int max ) { + return splitByWholeSeparatorWorker(str, separator, max, false); + } + + /** + *

Splits the provided text into an array, separator string specified.

+ * + *

The separator is not included in the returned String array. + * Adjacent separators are treated as separators for empty tokens. + * For more control over the split use the StrTokenizer class.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} separator splits on whitespace.

+ * + *
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *)               = null
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("", *)                 = []
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null)      = ["ab", "de", "fg"]
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab   de fg", null)    = ["ab", "", "", "de", "fg"]
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":")       = ["ab", "cd", "ef"]
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
+     * 
+ * + * @param str the String to parse, may be null + * @param separator String containing the String to be used as a delimiter, + * {@code null} splits on whitespace + * @return an array of parsed Strings, {@code null} if null String was input + * @since 2.4 + */ + public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator) { + return splitByWholeSeparatorWorker(str, separator, -1, true); + } + + /** + *

Splits the provided text into an array, separator string specified. + * Returns a maximum of {@code max} substrings.

+ * + *

The separator is not included in the returned String array. + * Adjacent separators are treated as separators for empty tokens. + * For more control over the split use the StrTokenizer class.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} separator splits on whitespace.

+ * + *
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *)               = null
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *)                 = []
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0)      = ["ab", "de", "fg"]
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab   de fg", null, 0)    = ["ab", "", "", "de", "fg"]
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2)       = ["ab", "cd:ef"]
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
+     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
+     * 
+ * + * @param str the String to parse, may be null + * @param separator String containing the String to be used as a delimiter, + * {@code null} splits on whitespace + * @param max the maximum number of elements to include in the returned + * array. A zero or negative value implies no limit. + * @return an array of parsed Strings, {@code null} if null String was input + * @since 2.4 + */ + public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator, int max) { + return splitByWholeSeparatorWorker(str, separator, max, true); + } + + /** + * Performs the logic for the {@code splitByWholeSeparatorPreserveAllTokens} methods. + * + * @param str the String to parse, may be {@code null} + * @param separator String containing the String to be used as a delimiter, + * {@code null} splits on whitespace + * @param max the maximum number of elements to include in the returned + * array. A zero or negative value implies no limit. + * @param preserveAllTokens if {@code true}, adjacent separators are + * treated as empty token separators; if {@code false}, adjacent + * separators are treated as one separator. + * @return an array of parsed Strings, {@code null} if null String input + * @since 2.4 + */ + private static String[] splitByWholeSeparatorWorker( + String str, String separator, int max, boolean preserveAllTokens) { + if (str == null) { + return null; + } + + int len = str.length(); + + if (len == 0) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + + if (separator == null || EMPTY.equals(separator)) { + // Split on whitespace. + return splitWorker(str, null, max, preserveAllTokens); + } + + int separatorLength = separator.length(); + + ArrayList substrings = new ArrayList(); + int numberOfSubstrings = 0; + int beg = 0; + int end = 0; + while (end < len) { + end = str.indexOf(separator, beg); + + if (end > -1) { + if (end > beg) { + numberOfSubstrings += 1; + + if (numberOfSubstrings == max) { + end = len; + substrings.add(str.substring(beg)); + } else { + // The following is OK, because String.substring( beg, end ) excludes + // the character at the position 'end'. + substrings.add(str.substring(beg, end)); + + // Set the starting point for the next search. + // The following is equivalent to beg = end + (separatorLength - 1) + 1, + // which is the right calculation: + beg = end + separatorLength; + } + } else { + // We found a consecutive occurrence of the separator, so skip it. + if (preserveAllTokens) { + numberOfSubstrings += 1; + if (numberOfSubstrings == max) { + end = len; + substrings.add(str.substring(beg)); + } else { + substrings.add(EMPTY); + } + } + beg = end + separatorLength; + } + } else { + // String.substring( beg ) goes from 'beg' to the end of the String. + substrings.add(str.substring(beg)); + end = len; + } + } + + return substrings.toArray(new String[substrings.size()]); + } + + // ----------------------------------------------------------------------- + /** + *

Splits the provided text into an array, using whitespace as the + * separator, preserving all tokens, including empty tokens created by + * adjacent separators. This is an alternative to using StringTokenizer. + * Whitespace is defined by {@link Character#isWhitespace(char)}.

+ * + *

The separator is not included in the returned String array. + * Adjacent separators are treated as separators for empty tokens. + * For more control over the split use the StrTokenizer class.

+ * + *

A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.splitPreserveAllTokens(null)       = null
+     * StringUtils.splitPreserveAllTokens("")         = []
+     * StringUtils.splitPreserveAllTokens("abc def")  = ["abc", "def"]
+     * StringUtils.splitPreserveAllTokens("abc  def") = ["abc", "", "def"]
+     * StringUtils.splitPreserveAllTokens(" abc ")    = ["", "abc", ""]
+     * 
+ * + * @param str the String to parse, may be {@code null} + * @return an array of parsed Strings, {@code null} if null String input + * @since 2.1 + */ + public static String[] splitPreserveAllTokens(String str) { + return splitWorker(str, null, -1, true); + } + + /** + *

Splits the provided text into an array, separator specified, + * preserving all tokens, including empty tokens created by adjacent + * separators. This is an alternative to using StringTokenizer.

+ * + *

The separator is not included in the returned String array. + * Adjacent separators are treated as separators for empty tokens. + * For more control over the split use the StrTokenizer class.

+ * + *

A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.splitPreserveAllTokens(null, *)         = null
+     * StringUtils.splitPreserveAllTokens("", *)           = []
+     * StringUtils.splitPreserveAllTokens("a.b.c", '.')    = ["a", "b", "c"]
+     * StringUtils.splitPreserveAllTokens("a..b.c", '.')   = ["a", "", "b", "c"]
+     * StringUtils.splitPreserveAllTokens("a:b:c", '.')    = ["a:b:c"]
+     * StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
+     * StringUtils.splitPreserveAllTokens("a b c", ' ')    = ["a", "b", "c"]
+     * StringUtils.splitPreserveAllTokens("a b c ", ' ')   = ["a", "b", "c", ""]
+     * StringUtils.splitPreserveAllTokens("a b c  ", ' ')   = ["a", "b", "c", "", ""]
+     * StringUtils.splitPreserveAllTokens(" a b c", ' ')   = ["", a", "b", "c"]
+     * StringUtils.splitPreserveAllTokens("  a b c", ' ')  = ["", "", a", "b", "c"]
+     * StringUtils.splitPreserveAllTokens(" a b c ", ' ')  = ["", a", "b", "c", ""]
+     * 
+ * + * @param str the String to parse, may be {@code null} + * @param separatorChar the character used as the delimiter, + * {@code null} splits on whitespace + * @return an array of parsed Strings, {@code null} if null String input + * @since 2.1 + */ + public static String[] splitPreserveAllTokens(String str, char separatorChar) { + return splitWorker(str, separatorChar, true); + } + + /** + * Performs the logic for the {@code split} and + * {@code splitPreserveAllTokens} methods that do not return a + * maximum array length. + * + * @param str the String to parse, may be {@code null} + * @param separatorChar the separate character + * @param preserveAllTokens if {@code true}, adjacent separators are + * treated as empty token separators; if {@code false}, adjacent + * separators are treated as one separator. + * @return an array of parsed Strings, {@code null} if null String input + */ + private static String[] splitWorker(String str, char separatorChar, boolean preserveAllTokens) { + // Performance tuned for 2.0 (JDK1.4) + + if (str == null) { + return null; + } + int len = str.length(); + if (len == 0) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + List list = new ArrayList(); + int i = 0, start = 0; + boolean match = false; + boolean lastMatch = false; + while (i < len) { + if (str.charAt(i) == separatorChar) { + if (match || preserveAllTokens) { + list.add(str.substring(start, i)); + match = false; + lastMatch = true; + } + start = ++i; + continue; + } + lastMatch = false; + match = true; + i++; + } + if (match || preserveAllTokens && lastMatch) { + list.add(str.substring(start, i)); + } + return list.toArray(new String[list.size()]); + } + + /** + *

Splits the provided text into an array, separators specified, + * preserving all tokens, including empty tokens created by adjacent + * separators. This is an alternative to using StringTokenizer.

+ * + *

The separator is not included in the returned String array. + * Adjacent separators are treated as separators for empty tokens. + * For more control over the split use the StrTokenizer class.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} separatorChars splits on whitespace.

+ * + *
+     * StringUtils.splitPreserveAllTokens(null, *)           = null
+     * StringUtils.splitPreserveAllTokens("", *)             = []
+     * StringUtils.splitPreserveAllTokens("abc def", null)   = ["abc", "def"]
+     * StringUtils.splitPreserveAllTokens("abc def", " ")    = ["abc", "def"]
+     * StringUtils.splitPreserveAllTokens("abc  def", " ")   = ["abc", "", def"]
+     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":")   = ["ab", "cd", "ef"]
+     * StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":")  = ["ab", "cd", "ef", ""]
+     * StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
+     * StringUtils.splitPreserveAllTokens("ab::cd:ef", ":")  = ["ab", "", cd", "ef"]
+     * StringUtils.splitPreserveAllTokens(":cd:ef", ":")     = ["", cd", "ef"]
+     * StringUtils.splitPreserveAllTokens("::cd:ef", ":")    = ["", "", cd", "ef"]
+     * StringUtils.splitPreserveAllTokens(":cd:ef:", ":")    = ["", cd", "ef", ""]
+     * 
+ * + * @param str the String to parse, may be {@code null} + * @param separatorChars the characters used as the delimiters, + * {@code null} splits on whitespace + * @return an array of parsed Strings, {@code null} if null String input + * @since 2.1 + */ + public static String[] splitPreserveAllTokens(String str, String separatorChars) { + return splitWorker(str, separatorChars, -1, true); + } + + /** + *

Splits the provided text into an array with a maximum length, + * separators specified, preserving all tokens, including empty tokens + * created by adjacent separators.

+ * + *

The separator is not included in the returned String array. + * Adjacent separators are treated as separators for empty tokens. + * Adjacent separators are treated as one separator.

+ * + *

A {@code null} input String returns {@code null}. + * A {@code null} separatorChars splits on whitespace.

+ * + *

If more than {@code max} delimited substrings are found, the last + * returned string includes all characters after the first {@code max - 1} + * returned strings (including separator characters).

+ * + *
+     * StringUtils.splitPreserveAllTokens(null, *, *)            = null
+     * StringUtils.splitPreserveAllTokens("", *, *)              = []
+     * StringUtils.splitPreserveAllTokens("ab de fg", null, 0)   = ["ab", "cd", "ef"]
+     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 0) = ["ab", "cd", "ef"]
+     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
+     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
+     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 2) = ["ab", "  de fg"]
+     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 3) = ["ab", "", " de fg"]
+     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 4) = ["ab", "", "", "de fg"]
+     * 
+ * + * @param str the String to parse, may be {@code null} + * @param separatorChars the characters used as the delimiters, + * {@code null} splits on whitespace + * @param max the maximum number of elements to include in the + * array. A zero or negative value implies no limit + * @return an array of parsed Strings, {@code null} if null String input + * @since 2.1 + */ + public static String[] splitPreserveAllTokens(String str, String separatorChars, int max) { + return splitWorker(str, separatorChars, max, true); + } + + /** + * Performs the logic for the {@code split} and + * {@code splitPreserveAllTokens} methods that return a maximum array + * length. + * + * @param str the String to parse, may be {@code null} + * @param separatorChars the separate character + * @param max the maximum number of elements to include in the + * array. A zero or negative value implies no limit. + * @param preserveAllTokens if {@code true}, adjacent separators are + * treated as empty token separators; if {@code false}, adjacent + * separators are treated as one separator. + * @return an array of parsed Strings, {@code null} if null String input + */ + private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) { + // Performance tuned for 2.0 (JDK1.4) + // Direct code is quicker than StringTokenizer. + // Also, StringTokenizer uses isSpace() not isWhitespace() + + if (str == null) { + return null; + } + int len = str.length(); + if (len == 0) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + List list = new ArrayList(); + int sizePlus1 = 1; + int i = 0, start = 0; + boolean match = false; + boolean lastMatch = false; + if (separatorChars == null) { + // Null separator means use whitespace + while (i < len) { + if (Character.isWhitespace(str.charAt(i))) { + if (match || preserveAllTokens) { + lastMatch = true; + if (sizePlus1++ == max) { + i = len; + lastMatch = false; + } + list.add(str.substring(start, i)); + match = false; + } + start = ++i; + continue; + } + lastMatch = false; + match = true; + i++; + } + } else if (separatorChars.length() == 1) { + // Optimise 1 character case + char sep = separatorChars.charAt(0); + while (i < len) { + if (str.charAt(i) == sep) { + if (match || preserveAllTokens) { + lastMatch = true; + if (sizePlus1++ == max) { + i = len; + lastMatch = false; + } + list.add(str.substring(start, i)); + match = false; + } + start = ++i; + continue; + } + lastMatch = false; + match = true; + i++; + } + } else { + // standard case + while (i < len) { + if (separatorChars.indexOf(str.charAt(i)) >= 0) { + if (match || preserveAllTokens) { + lastMatch = true; + if (sizePlus1++ == max) { + i = len; + lastMatch = false; + } + list.add(str.substring(start, i)); + match = false; + } + start = ++i; + continue; + } + lastMatch = false; + match = true; + i++; + } + } + if (match || preserveAllTokens && lastMatch) { + list.add(str.substring(start, i)); + } + return list.toArray(new String[list.size()]); + } + + /** + *

Splits a String by Character type as returned by + * {@code java.lang.Character.getType(char)}. Groups of contiguous + * characters of the same type are returned as complete tokens. + *

+     * StringUtils.splitByCharacterType(null)         = null
+     * StringUtils.splitByCharacterType("")           = []
+     * StringUtils.splitByCharacterType("ab de fg")   = ["ab", " ", "de", " ", "fg"]
+     * StringUtils.splitByCharacterType("ab   de fg") = ["ab", "   ", "de", " ", "fg"]
+     * StringUtils.splitByCharacterType("ab:cd:ef")   = ["ab", ":", "cd", ":", "ef"]
+     * StringUtils.splitByCharacterType("number5")    = ["number", "5"]
+     * StringUtils.splitByCharacterType("fooBar")     = ["foo", "B", "ar"]
+     * StringUtils.splitByCharacterType("foo200Bar")  = ["foo", "200", "B", "ar"]
+     * StringUtils.splitByCharacterType("ASFRules")   = ["ASFR", "ules"]
+     * 
+ * @param str the String to split, may be {@code null} + * @return an array of parsed Strings, {@code null} if null String input + * @since 2.4 + */ + public static String[] splitByCharacterType(String str) { + return splitByCharacterType(str, false); + } + + /** + *

Splits a String by Character type as returned by + * {@code java.lang.Character.getType(char)}. Groups of contiguous + * characters of the same type are returned as complete tokens, with the + * following exception: the character of type + * {@code Character.UPPERCASE_LETTER}, if any, immediately + * preceding a token of type {@code Character.LOWERCASE_LETTER} + * will belong to the following token rather than to the preceding, if any, + * {@code Character.UPPERCASE_LETTER} token. + *

+     * StringUtils.splitByCharacterTypeCamelCase(null)         = null
+     * StringUtils.splitByCharacterTypeCamelCase("")           = []
+     * StringUtils.splitByCharacterTypeCamelCase("ab de fg")   = ["ab", " ", "de", " ", "fg"]
+     * StringUtils.splitByCharacterTypeCamelCase("ab   de fg") = ["ab", "   ", "de", " ", "fg"]
+     * StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef")   = ["ab", ":", "cd", ":", "ef"]
+     * StringUtils.splitByCharacterTypeCamelCase("number5")    = ["number", "5"]
+     * StringUtils.splitByCharacterTypeCamelCase("fooBar")     = ["foo", "Bar"]
+     * StringUtils.splitByCharacterTypeCamelCase("foo200Bar")  = ["foo", "200", "Bar"]
+     * StringUtils.splitByCharacterTypeCamelCase("ASFRules")   = ["ASF", "Rules"]
+     * 
+ * @param str the String to split, may be {@code null} + * @return an array of parsed Strings, {@code null} if null String input + * @since 2.4 + */ + public static String[] splitByCharacterTypeCamelCase(String str) { + return splitByCharacterType(str, true); + } + + /** + *

Splits a String by Character type as returned by + * {@code java.lang.Character.getType(char)}. Groups of contiguous + * characters of the same type are returned as complete tokens, with the + * following exception: if {@code camelCase} is {@code true}, + * the character of type {@code Character.UPPERCASE_LETTER}, if any, + * immediately preceding a token of type {@code Character.LOWERCASE_LETTER} + * will belong to the following token rather than to the preceding, if any, + * {@code Character.UPPERCASE_LETTER} token. + * @param str the String to split, may be {@code null} + * @param camelCase whether to use so-called "camel-case" for letter types + * @return an array of parsed Strings, {@code null} if null String input + * @since 2.4 + */ + private static String[] splitByCharacterType(String str, boolean camelCase) { + if (str == null) { + return null; + } + if (str.length() == 0) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + char[] c = str.toCharArray(); + List list = new ArrayList(); + int tokenStart = 0; + int currentType = Character.getType(c[tokenStart]); + for (int pos = tokenStart + 1; pos < c.length; pos++) { + int type = Character.getType(c[pos]); + if (type == currentType) { + continue; + } + if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) { + int newTokenStart = pos - 1; + if (newTokenStart != tokenStart) { + list.add(new String(c, tokenStart, newTokenStart - tokenStart)); + tokenStart = newTokenStart; + } + } else { + list.add(new String(c, tokenStart, pos - tokenStart)); + tokenStart = pos; + } + currentType = type; + } + list.add(new String(c, tokenStart, c.length - tokenStart)); + return list.toArray(new String[list.size()]); + } + + // Joining + //----------------------------------------------------------------------- + /** + *

Joins the elements of the provided array into a single String + * containing the provided list of elements.

+ * + *

No separator is added to the joined String. + * Null objects or empty strings within the array are represented by + * empty strings.

+ * + *
+     * StringUtils.join(null)            = null
+     * StringUtils.join([])              = ""
+     * StringUtils.join([null])          = ""
+     * StringUtils.join(["a", "b", "c"]) = "abc"
+     * StringUtils.join([null, "", "a"]) = "a"
+     * 
+ * + * @param the specific type of values to join together + * @param elements the values to join together, may be null + * @return the joined String, {@code null} if null array input + * @since 2.0 + * @since 3.0 Changed signature to use varargs + */ + public static String join(T... elements) { + return join(elements, null); + } + + /** + *

Joins the elements of the provided array into a single String + * containing the provided list of elements.

+ * + *

No delimiter is added before or after the list. + * Null objects or empty strings within the array are represented by + * empty strings.

+ * + *
+     * StringUtils.join(null, *)               = null
+     * StringUtils.join([], *)                 = ""
+     * StringUtils.join([null], *)             = ""
+     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
+     * StringUtils.join(["a", "b", "c"], null) = "abc"
+     * StringUtils.join([null, "", "a"], ';')  = ";;a"
+     * 
+ * + * @param array the array of values to join together, may be null + * @param separator the separator character to use + * @return the joined String, {@code null} if null array input + * @since 2.0 + */ + public static String join(Object[] array, char separator) { + if (array == null) { + return null; + } + + return join(array, separator, 0, array.length); + } + + /** + *

Joins the elements of the provided array into a single String + * containing the provided list of elements.

+ * + *

No delimiter is added before or after the list. + * Null objects or empty strings within the array are represented by + * empty strings.

+ * + *
+     * StringUtils.join(null, *)               = null
+     * StringUtils.join([], *)                 = ""
+     * StringUtils.join([null], *)             = ""
+     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
+     * StringUtils.join(["a", "b", "c"], null) = "abc"
+     * StringUtils.join([null, "", "a"], ';')  = ";;a"
+     * 
+ * + * @param array the array of values to join together, may be null + * @param separator the separator character to use + * @param startIndex the first index to start joining from. It is + * an error to pass in an end index past the end of the array + * @param endIndex the index to stop joining from (exclusive). It is + * an error to pass in an end index past the end of the array + * @return the joined String, {@code null} if null array input + * @since 2.0 + */ + public static String join(Object[] array, char separator, int startIndex, int endIndex) { + if (array == null) { + return null; + } + int noOfItems = endIndex - startIndex; + if (noOfItems <= 0) { + return EMPTY; + } + + StringBuilder buf = new StringBuilder(noOfItems * 16); + + for (int i = startIndex; i < endIndex; i++) { + if (i > startIndex) { + buf.append(separator); + } + if (array[i] != null) { + buf.append(array[i]); + } + } + return buf.toString(); + } + + /** + *

Joins the elements of the provided array into a single String + * containing the provided list of elements.

+ * + *

No delimiter is added before or after the list. + * A {@code null} separator is the same as an empty String (""). + * Null objects or empty strings within the array are represented by + * empty strings.

+ * + *
+     * StringUtils.join(null, *)                = null
+     * StringUtils.join([], *)                  = ""
+     * StringUtils.join([null], *)              = ""
+     * StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
+     * StringUtils.join(["a", "b", "c"], null)  = "abc"
+     * StringUtils.join(["a", "b", "c"], "")    = "abc"
+     * StringUtils.join([null, "", "a"], ',')   = ",,a"
+     * 
+ * + * @param array the array of values to join together, may be null + * @param separator the separator character to use, null treated as "" + * @return the joined String, {@code null} if null array input + */ + public static String join(Object[] array, String separator) { + if (array == null) { + return null; + } + return join(array, separator, 0, array.length); + } + + /** + *

Joins the elements of the provided array into a single String + * containing the provided list of elements.

+ * + *

No delimiter is added before or after the list. + * A {@code null} separator is the same as an empty String (""). + * Null objects or empty strings within the array are represented by + * empty strings.

+ * + *
+     * StringUtils.join(null, *)                = null
+     * StringUtils.join([], *)                  = ""
+     * StringUtils.join([null], *)              = ""
+     * StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
+     * StringUtils.join(["a", "b", "c"], null)  = "abc"
+     * StringUtils.join(["a", "b", "c"], "")    = "abc"
+     * StringUtils.join([null, "", "a"], ',')   = ",,a"
+     * 
+ * + * @param array the array of values to join together, may be null + * @param separator the separator character to use, null treated as "" + * @param startIndex the first index to start joining from. It is + * an error to pass in an end index past the end of the array + * @param endIndex the index to stop joining from (exclusive). It is + * an error to pass in an end index past the end of the array + * @return the joined String, {@code null} if null array input + */ + public static String join(Object[] array, String separator, int startIndex, int endIndex) { + if (array == null) { + return null; + } + if (separator == null) { + separator = EMPTY; + } + + // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator)) + // (Assuming that all Strings are roughly equally long) + int noOfItems = endIndex - startIndex; + if (noOfItems <= 0) { + return EMPTY; + } + + StringBuilder buf = new StringBuilder(noOfItems * 16); + + for (int i = startIndex; i < endIndex; i++) { + if (i > startIndex) { + buf.append(separator); + } + if (array[i] != null) { + buf.append(array[i]); + } + } + return buf.toString(); + } + + /** + *

Joins the elements of the provided {@code Iterator} into + * a single String containing the provided elements.

+ * + *

No delimiter is added before or after the list. Null objects or empty + * strings within the iteration are represented by empty strings.

+ * + *

See the examples here: {@link #join(Object[],char)}.

+ * + * @param iterator the {@code Iterator} of values to join together, may be null + * @param separator the separator character to use + * @return the joined String, {@code null} if null iterator input + * @since 2.0 + */ + public static String join(Iterator iterator, char separator) { + + // handle null, zero and one elements before building a buffer + if (iterator == null) { + return null; + } + if (!iterator.hasNext()) { + return EMPTY; + } + Object first = iterator.next(); + if (!iterator.hasNext()) { + return ObjectUtils.toString(first); + } + + // two or more elements + StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small + if (first != null) { + buf.append(first); + } + + while (iterator.hasNext()) { + buf.append(separator); + Object obj = iterator.next(); + if (obj != null) { + buf.append(obj); + } + } + + return buf.toString(); + } + + /** + *

Joins the elements of the provided {@code Iterator} into + * a single String containing the provided elements.

+ * + *

No delimiter is added before or after the list. + * A {@code null} separator is the same as an empty String ("").

+ * + *

See the examples here: {@link #join(Object[],String)}.

+ * + * @param iterator the {@code Iterator} of values to join together, may be null + * @param separator the separator character to use, null treated as "" + * @return the joined String, {@code null} if null iterator input + */ + public static String join(Iterator iterator, String separator) { + + // handle null, zero and one elements before building a buffer + if (iterator == null) { + return null; + } + if (!iterator.hasNext()) { + return EMPTY; + } + Object first = iterator.next(); + if (!iterator.hasNext()) { + return ObjectUtils.toString(first); + } + + // two or more elements + StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small + if (first != null) { + buf.append(first); + } + + while (iterator.hasNext()) { + if (separator != null) { + buf.append(separator); + } + Object obj = iterator.next(); + if (obj != null) { + buf.append(obj); + } + } + return buf.toString(); + } + + /** + *

Joins the elements of the provided {@code Iterable} into + * a single String containing the provided elements.

+ * + *

No delimiter is added before or after the list. Null objects or empty + * strings within the iteration are represented by empty strings.

+ * + *

See the examples here: {@link #join(Object[],char)}.

+ * + * @param iterable the {@code Iterable} providing the values to join together, may be null + * @param separator the separator character to use + * @return the joined String, {@code null} if null iterator input + * @since 2.3 + */ + public static String join(Iterable iterable, char separator) { + if (iterable == null) { + return null; + } + return join(iterable.iterator(), separator); + } + + /** + *

Joins the elements of the provided {@code Iterable} into + * a single String containing the provided elements.

+ * + *

No delimiter is added before or after the list. + * A {@code null} separator is the same as an empty String ("").

+ * + *

See the examples here: {@link #join(Object[],String)}.

+ * + * @param iterable the {@code Iterable} providing the values to join together, may be null + * @param separator the separator character to use, null treated as "" + * @return the joined String, {@code null} if null iterator input + * @since 2.3 + */ + public static String join(Iterable iterable, String separator) { + if (iterable == null) { + return null; + } + return join(iterable.iterator(), separator); + } + + // Delete + //----------------------------------------------------------------------- + /** + *

Deletes all whitespaces from a String as defined by + * {@link Character#isWhitespace(char)}.

+ * + *
+     * StringUtils.deleteWhitespace(null)         = null
+     * StringUtils.deleteWhitespace("")           = ""
+     * StringUtils.deleteWhitespace("abc")        = "abc"
+     * StringUtils.deleteWhitespace("   ab  c  ") = "abc"
+     * 
+ * + * @param str the String to delete whitespace from, may be null + * @return the String without whitespaces, {@code null} if null String input + */ + public static String deleteWhitespace(String str) { + if (isEmpty(str)) { + return str; + } + int sz = str.length(); + char[] chs = new char[sz]; + int count = 0; + for (int i = 0; i < sz; i++) { + if (!Character.isWhitespace(str.charAt(i))) { + chs[count++] = str.charAt(i); + } + } + if (count == sz) { + return str; + } + return new String(chs, 0, count); + } + + // Remove + //----------------------------------------------------------------------- + /** + *

Removes a substring only if it is at the beginning of a source string, + * otherwise returns the source string.

+ * + *

A {@code null} source string will return {@code null}. + * An empty ("") source string will return the empty string. + * A {@code null} search string will return the source string.

+ * + *
+     * StringUtils.removeStart(null, *)      = null
+     * StringUtils.removeStart("", *)        = ""
+     * StringUtils.removeStart(*, null)      = *
+     * StringUtils.removeStart("www.domain.com", "www.")   = "domain.com"
+     * StringUtils.removeStart("domain.com", "www.")       = "domain.com"
+     * StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
+     * StringUtils.removeStart("abc", "")    = "abc"
+     * 
+ * + * @param str the source String to search, may be null + * @param remove the String to search for and remove, may be null + * @return the substring with the string removed if found, + * {@code null} if null String input + * @since 2.1 + */ + public static String removeStart(String str, String remove) { + if (isEmpty(str) || isEmpty(remove)) { + return str; + } + if (str.startsWith(remove)){ + return str.substring(remove.length()); + } + return str; + } + + /** + *

Case insensitive removal of a substring if it is at the beginning of a source string, + * otherwise returns the source string.

+ * + *

A {@code null} source string will return {@code null}. + * An empty ("") source string will return the empty string. + * A {@code null} search string will return the source string.

+ * + *
+     * StringUtils.removeStartIgnoreCase(null, *)      = null
+     * StringUtils.removeStartIgnoreCase("", *)        = ""
+     * StringUtils.removeStartIgnoreCase(*, null)      = *
+     * StringUtils.removeStartIgnoreCase("www.domain.com", "www.")   = "domain.com"
+     * StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.")   = "domain.com"
+     * StringUtils.removeStartIgnoreCase("domain.com", "www.")       = "domain.com"
+     * StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
+     * StringUtils.removeStartIgnoreCase("abc", "")    = "abc"
+     * 
+ * + * @param str the source String to search, may be null + * @param remove the String to search for (case insensitive) and remove, may be null + * @return the substring with the string removed if found, + * {@code null} if null String input + * @since 2.4 + */ + public static String removeStartIgnoreCase(String str, String remove) { + if (isEmpty(str) || isEmpty(remove)) { + return str; + } + if (startsWithIgnoreCase(str, remove)) { + return str.substring(remove.length()); + } + return str; + } + + /** + *

Removes a substring only if it is at the end of a source string, + * otherwise returns the source string.

+ * + *

A {@code null} source string will return {@code null}. + * An empty ("") source string will return the empty string. + * A {@code null} search string will return the source string.

+ * + *
+     * StringUtils.removeEnd(null, *)      = null
+     * StringUtils.removeEnd("", *)        = ""
+     * StringUtils.removeEnd(*, null)      = *
+     * StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
+     * StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
+     * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
+     * StringUtils.removeEnd("abc", "")    = "abc"
+     * 
+ * + * @param str the source String to search, may be null + * @param remove the String to search for and remove, may be null + * @return the substring with the string removed if found, + * {@code null} if null String input + * @since 2.1 + */ + public static String removeEnd(String str, String remove) { + if (isEmpty(str) || isEmpty(remove)) { + return str; + } + if (str.endsWith(remove)) { + return str.substring(0, str.length() - remove.length()); + } + return str; + } + + /** + *

Case insensitive removal of a substring if it is at the end of a source string, + * otherwise returns the source string.

+ * + *

A {@code null} source string will return {@code null}. + * An empty ("") source string will return the empty string. + * A {@code null} search string will return the source string.

+ * + *
+     * StringUtils.removeEndIgnoreCase(null, *)      = null
+     * StringUtils.removeEndIgnoreCase("", *)        = ""
+     * StringUtils.removeEndIgnoreCase(*, null)      = *
+     * StringUtils.removeEndIgnoreCase("www.domain.com", ".com.")  = "www.domain.com"
+     * StringUtils.removeEndIgnoreCase("www.domain.com", ".com")   = "www.domain"
+     * StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
+     * StringUtils.removeEndIgnoreCase("abc", "")    = "abc"
+     * StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
+     * StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
+     * 
+ * + * @param str the source String to search, may be null + * @param remove the String to search for (case insensitive) and remove, may be null + * @return the substring with the string removed if found, + * {@code null} if null String input + * @since 2.4 + */ + public static String removeEndIgnoreCase(String str, String remove) { + if (isEmpty(str) || isEmpty(remove)) { + return str; + } + if (endsWithIgnoreCase(str, remove)) { + return str.substring(0, str.length() - remove.length()); + } + return str; + } + + /** + *

Removes all occurrences of a substring from within the source string.

+ * + *

A {@code null} source string will return {@code null}. + * An empty ("") source string will return the empty string. + * A {@code null} remove string will return the source string. + * An empty ("") remove string will return the source string.

+ * + *
+     * StringUtils.remove(null, *)        = null
+     * StringUtils.remove("", *)          = ""
+     * StringUtils.remove(*, null)        = *
+     * StringUtils.remove(*, "")          = *
+     * StringUtils.remove("queued", "ue") = "qd"
+     * StringUtils.remove("queued", "zz") = "queued"
+     * 
+ * + * @param str the source String to search, may be null + * @param remove the String to search for and remove, may be null + * @return the substring with the string removed if found, + * {@code null} if null String input + * @since 2.1 + */ + public static String remove(String str, String remove) { + if (isEmpty(str) || isEmpty(remove)) { + return str; + } + return replace(str, remove, EMPTY, -1); + } + + /** + *

Removes all occurrences of a character from within the source string.

+ * + *

A {@code null} source string will return {@code null}. + * An empty ("") source string will return the empty string.

+ * + *
+     * StringUtils.remove(null, *)       = null
+     * StringUtils.remove("", *)         = ""
+     * StringUtils.remove("queued", 'u') = "qeed"
+     * StringUtils.remove("queued", 'z') = "queued"
+     * 
+ * + * @param str the source String to search, may be null + * @param remove the char to search for and remove, may be null + * @return the substring with the char removed if found, + * {@code null} if null String input + * @since 2.1 + */ + public static String remove(String str, char remove) { + if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) { + return str; + } + char[] chars = str.toCharArray(); + int pos = 0; + for (int i = 0; i < chars.length; i++) { + if (chars[i] != remove) { + chars[pos++] = chars[i]; + } + } + return new String(chars, 0, pos); + } + + // Replacing + //----------------------------------------------------------------------- + /** + *

Replaces a String with another String inside a larger String, once.

+ * + *

A {@code null} reference passed to this method is a no-op.

+ * + *
+     * StringUtils.replaceOnce(null, *, *)        = null
+     * StringUtils.replaceOnce("", *, *)          = ""
+     * StringUtils.replaceOnce("any", null, *)    = "any"
+     * StringUtils.replaceOnce("any", *, null)    = "any"
+     * StringUtils.replaceOnce("any", "", *)      = "any"
+     * StringUtils.replaceOnce("aba", "a", null)  = "aba"
+     * StringUtils.replaceOnce("aba", "a", "")    = "ba"
+     * StringUtils.replaceOnce("aba", "a", "z")   = "zba"
+     * 
+ * + * @see #replace(String text, String searchString, String replacement, int max) + * @param text text to search and replace in, may be null + * @param searchString the String to search for, may be null + * @param replacement the String to replace with, may be null + * @return the text with any replacements processed, + * {@code null} if null String input + */ + public static String replaceOnce(String text, String searchString, String replacement) { + return replace(text, searchString, replacement, 1); + } + + /** + *

Replaces all occurrences of a String within another String.

+ * + *

A {@code null} reference passed to this method is a no-op.

+ * + *
+     * StringUtils.replace(null, *, *)        = null
+     * StringUtils.replace("", *, *)          = ""
+     * StringUtils.replace("any", null, *)    = "any"
+     * StringUtils.replace("any", *, null)    = "any"
+     * StringUtils.replace("any", "", *)      = "any"
+     * StringUtils.replace("aba", "a", null)  = "aba"
+     * StringUtils.replace("aba", "a", "")    = "b"
+     * StringUtils.replace("aba", "a", "z")   = "zbz"
+     * 
+ * + * @see #replace(String text, String searchString, String replacement, int max) + * @param text text to search and replace in, may be null + * @param searchString the String to search for, may be null + * @param replacement the String to replace it with, may be null + * @return the text with any replacements processed, + * {@code null} if null String input + */ + public static String replace(String text, String searchString, String replacement) { + return replace(text, searchString, replacement, -1); + } + + /** + *

Replaces a String with another String inside a larger String, + * for the first {@code max} values of the search String.

+ * + *

A {@code null} reference passed to this method is a no-op.

+ * + *
+     * StringUtils.replace(null, *, *, *)         = null
+     * StringUtils.replace("", *, *, *)           = ""
+     * StringUtils.replace("any", null, *, *)     = "any"
+     * StringUtils.replace("any", *, null, *)     = "any"
+     * StringUtils.replace("any", "", *, *)       = "any"
+     * StringUtils.replace("any", *, *, 0)        = "any"
+     * StringUtils.replace("abaa", "a", null, -1) = "abaa"
+     * StringUtils.replace("abaa", "a", "", -1)   = "b"
+     * StringUtils.replace("abaa", "a", "z", 0)   = "abaa"
+     * StringUtils.replace("abaa", "a", "z", 1)   = "zbaa"
+     * StringUtils.replace("abaa", "a", "z", 2)   = "zbza"
+     * StringUtils.replace("abaa", "a", "z", -1)  = "zbzz"
+     * 
+ * + * @param text text to search and replace in, may be null + * @param searchString the String to search for, may be null + * @param replacement the String to replace it with, may be null + * @param max maximum number of values to replace, or {@code -1} if no maximum + * @return the text with any replacements processed, + * {@code null} if null String input + */ + public static String replace(String text, String searchString, String replacement, int max) { + if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { + return text; + } + int start = 0; + int end = text.indexOf(searchString, start); + if (end == INDEX_NOT_FOUND) { + return text; + } + int replLength = searchString.length(); + int increase = replacement.length() - replLength; + increase = increase < 0 ? 0 : increase; + increase *= max < 0 ? 16 : max > 64 ? 64 : max; + StringBuilder buf = new StringBuilder(text.length() + increase); + while (end != INDEX_NOT_FOUND) { + buf.append(text.substring(start, end)).append(replacement); + start = end + replLength; + if (--max == 0) { + break; + } + end = text.indexOf(searchString, start); + } + buf.append(text.substring(start)); + return buf.toString(); + } + + /** + *

+ * Replaces all occurrences of Strings within another String. + *

+ * + *

+ * A {@code null} reference passed to this method is a no-op, or if + * any "search string" or "string to replace" is null, that replace will be + * ignored. This will not repeat. For repeating replaces, call the + * overloaded method. + *

+ * + *
+     *  StringUtils.replaceEach(null, *, *)        = null
+     *  StringUtils.replaceEach("", *, *)          = ""
+     *  StringUtils.replaceEach("aba", null, null) = "aba"
+     *  StringUtils.replaceEach("aba", new String[0], null) = "aba"
+     *  StringUtils.replaceEach("aba", null, new String[0]) = "aba"
+     *  StringUtils.replaceEach("aba", new String[]{"a"}, null)  = "aba"
+     *  StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""})  = "b"
+     *  StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"})  = "aba"
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"})  = "wcte"
+     *  (example of how it does not repeat)
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"})  = "dcte"
+     * 
+ * + * @param text + * text to search and replace in, no-op if null + * @param searchList + * the Strings to search for, no-op if null + * @param replacementList + * the Strings to replace them with, no-op if null + * @return the text with any replacements processed, {@code null} if + * null String input + * @throws IllegalArgumentException + * if the lengths of the arrays are not the same (null is ok, + * and/or size 0) + * @since 2.4 + */ + public static String replaceEach(String text, String[] searchList, String[] replacementList) { + return replaceEach(text, searchList, replacementList, false, 0); + } + + /** + *

+ * Replaces all occurrences of Strings within another String. + *

+ * + *

+ * A {@code null} reference passed to this method is a no-op, or if + * any "search string" or "string to replace" is null, that replace will be + * ignored. + *

+ * + *
+     *  StringUtils.replaceEach(null, *, *, *) = null
+     *  StringUtils.replaceEach("", *, *, *) = ""
+     *  StringUtils.replaceEach("aba", null, null, *) = "aba"
+     *  StringUtils.replaceEach("aba", new String[0], null, *) = "aba"
+     *  StringUtils.replaceEach("aba", null, new String[0], *) = "aba"
+     *  StringUtils.replaceEach("aba", new String[]{"a"}, null, *) = "aba"
+     *  StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *) = "b"
+     *  StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *) = "aba"
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *) = "wcte"
+     *  (example of how it repeats)
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false) = "dcte"
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true) = "tcte"
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, true) = IllegalStateException
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, false) = "dcabe"
+     * 
+ * + * @param text + * text to search and replace in, no-op if null + * @param searchList + * the Strings to search for, no-op if null + * @param replacementList + * the Strings to replace them with, no-op if null + * @return the text with any replacements processed, {@code null} if + * null String input + * @throws IllegalStateException + * if the search is repeating and there is an endless loop due + * to outputs of one being inputs to another + * @throws IllegalArgumentException + * if the lengths of the arrays are not the same (null is ok, + * and/or size 0) + * @since 2.4 + */ + public static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) { + // timeToLive should be 0 if not used or nothing to replace, else it's + // the length of the replace array + int timeToLive = searchList == null ? 0 : searchList.length; + return replaceEach(text, searchList, replacementList, true, timeToLive); + } + + /** + *

+ * Replaces all occurrences of Strings within another String. + *

+ * + *

+ * A {@code null} reference passed to this method is a no-op, or if + * any "search string" or "string to replace" is null, that replace will be + * ignored. + *

+ * + *
+     *  StringUtils.replaceEach(null, *, *, *) = null
+     *  StringUtils.replaceEach("", *, *, *) = ""
+     *  StringUtils.replaceEach("aba", null, null, *) = "aba"
+     *  StringUtils.replaceEach("aba", new String[0], null, *) = "aba"
+     *  StringUtils.replaceEach("aba", null, new String[0], *) = "aba"
+     *  StringUtils.replaceEach("aba", new String[]{"a"}, null, *) = "aba"
+     *  StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *) = "b"
+     *  StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *) = "aba"
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *) = "wcte"
+     *  (example of how it repeats)
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false) = "dcte"
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true) = "tcte"
+     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *) = IllegalStateException
+     * 
+ * + * @param text + * text to search and replace in, no-op if null + * @param searchList + * the Strings to search for, no-op if null + * @param replacementList + * the Strings to replace them with, no-op if null + * @param repeat if true, then replace repeatedly + * until there are no more possible replacements or timeToLive < 0 + * @param timeToLive + * if less than 0 then there is a circular reference and endless + * loop + * @return the text with any replacements processed, {@code null} if + * null String input + * @throws IllegalStateException + * if the search is repeating and there is an endless loop due + * to outputs of one being inputs to another + * @throws IllegalArgumentException + * if the lengths of the arrays are not the same (null is ok, + * and/or size 0) + * @since 2.4 + */ + private static String replaceEach( + String text, String[] searchList, String[] replacementList, boolean repeat, int timeToLive) { + + // mchyzer Performance note: This creates very few new objects (one major goal) + // let me know if there are performance requests, we can create a harness to measure + + if (text == null || text.length() == 0 || searchList == null || + searchList.length == 0 || replacementList == null || replacementList.length == 0) { + return text; + } + + // if recursing, this shouldn't be less than 0 + if (timeToLive < 0) { + throw new IllegalStateException("Aborting to protect against StackOverflowError - " + + "output of one loop is the input of another"); + } + + int searchLength = searchList.length; + int replacementLength = replacementList.length; + + // make sure lengths are ok, these need to be equal + if (searchLength != replacementLength) { + throw new IllegalArgumentException("Search and Replace array lengths don't match: " + + searchLength + + " vs " + + replacementLength); + } + + // keep track of which still have matches + boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; + + // index on index that the match was found + int textIndex = -1; + int replaceIndex = -1; + int tempIndex = -1; + + // index of replace array that will replace the search string found + // NOTE: logic duplicated below START + for (int i = 0; i < searchLength; i++) { + if (noMoreMatchesForReplIndex[i] || searchList[i] == null || + searchList[i].length() == 0 || replacementList[i] == null) { + continue; + } + tempIndex = text.indexOf(searchList[i]); + + // see if we need to keep searching for this + if (tempIndex == -1) { + noMoreMatchesForReplIndex[i] = true; + } else { + if (textIndex == -1 || tempIndex < textIndex) { + textIndex = tempIndex; + replaceIndex = i; + } + } + } + // NOTE: logic mostly below END + + // no search strings found, we are done + if (textIndex == -1) { + return text; + } + + int start = 0; + + // get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit + int increase = 0; + + // count the replacement text elements that are larger than their corresponding text being replaced + for (int i = 0; i < searchList.length; i++) { + if (searchList[i] == null || replacementList[i] == null) { + continue; + } + int greater = replacementList[i].length() - searchList[i].length(); + if (greater > 0) { + increase += 3 * greater; // assume 3 matches + } + } + // have upper-bound at 20% increase, then let Java take over + increase = Math.min(increase, text.length() / 5); + + StringBuilder buf = new StringBuilder(text.length() + increase); + + while (textIndex != -1) { + + for (int i = start; i < textIndex; i++) { + buf.append(text.charAt(i)); + } + buf.append(replacementList[replaceIndex]); + + start = textIndex + searchList[replaceIndex].length(); + + textIndex = -1; + replaceIndex = -1; + tempIndex = -1; + // find the next earliest match + // NOTE: logic mostly duplicated above START + for (int i = 0; i < searchLength; i++) { + if (noMoreMatchesForReplIndex[i] || searchList[i] == null || + searchList[i].length() == 0 || replacementList[i] == null) { + continue; + } + tempIndex = text.indexOf(searchList[i], start); + + // see if we need to keep searching for this + if (tempIndex == -1) { + noMoreMatchesForReplIndex[i] = true; + } else { + if (textIndex == -1 || tempIndex < textIndex) { + textIndex = tempIndex; + replaceIndex = i; + } + } + } + // NOTE: logic duplicated above END + + } + int textLength = text.length(); + for (int i = start; i < textLength; i++) { + buf.append(text.charAt(i)); + } + String result = buf.toString(); + if (!repeat) { + return result; + } + + return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1); + } + + // Replace, character based + //----------------------------------------------------------------------- + /** + *

Replaces all occurrences of a character in a String with another. + * This is a null-safe version of {@link String#replace(char, char)}.

+ * + *

A {@code null} string input returns {@code null}. + * An empty ("") string input returns an empty string.

+ * + *
+     * StringUtils.replaceChars(null, *, *)        = null
+     * StringUtils.replaceChars("", *, *)          = ""
+     * StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
+     * StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
+     * 
+ * + * @param str String to replace characters in, may be null + * @param searchChar the character to search for, may be null + * @param replaceChar the character to replace, may be null + * @return modified String, {@code null} if null string input + * @since 2.0 + */ + public static String replaceChars(String str, char searchChar, char replaceChar) { + if (str == null) { + return null; + } + return str.replace(searchChar, replaceChar); + } + + /** + *

Replaces multiple characters in a String in one go. + * This method can also be used to delete characters.

+ * + *

For example:
+ * replaceChars("hello", "ho", "jy") = jelly.

+ * + *

A {@code null} string input returns {@code null}. + * An empty ("") string input returns an empty string. + * A null or empty set of search characters returns the input string.

+ * + *

The length of the search characters should normally equal the length + * of the replace characters. + * If the search characters is longer, then the extra search characters + * are deleted. + * If the search characters is shorter, then the extra replace characters + * are ignored.

+ * + *
+     * StringUtils.replaceChars(null, *, *)           = null
+     * StringUtils.replaceChars("", *, *)             = ""
+     * StringUtils.replaceChars("abc", null, *)       = "abc"
+     * StringUtils.replaceChars("abc", "", *)         = "abc"
+     * StringUtils.replaceChars("abc", "b", null)     = "ac"
+     * StringUtils.replaceChars("abc", "b", "")       = "ac"
+     * StringUtils.replaceChars("abcba", "bc", "yz")  = "ayzya"
+     * StringUtils.replaceChars("abcba", "bc", "y")   = "ayya"
+     * StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
+     * 
+ * + * @param str String to replace characters in, may be null + * @param searchChars a set of characters to search for, may be null + * @param replaceChars a set of characters to replace, may be null + * @return modified String, {@code null} if null string input + * @since 2.0 + */ + public static String replaceChars(String str, String searchChars, String replaceChars) { + if (isEmpty(str) || isEmpty(searchChars)) { + return str; + } + if (replaceChars == null) { + replaceChars = EMPTY; + } + boolean modified = false; + int replaceCharsLength = replaceChars.length(); + int strLength = str.length(); + StringBuilder buf = new StringBuilder(strLength); + for (int i = 0; i < strLength; i++) { + char ch = str.charAt(i); + int index = searchChars.indexOf(ch); + if (index >= 0) { + modified = true; + if (index < replaceCharsLength) { + buf.append(replaceChars.charAt(index)); + } + } else { + buf.append(ch); + } + } + if (modified) { + return buf.toString(); + } + return str; + } + + // Overlay + //----------------------------------------------------------------------- + /** + *

Overlays part of a String with another String.

+ * + *

A {@code null} string input returns {@code null}. + * A negative index is treated as zero. + * An index greater than the string length is treated as the string length. + * The start index is always the smaller of the two indices.

+ * + *
+     * StringUtils.overlay(null, *, *, *)            = null
+     * StringUtils.overlay("", "abc", 0, 0)          = "abc"
+     * StringUtils.overlay("abcdef", null, 2, 4)     = "abef"
+     * StringUtils.overlay("abcdef", "", 2, 4)       = "abef"
+     * StringUtils.overlay("abcdef", "", 4, 2)       = "abef"
+     * StringUtils.overlay("abcdef", "zzzz", 2, 4)   = "abzzzzef"
+     * StringUtils.overlay("abcdef", "zzzz", 4, 2)   = "abzzzzef"
+     * StringUtils.overlay("abcdef", "zzzz", -1, 4)  = "zzzzef"
+     * StringUtils.overlay("abcdef", "zzzz", 2, 8)   = "abzzzz"
+     * StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
+     * StringUtils.overlay("abcdef", "zzzz", 8, 10)  = "abcdefzzzz"
+     * 
+ * + * @param str the String to do overlaying in, may be null + * @param overlay the String to overlay, may be null + * @param start the position to start overlaying at + * @param end the position to stop overlaying before + * @return overlayed String, {@code null} if null String input + * @since 2.0 + */ + public static String overlay(String str, String overlay, int start, int end) { + if (str == null) { + return null; + } + if (overlay == null) { + overlay = EMPTY; + } + int len = str.length(); + if (start < 0) { + start = 0; + } + if (start > len) { + start = len; + } + if (end < 0) { + end = 0; + } + if (end > len) { + end = len; + } + if (start > end) { + int temp = start; + start = end; + end = temp; + } + return new StringBuilder(len + start - end + overlay.length() + 1) + .append(str.substring(0, start)) + .append(overlay) + .append(str.substring(end)) + .toString(); + } + + // Chomping + //----------------------------------------------------------------------- + /** + *

Removes one newline from end of a String if it's there, + * otherwise leave it alone. A newline is "{@code \n}", + * "{@code \r}", or "{@code \r\n}".

+ * + *

NOTE: This method changed in 2.0. + * It now more closely matches Perl chomp.

+ * + *
+     * StringUtils.chomp(null)          = null
+     * StringUtils.chomp("")            = ""
+     * StringUtils.chomp("abc \r")      = "abc "
+     * StringUtils.chomp("abc\n")       = "abc"
+     * StringUtils.chomp("abc\r\n")     = "abc"
+     * StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
+     * StringUtils.chomp("abc\n\r")     = "abc\n"
+     * StringUtils.chomp("abc\n\rabc")  = "abc\n\rabc"
+     * StringUtils.chomp("\r")          = ""
+     * StringUtils.chomp("\n")          = ""
+     * StringUtils.chomp("\r\n")        = ""
+     * 
+ * + * @param str the String to chomp a newline from, may be null + * @return String without newline, {@code null} if null String input + */ + public static String chomp(String str) { + if (isEmpty(str)) { + return str; + } + + if (str.length() == 1) { + char ch = str.charAt(0); + if (ch == CharUtils.CR || ch == CharUtils.LF) { + return EMPTY; + } + return str; + } + + int lastIdx = str.length() - 1; + char last = str.charAt(lastIdx); + + if (last == CharUtils.LF) { + if (str.charAt(lastIdx - 1) == CharUtils.CR) { + lastIdx--; + } + } else if (last != CharUtils.CR) { + lastIdx++; + } + return str.substring(0, lastIdx); + } + + /** + *

Removes {@code separator} from the end of + * {@code str} if it's there, otherwise leave it alone.

+ * + *

NOTE: This method changed in version 2.0. + * It now more closely matches Perl chomp. + * For the previous behavior, use {@link #substringBeforeLast(String, String)}. + * This method uses {@link String#endsWith(String)}.

+ * + *
+     * StringUtils.chomp(null, *)         = null
+     * StringUtils.chomp("", *)           = ""
+     * StringUtils.chomp("foobar", "bar") = "foo"
+     * StringUtils.chomp("foobar", "baz") = "foobar"
+     * StringUtils.chomp("foo", "foo")    = ""
+     * StringUtils.chomp("foo ", "foo")   = "foo "
+     * StringUtils.chomp(" foo", "foo")   = " "
+     * StringUtils.chomp("foo", "foooo")  = "foo"
+     * StringUtils.chomp("foo", "")       = "foo"
+     * StringUtils.chomp("foo", null)     = "foo"
+     * 
+ * + * @param str the String to chomp from, may be null + * @param separator separator String, may be null + * @return String without trailing separator, {@code null} if null String input + * @deprecated This feature will be removed in Lang 4.0, use {@link StringUtils#removeEnd(String, String)} instead + */ + @Deprecated + public static String chomp(String str, String separator) { + return removeEnd(str,separator); + } + + // Chopping + //----------------------------------------------------------------------- + /** + *

Remove the last character from a String.

+ * + *

If the String ends in {@code \r\n}, then remove both + * of them.

+ * + *
+     * StringUtils.chop(null)          = null
+     * StringUtils.chop("")            = ""
+     * StringUtils.chop("abc \r")      = "abc "
+     * StringUtils.chop("abc\n")       = "abc"
+     * StringUtils.chop("abc\r\n")     = "abc"
+     * StringUtils.chop("abc")         = "ab"
+     * StringUtils.chop("abc\nabc")    = "abc\nab"
+     * StringUtils.chop("a")           = ""
+     * StringUtils.chop("\r")          = ""
+     * StringUtils.chop("\n")          = ""
+     * StringUtils.chop("\r\n")        = ""
+     * 
+ * + * @param str the String to chop last character from, may be null + * @return String without last character, {@code null} if null String input + */ + public static String chop(String str) { + if (str == null) { + return null; + } + int strLen = str.length(); + if (strLen < 2) { + return EMPTY; + } + int lastIdx = strLen - 1; + String ret = str.substring(0, lastIdx); + char last = str.charAt(lastIdx); + if (last == CharUtils.LF && ret.charAt(lastIdx - 1) == CharUtils.CR) { + return ret.substring(0, lastIdx - 1); + } + return ret; + } + + // Conversion + //----------------------------------------------------------------------- + + // Padding + //----------------------------------------------------------------------- + /** + *

Repeat a String {@code repeat} times to form a + * new String.

+ * + *
+     * StringUtils.repeat(null, 2) = null
+     * StringUtils.repeat("", 0)   = ""
+     * StringUtils.repeat("", 2)   = ""
+     * StringUtils.repeat("a", 3)  = "aaa"
+     * StringUtils.repeat("ab", 2) = "abab"
+     * StringUtils.repeat("a", -2) = ""
+     * 
+ * + * @param str the String to repeat, may be null + * @param repeat number of times to repeat str, negative treated as zero + * @return a new String consisting of the original String repeated, + * {@code null} if null String input + */ + public static String repeat(String str, int repeat) { + // Performance tuned for 2.0 (JDK1.4) + + if (str == null) { + return null; + } + if (repeat <= 0) { + return EMPTY; + } + int inputLength = str.length(); + if (repeat == 1 || inputLength == 0) { + return str; + } + if (inputLength == 1 && repeat <= PAD_LIMIT) { + return repeat(str.charAt(0), repeat); + } + + int outputLength = inputLength * repeat; + switch (inputLength) { + case 1 : + return repeat(str.charAt(0), repeat); + case 2 : + char ch0 = str.charAt(0); + char ch1 = str.charAt(1); + char[] output2 = new char[outputLength]; + for (int i = repeat * 2 - 2; i >= 0; i--, i--) { + output2[i] = ch0; + output2[i + 1] = ch1; + } + return new String(output2); + default : + StringBuilder buf = new StringBuilder(outputLength); + for (int i = 0; i < repeat; i++) { + buf.append(str); + } + return buf.toString(); + } + } + + /** + *

Repeat a String {@code repeat} times to form a + * new String, with a String separator injected each time.

+ * + *
+     * StringUtils.repeat(null, null, 2) = null
+     * StringUtils.repeat(null, "x", 2)  = null
+     * StringUtils.repeat("", null, 0)   = ""
+     * StringUtils.repeat("", "", 2)     = ""
+     * StringUtils.repeat("", "x", 3)    = "xxx"
+     * StringUtils.repeat("?", ", ", 3)  = "?, ?, ?"
+     * 
+ * + * @param str the String to repeat, may be null + * @param separator the String to inject, may be null + * @param repeat number of times to repeat str, negative treated as zero + * @return a new String consisting of the original String repeated, + * {@code null} if null String input + * @since 2.5 + */ + public static String repeat(String str, String separator, int repeat) { + if(str == null || separator == null) { + return repeat(str, repeat); + } else { + // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it + String result = repeat(str + separator, repeat); + return removeEnd(result, separator); + } + } + + /** + *

Returns padding using the specified delimiter repeated + * to a given length.

+ * + *
+     * StringUtils.repeat(0, 'e')  = ""
+     * StringUtils.repeat(3, 'e')  = "eee"
+     * StringUtils.repeat(-2, 'e') = ""
+     * 
+ * + *

Note: this method doesn't not support padding with + * Unicode Supplementary Characters + * as they require a pair of {@code char}s to be represented. + * If you are needing to support full I18N of your applications + * consider using {@link #repeat(String, int)} instead. + *

+ * + * @param ch character to repeat + * @param repeat number of times to repeat char, negative treated as zero + * @return String with repeated character + * @see #repeat(String, int) + */ + public static String repeat(char ch, int repeat) { + char[] buf = new char[repeat]; + for (int i = repeat - 1; i >= 0; i--) { + buf[i] = ch; + } + return new String(buf); + } + + /** + *

Right pad a String with spaces (' ').

+ * + *

The String is padded to the size of {@code size}.

+ * + *
+     * StringUtils.rightPad(null, *)   = null
+     * StringUtils.rightPad("", 3)     = "   "
+     * StringUtils.rightPad("bat", 3)  = "bat"
+     * StringUtils.rightPad("bat", 5)  = "bat  "
+     * StringUtils.rightPad("bat", 1)  = "bat"
+     * StringUtils.rightPad("bat", -1) = "bat"
+     * 
+ * + * @param str the String to pad out, may be null + * @param size the size to pad to + * @return right padded String or original String if no padding is necessary, + * {@code null} if null String input + */ + public static String rightPad(String str, int size) { + return rightPad(str, size, ' '); + } + + /** + *

Right pad a String with a specified character.

+ * + *

The String is padded to the size of {@code size}.

+ * + *
+     * StringUtils.rightPad(null, *, *)     = null
+     * StringUtils.rightPad("", 3, 'z')     = "zzz"
+     * StringUtils.rightPad("bat", 3, 'z')  = "bat"
+     * StringUtils.rightPad("bat", 5, 'z')  = "batzz"
+     * StringUtils.rightPad("bat", 1, 'z')  = "bat"
+     * StringUtils.rightPad("bat", -1, 'z') = "bat"
+     * 
+ * + * @param str the String to pad out, may be null + * @param size the size to pad to + * @param padChar the character to pad with + * @return right padded String or original String if no padding is necessary, + * {@code null} if null String input + * @since 2.0 + */ + public static String rightPad(String str, int size, char padChar) { + if (str == null) { + return null; + } + int pads = size - str.length(); + if (pads <= 0) { + return str; // returns original String when possible + } + if (pads > PAD_LIMIT) { + return rightPad(str, size, String.valueOf(padChar)); + } + return str.concat(repeat(padChar, pads)); + } + + /** + *

Right pad a String with a specified String.

+ * + *

The String is padded to the size of {@code size}.

+ * + *
+     * StringUtils.rightPad(null, *, *)      = null
+     * StringUtils.rightPad("", 3, "z")      = "zzz"
+     * StringUtils.rightPad("bat", 3, "yz")  = "bat"
+     * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
+     * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
+     * StringUtils.rightPad("bat", 1, "yz")  = "bat"
+     * StringUtils.rightPad("bat", -1, "yz") = "bat"
+     * StringUtils.rightPad("bat", 5, null)  = "bat  "
+     * StringUtils.rightPad("bat", 5, "")    = "bat  "
+     * 
+ * + * @param str the String to pad out, may be null + * @param size the size to pad to + * @param padStr the String to pad with, null or empty treated as single space + * @return right padded String or original String if no padding is necessary, + * {@code null} if null String input + */ + public static String rightPad(String str, int size, String padStr) { + if (str == null) { + return null; + } + if (isEmpty(padStr)) { + padStr = " "; + } + int padLen = padStr.length(); + int strLen = str.length(); + int pads = size - strLen; + if (pads <= 0) { + return str; // returns original String when possible + } + if (padLen == 1 && pads <= PAD_LIMIT) { + return rightPad(str, size, padStr.charAt(0)); + } + + if (pads == padLen) { + return str.concat(padStr); + } else if (pads < padLen) { + return str.concat(padStr.substring(0, pads)); + } else { + char[] padding = new char[pads]; + char[] padChars = padStr.toCharArray(); + for (int i = 0; i < pads; i++) { + padding[i] = padChars[i % padLen]; + } + return str.concat(new String(padding)); + } + } + + /** + *

Left pad a String with spaces (' ').

+ * + *

The String is padded to the size of {@code size}.

+ * + *
+     * StringUtils.leftPad(null, *)   = null
+     * StringUtils.leftPad("", 3)     = "   "
+     * StringUtils.leftPad("bat", 3)  = "bat"
+     * StringUtils.leftPad("bat", 5)  = "  bat"
+     * StringUtils.leftPad("bat", 1)  = "bat"
+     * StringUtils.leftPad("bat", -1) = "bat"
+     * 
+ * + * @param str the String to pad out, may be null + * @param size the size to pad to + * @return left padded String or original String if no padding is necessary, + * {@code null} if null String input + */ + public static String leftPad(String str, int size) { + return leftPad(str, size, ' '); + } + + /** + *

Left pad a String with a specified character.

+ * + *

Pad to a size of {@code size}.

+ * + *
+     * StringUtils.leftPad(null, *, *)     = null
+     * StringUtils.leftPad("", 3, 'z')     = "zzz"
+     * StringUtils.leftPad("bat", 3, 'z')  = "bat"
+     * StringUtils.leftPad("bat", 5, 'z')  = "zzbat"
+     * StringUtils.leftPad("bat", 1, 'z')  = "bat"
+     * StringUtils.leftPad("bat", -1, 'z') = "bat"
+     * 
+ * + * @param str the String to pad out, may be null + * @param size the size to pad to + * @param padChar the character to pad with + * @return left padded String or original String if no padding is necessary, + * {@code null} if null String input + * @since 2.0 + */ + public static String leftPad(String str, int size, char padChar) { + if (str == null) { + return null; + } + int pads = size - str.length(); + if (pads <= 0) { + return str; // returns original String when possible + } + if (pads > PAD_LIMIT) { + return leftPad(str, size, String.valueOf(padChar)); + } + return repeat(padChar, pads).concat(str); + } + + /** + *

Left pad a String with a specified String.

+ * + *

Pad to a size of {@code size}.

+ * + *
+     * StringUtils.leftPad(null, *, *)      = null
+     * StringUtils.leftPad("", 3, "z")      = "zzz"
+     * StringUtils.leftPad("bat", 3, "yz")  = "bat"
+     * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
+     * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
+     * StringUtils.leftPad("bat", 1, "yz")  = "bat"
+     * StringUtils.leftPad("bat", -1, "yz") = "bat"
+     * StringUtils.leftPad("bat", 5, null)  = "  bat"
+     * StringUtils.leftPad("bat", 5, "")    = "  bat"
+     * 
+ * + * @param str the String to pad out, may be null + * @param size the size to pad to + * @param padStr the String to pad with, null or empty treated as single space + * @return left padded String or original String if no padding is necessary, + * {@code null} if null String input + */ + public static String leftPad(String str, int size, String padStr) { + if (str == null) { + return null; + } + if (isEmpty(padStr)) { + padStr = " "; + } + int padLen = padStr.length(); + int strLen = str.length(); + int pads = size - strLen; + if (pads <= 0) { + return str; // returns original String when possible + } + if (padLen == 1 && pads <= PAD_LIMIT) { + return leftPad(str, size, padStr.charAt(0)); + } + + if (pads == padLen) { + return padStr.concat(str); + } else if (pads < padLen) { + return padStr.substring(0, pads).concat(str); + } else { + char[] padding = new char[pads]; + char[] padChars = padStr.toCharArray(); + for (int i = 0; i < pads; i++) { + padding[i] = padChars[i % padLen]; + } + return new String(padding).concat(str); + } + } + + /** + * Gets a CharSequence length or {@code 0} if the CharSequence is + * {@code null}. + * + * @param cs + * a CharSequence or {@code null} + * @return CharSequence length or {@code 0} if the CharSequence is + * {@code null}. + * @since 2.4 + * @since 3.0 Changed signature from length(String) to length(CharSequence) + */ + public static int length(CharSequence cs) { + return cs == null ? 0 : cs.length(); + } + + // Centering + //----------------------------------------------------------------------- + /** + *

Centers a String in a larger String of size {@code size} + * using the space character (' ').

+ * + *

If the size is less than the String length, the String is returned. + * A {@code null} String returns {@code null}. + * A negative size is treated as zero.

+ * + *

Equivalent to {@code center(str, size, " ")}.

+ * + *
+     * StringUtils.center(null, *)   = null
+     * StringUtils.center("", 4)     = "    "
+     * StringUtils.center("ab", -1)  = "ab"
+     * StringUtils.center("ab", 4)   = " ab "
+     * StringUtils.center("abcd", 2) = "abcd"
+     * StringUtils.center("a", 4)    = " a  "
+     * 
+ * + * @param str the String to center, may be null + * @param size the int size of new String, negative treated as zero + * @return centered String, {@code null} if null String input + */ + public static String center(String str, int size) { + return center(str, size, ' '); + } + + /** + *

Centers a String in a larger String of size {@code size}. + * Uses a supplied character as the value to pad the String with.

+ * + *

If the size is less than the String length, the String is returned. + * A {@code null} String returns {@code null}. + * A negative size is treated as zero.

+ * + *
+     * StringUtils.center(null, *, *)     = null
+     * StringUtils.center("", 4, ' ')     = "    "
+     * StringUtils.center("ab", -1, ' ')  = "ab"
+     * StringUtils.center("ab", 4, ' ')   = " ab"
+     * StringUtils.center("abcd", 2, ' ') = "abcd"
+     * StringUtils.center("a", 4, ' ')    = " a  "
+     * StringUtils.center("a", 4, 'y')    = "yayy"
+     * 
+ * + * @param str the String to center, may be null + * @param size the int size of new String, negative treated as zero + * @param padChar the character to pad the new String with + * @return centered String, {@code null} if null String input + * @since 2.0 + */ + public static String center(String str, int size, char padChar) { + if (str == null || size <= 0) { + return str; + } + int strLen = str.length(); + int pads = size - strLen; + if (pads <= 0) { + return str; + } + str = leftPad(str, strLen + pads / 2, padChar); + str = rightPad(str, size, padChar); + return str; + } + + /** + *

Centers a String in a larger String of size {@code size}. + * Uses a supplied String as the value to pad the String with.

+ * + *

If the size is less than the String length, the String is returned. + * A {@code null} String returns {@code null}. + * A negative size is treated as zero.

+ * + *
+     * StringUtils.center(null, *, *)     = null
+     * StringUtils.center("", 4, " ")     = "    "
+     * StringUtils.center("ab", -1, " ")  = "ab"
+     * StringUtils.center("ab", 4, " ")   = " ab"
+     * StringUtils.center("abcd", 2, " ") = "abcd"
+     * StringUtils.center("a", 4, " ")    = " a  "
+     * StringUtils.center("a", 4, "yz")   = "yayz"
+     * StringUtils.center("abc", 7, null) = "  abc  "
+     * StringUtils.center("abc", 7, "")   = "  abc  "
+     * 
+ * + * @param str the String to center, may be null + * @param size the int size of new String, negative treated as zero + * @param padStr the String to pad the new String with, must not be null or empty + * @return centered String, {@code null} if null String input + * @throws IllegalArgumentException if padStr is {@code null} or empty + */ + public static String center(String str, int size, String padStr) { + if (str == null || size <= 0) { + return str; + } + if (isEmpty(padStr)) { + padStr = " "; + } + int strLen = str.length(); + int pads = size - strLen; + if (pads <= 0) { + return str; + } + str = leftPad(str, strLen + pads / 2, padStr); + str = rightPad(str, size, padStr); + return str; + } + + // Case conversion + //----------------------------------------------------------------------- + /** + *

Converts a String to upper case as per {@link String#toUpperCase()}.

+ * + *

A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.upperCase(null)  = null
+     * StringUtils.upperCase("")    = ""
+     * StringUtils.upperCase("aBc") = "ABC"
+     * 
+ * + *

Note: As described in the documentation for {@link String#toUpperCase()}, + * the result of this method is affected by the current locale. + * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)} + * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

+ * + * @param str the String to upper case, may be null + * @return the upper cased String, {@code null} if null String input + */ + public static String upperCase(String str) { + if (str == null) { + return null; + } + return str.toUpperCase(); + } + + /** + *

Converts a String to upper case as per {@link String#toUpperCase(Locale)}.

+ * + *

A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.upperCase(null, Locale.ENGLISH)  = null
+     * StringUtils.upperCase("", Locale.ENGLISH)    = ""
+     * StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC"
+     * 
+ * + * @param str the String to upper case, may be null + * @param locale the locale that defines the case transformation rules, must not be null + * @return the upper cased String, {@code null} if null String input + * @since 2.5 + */ + public static String upperCase(String str, Locale locale) { + if (str == null) { + return null; + } + return str.toUpperCase(locale); + } + + /** + *

Converts a String to lower case as per {@link String#toLowerCase()}.

+ * + *

A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.lowerCase(null)  = null
+     * StringUtils.lowerCase("")    = ""
+     * StringUtils.lowerCase("aBc") = "abc"
+     * 
+ * + *

Note: As described in the documentation for {@link String#toLowerCase()}, + * the result of this method is affected by the current locale. + * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)} + * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

+ * + * @param str the String to lower case, may be null + * @return the lower cased String, {@code null} if null String input + */ + public static String lowerCase(String str) { + if (str == null) { + return null; + } + return str.toLowerCase(); + } + + /** + *

Converts a String to lower case as per {@link String#toLowerCase(Locale)}.

+ * + *

A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.lowerCase(null, Locale.ENGLISH)  = null
+     * StringUtils.lowerCase("", Locale.ENGLISH)    = ""
+     * StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc"
+     * 
+ * + * @param str the String to lower case, may be null + * @param locale the locale that defines the case transformation rules, must not be null + * @return the lower cased String, {@code null} if null String input + * @since 2.5 + */ + public static String lowerCase(String str, Locale locale) { + if (str == null) { + return null; + } + return str.toLowerCase(locale); + } + + /** + *

Capitalizes a String changing the first letter to title case as + * per {@link Character#toTitleCase(char)}. No other letters are changed.

+ * + *

For a word based algorithm, see {@link external.org.apache.commons.lang3.text.WordUtils#capitalize(String)}. + * A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.capitalize(null)  = null
+     * StringUtils.capitalize("")    = ""
+     * StringUtils.capitalize("cat") = "Cat"
+     * StringUtils.capitalize("cAt") = "CAt"
+     * 
+ * + * @param str the String to capitalize, may be null + * @return the capitalized String, {@code null} if null String input + * @see external.org.apache.commons.lang3.text.WordUtils#capitalize(String) + * @see #uncapitalize(String) + * @since 2.0 + */ + public static String capitalize(String str) { + int strLen; + if (str == null || (strLen = str.length()) == 0) { + return str; + } + return new StringBuilder(strLen) + .append(Character.toTitleCase(str.charAt(0))) + .append(str.substring(1)) + .toString(); + } + + /** + *

Uncapitalizes a String changing the first letter to title case as + * per {@link Character#toLowerCase(char)}. No other letters are changed.

+ * + *

For a word based algorithm, see {@link external.org.apache.commons.lang3.text.WordUtils#uncapitalize(String)}. + * A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.uncapitalize(null)  = null
+     * StringUtils.uncapitalize("")    = ""
+     * StringUtils.uncapitalize("Cat") = "cat"
+     * StringUtils.uncapitalize("CAT") = "cAT"
+     * 
+ * + * @param str the String to uncapitalize, may be null + * @return the uncapitalized String, {@code null} if null String input + * @see external.org.apache.commons.lang3.text.WordUtils#uncapitalize(String) + * @see #capitalize(String) + * @since 2.0 + */ + public static String uncapitalize(String str) { + int strLen; + if (str == null || (strLen = str.length()) == 0) { + return str; + } + return new StringBuilder(strLen) + .append(Character.toLowerCase(str.charAt(0))) + .append(str.substring(1)) + .toString(); + } + + /** + *

Swaps the case of a String changing upper and title case to + * lower case, and lower case to upper case.

+ * + *
    + *
  • Upper case character converts to Lower case
  • + *
  • Title case character converts to Lower case
  • + *
  • Lower case character converts to Upper case
  • + *
+ * + *

For a word based algorithm, see {@link external.org.apache.commons.lang3.text.WordUtils#swapCase(String)}. + * A {@code null} input String returns {@code null}.

+ * + *
+     * StringUtils.swapCase(null)                 = null
+     * StringUtils.swapCase("")                   = ""
+     * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
+     * 
+ * + *

NOTE: This method changed in Lang version 2.0. + * It no longer performs a word based algorithm. + * If you only use ASCII, you will notice no change. + * That functionality is available in org.apache.commons.lang3.text.WordUtils.

+ * + * @param str the String to swap case, may be null + * @return the changed String, {@code null} if null String input + */ + public static String swapCase(String str) { + if (StringUtils.isEmpty(str)) { + return str; + } + + char[] buffer = str.toCharArray(); + + for (int i = 0; i < buffer.length; i++) { + char ch = buffer[i]; + if (Character.isUpperCase(ch)) { + buffer[i] = Character.toLowerCase(ch); + } else if (Character.isTitleCase(ch)) { + buffer[i] = Character.toLowerCase(ch); + } else if (Character.isLowerCase(ch)) { + buffer[i] = Character.toUpperCase(ch); + } + } + return new String(buffer); + } + + // Count matches + //----------------------------------------------------------------------- + /** + *

Counts how many times the substring appears in the larger string.

+ * + *

A {@code null} or empty ("") String input returns {@code 0}.

+ * + *
+     * StringUtils.countMatches(null, *)       = 0
+     * StringUtils.countMatches("", *)         = 0
+     * StringUtils.countMatches("abba", null)  = 0
+     * StringUtils.countMatches("abba", "")    = 0
+     * StringUtils.countMatches("abba", "a")   = 2
+     * StringUtils.countMatches("abba", "ab")  = 1
+     * StringUtils.countMatches("abba", "xxx") = 0
+     * 
+ * + * @param str the CharSequence to check, may be null + * @param sub the substring to count, may be null + * @return the number of occurrences, 0 if either CharSequence is {@code null} + * @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence) + */ + public static int countMatches(CharSequence str, CharSequence sub) { + if (isEmpty(str) || isEmpty(sub)) { + return 0; + } + int count = 0; + int idx = 0; + while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) { + count++; + idx += sub.length(); + } + return count; + } + + // Character Tests + //----------------------------------------------------------------------- + /** + *

Checks if the CharSequence contains only Unicode letters.

+ * + *

{@code null} will return {@code false}. + * An empty CharSequence (length()=0) will return {@code false}.

+ * + *
+     * StringUtils.isAlpha(null)   = false
+     * StringUtils.isAlpha("")     = false
+     * StringUtils.isAlpha("  ")   = false
+     * StringUtils.isAlpha("abc")  = true
+     * StringUtils.isAlpha("ab2c") = false
+     * StringUtils.isAlpha("ab-c") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if only contains letters, and is non-null + * @since 3.0 Changed signature from isAlpha(String) to isAlpha(CharSequence) + * @since 3.0 Changed "" to return false and not true + */ + public static boolean isAlpha(CharSequence cs) { + if (cs == null || cs.length() == 0) { + return false; + } + int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (Character.isLetter(cs.charAt(i)) == false) { + return false; + } + } + return true; + } + + /** + *

Checks if the CharSequence contains only Unicode letters and + * space (' ').

+ * + *

{@code null} will return {@code false} + * An empty CharSequence (length()=0) will return {@code true}.

+ * + *
+     * StringUtils.isAlphaSpace(null)   = false
+     * StringUtils.isAlphaSpace("")     = true
+     * StringUtils.isAlphaSpace("  ")   = true
+     * StringUtils.isAlphaSpace("abc")  = true
+     * StringUtils.isAlphaSpace("ab c") = true
+     * StringUtils.isAlphaSpace("ab2c") = false
+     * StringUtils.isAlphaSpace("ab-c") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if only contains letters and space, + * and is non-null + * @since 3.0 Changed signature from isAlphaSpace(String) to isAlphaSpace(CharSequence) + */ + public static boolean isAlphaSpace(CharSequence cs) { + if (cs == null) { + return false; + } + int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (Character.isLetter(cs.charAt(i)) == false && cs.charAt(i) != ' ') { + return false; + } + } + return true; + } + + /** + *

Checks if the CharSequence contains only Unicode letters or digits.

+ * + *

{@code null} will return {@code false}. + * An empty CharSequence (length()=0) will return {@code false}.

+ * + *
+     * StringUtils.isAlphanumeric(null)   = false
+     * StringUtils.isAlphanumeric("")     = false
+     * StringUtils.isAlphanumeric("  ")   = false
+     * StringUtils.isAlphanumeric("abc")  = true
+     * StringUtils.isAlphanumeric("ab c") = false
+     * StringUtils.isAlphanumeric("ab2c") = true
+     * StringUtils.isAlphanumeric("ab-c") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if only contains letters or digits, + * and is non-null + * @since 3.0 Changed signature from isAlphanumeric(String) to isAlphanumeric(CharSequence) + * @since 3.0 Changed "" to return false and not true + */ + public static boolean isAlphanumeric(CharSequence cs) { + if (cs == null || cs.length() == 0) { + return false; + } + int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (Character.isLetterOrDigit(cs.charAt(i)) == false) { + return false; + } + } + return true; + } + + /** + *

Checks if the CharSequence contains only Unicode letters, digits + * or space ({@code ' '}).

+ * + *

{@code null} will return {@code false}. + * An empty CharSequence (length()=0) will return {@code true}.

+ * + *
+     * StringUtils.isAlphanumericSpace(null)   = false
+     * StringUtils.isAlphanumericSpace("")     = true
+     * StringUtils.isAlphanumericSpace("  ")   = true
+     * StringUtils.isAlphanumericSpace("abc")  = true
+     * StringUtils.isAlphanumericSpace("ab c") = true
+     * StringUtils.isAlphanumericSpace("ab2c") = true
+     * StringUtils.isAlphanumericSpace("ab-c") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if only contains letters, digits or space, + * and is non-null + * @since 3.0 Changed signature from isAlphanumericSpace(String) to isAlphanumericSpace(CharSequence) + */ + public static boolean isAlphanumericSpace(CharSequence cs) { + if (cs == null) { + return false; + } + int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (Character.isLetterOrDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') { + return false; + } + } + return true; + } + + /** + *

Checks if the CharSequence contains only ASCII printable characters.

+ * + *

{@code null} will return {@code false}. + * An empty CharSequence (length()=0) will return {@code true}.

+ * + *
+     * StringUtils.isAsciiPrintable(null)     = false
+     * StringUtils.isAsciiPrintable("")       = true
+     * StringUtils.isAsciiPrintable(" ")      = true
+     * StringUtils.isAsciiPrintable("Ceki")   = true
+     * StringUtils.isAsciiPrintable("ab2c")   = true
+     * StringUtils.isAsciiPrintable("!ab-c~") = true
+     * StringUtils.isAsciiPrintable("\u0020") = true
+     * StringUtils.isAsciiPrintable("\u0021") = true
+     * StringUtils.isAsciiPrintable("\u007e") = true
+     * StringUtils.isAsciiPrintable("\u007f") = false
+     * StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if every character is in the range + * 32 thru 126 + * @since 2.1 + * @since 3.0 Changed signature from isAsciiPrintable(String) to isAsciiPrintable(CharSequence) + */ + public static boolean isAsciiPrintable(CharSequence cs) { + if (cs == null) { + return false; + } + int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (CharUtils.isAsciiPrintable(cs.charAt(i)) == false) { + return false; + } + } + return true; + } + + /** + *

Checks if the CharSequence contains only Unicode digits. + * A decimal point is not a Unicode digit and returns false.

+ * + *

{@code null} will return {@code false}. + * An empty CharSequence (length()=0) will return {@code false}.

+ * + *
+     * StringUtils.isNumeric(null)   = false
+     * StringUtils.isNumeric("")     = false
+     * StringUtils.isNumeric("  ")   = false
+     * StringUtils.isNumeric("123")  = true
+     * StringUtils.isNumeric("12 3") = false
+     * StringUtils.isNumeric("ab2c") = false
+     * StringUtils.isNumeric("12-3") = false
+     * StringUtils.isNumeric("12.3") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if only contains digits, and is non-null + * @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence) + * @since 3.0 Changed "" to return false and not true + */ + public static boolean isNumeric(CharSequence cs) { + if (cs == null || cs.length() == 0) { + return false; + } + int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (Character.isDigit(cs.charAt(i)) == false) { + return false; + } + } + return true; + } + + /** + *

Checks if the CharSequence contains only Unicode digits or space + * ({@code ' '}). + * A decimal point is not a Unicode digit and returns false.

+ * + *

{@code null} will return {@code false}. + * An empty CharSequence (length()=0) will return {@code true}.

+ * + *
+     * StringUtils.isNumericSpace(null)   = false
+     * StringUtils.isNumericSpace("")     = true
+     * StringUtils.isNumericSpace("  ")   = true
+     * StringUtils.isNumericSpace("123")  = true
+     * StringUtils.isNumericSpace("12 3") = true
+     * StringUtils.isNumericSpace("ab2c") = false
+     * StringUtils.isNumericSpace("12-3") = false
+     * StringUtils.isNumericSpace("12.3") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if only contains digits or space, + * and is non-null + * @since 3.0 Changed signature from isNumericSpace(String) to isNumericSpace(CharSequence) + */ + public static boolean isNumericSpace(CharSequence cs) { + if (cs == null) { + return false; + } + int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (Character.isDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') { + return false; + } + } + return true; + } + + /** + *

Checks if the CharSequence contains only whitespace.

+ * + *

{@code null} will return {@code false}. + * An empty CharSequence (length()=0) will return {@code true}.

+ * + *
+     * StringUtils.isWhitespace(null)   = false
+     * StringUtils.isWhitespace("")     = true
+     * StringUtils.isWhitespace("  ")   = true
+     * StringUtils.isWhitespace("abc")  = false
+     * StringUtils.isWhitespace("ab2c") = false
+     * StringUtils.isWhitespace("ab-c") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if only contains whitespace, and is non-null + * @since 2.0 + * @since 3.0 Changed signature from isWhitespace(String) to isWhitespace(CharSequence) + */ + public static boolean isWhitespace(CharSequence cs) { + if (cs == null) { + return false; + } + int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (Character.isWhitespace(cs.charAt(i)) == false) { + return false; + } + } + return true; + } + + /** + *

Checks if the CharSequence contains only lowercase characters.

+ * + *

{@code null} will return {@code false}. + * An empty CharSequence (length()=0) will return {@code false}.

+ * + *
+     * StringUtils.isAllLowerCase(null)   = false
+     * StringUtils.isAllLowerCase("")     = false
+     * StringUtils.isAllLowerCase("  ")   = false
+     * StringUtils.isAllLowerCase("abc")  = true
+     * StringUtils.isAllLowerCase("abC") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if only contains lowercase characters, and is non-null + * @since 2.5 + * @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence) + */ + public static boolean isAllLowerCase(CharSequence cs) { + if (cs == null || isEmpty(cs)) { + return false; + } + int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (Character.isLowerCase(cs.charAt(i)) == false) { + return false; + } + } + return true; + } + + /** + *

Checks if the CharSequence contains only uppercase characters.

+ * + *

{@code null} will return {@code false}. + * An empty String (length()=0) will return {@code false}.

+ * + *
+     * StringUtils.isAllUpperCase(null)   = false
+     * StringUtils.isAllUpperCase("")     = false
+     * StringUtils.isAllUpperCase("  ")   = false
+     * StringUtils.isAllUpperCase("ABC")  = true
+     * StringUtils.isAllUpperCase("aBC") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if only contains uppercase characters, and is non-null + * @since 2.5 + * @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence) + */ + public static boolean isAllUpperCase(CharSequence cs) { + if (cs == null || isEmpty(cs)) { + return false; + } + int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (Character.isUpperCase(cs.charAt(i)) == false) { + return false; + } + } + return true; + } + + // Defaults + //----------------------------------------------------------------------- + /** + *

Returns either the passed in String, + * or if the String is {@code null}, an empty String ("").

+ * + *
+     * StringUtils.defaultString(null)  = ""
+     * StringUtils.defaultString("")    = ""
+     * StringUtils.defaultString("bat") = "bat"
+     * 
+ * + * @see ObjectUtils#toString(Object) + * @see String#valueOf(Object) + * @param str the String to check, may be null + * @return the passed in String, or the empty String if it + * was {@code null} + */ + public static String defaultString(String str) { + return str == null ? EMPTY : str; + } + + /** + *

Returns either the passed in String, or if the String is + * {@code null}, the value of {@code defaultStr}.

+ * + *
+     * StringUtils.defaultString(null, "NULL")  = "NULL"
+     * StringUtils.defaultString("", "NULL")    = ""
+     * StringUtils.defaultString("bat", "NULL") = "bat"
+     * 
+ * + * @see ObjectUtils#toString(Object,String) + * @see String#valueOf(Object) + * @param str the String to check, may be null + * @param defaultStr the default String to return + * if the input is {@code null}, may be null + * @return the passed in String, or the default if it was {@code null} + */ + public static String defaultString(String str, String defaultStr) { + return str == null ? defaultStr : str; + } + + /** + *

Returns either the passed in CharSequence, or if the CharSequence is + * whitespace, empty ("") or {@code null}, the value of {@code defaultStr}.

+ * + *
+     * StringUtils.defaultIfBlank(null, "NULL")  = "NULL"
+     * StringUtils.defaultIfBlank("", "NULL")    = "NULL"
+     * StringUtils.defaultIfBlank(" ", "NULL")   = "NULL"
+     * StringUtils.defaultIfBlank("bat", "NULL") = "bat"
+     * StringUtils.defaultIfBlank("", null)      = null
+     * 
+ * @param the specific kind of CharSequence + * @param str the CharSequence to check, may be null + * @param defaultStr the default CharSequence to return + * if the input is whitespace, empty ("") or {@code null}, may be null + * @return the passed in CharSequence, or the default + * @see StringUtils#defaultString(String, String) + */ + public static T defaultIfBlank(T str, T defaultStr) { + return StringUtils.isBlank(str) ? defaultStr : str; + } + + /** + *

Returns either the passed in CharSequence, or if the CharSequence is + * empty or {@code null}, the value of {@code defaultStr}.

+ * + *
+     * StringUtils.defaultIfEmpty(null, "NULL")  = "NULL"
+     * StringUtils.defaultIfEmpty("", "NULL")    = "NULL"
+     * StringUtils.defaultIfEmpty(" ", "NULL")   = " "
+     * StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
+     * StringUtils.defaultIfEmpty("", null)      = null
+     * 
+ * @param the specific kind of CharSequence + * @param str the CharSequence to check, may be null + * @param defaultStr the default CharSequence to return + * if the input is empty ("") or {@code null}, may be null + * @return the passed in CharSequence, or the default + * @see StringUtils#defaultString(String, String) + */ + public static T defaultIfEmpty(T str, T defaultStr) { + return StringUtils.isEmpty(str) ? defaultStr : str; + } + + // Reversing + //----------------------------------------------------------------------- + /** + *

Reverses a String as per {@link StringBuilder#reverse()}.

+ * + *

A {@code null} String returns {@code null}.

+ * + *
+     * StringUtils.reverse(null)  = null
+     * StringUtils.reverse("")    = ""
+     * StringUtils.reverse("bat") = "tab"
+     * 
+ * + * @param str the String to reverse, may be null + * @return the reversed String, {@code null} if null String input + */ + public static String reverse(String str) { + if (str == null) { + return null; + } + return new StringBuilder(str).reverse().toString(); + } + + /** + *

Reverses a String that is delimited by a specific character.

+ * + *

The Strings between the delimiters are not reversed. + * Thus java.lang.String becomes String.lang.java (if the delimiter + * is {@code '.'}).

+ * + *
+     * StringUtils.reverseDelimited(null, *)      = null
+     * StringUtils.reverseDelimited("", *)        = ""
+     * StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
+     * StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
+     * 
+ * + * @param str the String to reverse, may be null + * @param separatorChar the separator character to use + * @return the reversed String, {@code null} if null String input + * @since 2.0 + */ + public static String reverseDelimited(String str, char separatorChar) { + if (str == null) { + return null; + } + // could implement manually, but simple way is to reuse other, + // probably slower, methods. + String[] strs = split(str, separatorChar); + ArrayUtils.reverse(strs); + return join(strs, separatorChar); + } + + // Abbreviating + //----------------------------------------------------------------------- + /** + *

Abbreviates a String using ellipses. This will turn + * "Now is the time for all good men" into "Now is the time for..."

+ * + *

Specifically: + *

    + *
  • If {@code str} is less than {@code maxWidth} characters + * long, return it.
  • + *
  • Else abbreviate it to {@code (substring(str, 0, max-3) + "...")}.
  • + *
  • If {@code maxWidth} is less than {@code 4}, throw an + * {@code IllegalArgumentException}.
  • + *
  • In no case will it return a String of length greater than + * {@code maxWidth}.
  • + *
+ *

+ * + *
+     * StringUtils.abbreviate(null, *)      = null
+     * StringUtils.abbreviate("", 4)        = ""
+     * StringUtils.abbreviate("abcdefg", 6) = "abc..."
+     * StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
+     * StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
+     * StringUtils.abbreviate("abcdefg", 4) = "a..."
+     * StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
+     * 
+ * + * @param str the String to check, may be null + * @param maxWidth maximum length of result String, must be at least 4 + * @return abbreviated String, {@code null} if null String input + * @throws IllegalArgumentException if the width is too small + * @since 2.0 + */ + public static String abbreviate(String str, int maxWidth) { + return abbreviate(str, 0, maxWidth); + } + + /** + *

Abbreviates a String using ellipses. This will turn + * "Now is the time for all good men" into "...is the time for..."

+ * + *

Works like {@code abbreviate(String, int)}, but allows you to specify + * a "left edge" offset. Note that this left edge is not necessarily going to + * be the leftmost character in the result, or the first character following the + * ellipses, but it will appear somewhere in the result. + * + *

In no case will it return a String of length greater than + * {@code maxWidth}.

+ * + *
+     * StringUtils.abbreviate(null, *, *)                = null
+     * StringUtils.abbreviate("", 0, 4)                  = ""
+     * StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
+     * StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."
+     * StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."
+     * StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."
+     * StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."
+     * StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
+     * StringUtils.abbreviate("abcdefghijklmno", 8, 10)  = "...ijklmno"
+     * StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
+     * StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
+     * StringUtils.abbreviate("abcdefghij", 0, 3)        = IllegalArgumentException
+     * StringUtils.abbreviate("abcdefghij", 5, 6)        = IllegalArgumentException
+     * 
+ * + * @param str the String to check, may be null + * @param offset left edge of source String + * @param maxWidth maximum length of result String, must be at least 4 + * @return abbreviated String, {@code null} if null String input + * @throws IllegalArgumentException if the width is too small + * @since 2.0 + */ + public static String abbreviate(String str, int offset, int maxWidth) { + if (str == null) { + return null; + } + if (maxWidth < 4) { + throw new IllegalArgumentException("Minimum abbreviation width is 4"); + } + if (str.length() <= maxWidth) { + return str; + } + if (offset > str.length()) { + offset = str.length(); + } + if (str.length() - offset < maxWidth - 3) { + offset = str.length() - (maxWidth - 3); + } + final String abrevMarker = "..."; + if (offset <= 4) { + return str.substring(0, maxWidth - 3) + abrevMarker; + } + if (maxWidth < 7) { + throw new IllegalArgumentException("Minimum abbreviation width with offset is 7"); + } + if (offset + maxWidth - 3 < str.length()) { + return abrevMarker + abbreviate(str.substring(offset), maxWidth - 3); + } + return abrevMarker + str.substring(str.length() - (maxWidth - 3)); + } + + /** + *

Abbreviates a String to the length passed, replacing the middle characters with the supplied + * replacement String.

+ * + *

This abbreviation only occurs if the following criteria is met: + *

    + *
  • Neither the String for abbreviation nor the replacement String are null or empty
  • + *
  • The length to truncate to is less than the length of the supplied String
  • + *
  • The length to truncate to is greater than 0
  • + *
  • The abbreviated String will have enough room for the length supplied replacement String + * and the first and last characters of the supplied String for abbreviation
  • + *
+ * Otherwise, the returned String will be the same as the supplied String for abbreviation. + *

+ * + *
+     * StringUtils.abbreviateMiddle(null, null, 0)      = null
+     * StringUtils.abbreviateMiddle("abc", null, 0)      = "abc"
+     * StringUtils.abbreviateMiddle("abc", ".", 0)      = "abc"
+     * StringUtils.abbreviateMiddle("abc", ".", 3)      = "abc"
+     * StringUtils.abbreviateMiddle("abcdef", ".", 4)     = "ab.f"
+     * 
+ * + * @param str the String to abbreviate, may be null + * @param middle the String to replace the middle characters with, may be null + * @param length the length to abbreviate {@code str} to. + * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation. + * @since 2.5 + */ + public static String abbreviateMiddle(String str, String middle, int length) { + if (isEmpty(str) || isEmpty(middle)) { + return str; + } + + if (length >= str.length() || length < middle.length()+2) { + return str; + } + + int targetSting = length-middle.length(); + int startOffset = targetSting/2+targetSting%2; + int endOffset = str.length()-targetSting/2; + + StringBuilder builder = new StringBuilder(length); + builder.append(str.substring(0,startOffset)); + builder.append(middle); + builder.append(str.substring(endOffset)); + + return builder.toString(); + } + + // Difference + //----------------------------------------------------------------------- + /** + *

Compares two Strings, and returns the portion where they differ. + * (More precisely, return the remainder of the second String, + * starting from where it's different from the first.)

+ * + *

For example, + * {@code difference("i am a machine", "i am a robot") -> "robot"}.

+ * + *
+     * StringUtils.difference(null, null) = null
+     * StringUtils.difference("", "") = ""
+     * StringUtils.difference("", "abc") = "abc"
+     * StringUtils.difference("abc", "") = ""
+     * StringUtils.difference("abc", "abc") = ""
+     * StringUtils.difference("ab", "abxyz") = "xyz"
+     * StringUtils.difference("abcde", "abxyz") = "xyz"
+     * StringUtils.difference("abcde", "xyz") = "xyz"
+     * 
+ * + * @param str1 the first String, may be null + * @param str2 the second String, may be null + * @return the portion of str2 where it differs from str1; returns the + * empty String if they are equal + * @since 2.0 + */ + public static String difference(String str1, String str2) { + if (str1 == null) { + return str2; + } + if (str2 == null) { + return str1; + } + int at = indexOfDifference(str1, str2); + if (at == INDEX_NOT_FOUND) { + return EMPTY; + } + return str2.substring(at); + } + + /** + *

Compares two CharSequences, and returns the index at which the + * CharSequences begin to differ.

+ * + *

For example, + * {@code indexOfDifference("i am a machine", "i am a robot") -> 7}

+ * + *
+     * StringUtils.indexOfDifference(null, null) = -1
+     * StringUtils.indexOfDifference("", "") = -1
+     * StringUtils.indexOfDifference("", "abc") = 0
+     * StringUtils.indexOfDifference("abc", "") = 0
+     * StringUtils.indexOfDifference("abc", "abc") = -1
+     * StringUtils.indexOfDifference("ab", "abxyz") = 2
+     * StringUtils.indexOfDifference("abcde", "abxyz") = 2
+     * StringUtils.indexOfDifference("abcde", "xyz") = 0
+     * 
+ * + * @param cs1 the first CharSequence, may be null + * @param cs2 the second CharSequence, may be null + * @return the index where cs1 and cs2 begin to differ; -1 if they are equal + * @since 2.0 + * @since 3.0 Changed signature from indexOfDifference(String, String) to + * indexOfDifference(CharSequence, CharSequence) + */ + public static int indexOfDifference(CharSequence cs1, CharSequence cs2) { + if (cs1 == cs2) { + return INDEX_NOT_FOUND; + } + if (cs1 == null || cs2 == null) { + return 0; + } + int i; + for (i = 0; i < cs1.length() && i < cs2.length(); ++i) { + if (cs1.charAt(i) != cs2.charAt(i)) { + break; + } + } + if (i < cs2.length() || i < cs1.length()) { + return i; + } + return INDEX_NOT_FOUND; + } + + /** + *

Compares all CharSequences in an array and returns the index at which the + * CharSequences begin to differ.

+ * + *

For example, + * indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7

+ * + *
+     * StringUtils.indexOfDifference(null) = -1
+     * StringUtils.indexOfDifference(new String[] {}) = -1
+     * StringUtils.indexOfDifference(new String[] {"abc"}) = -1
+     * StringUtils.indexOfDifference(new String[] {null, null}) = -1
+     * StringUtils.indexOfDifference(new String[] {"", ""}) = -1
+     * StringUtils.indexOfDifference(new String[] {"", null}) = 0
+     * StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
+     * StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
+     * StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
+     * StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
+     * StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
+     * StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
+     * StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
+     * StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
+     * StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
+     * StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
+     * StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
+     * 
+ * + * @param css array of CharSequences, entries may be null + * @return the index where the strings begin to differ; -1 if they are all equal + * @since 2.4 + * @since 3.0 Changed signature from indexOfDifference(String...) to indexOfDifference(CharSequence...) + */ + public static int indexOfDifference(CharSequence... css) { + if (css == null || css.length <= 1) { + return INDEX_NOT_FOUND; + } + boolean anyStringNull = false; + boolean allStringsNull = true; + int arrayLen = css.length; + int shortestStrLen = Integer.MAX_VALUE; + int longestStrLen = 0; + + // find the min and max string lengths; this avoids checking to make + // sure we are not exceeding the length of the string each time through + // the bottom loop. + for (int i = 0; i < arrayLen; i++) { + if (css[i] == null) { + anyStringNull = true; + shortestStrLen = 0; + } else { + allStringsNull = false; + shortestStrLen = Math.min(css[i].length(), shortestStrLen); + longestStrLen = Math.max(css[i].length(), longestStrLen); + } + } + + // handle lists containing all nulls or all empty strings + if (allStringsNull || longestStrLen == 0 && !anyStringNull) { + return INDEX_NOT_FOUND; + } + + // handle lists containing some nulls or some empty strings + if (shortestStrLen == 0) { + return 0; + } + + // find the position with the first difference across all strings + int firstDiff = -1; + for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) { + char comparisonChar = css[0].charAt(stringPos); + for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) { + if (css[arrayPos].charAt(stringPos) != comparisonChar) { + firstDiff = stringPos; + break; + } + } + if (firstDiff != -1) { + break; + } + } + + if (firstDiff == -1 && shortestStrLen != longestStrLen) { + // we compared all of the characters up to the length of the + // shortest string and didn't find a match, but the string lengths + // vary, so return the length of the shortest string. + return shortestStrLen; + } + return firstDiff; + } + + /** + *

Compares all Strings in an array and returns the initial sequence of + * characters that is common to all of them.

+ * + *

For example, + * getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "

+ * + *
+     * StringUtils.getCommonPrefix(null) = ""
+     * StringUtils.getCommonPrefix(new String[] {}) = ""
+     * StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
+     * StringUtils.getCommonPrefix(new String[] {null, null}) = ""
+     * StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
+     * StringUtils.getCommonPrefix(new String[] {"", null}) = ""
+     * StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
+     * StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
+     * StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
+     * StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
+     * StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
+     * StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
+     * StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
+     * StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
+     * StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
+     * StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
+     * StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
+     * 
+ * + * @param strs array of String objects, entries may be null + * @return the initial sequence of characters that are common to all Strings + * in the array; empty String if the array is null, the elements are all null + * or if there is no common prefix. + * @since 2.4 + */ + public static String getCommonPrefix(String... strs) { + if (strs == null || strs.length == 0) { + return EMPTY; + } + int smallestIndexOfDiff = indexOfDifference(strs); + if (smallestIndexOfDiff == INDEX_NOT_FOUND) { + // all strings were identical + if (strs[0] == null) { + return EMPTY; + } + return strs[0]; + } else if (smallestIndexOfDiff == 0) { + // there were no common initial characters + return EMPTY; + } else { + // we found a common initial character sequence + return strs[0].substring(0, smallestIndexOfDiff); + } + } + + // Misc + //----------------------------------------------------------------------- + /** + *

Find the Levenshtein distance between two Strings.

+ * + *

This is the number of changes needed to change one String into + * another, where each change is a single character modification (deletion, + * insertion or substitution).

+ * + *

The previous implementation of the Levenshtein distance algorithm + * was from http://www.merriampark.com/ld.htm

+ * + *

Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError + * which can occur when my Java implementation is used with very large strings.
+ * This implementation of the Levenshtein distance algorithm + * is from http://www.merriampark.com/ldjava.htm

+ * + *
+     * StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException
+     * StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException
+     * StringUtils.getLevenshteinDistance("","")               = 0
+     * StringUtils.getLevenshteinDistance("","a")              = 1
+     * StringUtils.getLevenshteinDistance("aaapppp", "")       = 7
+     * StringUtils.getLevenshteinDistance("frog", "fog")       = 1
+     * StringUtils.getLevenshteinDistance("fly", "ant")        = 3
+     * StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
+     * StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
+     * StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
+     * StringUtils.getLevenshteinDistance("hello", "hallo")    = 1
+     * 
+ * + * @param s the first String, must not be null + * @param t the second String, must not be null + * @return result distance + * @throws IllegalArgumentException if either String input {@code null} + * @since 3.0 Changed signature from getLevenshteinDistance(String, String) to + * getLevenshteinDistance(CharSequence, CharSequence) + */ + public static int getLevenshteinDistance(CharSequence s, CharSequence t) { + if (s == null || t == null) { + throw new IllegalArgumentException("Strings must not be null"); + } + + /* + The difference between this impl. and the previous is that, rather + than creating and retaining a matrix of size s.length() + 1 by t.length() + 1, + we maintain two single-dimensional arrays of length s.length() + 1. The first, d, + is the 'current working' distance array that maintains the newest distance cost + counts as we iterate through the characters of String s. Each time we increment + the index of String t we are comparing, d is copied to p, the second int[]. Doing so + allows us to retain the previous cost counts as required by the algorithm (taking + the minimum of the cost count to the left, up one, and diagonally up and to the left + of the current cost count being calculated). (Note that the arrays aren't really + copied anymore, just switched...this is clearly much better than cloning an array + or doing a System.arraycopy() each time through the outer loop.) + + Effectively, the difference between the two implementations is this one does not + cause an out of memory condition when calculating the LD over two very large strings. + */ + + int n = s.length(); // length of s + int m = t.length(); // length of t + + if (n == 0) { + return m; + } else if (m == 0) { + return n; + } + + if (n > m) { + // swap the input strings to consume less memory + CharSequence tmp = s; + s = t; + t = tmp; + n = m; + m = t.length(); + } + + int p[] = new int[n + 1]; //'previous' cost array, horizontally + int d[] = new int[n + 1]; // cost array, horizontally + int _d[]; //placeholder to assist in swapping p and d + + // indexes into strings s and t + int i; // iterates through s + int j; // iterates through t + + char t_j; // jth character of t + + int cost; // cost + + for (i = 0; i <= n; i++) { + p[i] = i; + } + + for (j = 1; j <= m; j++) { + t_j = t.charAt(j - 1); + d[0] = j; + + for (i = 1; i <= n; i++) { + cost = s.charAt(i - 1) == t_j ? 0 : 1; + // minimum of cell to the left+1, to the top+1, diagonally left and up +cost + d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); + } + + // copy current distance counts to 'previous row' distance counts + _d = p; + p = d; + d = _d; + } + + // our last action in the above loop was to switch d and p, so p now + // actually has the most recent cost counts + return p[n]; + } + + /** + *

Find the Levenshtein distance between two Strings if it's less than or equal to a given + * threshold.

+ * + *

This is the number of changes needed to change one String into + * another, where each change is a single character modification (deletion, + * insertion or substitution).

+ * + *

This implementation follows from Algorithms on Strings, Trees and Sequences by Dan Gusfield + * and Chas Emerick's implementation of the Levenshtein distance algorithm from + * http://www.merriampark.com/ld.htm

+ * + *
+     * StringUtils.getLevenshteinDistance(null, *, *)             = IllegalArgumentException
+     * StringUtils.getLevenshteinDistance(*, null, *)             = IllegalArgumentException
+     * StringUtils.getLevenshteinDistance(*, *, -1)               = IllegalArgumentException
+     * StringUtils.getLevenshteinDistance("","", 0)               = 0
+     * StringUtils.getLevenshteinDistance("aaapppp", "", 8)       = 7
+     * StringUtils.getLevenshteinDistance("aaapppp", "", 7)       = 7
+     * StringUtils.getLevenshteinDistance("aaapppp", "", 6))      = -1
+     * StringUtils.getLevenshteinDistance("elephant", "hippo", 7) = 7
+     * StringUtils.getLevenshteinDistance("elephant", "hippo", 6) = -1
+     * StringUtils.getLevenshteinDistance("hippo", "elephant", 7) = 7
+     * StringUtils.getLevenshteinDistance("hippo", "elephant", 6) = -1
+     * 
+ * + * @param s the first String, must not be null + * @param t the second String, must not be null + * @param threshold the target threshold, must not be negative + * @return result distance, or {@code -1} if the distance would be greater than the threshold + * @throws IllegalArgumentException if either String input {@code null} or negative threshold + */ + public static int getLevenshteinDistance(CharSequence s, CharSequence t, int threshold) { + if (s == null || t == null) { + throw new IllegalArgumentException("Strings must not be null"); + } + if (threshold < 0) { + throw new IllegalArgumentException("Threshold must not be negative"); + } + + /* + This implementation only computes the distance if it's less than or equal to the + threshold value, returning -1 if it's greater. The advantage is performance: unbounded + distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only + computing a diagonal stripe of width 2k + 1 of the cost table. + It is also possible to use this to compute the unbounded Levenshtein distance by starting + the threshold at 1 and doubling each time until the distance is found; this is O(dm), where + d is the distance. + + One subtlety comes from needing to ignore entries on the border of our stripe + eg. + p[] = |#|#|#|* + d[] = *|#|#|#| + We must ignore the entry to the left of the leftmost member + We must ignore the entry above the rightmost member + + Another subtlety comes from our stripe running off the matrix if the strings aren't + of the same size. Since string s is always swapped to be the shorter of the two, + the stripe will always run off to the upper right instead of the lower left of the matrix. + + As a concrete example, suppose s is of length 5, t is of length 7, and our threshold is 1. + In this case we're going to walk a stripe of length 3. The matrix would look like so: + + 1 2 3 4 5 + 1 |#|#| | | | + 2 |#|#|#| | | + 3 | |#|#|#| | + 4 | | |#|#|#| + 5 | | | |#|#| + 6 | | | | |#| + 7 | | | | | | + + Note how the stripe leads off the table as there is no possible way to turn a string of length 5 + into one of length 7 in edit distance of 1. + + Additionally, this implementation decreases memory usage by using two + single-dimensional arrays and swapping them back and forth instead of allocating + an entire n by m matrix. This requires a few minor changes, such as immediately returning + when it's detected that the stripe has run off the matrix and initially filling the arrays with + large values so that entries we don't compute are ignored. + + See Algorithms on Strings, Trees and Sequences by Dan Gusfield for some discussion. + */ + + int n = s.length(); // length of s + int m = t.length(); // length of t + + // if one string is empty, the edit distance is necessarily the length of the other + if (n == 0) { + return m <= threshold ? m : -1; + } else if (m == 0) { + return n <= threshold ? n : -1; + } + + if (n > m) { + // swap the two strings to consume less memory + CharSequence tmp = s; + s = t; + t = tmp; + n = m; + m = t.length(); + } + + int p[] = new int[n + 1]; // 'previous' cost array, horizontally + int d[] = new int[n + 1]; // cost array, horizontally + int _d[]; // placeholder to assist in swapping p and d + + // fill in starting table values + int boundary = Math.min(n, threshold) + 1; + for (int i = 0; i < boundary; i++) { + p[i] = i; + } + // these fills ensure that the value above the rightmost entry of our + // stripe will be ignored in following loop iterations + Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE); + Arrays.fill(d, Integer.MAX_VALUE); + + // iterates through t + for (int j = 1; j <= m; j++) { + char t_j = t.charAt(j - 1); // jth character of t + d[0] = j; + + // compute stripe indices, constrain to array size + int min = Math.max(1, j - threshold); + int max = Math.min(n, j + threshold); + + // the stripe may lead off of the table if s and t are of different sizes + if (min > max) { + return -1; + } + + // ignore entry left of leftmost + if (min > 1) { + d[min - 1] = Integer.MAX_VALUE; + } + + // iterates through [min, max] in s + for (int i = min; i <= max; i++) { + if (s.charAt(i - 1) == t_j) { + // diagonally left and up + d[i] = p[i - 1]; + } else { + // 1 + minimum of cell to the left, to the top, diagonally left and up + d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]); + } + } + + // copy current distance counts to 'previous row' distance counts + _d = p; + p = d; + d = _d; + } + + // if p[n] is greater than the threshold, there's no guarantee on it being the correct + // distance + if (p[n] <= threshold) { + return p[n]; + } else { + return -1; + } + } + + // startsWith + //----------------------------------------------------------------------- + + /** + *

Check if a CharSequence starts with a specified prefix.

+ * + *

{@code null}s are handled without exceptions. Two {@code null} + * references are considered to be equal. The comparison is case sensitive.

+ * + *
+     * StringUtils.startsWith(null, null)      = true
+     * StringUtils.startsWith(null, "abc")     = false
+     * StringUtils.startsWith("abcdef", null)  = false
+     * StringUtils.startsWith("abcdef", "abc") = true
+     * StringUtils.startsWith("ABCDEF", "abc") = false
+     * 
+ * + * @see java.lang.String#startsWith(String) + * @param str the CharSequence to check, may be null + * @param prefix the prefix to find, may be null + * @return {@code true} if the CharSequence starts with the prefix, case sensitive, or + * both {@code null} + * @since 2.4 + * @since 3.0 Changed signature from startsWith(String, String) to startsWith(CharSequence, CharSequence) + */ + public static boolean startsWith(CharSequence str, CharSequence prefix) { + return startsWith(str, prefix, false); + } + + /** + *

Case insensitive check if a CharSequence starts with a specified prefix.

+ * + *

{@code null}s are handled without exceptions. Two {@code null} + * references are considered to be equal. The comparison is case insensitive.

+ * + *
+     * StringUtils.startsWithIgnoreCase(null, null)      = true
+     * StringUtils.startsWithIgnoreCase(null, "abc")     = false
+     * StringUtils.startsWithIgnoreCase("abcdef", null)  = false
+     * StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
+     * StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
+     * 
+ * + * @see java.lang.String#startsWith(String) + * @param str the CharSequence to check, may be null + * @param prefix the prefix to find, may be null + * @return {@code true} if the CharSequence starts with the prefix, case insensitive, or + * both {@code null} + * @since 2.4 + * @since 3.0 Changed signature from startsWithIgnoreCase(String, String) to startsWithIgnoreCase(CharSequence, CharSequence) + */ + public static boolean startsWithIgnoreCase(CharSequence str, CharSequence prefix) { + return startsWith(str, prefix, true); + } + + /** + *

Check if a CharSequence starts with a specified prefix (optionally case insensitive).

+ * + * @see java.lang.String#startsWith(String) + * @param str the CharSequence to check, may be null + * @param prefix the prefix to find, may be null + * @param ignoreCase indicates whether the compare should ignore case + * (case insensitive) or not. + * @return {@code true} if the CharSequence starts with the prefix or + * both {@code null} + */ + private static boolean startsWith(CharSequence str, CharSequence prefix, boolean ignoreCase) { + if (str == null || prefix == null) { + return str == null && prefix == null; + } + if (prefix.length() > str.length()) { + return false; + } + return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, prefix.length()); + } + + /** + *

Check if a CharSequence starts with any of an array of specified strings.

+ * + *
+     * StringUtils.startsWithAny(null, null)      = false
+     * StringUtils.startsWithAny(null, new String[] {"abc"})  = false
+     * StringUtils.startsWithAny("abcxyz", null)     = false
+     * StringUtils.startsWithAny("abcxyz", new String[] {""}) = false
+     * StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
+     * StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
+     * 
+ * + * @param string the CharSequence to check, may be null + * @param searchStrings the CharSequences to find, may be null or empty + * @return {@code true} if the CharSequence starts with any of the the prefixes, case insensitive, or + * both {@code null} + * @since 2.5 + * @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...) + */ + public static boolean startsWithAny(CharSequence string, CharSequence... searchStrings) { + if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) { + return false; + } + for (CharSequence searchString : searchStrings) { + if (StringUtils.startsWith(string, searchString)) { + return true; + } + } + return false; + } + + // endsWith + //----------------------------------------------------------------------- + + /** + *

Check if a CharSequence ends with a specified suffix.

+ * + *

{@code null}s are handled without exceptions. Two {@code null} + * references are considered to be equal. The comparison is case sensitive.

+ * + *
+     * StringUtils.endsWith(null, null)      = true
+     * StringUtils.endsWith(null, "def")     = false
+     * StringUtils.endsWith("abcdef", null)  = false
+     * StringUtils.endsWith("abcdef", "def") = true
+     * StringUtils.endsWith("ABCDEF", "def") = false
+     * StringUtils.endsWith("ABCDEF", "cde") = false
+     * 
+ * + * @see java.lang.String#endsWith(String) + * @param str the CharSequence to check, may be null + * @param suffix the suffix to find, may be null + * @return {@code true} if the CharSequence ends with the suffix, case sensitive, or + * both {@code null} + * @since 2.4 + * @since 3.0 Changed signature from endsWith(String, String) to endsWith(CharSequence, CharSequence) + */ + public static boolean endsWith(CharSequence str, CharSequence suffix) { + return endsWith(str, suffix, false); + } + + /** + *

Case insensitive check if a CharSequence ends with a specified suffix.

+ * + *

{@code null}s are handled without exceptions. Two {@code null} + * references are considered to be equal. The comparison is case insensitive.

+ * + *
+     * StringUtils.endsWithIgnoreCase(null, null)      = true
+     * StringUtils.endsWithIgnoreCase(null, "def")     = false
+     * StringUtils.endsWithIgnoreCase("abcdef", null)  = false
+     * StringUtils.endsWithIgnoreCase("abcdef", "def") = true
+     * StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
+     * StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
+     * 
+ * + * @see java.lang.String#endsWith(String) + * @param str the CharSequence to check, may be null + * @param suffix the suffix to find, may be null + * @return {@code true} if the CharSequence ends with the suffix, case insensitive, or + * both {@code null} + * @since 2.4 + * @since 3.0 Changed signature from endsWithIgnoreCase(String, String) to endsWithIgnoreCase(CharSequence, CharSequence) + */ + public static boolean endsWithIgnoreCase(CharSequence str, CharSequence suffix) { + return endsWith(str, suffix, true); + } + + /** + *

Check if a CharSequence ends with a specified suffix (optionally case insensitive).

+ * + * @see java.lang.String#endsWith(String) + * @param str the CharSequence to check, may be null + * @param suffix the suffix to find, may be null + * @param ignoreCase indicates whether the compare should ignore case + * (case insensitive) or not. + * @return {@code true} if the CharSequence starts with the prefix or + * both {@code null} + */ + private static boolean endsWith(CharSequence str, CharSequence suffix, boolean ignoreCase) { + if (str == null || suffix == null) { + return str == null && suffix == null; + } + if (suffix.length() > str.length()) { + return false; + } + int strOffset = str.length() - suffix.length(); + return CharSequenceUtils.regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length()); + } + + /** + *

+ * Similar to http://www.w3.org/TR/xpath/#function-normalize + * -space + *

+ *

+ * The function returns the argument string with whitespace normalized by using + * {@link #trim(String)} to remove leading and trailing whitespace + * and then replacing sequences of whitespace characters by a single space. + *

+ * In XML Whitespace characters are the same as those allowed by the S production, which is S ::= (#x20 | #x9 | #xD | #xA)+ + *

+ * Java's regexp pattern \s defines whitespace as [ \t\n\x0B\f\r] + *

+ * For reference: + *

    + *
  • \x0B = vertical tab
  • + *
  • \f = #xC = form feed
  • + *
  • #x20 = space
  • + *
  • #x9 = \t
  • + *
  • #xA = \n
  • + *
  • #xD = \r
  • + *
+ *

+ *

+ * The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also + * normalize. Additionally {@link #trim(String)} removes control characters (char <= 32) from both + * ends of this String. + *

+ * + * @see Pattern + * @see #trim(String) + * @see http://www.w3.org/TR/xpath/#function-normalize-space + * @param str the source String to normalize whitespaces from, may be null + * @return the modified string with whitespace normalized, {@code null} if null String input + * + * @since 3.0 + */ + public static String normalizeSpace(String str) { + if (str == null) { + return null; + } + return WHITESPACE_BLOCK.matcher(trim(str)).replaceAll(" "); + } + + /** + *

Check if a CharSequence ends with any of an array of specified strings.

+ * + *
+     * StringUtils.endsWithAny(null, null)      = false
+     * StringUtils.endsWithAny(null, new String[] {"abc"})  = false
+     * StringUtils.endsWithAny("abcxyz", null)     = false
+     * StringUtils.endsWithAny("abcxyz", new String[] {""}) = true
+     * StringUtils.endsWithAny("abcxyz", new String[] {"xyz"}) = true
+     * StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
+     * 
+ * + * @param string the CharSequence to check, may be null + * @param searchStrings the CharSequences to find, may be null or empty + * @return {@code true} if the CharSequence ends with any of the the prefixes, case insensitive, or + * both {@code null} + * @since 3.0 + */ + public static boolean endsWithAny(CharSequence string, CharSequence... searchStrings) { + if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) { + return false; + } + for (CharSequence searchString : searchStrings) { + if (StringUtils.endsWith(string, searchString)) { + return true; + } + } + return false; + } + + /** + * Converts a byte[] to a String using the specified character encoding. + * + * @param bytes + * the byte array to read from + * @param charsetName + * the encoding to use, if null then use the platform default + * @return a new String + * @throws UnsupportedEncodingException + * If the named charset is not supported + * @throws NullPointerException + * if the input is null + * @since 3.1 + */ + public static String toString(byte[] bytes, String charsetName) throws UnsupportedEncodingException { + return charsetName == null ? new String(bytes) : new String(bytes, charsetName); + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/SystemUtils.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/SystemUtils.java new file mode 100644 index 00000000..e6a1c10f --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/SystemUtils.java @@ -0,0 +1,1443 @@ +/* + * 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.File; + +/** + *

+ * Helpers for {@code java.lang.System}. + *

+ *

+ * If a system property cannot be read due to security restrictions, the corresponding field in this class will be set + * to {@code null} and a message will be written to {@code System.err}. + *

+ *

+ * #ThreadSafe# + *

+ * + * @since 1.0 + * @version $Id: SystemUtils.java 1199816 2011-11-09 16:11:34Z bayard $ + */ +public class SystemUtils { + + /** + * The prefix String for all Windows OS. + */ + private static final String OS_NAME_WINDOWS_PREFIX = "Windows"; + + // System property constants + // ----------------------------------------------------------------------- + // These MUST be declared first. Other constants depend on this. + + /** + * The System property key for the user home directory. + */ + private static final String USER_HOME_KEY = "user.home"; + + /** + * The System property key for the user directory. + */ + private static final String USER_DIR_KEY = "user.dir"; + + /** + * The System property key for the Java IO temporary directory. + */ + private static final String JAVA_IO_TMPDIR_KEY = "java.io.tmpdir"; + + /** + * The System property key for the Java home directory. + */ + private static final String JAVA_HOME_KEY = "java.home"; + + /** + *

+ * The {@code awt.toolkit} System Property. + *

+ *

+ * Holds a class name, on Windows XP this is {@code sun.awt.windows.WToolkit}. + *

+ *

+ * On platforms without a GUI, this value is {@code null}. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.1 + */ + public static final String AWT_TOOLKIT = getSystemProperty("awt.toolkit"); + + /** + *

+ * The {@code file.encoding} System Property. + *

+ *

+ * File encoding, such as {@code Cp1252}. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.0 + * @since Java 1.2 + */ + public static final String FILE_ENCODING = getSystemProperty("file.encoding"); + + /** + *

+ * The {@code file.separator} System Property. File separator ("/" on UNIX). + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String FILE_SEPARATOR = getSystemProperty("file.separator"); + + /** + *

+ * The {@code java.awt.fonts} System Property. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.1 + */ + public static final String JAVA_AWT_FONTS = getSystemProperty("java.awt.fonts"); + + /** + *

+ * The {@code java.awt.graphicsenv} System Property. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.1 + */ + public static final String JAVA_AWT_GRAPHICSENV = getSystemProperty("java.awt.graphicsenv"); + + /** + *

+ * The {@code java.awt.headless} System Property. The value of this property is the String {@code "true"} or + * {@code "false"}. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @see #isJavaAwtHeadless() + * @since 2.1 + * @since Java 1.4 + */ + public static final String JAVA_AWT_HEADLESS = getSystemProperty("java.awt.headless"); + + /** + *

+ * The {@code java.awt.printerjob} System Property. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.1 + */ + public static final String JAVA_AWT_PRINTERJOB = getSystemProperty("java.awt.printerjob"); + + /** + *

+ * The {@code java.class.path} System Property. Java class path. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String JAVA_CLASS_PATH = getSystemProperty("java.class.path"); + + /** + *

+ * The {@code java.class.version} System Property. Java class format version number. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String JAVA_CLASS_VERSION = getSystemProperty("java.class.version"); + + /** + *

+ * The {@code java.compiler} System Property. Name of JIT compiler to use. First in JDK version 1.2. Not used in Sun + * JDKs after 1.2. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2. Not used in Sun versions after 1.2. + */ + public static final String JAVA_COMPILER = getSystemProperty("java.compiler"); + + /** + *

+ * The {@code java.endorsed.dirs} System Property. Path of endorsed directory or directories. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.4 + */ + public static final String JAVA_ENDORSED_DIRS = getSystemProperty("java.endorsed.dirs"); + + /** + *

+ * The {@code java.ext.dirs} System Property. Path of extension directory or directories. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.3 + */ + public static final String JAVA_EXT_DIRS = getSystemProperty("java.ext.dirs"); + + /** + *

+ * The {@code java.home} System Property. Java installation directory. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String JAVA_HOME = getSystemProperty(JAVA_HOME_KEY); + + /** + *

+ * The {@code java.io.tmpdir} System Property. Default temp file path. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2 + */ + public static final String JAVA_IO_TMPDIR = getSystemProperty(JAVA_IO_TMPDIR_KEY); + + /** + *

+ * The {@code java.library.path} System Property. List of paths to search when loading libraries. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2 + */ + public static final String JAVA_LIBRARY_PATH = getSystemProperty("java.library.path"); + + /** + *

+ * The {@code java.runtime.name} System Property. Java Runtime Environment name. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.0 + * @since Java 1.3 + */ + public static final String JAVA_RUNTIME_NAME = getSystemProperty("java.runtime.name"); + + /** + *

+ * The {@code java.runtime.version} System Property. Java Runtime Environment version. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.0 + * @since Java 1.3 + */ + public static final String JAVA_RUNTIME_VERSION = getSystemProperty("java.runtime.version"); + + /** + *

+ * The {@code java.specification.name} System Property. Java Runtime Environment specification name. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2 + */ + public static final String JAVA_SPECIFICATION_NAME = getSystemProperty("java.specification.name"); + + /** + *

+ * The {@code java.specification.vendor} System Property. Java Runtime Environment specification vendor. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2 + */ + public static final String JAVA_SPECIFICATION_VENDOR = getSystemProperty("java.specification.vendor"); + + /** + *

+ * The {@code java.specification.version} System Property. Java Runtime Environment specification version. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.3 + */ + public static final String JAVA_SPECIFICATION_VERSION = getSystemProperty("java.specification.version"); + private static final JavaVersion JAVA_SPECIFICATION_VERSION_AS_ENUM = JavaVersion.get(JAVA_SPECIFICATION_VERSION); + + /** + *

+ * The {@code java.util.prefs.PreferencesFactory} System Property. A class name. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.1 + * @since Java 1.4 + */ + public static final String JAVA_UTIL_PREFS_PREFERENCES_FACTORY = + getSystemProperty("java.util.prefs.PreferencesFactory"); + + /** + *

+ * The {@code java.vendor} System Property. Java vendor-specific string. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String JAVA_VENDOR = getSystemProperty("java.vendor"); + + /** + *

+ * The {@code java.vendor.url} System Property. Java vendor URL. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String JAVA_VENDOR_URL = getSystemProperty("java.vendor.url"); + + /** + *

+ * The {@code java.version} System Property. Java version number. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String JAVA_VERSION = getSystemProperty("java.version"); + + /** + *

+ * The {@code java.vm.info} System Property. Java Virtual Machine implementation info. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.0 + * @since Java 1.2 + */ + public static final String JAVA_VM_INFO = getSystemProperty("java.vm.info"); + + /** + *

+ * The {@code java.vm.name} System Property. Java Virtual Machine implementation name. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2 + */ + public static final String JAVA_VM_NAME = getSystemProperty("java.vm.name"); + + /** + *

+ * The {@code java.vm.specification.name} System Property. Java Virtual Machine specification name. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2 + */ + public static final String JAVA_VM_SPECIFICATION_NAME = getSystemProperty("java.vm.specification.name"); + + /** + *

+ * The {@code java.vm.specification.vendor} System Property. Java Virtual Machine specification vendor. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2 + */ + public static final String JAVA_VM_SPECIFICATION_VENDOR = getSystemProperty("java.vm.specification.vendor"); + + /** + *

+ * The {@code java.vm.specification.version} System Property. Java Virtual Machine specification version. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2 + */ + public static final String JAVA_VM_SPECIFICATION_VERSION = getSystemProperty("java.vm.specification.version"); + + /** + *

+ * The {@code java.vm.vendor} System Property. Java Virtual Machine implementation vendor. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2 + */ + public static final String JAVA_VM_VENDOR = getSystemProperty("java.vm.vendor"); + + /** + *

+ * The {@code java.vm.version} System Property. Java Virtual Machine implementation version. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.2 + */ + public static final String JAVA_VM_VERSION = getSystemProperty("java.vm.version"); + + /** + *

+ * The {@code line.separator} System Property. Line separator ("\n" on UNIX). + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String LINE_SEPARATOR = getSystemProperty("line.separator"); + + /** + *

+ * The {@code os.arch} System Property. Operating system architecture. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String OS_ARCH = getSystemProperty("os.arch"); + + /** + *

+ * The {@code os.name} System Property. Operating system name. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String OS_NAME = getSystemProperty("os.name"); + + /** + *

+ * The {@code os.version} System Property. Operating system version. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String OS_VERSION = getSystemProperty("os.version"); + + /** + *

+ * The {@code path.separator} System Property. Path separator (":" on UNIX). + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String PATH_SEPARATOR = getSystemProperty("path.separator"); + + /** + *

+ * The {@code user.country} or {@code user.region} System Property. User's country code, such as {@code GB}. First + * in Java version 1.2 as {@code user.region}. Renamed to {@code user.country} in 1.4 + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.0 + * @since Java 1.2 + */ + public static final String USER_COUNTRY = getSystemProperty("user.country") == null ? + getSystemProperty("user.region") : getSystemProperty("user.country"); + + /** + *

+ * The {@code user.dir} System Property. User's current working directory. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String USER_DIR = getSystemProperty(USER_DIR_KEY); + + /** + *

+ * The {@code user.home} System Property. User's home directory. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String USER_HOME = getSystemProperty(USER_HOME_KEY); + + /** + *

+ * The {@code user.language} System Property. User's language code, such as {@code "en"}. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.0 + * @since Java 1.2 + */ + public static final String USER_LANGUAGE = getSystemProperty("user.language"); + + /** + *

+ * The {@code user.name} System Property. User's account name. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since Java 1.1 + */ + public static final String USER_NAME = getSystemProperty("user.name"); + + /** + *

+ * The {@code user.timezone} System Property. For example: {@code "America/Los_Angeles"}. + *

+ *

+ * Defaults to {@code null} if the runtime does not have security access to read this property or the property does + * not exist. + *

+ *

+ * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or + * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of + * sync with that System property. + *

+ * + * @since 2.1 + */ + public static final String USER_TIMEZONE = getSystemProperty("user.timezone"); + + // Java version checks + // ----------------------------------------------------------------------- + // These MUST be declared after those above as they depend on the + // values being set up + + /** + *

+ * Is {@code true} if this is Java version 1.1 (also 1.1.x versions). + *

+ *

+ * The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}. + *

+ */ + public static final boolean IS_JAVA_1_1 = getJavaVersionMatches("1.1"); + + /** + *

+ * Is {@code true} if this is Java version 1.2 (also 1.2.x versions). + *

+ *

+ * The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}. + *

+ */ + public static final boolean IS_JAVA_1_2 = getJavaVersionMatches("1.2"); + + /** + *

+ * Is {@code true} if this is Java version 1.3 (also 1.3.x versions). + *

+ *

+ * The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}. + *

+ */ + public static final boolean IS_JAVA_1_3 = getJavaVersionMatches("1.3"); + + /** + *

+ * Is {@code true} if this is Java version 1.4 (also 1.4.x versions). + *

+ *

+ * The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}. + *

+ */ + public static final boolean IS_JAVA_1_4 = getJavaVersionMatches("1.4"); + + /** + *

+ * Is {@code true} if this is Java version 1.5 (also 1.5.x versions). + *

+ *

+ * The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}. + *

+ */ + public static final boolean IS_JAVA_1_5 = getJavaVersionMatches("1.5"); + + /** + *

+ * Is {@code true} if this is Java version 1.6 (also 1.6.x versions). + *

+ *

+ * The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}. + *

+ */ + public static final boolean IS_JAVA_1_6 = getJavaVersionMatches("1.6"); + + /** + *

+ * Is {@code true} if this is Java version 1.7 (also 1.7.x versions). + *

+ *

+ * The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}. + *

+ * + * @since 3.0 + */ + public static final boolean IS_JAVA_1_7 = getJavaVersionMatches("1.7"); + + // Operating system checks + // ----------------------------------------------------------------------- + // These MUST be declared after those above as they depend on the + // values being set up + // OS names from http://www.vamphq.com/os.html + // Selected ones included - please advise dev@commons.apache.org + // if you want another added or a mistake corrected + + /** + *

+ * Is {@code true} if this is AIX. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_AIX = getOSMatchesName("AIX"); + + /** + *

+ * Is {@code true} if this is HP-UX. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_HP_UX = getOSMatchesName("HP-UX"); + + /** + *

+ * Is {@code true} if this is Irix. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_IRIX = getOSMatchesName("Irix"); + + /** + *

+ * Is {@code true} if this is Linux. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_LINUX = getOSMatchesName("Linux") || getOSMatchesName("LINUX"); + + /** + *

+ * Is {@code true} if this is Mac. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_MAC = getOSMatchesName("Mac"); + + /** + *

+ * Is {@code true} if this is Mac. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_MAC_OSX = getOSMatchesName("Mac OS X"); + + /** + *

+ * Is {@code true} if this is FreeBSD. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 3.1 + */ + public static final boolean IS_OS_FREE_BSD = getOSMatchesName("FreeBSD"); + + /** + *

+ * Is {@code true} if this is OpenBSD. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 3.1 + */ + public static final boolean IS_OS_OPEN_BSD = getOSMatchesName("OpenBSD"); + + /** + *

+ * Is {@code true} if this is NetBSD. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 3.1 + */ + public static final boolean IS_OS_NET_BSD = getOSMatchesName("NetBSD"); + + /** + *

+ * Is {@code true} if this is OS/2. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_OS2 = getOSMatchesName("OS/2"); + + /** + *

+ * Is {@code true} if this is Solaris. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_SOLARIS = getOSMatchesName("Solaris"); + + /** + *

+ * Is {@code true} if this is SunOS. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_SUN_OS = getOSMatchesName("SunOS"); + + /** + *

+ * Is {@code true} if this is a UNIX like system, as in any of AIX, HP-UX, Irix, Linux, MacOSX, Solaris or SUN OS. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.1 + */ + public static final boolean IS_OS_UNIX = IS_OS_AIX || IS_OS_HP_UX || IS_OS_IRIX || IS_OS_LINUX || IS_OS_MAC_OSX + || IS_OS_SOLARIS || IS_OS_SUN_OS || IS_OS_FREE_BSD || IS_OS_OPEN_BSD || IS_OS_NET_BSD; + + /** + *

+ * Is {@code true} if this is Windows. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_WINDOWS = getOSMatchesName(OS_NAME_WINDOWS_PREFIX); + + /** + *

+ * Is {@code true} if this is Windows 2000. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_WINDOWS_2000 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.0"); + + /** + *

+ * Is {@code true} if this is Windows 2003. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 3.1 + */ + public static final boolean IS_OS_WINDOWS_2003 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.2"); + + /** + *

+ * Is {@code true} if this is Windows 2008. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 3.1 + */ + public static final boolean IS_OS_WINDOWS_2008 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " Server 2008", "6.1"); + + /** + *

+ * Is {@code true} if this is Windows 95. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_WINDOWS_95 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.0"); + // Java 1.2 running on Windows98 returns 'Windows 95', hence the above + + /** + *

+ * Is {@code true} if this is Windows 98. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_WINDOWS_98 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.1"); + // Java 1.2 running on Windows98 returns 'Windows 95', hence the above + + /** + *

+ * Is {@code true} if this is Windows ME. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_WINDOWS_ME = getOSMatches(OS_NAME_WINDOWS_PREFIX, "4.9"); + // Java 1.2 running on WindowsME may return 'Windows 95', hence the above + + /** + *

+ * Is {@code true} if this is Windows NT. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_WINDOWS_NT = getOSMatchesName(OS_NAME_WINDOWS_PREFIX + " NT"); + // Windows 2000 returns 'Windows 2000' but may suffer from same Java1.2 problem + + /** + *

+ * Is {@code true} if this is Windows XP. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.0 + */ + public static final boolean IS_OS_WINDOWS_XP = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.1"); + + // ----------------------------------------------------------------------- + /** + *

+ * Is {@code true} if this is Windows Vista. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 2.4 + */ + public static final boolean IS_OS_WINDOWS_VISTA = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.0"); + + /** + *

+ * Is {@code true} if this is Windows 7. + *

+ *

+ * The field will return {@code false} if {@code OS_NAME} is {@code null}. + *

+ * + * @since 3.0 + */ + public static final boolean IS_OS_WINDOWS_7 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.1"); + + /** + *

+ * Gets the Java home directory as a {@code File}. + *

+ * + * @return a directory + * @throws SecurityException if a security manager exists and its {@code checkPropertyAccess} method doesn't allow + * access to the specified system property. + * @see System#getProperty(String) + * @since 2.1 + */ + public static File getJavaHome() { + return new File(System.getProperty(JAVA_HOME_KEY)); + } + + /** + *

+ * Gets the Java IO temporary directory as a {@code File}. + *

+ * + * @return a directory + * @throws SecurityException if a security manager exists and its {@code checkPropertyAccess} method doesn't allow + * access to the specified system property. + * @see System#getProperty(String) + * @since 2.1 + */ + public static File getJavaIoTmpDir() { + return new File(System.getProperty(JAVA_IO_TMPDIR_KEY)); + } + + /** + *

+ * Decides if the Java version matches. + *

+ * + * @param versionPrefix the prefix for the java version + * @return true if matches, or false if not or can't determine + */ + private static boolean getJavaVersionMatches(String versionPrefix) { + return isJavaVersionMatch(JAVA_SPECIFICATION_VERSION, versionPrefix); + } + + /** + * Decides if the operating system matches. + * + * @param osNamePrefix the prefix for the os name + * @param osVersionPrefix the prefix for the version + * @return true if matches, or false if not or can't determine + */ + private static boolean getOSMatches(String osNamePrefix, String osVersionPrefix) { + return isOSMatch(OS_NAME, OS_VERSION, osNamePrefix, osVersionPrefix); + } + + /** + * Decides if the operating system matches. + * + * @param osNamePrefix the prefix for the os name + * @return true if matches, or false if not or can't determine + */ + private static boolean getOSMatchesName(String osNamePrefix) { + return isOSNameMatch(OS_NAME, osNamePrefix); + } + + // ----------------------------------------------------------------------- + /** + *

+ * Gets a System property, defaulting to {@code null} if the property cannot be read. + *

+ *

+ * If a {@code SecurityException} is caught, the return value is {@code null} and a message is written to + * {@code System.err}. + *

+ * + * @param property the system property name + * @return the system property value or {@code null} if a security problem occurs + */ + private static String getSystemProperty(String property) { + try { + return System.getProperty(property); + } catch (SecurityException ex) { + // we are not allowed to look at this property + System.err.println("Caught a SecurityException reading the system property '" + property + + "'; the SystemUtils property value will default to null."); + return null; + } + } + + /** + *

+ * Gets the user directory as a {@code File}. + *

+ * + * @return a directory + * @throws SecurityException if a security manager exists and its {@code checkPropertyAccess} method doesn't allow + * access to the specified system property. + * @see System#getProperty(String) + * @since 2.1 + */ + public static File getUserDir() { + return new File(System.getProperty(USER_DIR_KEY)); + } + + /** + *

+ * Gets the user home directory as a {@code File}. + *

+ * + * @return a directory + * @throws SecurityException if a security manager exists and its {@code checkPropertyAccess} method doesn't allow + * access to the specified system property. + * @see System#getProperty(String) + * @since 2.1 + */ + public static File getUserHome() { + return new File(System.getProperty(USER_HOME_KEY)); + } + + /** + * Returns whether the {@link #JAVA_AWT_HEADLESS} value is {@code true}. + * + * @return {@code true} if {@code JAVA_AWT_HEADLESS} is {@code "true"}, {@code false} otherwise. + * @see #JAVA_AWT_HEADLESS + * @since 2.1 + * @since Java 1.4 + */ + public static boolean isJavaAwtHeadless() { + return JAVA_AWT_HEADLESS != null ? JAVA_AWT_HEADLESS.equals(Boolean.TRUE.toString()) : false; + } + + /** + *

+ * Is the Java version at least the requested version. + *

+ *

+ * Example input: + *

+ *
    + *
  • {@code 1.2f} to test for Java 1.2
  • + *
  • {@code 1.31f} to test for Java 1.3.1
  • + *
+ * + * @param requiredVersion the required version, for example 1.31f + * @return {@code true} if the actual version is equal or greater than the required version + */ + public static boolean isJavaVersionAtLeast(JavaVersion requiredVersion) { + return JAVA_SPECIFICATION_VERSION_AS_ENUM.atLeast(requiredVersion); + } + + /** + *

+ * Decides if the Java version matches. + *

+ *

+ * This method is package private instead of private to support unit test invocation. + *

+ * + * @param version the actual Java version + * @param versionPrefix the prefix for the expected Java version + * @return true if matches, or false if not or can't determine + */ + static boolean isJavaVersionMatch(String version, String versionPrefix) { + if (version == null) { + return false; + } + return version.startsWith(versionPrefix); + } + + /** + * Decides if the operating system matches. + *

+ * This method is package private instead of private to support unit test invocation. + *

+ * + * @param osName the actual OS name + * @param osVersion the actual OS version + * @param osNamePrefix the prefix for the expected OS name + * @param osVersionPrefix the prefix for the expected OS version + * @return true if matches, or false if not or can't determine + */ + static boolean isOSMatch(String osName, String osVersion, String osNamePrefix, String osVersionPrefix) { + if (osName == null || osVersion == null) { + return false; + } + return osName.startsWith(osNamePrefix) && osVersion.startsWith(osVersionPrefix); + } + + /** + * Decides if the operating system matches. + *

+ * This method is package private instead of private to support unit test invocation. + *

+ * + * @param osName the actual OS name + * @param osNamePrefix the prefix for the expected OS name + * @return true if matches, or false if not or can't determine + */ + static boolean isOSNameMatch(String osName, String osNamePrefix) { + if (osName == null) { + return false; + } + return osName.startsWith(osNamePrefix); + } + + // ----------------------------------------------------------------------- + /** + *

+ * SystemUtils instances should NOT be constructed in standard programming. Instead, the class should be used as + * {@code SystemUtils.FILE_SEPARATOR}. + *

+ *

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

+ */ + public SystemUtils() { + super(); + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/Validate.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/Validate.java new file mode 100644 index 00000000..72213854 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/Validate.java @@ -0,0 +1,1070 @@ +/* + * 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.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.regex.Pattern; + +/** + *

This class assists in validating arguments. The validation methods are + * based along the following principles: + *

    + *
  • An invalid {@code null} argument causes a {@link NullPointerException}.
  • + *
  • A non-{@code null} argument causes an {@link IllegalArgumentException}.
  • + *
  • An invalid index into an array/collection/map/string causes an {@link IndexOutOfBoundsException}.
  • + *
+ * + *

All exceptions messages are + * format strings + * as defined by the Java platform. For example:

+ * + *
+ * Validate.isTrue(i > 0, "The value must be greater than zero: %d", i);
+ * Validate.notNull(surname, "The surname must not be %s", null);
+ * 
+ * + *

#ThreadSafe#

+ * @version $Id: Validate.java 1199983 2011-11-09 21:41:24Z ggregory $ + * @see java.lang.String#format(String, Object...) + * @since 2.0 + */ +public class Validate { + + private static final String DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE = + "The value %s is not in the specified exclusive range of %s to %s"; + private static final String DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE = + "The value %s is not in the specified inclusive range of %s to %s"; + private static final String DEFAULT_MATCHES_PATTERN_EX = "The string %s does not match the pattern %s"; + private static final String DEFAULT_IS_NULL_EX_MESSAGE = "The validated object is null"; + private static final String DEFAULT_IS_TRUE_EX_MESSAGE = "The validated expression is false"; + private static final String DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE = + "The validated array contains null element at index: %d"; + private static final String DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE = + "The validated collection contains null element at index: %d"; + private static final String DEFAULT_NOT_BLANK_EX_MESSAGE = "The validated character sequence is blank"; + private static final String DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE = "The validated array is empty"; + private static final String DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE = + "The validated character sequence is empty"; + private static final String DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE = "The validated collection is empty"; + private static final String DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE = "The validated map is empty"; + private static final String DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE = "The validated array index is invalid: %d"; + private static final String DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE = + "The validated character sequence index is invalid: %d"; + private static final String DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE = + "The validated collection index is invalid: %d"; + private static final String DEFAULT_VALID_STATE_EX_MESSAGE = "The validated state is false"; + private static final String DEFAULT_IS_ASSIGNABLE_EX_MESSAGE = "Cannot assign a %s to a %s"; + private static final String DEFAULT_IS_INSTANCE_OF_EX_MESSAGE = "Expected type: %s, actual: %s"; + + /** + * Constructor. This class should not normally be instantiated. + */ + public Validate() { + super(); + } + + // isTrue + //--------------------------------------------------------------------------------- + + /** + *

Validate that the argument condition is {@code true}; otherwise + * throwing an exception with the specified message. This method is useful when + * validating according to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression.

+ * + *
Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);
+ * + *

For performance reasons, the long value is passed as a separate parameter and + * appended to the exception message only in the case of an error.

+ * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param value the value to append to the message when invalid + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean) + * @see #isTrue(boolean, String, double) + * @see #isTrue(boolean, String, Object...) + */ + public static void isTrue(boolean expression, String message, long value) { + if (expression == false) { + throw new IllegalArgumentException(String.format(message, Long.valueOf(value))); + } + } + + /** + *

Validate that the argument condition is {@code true}; otherwise + * throwing an exception with the specified message. This method is useful when + * validating according to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression.

+ * + *
Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);
+ * + *

For performance reasons, the double value is passed as a separate parameter and + * appended to the exception message only in the case of an error.

+ * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param value the value to append to the message when invalid + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean) + * @see #isTrue(boolean, String, long) + * @see #isTrue(boolean, String, Object...) + */ + public static void isTrue(boolean expression, String message, double value) { + if (expression == false) { + throw new IllegalArgumentException(String.format(message, Double.valueOf(value))); + } + } + + /** + *

Validate that the argument condition is {@code true}; otherwise + * throwing an exception with the specified message. This method is useful when + * validating according to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression.

+ * + *
+     * Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);
+     * Validate.isTrue(myObject.isOk(), "The object is not okay");
+ * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean) + * @see #isTrue(boolean, String, long) + * @see #isTrue(boolean, String, double) + */ + public static void isTrue(boolean expression, String message, Object... values) { + if (expression == false) { + throw new IllegalArgumentException(String.format(message, values)); + } + } + + /** + *

Validate that the argument condition is {@code true}; otherwise + * throwing an exception. This method is useful when validating according + * to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression.

+ * + *
+     * Validate.isTrue(i > 0);
+     * Validate.isTrue(myObject.isOk());
+ * + *

The message of the exception is "The validated expression is + * false".

+ * + * @param expression the boolean expression to check + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean, String, long) + * @see #isTrue(boolean, String, double) + * @see #isTrue(boolean, String, Object...) + */ + public static void isTrue(boolean expression) { + if (expression == false) { + throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE); + } + } + + // notNull + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument is not {@code null}; + * otherwise throwing an exception. + * + *

Validate.notNull(myObject, "The object must not be null");
+ * + *

The message of the exception is "The validated object is + * null".

+ * + * @param the object type + * @param object the object to check + * @return the validated object (never {@code null} for method chaining) + * @throws NullPointerException if the object is {@code null} + * @see #notNull(Object, String, Object...) + */ + public static T notNull(T object) { + return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE); + } + + /** + *

Validate that the specified argument is not {@code null}; + * otherwise throwing an exception with the specified message. + * + *

Validate.notNull(myObject, "The object must not be null");
+ * + * @param the object type + * @param object the object to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message + * @return the validated object (never {@code null} for method chaining) + * @throws NullPointerException if the object is {@code null} + * @see #notNull(Object) + */ + public static T notNull(T object, String message, Object... values) { + if (object == null) { + throw new NullPointerException(String.format(message, values)); + } + return object; + } + + // notEmpty array + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument array is neither {@code null} + * nor a length of zero (no elements); otherwise throwing an exception + * with the specified message. + * + *

Validate.notEmpty(myArray, "The array must not be empty");
+ * + * @param the array type + * @param array the array to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @return the validated array (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if the array is empty + * @see #notEmpty(Object[]) + */ + public static T[] notEmpty(T[] array, String message, Object... values) { + if (array == null) { + throw new NullPointerException(String.format(message, values)); + } + if (array.length == 0) { + throw new IllegalArgumentException(String.format(message, values)); + } + return array; + } + + /** + *

Validate that the specified argument array is neither {@code null} + * nor a length of zero (no elements); otherwise throwing an exception. + * + *

Validate.notEmpty(myArray);
+ * + *

The message in the exception is "The validated array is + * empty". + * + * @param the array type + * @param array the array to check, validated not null by this method + * @return the validated array (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if the array is empty + * @see #notEmpty(Object[], String, Object...) + */ + public static T[] notEmpty(T[] array) { + return notEmpty(array, DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE); + } + + // notEmpty collection + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument collection is neither {@code null} + * nor a size of zero (no elements); otherwise throwing an exception + * with the specified message. + * + *

Validate.notEmpty(myCollection, "The collection must not be empty");
+ * + * @param the collection type + * @param collection the collection to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @return the validated collection (never {@code null} method for chaining) + * @throws NullPointerException if the collection is {@code null} + * @throws IllegalArgumentException if the collection is empty + * @see #notEmpty(Object[]) + */ + public static > T notEmpty(T collection, String message, Object... values) { + if (collection == null) { + throw new NullPointerException(String.format(message, values)); + } + if (collection.isEmpty()) { + throw new IllegalArgumentException(String.format(message, values)); + } + return collection; + } + + /** + *

Validate that the specified argument collection is neither {@code null} + * nor a size of zero (no elements); otherwise throwing an exception. + * + *

Validate.notEmpty(myCollection);
+ * + *

The message in the exception is "The validated collection is + * empty".

+ * + * @param the collection type + * @param collection the collection to check, validated not null by this method + * @return the validated collection (never {@code null} method for chaining) + * @throws NullPointerException if the collection is {@code null} + * @throws IllegalArgumentException if the collection is empty + * @see #notEmpty(Collection, String, Object...) + */ + public static > T notEmpty(T collection) { + return notEmpty(collection, DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE); + } + + // notEmpty map + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument map is neither {@code null} + * nor a size of zero (no elements); otherwise throwing an exception + * with the specified message. + * + *

Validate.notEmpty(myMap, "The map must not be empty");
+ * + * @param the map type + * @param map the map to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @return the validated map (never {@code null} method for chaining) + * @throws NullPointerException if the map is {@code null} + * @throws IllegalArgumentException if the map is empty + * @see #notEmpty(Object[]) + */ + public static > T notEmpty(T map, String message, Object... values) { + if (map == null) { + throw new NullPointerException(String.format(message, values)); + } + if (map.isEmpty()) { + throw new IllegalArgumentException(String.format(message, values)); + } + return map; + } + + /** + *

Validate that the specified argument map is neither {@code null} + * nor a size of zero (no elements); otherwise throwing an exception. + * + *

Validate.notEmpty(myMap);
+ * + *

The message in the exception is "The validated map is + * empty".

+ * + * @param the map type + * @param map the map to check, validated not null by this method + * @return the validated map (never {@code null} method for chaining) + * @throws NullPointerException if the map is {@code null} + * @throws IllegalArgumentException if the map is empty + * @see #notEmpty(Map, String, Object...) + */ + public static > T notEmpty(T map) { + return notEmpty(map, DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE); + } + + // notEmpty string + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument character sequence is + * neither {@code null} nor a length of zero (no characters); + * otherwise throwing an exception with the specified message. + * + *

Validate.notEmpty(myString, "The string must not be empty");
+ * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @return the validated character sequence (never {@code null} method for chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IllegalArgumentException if the character sequence is empty + * @see #notEmpty(CharSequence) + */ + public static T notEmpty(T chars, String message, Object... values) { + if (chars == null) { + throw new NullPointerException(String.format(message, values)); + } + if (chars.length() == 0) { + throw new IllegalArgumentException(String.format(message, values)); + } + return chars; + } + + /** + *

Validate that the specified argument character sequence is + * neither {@code null} nor a length of zero (no characters); + * otherwise throwing an exception with the specified message. + * + *

Validate.notEmpty(myString);
+ * + *

The message in the exception is "The validated + * character sequence is empty".

+ * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this method + * @return the validated character sequence (never {@code null} method for chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IllegalArgumentException if the character sequence is empty + * @see #notEmpty(CharSequence, String, Object...) + */ + public static T notEmpty(T chars) { + return notEmpty(chars, DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE); + } + + // notBlank string + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument character sequence is + * neither {@code null}, a length of zero (no characters), empty + * nor whitespace; otherwise throwing an exception with the specified + * message. + * + *

Validate.notBlank(myString, "The string must not be blank");
+ * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @return the validated character sequence (never {@code null} method for chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IllegalArgumentException if the character sequence is blank + * @see #notBlank(CharSequence) + * + * @since 3.0 + */ + public static T notBlank(T chars, String message, Object... values) { + if (chars == null) { + throw new NullPointerException(String.format(message, values)); + } + if (StringUtils.isBlank(chars)) { + throw new IllegalArgumentException(String.format(message, values)); + } + return chars; + } + + /** + *

Validate that the specified argument character sequence is + * neither {@code null}, a length of zero (no characters), empty + * nor whitespace; otherwise throwing an exception. + * + *

Validate.notBlank(myString);
+ * + *

The message in the exception is "The validated character + * sequence is blank".

+ * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this method + * @return the validated character sequence (never {@code null} method for chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IllegalArgumentException if the character sequence is blank + * @see #notBlank(CharSequence, String, Object...) + * + * @since 3.0 + */ + public static T notBlank(T chars) { + return notBlank(chars, DEFAULT_NOT_BLANK_EX_MESSAGE); + } + + // noNullElements array + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument array is neither + * {@code null} nor contains any elements that are {@code null}; + * otherwise throwing an exception with the specified message. + * + *

Validate.noNullElements(myArray, "The array contain null at position %d");
+ * + *

If the array is {@code null}, then the message in the exception + * is "The validated object is null".

+ * + *

If the array has a {@code null} element, then the iteration + * index of the invalid element is appended to the {@code values} + * argument.

+ * + * @param the array type + * @param array the array to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @return the validated array (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if an element is {@code null} + * @see #noNullElements(Object[]) + */ + public static T[] noNullElements(T[] array, String message, Object... values) { + Validate.notNull(array); + for (int i = 0; i < array.length; i++) { + if (array[i] == null) { + Object[] values2 = ArrayUtils.add(values, Integer.valueOf(i)); + throw new IllegalArgumentException(String.format(message, values2)); + } + } + return array; + } + + /** + *

Validate that the specified argument array is neither + * {@code null} nor contains any elements that are {@code null}; + * otherwise throwing an exception. + * + *

Validate.noNullElements(myArray);
+ * + *

If the array is {@code null}, then the message in the exception + * is "The validated object is null".

+ * + *

If the array has a {@code null} element, then the message in the + * exception is "The validated array contains null element at index: + * " followed by the index.

+ * + * @param the array type + * @param array the array to check, validated not null by this method + * @return the validated array (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if an element is {@code null} + * @see #noNullElements(Object[], String, Object...) + */ + public static T[] noNullElements(T[] array) { + return noNullElements(array, DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE); + } + + // noNullElements iterable + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument iterable is neither + * {@code null} nor contains any elements that are {@code null}; + * otherwise throwing an exception with the specified message. + * + *

Validate.noNullElements(myCollection, "The collection contains null at position %d");
+ * + *

If the iterable is {@code null}, then the message in the exception + * is "The validated object is null".

+ * + *

If the iterable has a {@code null} element, then the iteration + * index of the invalid element is appended to the {@code values} + * argument.

+ * + * @param the iterable type + * @param iterable the iterable to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @return the validated iterable (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if an element is {@code null} + * @see #noNullElements(Iterable) + */ + public static > T noNullElements(T iterable, String message, Object... values) { + Validate.notNull(iterable); + int i = 0; + for (Iterator it = iterable.iterator(); it.hasNext(); i++) { + if (it.next() == null) { + Object[] values2 = ArrayUtils.addAll(values, Integer.valueOf(i)); + throw new IllegalArgumentException(String.format(message, values2)); + } + } + return iterable; + } + + /** + *

Validate that the specified argument iterable is neither + * {@code null} nor contains any elements that are {@code null}; + * otherwise throwing an exception. + * + *

Validate.noNullElements(myCollection);
+ * + *

If the iterable is {@code null}, then the message in the exception + * is "The validated object is null".

+ * + *

If the array has a {@code null} element, then the message in the + * exception is "The validated iterable contains null element at index: + * " followed by the index.

+ * + * @param the iterable type + * @param iterable the iterable to check, validated not null by this method + * @return the validated iterable (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if an element is {@code null} + * @see #noNullElements(Iterable, String, Object...) + */ + public static > T noNullElements(T iterable) { + return noNullElements(iterable, DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE); + } + + // validIndex array + //--------------------------------------------------------------------------------- + + /** + *

Validates that the index is within the bounds of the argument + * array; otherwise throwing an exception with the specified message.

+ * + *
Validate.validIndex(myArray, 2, "The array index is invalid: ");
+ * + *

If the array is {@code null}, then the message of the exception + * is "The validated object is null".

+ * + * @param the array type + * @param array the array to check, validated not null by this method + * @param index the index to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @return the validated array (never {@code null} for method chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(Object[], int) + * + * @since 3.0 + */ + public static T[] validIndex(T[] array, int index, String message, Object... values) { + Validate.notNull(array); + if (index < 0 || index >= array.length) { + throw new IndexOutOfBoundsException(String.format(message, values)); + } + return array; + } + + /** + *

Validates that the index is within the bounds of the argument + * array; otherwise throwing an exception.

+ * + *
Validate.validIndex(myArray, 2);
+ * + *

If the array is {@code null}, then the message of the exception + * is "The validated object is null".

+ * + *

If the index is invalid, then the message of the exception is + * "The validated array index is invalid: " followed by the + * index.

+ * + * @param the array type + * @param array the array to check, validated not null by this method + * @param index the index to check + * @return the validated array (never {@code null} for method chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(Object[], int, String, Object...) + * + * @since 3.0 + */ + public static T[] validIndex(T[] array, int index) { + return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index)); + } + + // validIndex collection + //--------------------------------------------------------------------------------- + + /** + *

Validates that the index is within the bounds of the argument + * collection; otherwise throwing an exception with the specified message.

+ * + *
Validate.validIndex(myCollection, 2, "The collection index is invalid: ");
+ * + *

If the collection is {@code null}, then the message of the + * exception is "The validated object is null".

+ * + * @param the collection type + * @param collection the collection to check, validated not null by this method + * @param index the index to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @return the validated collection (never {@code null} for chaining) + * @throws NullPointerException if the collection is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(Collection, int) + * + * @since 3.0 + */ + public static > T validIndex(T collection, int index, String message, Object... values) { + Validate.notNull(collection); + if (index < 0 || index >= collection.size()) { + throw new IndexOutOfBoundsException(String.format(message, values)); + } + return collection; + } + + /** + *

Validates that the index is within the bounds of the argument + * collection; otherwise throwing an exception.

+ * + *
Validate.validIndex(myCollection, 2);
+ * + *

If the index is invalid, then the message of the exception + * is "The validated collection index is invalid: " + * followed by the index.

+ * + * @param the collection type + * @param collection the collection to check, validated not null by this method + * @param index the index to check + * @return the validated collection (never {@code null} for method chaining) + * @throws NullPointerException if the collection is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(Collection, int, String, Object...) + * + * @since 3.0 + */ + public static > T validIndex(T collection, int index) { + return validIndex(collection, index, DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE, Integer.valueOf(index)); + } + + // validIndex string + //--------------------------------------------------------------------------------- + + /** + *

Validates that the index is within the bounds of the argument + * character sequence; otherwise throwing an exception with the + * specified message.

+ * + *
Validate.validIndex(myStr, 2, "The string index is invalid: ");
+ * + *

If the character sequence is {@code null}, then the message + * of the exception is "The validated object is null".

+ * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this method + * @param index the index to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @return the validated character sequence (never {@code null} for method chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(CharSequence, int) + * + * @since 3.0 + */ + public static T validIndex(T chars, int index, String message, Object... values) { + Validate.notNull(chars); + if (index < 0 || index >= chars.length()) { + throw new IndexOutOfBoundsException(String.format(message, values)); + } + return chars; + } + + /** + *

Validates that the index is within the bounds of the argument + * character sequence; otherwise throwing an exception.

+ * + *
Validate.validIndex(myStr, 2);
+ * + *

If the character sequence is {@code null}, then the message + * of the exception is "The validated object is + * null".

+ * + *

If the index is invalid, then the message of the exception + * is "The validated character sequence index is invalid: " + * followed by the index.

+ * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this method + * @param index the index to check + * @return the validated character sequence (never {@code null} for method chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(CharSequence, int, String, Object...) + * + * @since 3.0 + */ + public static T validIndex(T chars, int index) { + return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index)); + } + + // validState + //--------------------------------------------------------------------------------- + + /** + *

Validate that the stateful condition is {@code true}; otherwise + * throwing an exception. This method is useful when validating according + * to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression.

+ * + *
+     * Validate.validState(field > 0);
+     * Validate.validState(this.isOk());
+ * + *

The message of the exception is "The validated state is + * false".

+ * + * @param expression the boolean expression to check + * @throws IllegalStateException if expression is {@code false} + * @see #validState(boolean, String, Object...) + * + * @since 3.0 + */ + public static void validState(boolean expression) { + if (expression == false) { + throw new IllegalStateException(DEFAULT_VALID_STATE_EX_MESSAGE); + } + } + + /** + *

Validate that the stateful condition is {@code true}; otherwise + * throwing an exception with the specified message. This method is useful when + * validating according to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression.

+ * + *
Validate.validState(this.isOk(), "The state is not OK: %s", myObject);
+ * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @throws IllegalStateException if expression is {@code false} + * @see #validState(boolean) + * + * @since 3.0 + */ + public static void validState(boolean expression, String message, Object... values) { + if (expression == false) { + throw new IllegalStateException(String.format(message, values)); + } + } + + // matchesPattern + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument character sequence matches the specified regular + * expression pattern; otherwise throwing an exception.

+ * + *
Validate.matchesPattern("hi", "[a-z]*");
+ * + *

The syntax of the pattern is the one used in the {@link Pattern} class.

+ * + * @param input the character sequence to validate, not null + * @param pattern the regular expression pattern, not null + * @throws IllegalArgumentException if the character sequence does not match the pattern + * @see #matchesPattern(CharSequence, String, String, Object...) + * + * @since 3.0 + */ + public static void matchesPattern(CharSequence input, String pattern) { + if (Pattern.matches(pattern, input) == false) { + throw new IllegalArgumentException(String.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern)); + } + } + + /** + *

Validate that the specified argument character sequence matches the specified regular + * expression pattern; otherwise throwing an exception with the specified message.

+ * + *
Validate.matchesPattern("hi", "[a-z]*", "%s does not match %s", "hi" "[a-z]*");
+ * + *

The syntax of the pattern is the one used in the {@link Pattern} class.

+ * + * @param input the character sequence to validate, not null + * @param pattern the regular expression pattern, not null + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @throws IllegalArgumentException if the character sequence does not match the pattern + * @see #matchesPattern(CharSequence, String) + * + * @since 3.0 + */ + public static void matchesPattern(CharSequence input, String pattern, String message, Object... values) { + if (Pattern.matches(pattern, input) == false) { + throw new IllegalArgumentException(String.format(message, values)); + } + } + + // inclusiveBetween + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument object fall between the two + * inclusive values specified; otherwise, throws an exception.

+ * + *
Validate.inclusiveBetween(0, 2, 1);
+ * + * @param the type of the argument object + * @param start the inclusive start value, not null + * @param end the inclusive end value, not null + * @param value the object to validate, not null + * @throws IllegalArgumentException if the value falls out of the boundaries + * @see #inclusiveBetween(Object, Object, Comparable, String, Object...) + * + * @since 3.0 + */ + public static void inclusiveBetween(T start, T end, Comparable value) { + if (value.compareTo(start) < 0 || value.compareTo(end) > 0) { + throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); + } + } + + /** + *

Validate that the specified argument object fall between the two + * inclusive values specified; otherwise, throws an exception with the + * specified message.

+ * + *
Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");
+ * + * @param the type of the argument object + * @param start the inclusive start value, not null + * @param end the inclusive end value, not null + * @param value the object to validate, not null + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @throws IllegalArgumentException if the value falls out of the boundaries + * @see #inclusiveBetween(Object, Object, Comparable) + * + * @since 3.0 + */ + public static void inclusiveBetween(T start, T end, Comparable value, String message, Object... values) { + if (value.compareTo(start) < 0 || value.compareTo(end) > 0) { + throw new IllegalArgumentException(String.format(message, values)); + } + } + + // exclusiveBetween + //--------------------------------------------------------------------------------- + + /** + *

Validate that the specified argument object fall between the two + * exclusive values specified; otherwise, throws an exception.

+ * + *
Validate.inclusiveBetween(0, 2, 1);
+ * + * @param the type of the argument object + * @param start the exclusive start value, not null + * @param end the exclusive end value, not null + * @param value the object to validate, not null + * @throws IllegalArgumentException if the value falls out of the boundaries + * @see #exclusiveBetween(Object, Object, Comparable, String, Object...) + * + * @since 3.0 + */ + public static void exclusiveBetween(T start, T end, Comparable value) { + if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) { + throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); + } + } + + /** + *

Validate that the specified argument object fall between the two + * exclusive values specified; otherwise, throws an exception with the + * specified message.

+ * + *
Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");
+ * + * @param the type of the argument object + * @param start the exclusive start value, not null + * @param end the exclusive end value, not null + * @param value the object to validate, not null + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @throws IllegalArgumentException if the value falls out of the boundaries + * @see #exclusiveBetween(Object, Object, Comparable) + * + * @since 3.0 + */ + public static void exclusiveBetween(T start, T end, Comparable value, String message, Object... values) { + if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) { + throw new IllegalArgumentException(String.format(message, values)); + } + } + + // isInstanceOf + //--------------------------------------------------------------------------------- + + /** + * Validates that the argument is an instance of the specified class, if not throws an exception. + * + *

This method is useful when validating according to an arbitrary class

+ * + *
Validate.isInstanceOf(OkClass.class, object);
+ * + *

The message of the exception is "Expected type: {type}, actual: {obj_type}"

+ * + * @param type the class the object must be validated against, not null + * @param obj the object to check, null throws an exception + * @throws IllegalArgumentException if argument is not of specified class + * @see #isInstanceOf(Class, Object, String, Object...) + * + * @since 3.0 + */ + public static void isInstanceOf(Class type, Object obj) { + if (type.isInstance(obj) == false) { + throw new IllegalArgumentException(String.format(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(), + obj == null ? "null" : obj.getClass().getName())); + } + } + + /** + *

Validate that the argument is an instance of the specified class; otherwise + * throwing an exception with the specified message. This method is useful when + * validating according to an arbitrary class

+ * + *
Validate.isInstanceOf(OkClass.classs, object, "Wrong class, object is of class %s",
+     *   object.getClass().getName());
+ * + * @param type the class the object must be validated against, not null + * @param obj the object to check, null throws an exception + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @throws IllegalArgumentException if argument is not of specified class + * @see #isInstanceOf(Class, Object) + * + * @since 3.0 + */ + public static void isInstanceOf(Class type, Object obj, String message, Object... values) { + if (type.isInstance(obj) == false) { + throw new IllegalArgumentException(String.format(message, values)); + } + } + + // isAssignableFrom + //--------------------------------------------------------------------------------- + + /** + * Validates that the argument can be converted to the specified class, if not, throws an exception. + * + *

This method is useful when validating that there will be no casting errors.

+ * + *
Validate.isAssignableFrom(SuperClass.class, object.getClass());
+ * + *

The message format of the exception is "Cannot assign {type} to {superType}"

+ * + * @param superType the class the class must be validated against, not null + * @param type the class to check, not null + * @throws IllegalArgumentException if type argument is not assignable to the specified superType + * @see #isAssignableFrom(Class, Class, String, Object...) + * + * @since 3.0 + */ + public static void isAssignableFrom(Class superType, Class type) { + if (superType.isAssignableFrom(type) == false) { + throw new IllegalArgumentException(String.format(DEFAULT_IS_ASSIGNABLE_EX_MESSAGE, type == null ? "null" : type.getName(), + superType.getName())); + } + } + + /** + * Validates that the argument can be converted to the specified class, if not throws an exception. + * + *

This method is useful when validating if there will be no casting errors.

+ * + *
Validate.isAssignableFrom(SuperClass.class, object.getClass());
+ * + *

The message of the exception is "The validated object can not be converted to the" + * followed by the name of the class and "class"

+ * + * @param superType the class the class must be validated against, not null + * @param type the class to check, not null + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @throws IllegalArgumentException if argument can not be converted to the specified class + * @see #isAssignableFrom(Class, Class) + */ + public static void isAssignableFrom(Class superType, Class type, String message, Object... values) { + if (superType.isAssignableFrom(type) == false) { + throw new IllegalArgumentException(String.format(message, values)); + } + } +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/Builder.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/Builder.java new file mode 100644 index 00000000..a3b840cf --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/Builder.java @@ -0,0 +1,89 @@ +/* + * 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; + +/** + *

+ * The Builder interface is designed to designate a class as a builder + * object in the Builder design pattern. Builders are capable of creating and + * configuring objects or results that normally take multiple steps to construct + * or are very complex to derive. + *

+ * + *

+ * The builder interface defines a single method, {@link #build()}, that + * classes must implement. The result of this method should be the final + * configured object or result after all building operations are performed. + *

+ * + *

+ * It is a recommended practice that the methods supplied to configure the + * object or result being built return a reference to {@code this} so that + * method calls can be chained together. + *

+ * + *

+ * Example Builder: + *

+ * class FontBuilder implements Builder<Font> {
+ *     private Font font;
+ *     
+ *     public FontBuilder(String fontName) {
+ *         this.font = new Font(fontName, Font.PLAIN, 12);
+ *     }
+ * 
+ *     public FontBuilder bold() {
+ *         this.font = this.font.deriveFont(Font.BOLD);
+ *         return this; // Reference returned so calls can be chained
+ *     }
+ *     
+ *     public FontBuilder size(float pointSize) {
+ *         this.font = this.font.deriveFont(pointSize);
+ *         return this; // Reference returned so calls can be chained
+ *     }
+ * 
+ *     // Other Font construction methods
+ * 
+ *     public Font build() {
+ *         return this.font;
+ *     }
+ * }
+ * 
+ * + * Example Builder Usage: + *
+ * Font bold14ptSansSerifFont = new FontBuilder(Font.SANS_SERIF).bold()
+ *                                                              .size(14.0f)
+ *                                                              .build();
+ * 
+ *

+ * + * @param the type of object that the builder will construct or compute. + * + * @since 3.0 + * @version $Id: Builder.java 1088899 2011-04-05 05:31:27Z bayard $ + */ +public interface Builder { + + /** + * Returns a reference to the object being constructed or result being + * calculated by the builder. + * + * @return the object constructed or result calculated by the builder. + */ + public T build(); +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/CompareToBuilder.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/CompareToBuilder.java new file mode 100644 index 00000000..9d06f589 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/CompareToBuilder.java @@ -0,0 +1,1020 @@ +/* + * 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; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.Comparator; + +import external.org.apache.commons.lang3.ArrayUtils; + +/** + * Assists in implementing {@link java.lang.Comparable#compareTo(Object)} methods. + * + * It is consistent with equals(Object) and + * hashcode() built with {@link EqualsBuilder} and + * {@link HashCodeBuilder}.

+ * + *

Two Objects that compare equal using equals(Object) should normally + * also compare equal using compareTo(Object).

+ * + *

All relevant fields should be included in the calculation of the + * comparison. Derived fields may be ignored. The same fields, in the same + * order, should be used in both compareTo(Object) and + * equals(Object).

+ * + *

To use this class write code as follows:

+ * + *
+ * public class MyClass {
+ *   String field1;
+ *   int field2;
+ *   boolean field3;
+ *
+ *   ...
+ *
+ *   public int compareTo(Object o) {
+ *     MyClass myClass = (MyClass) o;
+ *     return new CompareToBuilder()
+ *       .appendSuper(super.compareTo(o)
+ *       .append(this.field1, myClass.field1)
+ *       .append(this.field2, myClass.field2)
+ *       .append(this.field3, myClass.field3)
+ *       .toComparison();
+ *   }
+ * }
+ * 
+ * + *

Alternatively, there are {@link #reflectionCompare(Object, Object) reflectionCompare} methods that use + * reflection to determine the fields to append. Because fields can be private, + * reflectionCompare uses {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} to + * bypass normal access control checks. This will fail under a security manager, + * unless the appropriate permissions are set up correctly. It is also + * slower than appending explicitly.

+ * + *

A typical implementation of compareTo(Object) using + * reflectionCompare looks like:

+ + *
+ * public int compareTo(Object o) {
+ *   return CompareToBuilder.reflectionCompare(this, o);
+ * }
+ * 
+ * + * @see java.lang.Comparable + * @see java.lang.Object#equals(Object) + * @see java.lang.Object#hashCode() + * @see EqualsBuilder + * @see HashCodeBuilder + * @since 1.0 + * @version $Id: CompareToBuilder.java 1199735 2011-11-09 13:11:07Z sebb $ + */ +public class CompareToBuilder implements Builder { + + /** + * Current state of the comparison as appended fields are checked. + */ + private int comparison; + + /** + *

Constructor for CompareToBuilder.

+ * + *

Starts off assuming that the objects are equal. Multiple calls are + * then made to the various append methods, followed by a call to + * {@link #toComparison} to get the result.

+ */ + public CompareToBuilder() { + super(); + comparison = 0; + } + + //----------------------------------------------------------------------- + /** + *

Compares two Objects via reflection.

+ * + *

Fields can be private, thus AccessibleObject.setAccessible + * is used to bypass normal access control checks. This will fail under a + * security manager unless the appropriate permissions are set.

+ * + *
    + *
  • Static fields will not be compared
  • + *
  • Transient members will be not be compared, as they are likely derived + * fields
  • + *
  • Superclass fields will be compared
  • + *
+ * + *

If both lhs and rhs are null, + * they are considered equal.

+ * + * @param lhs left-hand object + * @param rhs right-hand object + * @return a negative integer, zero, or a positive integer as lhs + * is less than, equal to, or greater than rhs + * @throws NullPointerException if either (but not both) parameters are + * null + * @throws ClassCastException if rhs is not assignment-compatible + * with lhs + */ + public static int reflectionCompare(Object lhs, Object rhs) { + return reflectionCompare(lhs, rhs, false, null); + } + + /** + *

Compares two Objects via reflection.

+ * + *

Fields can be private, thus AccessibleObject.setAccessible + * is used to bypass normal access control checks. This will fail under a + * security manager unless the appropriate permissions are set.

+ * + *
    + *
  • Static fields will not be compared
  • + *
  • If compareTransients is true, + * compares transient members. Otherwise ignores them, as they + * are likely derived fields.
  • + *
  • Superclass fields will be compared
  • + *
+ * + *

If both lhs and rhs are null, + * they are considered equal.

+ * + * @param lhs left-hand object + * @param rhs right-hand object + * @param compareTransients whether to compare transient fields + * @return a negative integer, zero, or a positive integer as lhs + * is less than, equal to, or greater than rhs + * @throws NullPointerException if either lhs or rhs + * (but not both) is null + * @throws ClassCastException if rhs is not assignment-compatible + * with lhs + */ + public static int reflectionCompare(Object lhs, Object rhs, boolean compareTransients) { + return reflectionCompare(lhs, rhs, compareTransients, null); + } + + /** + *

Compares two Objects via reflection.

+ * + *

Fields can be private, thus AccessibleObject.setAccessible + * is used to bypass normal access control checks. This will fail under a + * security manager unless the appropriate permissions are set.

+ * + *
    + *
  • Static fields will not be compared
  • + *
  • If compareTransients is true, + * compares transient members. Otherwise ignores them, as they + * are likely derived fields.
  • + *
  • Superclass fields will be compared
  • + *
+ * + *

If both lhs and rhs are null, + * they are considered equal.

+ * + * @param lhs left-hand object + * @param rhs right-hand object + * @param excludeFields Collection of String fields to exclude + * @return a negative integer, zero, or a positive integer as lhs + * is less than, equal to, or greater than rhs + * @throws NullPointerException if either lhs or rhs + * (but not both) is null + * @throws ClassCastException if rhs is not assignment-compatible + * with lhs + * @since 2.2 + */ + public static int reflectionCompare(Object lhs, Object rhs, Collection excludeFields) { + return reflectionCompare(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields)); + } + + /** + *

Compares two Objects via reflection.

+ * + *

Fields can be private, thus AccessibleObject.setAccessible + * is used to bypass normal access control checks. This will fail under a + * security manager unless the appropriate permissions are set.

+ * + *
    + *
  • Static fields will not be compared
  • + *
  • If compareTransients is true, + * compares transient members. Otherwise ignores them, as they + * are likely derived fields.
  • + *
  • Superclass fields will be compared
  • + *
+ * + *

If both lhs and rhs are null, + * they are considered equal.

+ * + * @param lhs left-hand object + * @param rhs right-hand object + * @param excludeFields array of fields to exclude + * @return a negative integer, zero, or a positive integer as lhs + * is less than, equal to, or greater than rhs + * @throws NullPointerException if either lhs or rhs + * (but not both) is null + * @throws ClassCastException if rhs is not assignment-compatible + * with lhs + * @since 2.2 + */ + public static int reflectionCompare(Object lhs, Object rhs, String... excludeFields) { + return reflectionCompare(lhs, rhs, false, null, excludeFields); + } + + /** + *

Compares two Objects via reflection.

+ * + *

Fields can be private, thus AccessibleObject.setAccessible + * is used to bypass normal access control checks. This will fail under a + * security manager unless the appropriate permissions are set.

+ * + *
    + *
  • Static fields will not be compared
  • + *
  • If the compareTransients is true, + * compares transient members. Otherwise ignores them, as they + * are likely derived fields.
  • + *
  • Compares superclass fields up to and including reflectUpToClass. + * If reflectUpToClass is null, compares all superclass fields.
  • + *
+ * + *

If both lhs and rhs are null, + * they are considered equal.

+ * + * @param lhs left-hand object + * @param rhs right-hand object + * @param compareTransients whether to compare transient fields + * @param reflectUpToClass last superclass for which fields are compared + * @param excludeFields fields to exclude + * @return a negative integer, zero, or a positive integer as lhs + * is less than, equal to, or greater than rhs + * @throws NullPointerException if either lhs or rhs + * (but not both) is null + * @throws ClassCastException if rhs is not assignment-compatible + * with lhs + * @since 2.2 (2.0 as reflectionCompare(Object, Object, boolean, Class)) + */ + public static int reflectionCompare( + Object lhs, + Object rhs, + boolean compareTransients, + Class reflectUpToClass, + String... excludeFields) { + + if (lhs == rhs) { + return 0; + } + if (lhs == null || rhs == null) { + throw new NullPointerException(); + } + Class lhsClazz = lhs.getClass(); + if (!lhsClazz.isInstance(rhs)) { + throw new ClassCastException(); + } + CompareToBuilder compareToBuilder = new CompareToBuilder(); + reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields); + while (lhsClazz.getSuperclass() != null && lhsClazz != reflectUpToClass) { + lhsClazz = lhsClazz.getSuperclass(); + reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields); + } + return compareToBuilder.toComparison(); + } + + /** + *

Appends to builder the comparison of lhs + * to rhs using the fields defined in clazz.

+ * + * @param lhs left-hand object + * @param rhs right-hand object + * @param clazz Class that defines fields to be compared + * @param builder CompareToBuilder to append to + * @param useTransients whether to compare transient fields + * @param excludeFields fields to exclude + */ + private static void reflectionAppend( + Object lhs, + Object rhs, + Class clazz, + CompareToBuilder builder, + boolean useTransients, + String[] excludeFields) { + + Field[] fields = clazz.getDeclaredFields(); + AccessibleObject.setAccessible(fields, true); + for (int i = 0; i < fields.length && builder.comparison == 0; i++) { + Field f = fields[i]; + if (!ArrayUtils.contains(excludeFields, f.getName()) + && (f.getName().indexOf('$') == -1) + && (useTransients || !Modifier.isTransient(f.getModifiers())) + && (!Modifier.isStatic(f.getModifiers()))) { + try { + builder.append(f.get(lhs), f.get(rhs)); + } catch (IllegalAccessException e) { + // This can't happen. Would get a Security exception instead. + // Throw a runtime exception in case the impossible happens. + throw new InternalError("Unexpected IllegalAccessException"); + } + } + } + } + + //----------------------------------------------------------------------- + /** + *

Appends to the builder the compareTo(Object) + * result of the superclass.

+ * + * @param superCompareTo result of calling super.compareTo(Object) + * @return this - used to chain append calls + * @since 2.0 + */ + public CompareToBuilder appendSuper(int superCompareTo) { + if (comparison != 0) { + return this; + } + comparison = superCompareTo; + return this; + } + + //----------------------------------------------------------------------- + /** + *

Appends to the builder the comparison of + * two Objects.

+ * + *
    + *
  1. Check if lhs == rhs
  2. + *
  3. Check if either lhs or rhs is null, + * a null object is less than a non-null object
  4. + *
  5. Check the object contents
  6. + *
+ * + *

lhs must either be an array or implement {@link Comparable}.

+ * + * @param lhs left-hand object + * @param rhs right-hand object + * @return this - used to chain append calls + * @throws ClassCastException if rhs is not assignment-compatible + * with lhs + */ + public CompareToBuilder append(Object lhs, Object rhs) { + return append(lhs, rhs, null); + } + + /** + *

Appends to the builder the comparison of + * two Objects.

+ * + *
    + *
  1. Check if lhs == rhs
  2. + *
  3. Check if either lhs or rhs is null, + * a null object is less than a non-null object
  4. + *
  5. Check the object contents
  6. + *
+ * + *

If lhs is an array, array comparison methods will be used. + * Otherwise comparator will be used to compare the objects. + * If comparator is null, lhs must + * implement {@link Comparable} instead.

+ * + * @param lhs left-hand object + * @param rhs right-hand object + * @param comparator Comparator used to compare the objects, + * null means treat lhs as Comparable + * @return this - used to chain append calls + * @throws ClassCastException if rhs is not assignment-compatible + * with lhs + * @since 2.0 + */ + public CompareToBuilder append(Object lhs, Object rhs, Comparator comparator) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null) { + comparison = -1; + return this; + } + if (rhs == null) { + comparison = +1; + return this; + } + if (lhs.getClass().isArray()) { + // switch on type of array, to dispatch to the correct handler + // handles multi dimensional arrays + // throws a ClassCastException if rhs is not the correct array type + if (lhs instanceof long[]) { + append((long[]) lhs, (long[]) rhs); + } else if (lhs instanceof int[]) { + append((int[]) lhs, (int[]) rhs); + } else if (lhs instanceof short[]) { + append((short[]) lhs, (short[]) rhs); + } else if (lhs instanceof char[]) { + append((char[]) lhs, (char[]) rhs); + } else if (lhs instanceof byte[]) { + append((byte[]) lhs, (byte[]) rhs); + } else if (lhs instanceof double[]) { + append((double[]) lhs, (double[]) rhs); + } else if (lhs instanceof float[]) { + append((float[]) lhs, (float[]) rhs); + } else if (lhs instanceof boolean[]) { + append((boolean[]) lhs, (boolean[]) rhs); + } else { + // not an array of primitives + // throws a ClassCastException if rhs is not an array + append((Object[]) lhs, (Object[]) rhs, comparator); + } + } else { + // the simple case, not an array, just test the element + if (comparator == null) { + @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc + final Comparable comparable = (Comparable) lhs; + comparison = comparable.compareTo(rhs); + } else { + @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc + final Comparator comparator2 = (Comparator) comparator; + comparison = comparator2.compare(lhs, rhs); + } + } + return this; + } + + //------------------------------------------------------------------------- + /** + * Appends to the builder the comparison of + * two longs. + * + * @param lhs left-hand value + * @param rhs right-hand value + * @return this - used to chain append calls + */ + public CompareToBuilder append(long lhs, long rhs) { + if (comparison != 0) { + return this; + } + comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0)); + return this; + } + + /** + * Appends to the builder the comparison of + * two ints. + * + * @param lhs left-hand value + * @param rhs right-hand value + * @return this - used to chain append calls + */ + public CompareToBuilder append(int lhs, int rhs) { + if (comparison != 0) { + return this; + } + comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0)); + return this; + } + + /** + * Appends to the builder the comparison of + * two shorts. + * + * @param lhs left-hand value + * @param rhs right-hand value + * @return this - used to chain append calls + */ + public CompareToBuilder append(short lhs, short rhs) { + if (comparison != 0) { + return this; + } + comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0)); + return this; + } + + /** + * Appends to the builder the comparison of + * two chars. + * + * @param lhs left-hand value + * @param rhs right-hand value + * @return this - used to chain append calls + */ + public CompareToBuilder append(char lhs, char rhs) { + if (comparison != 0) { + return this; + } + comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0)); + return this; + } + + /** + * Appends to the builder the comparison of + * two bytes. + * + * @param lhs left-hand value + * @param rhs right-hand value + * @return this - used to chain append calls + */ + public CompareToBuilder append(byte lhs, byte rhs) { + if (comparison != 0) { + return this; + } + comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0)); + return this; + } + + /** + *

Appends to the builder the comparison of + * two doubles.

+ * + *

This handles NaNs, Infinities, and -0.0.

+ * + *

It is compatible with the hash code generated by + * HashCodeBuilder.

+ * + * @param lhs left-hand value + * @param rhs right-hand value + * @return this - used to chain append calls + */ + public CompareToBuilder append(double lhs, double rhs) { + if (comparison != 0) { + return this; + } + comparison = Double.compare(lhs, rhs); + return this; + } + + /** + *

Appends to the builder the comparison of + * two floats.

+ * + *

This handles NaNs, Infinities, and -0.0.

+ * + *

It is compatible with the hash code generated by + * HashCodeBuilder.

+ * + * @param lhs left-hand value + * @param rhs right-hand value + * @return this - used to chain append calls + */ + public CompareToBuilder append(float lhs, float rhs) { + if (comparison != 0) { + return this; + } + comparison = Float.compare(lhs, rhs); + return this; + } + + /** + * Appends to the builder the comparison of + * two booleanss. + * + * @param lhs left-hand value + * @param rhs right-hand value + * @return this - used to chain append calls + */ + public CompareToBuilder append(boolean lhs, boolean rhs) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == false) { + comparison = -1; + } else { + comparison = +1; + } + return this; + } + + //----------------------------------------------------------------------- + /** + *

Appends to the builder the deep comparison of + * two Object arrays.

+ * + *
    + *
  1. Check if arrays are the same using ==
  2. + *
  3. Check if for null, null is less than non-null
  4. + *
  5. Check array length, a short length array is less than a long length array
  6. + *
  7. Check array contents element by element using {@link #append(Object, Object, Comparator)}
  8. + *
+ * + *

This method will also will be called for the top level of multi-dimensional, + * ragged, and multi-typed arrays.

+ * + * @param lhs left-hand array + * @param rhs right-hand array + * @return this - used to chain append calls + * @throws ClassCastException if rhs is not assignment-compatible + * with lhs + */ + public CompareToBuilder append(Object[] lhs, Object[] rhs) { + return append(lhs, rhs, null); + } + + /** + *

Appends to the builder the deep comparison of + * two Object arrays.

+ * + *
    + *
  1. Check if arrays are the same using ==
  2. + *
  3. Check if for null, null is less than non-null
  4. + *
  5. Check array length, a short length array is less than a long length array
  6. + *
  7. Check array contents element by element using {@link #append(Object, Object, Comparator)}
  8. + *
+ * + *

This method will also will be called for the top level of multi-dimensional, + * ragged, and multi-typed arrays.

+ * + * @param lhs left-hand array + * @param rhs right-hand array + * @param comparator Comparator to use to compare the array elements, + * null means to treat lhs elements as Comparable. + * @return this - used to chain append calls + * @throws ClassCastException if rhs is not assignment-compatible + * with lhs + * @since 2.0 + */ + public CompareToBuilder append(Object[] lhs, Object[] rhs, Comparator comparator) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null) { + comparison = -1; + return this; + } + if (rhs == null) { + comparison = +1; + return this; + } + if (lhs.length != rhs.length) { + comparison = (lhs.length < rhs.length) ? -1 : +1; + return this; + } + for (int i = 0; i < lhs.length && comparison == 0; i++) { + append(lhs[i], rhs[i], comparator); + } + return this; + } + + /** + *

Appends to the builder the deep comparison of + * two long arrays.

+ * + *
    + *
  1. Check if arrays are the same using ==
  2. + *
  3. Check if for null, null is less than non-null
  4. + *
  5. Check array length, a shorter length array is less than a longer length array
  6. + *
  7. Check array contents element by element using {@link #append(long, long)}
  8. + *
+ * + * @param lhs left-hand array + * @param rhs right-hand array + * @return this - used to chain append calls + */ + public CompareToBuilder append(long[] lhs, long[] rhs) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null) { + comparison = -1; + return this; + } + if (rhs == null) { + comparison = +1; + return this; + } + if (lhs.length != rhs.length) { + comparison = (lhs.length < rhs.length) ? -1 : +1; + return this; + } + for (int i = 0; i < lhs.length && comparison == 0; i++) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Appends to the builder the deep comparison of + * two int arrays.

+ * + *
    + *
  1. Check if arrays are the same using ==
  2. + *
  3. Check if for null, null is less than non-null
  4. + *
  5. Check array length, a shorter length array is less than a longer length array
  6. + *
  7. Check array contents element by element using {@link #append(int, int)}
  8. + *
+ * + * @param lhs left-hand array + * @param rhs right-hand array + * @return this - used to chain append calls + */ + public CompareToBuilder append(int[] lhs, int[] rhs) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null) { + comparison = -1; + return this; + } + if (rhs == null) { + comparison = +1; + return this; + } + if (lhs.length != rhs.length) { + comparison = (lhs.length < rhs.length) ? -1 : +1; + return this; + } + for (int i = 0; i < lhs.length && comparison == 0; i++) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Appends to the builder the deep comparison of + * two short arrays.

+ * + *
    + *
  1. Check if arrays are the same using ==
  2. + *
  3. Check if for null, null is less than non-null
  4. + *
  5. Check array length, a shorter length array is less than a longer length array
  6. + *
  7. Check array contents element by element using {@link #append(short, short)}
  8. + *
+ * + * @param lhs left-hand array + * @param rhs right-hand array + * @return this - used to chain append calls + */ + public CompareToBuilder append(short[] lhs, short[] rhs) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null) { + comparison = -1; + return this; + } + if (rhs == null) { + comparison = +1; + return this; + } + if (lhs.length != rhs.length) { + comparison = (lhs.length < rhs.length) ? -1 : +1; + return this; + } + for (int i = 0; i < lhs.length && comparison == 0; i++) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Appends to the builder the deep comparison of + * two char arrays.

+ * + *
    + *
  1. Check if arrays are the same using ==
  2. + *
  3. Check if for null, null is less than non-null
  4. + *
  5. Check array length, a shorter length array is less than a longer length array
  6. + *
  7. Check array contents element by element using {@link #append(char, char)}
  8. + *
+ * + * @param lhs left-hand array + * @param rhs right-hand array + * @return this - used to chain append calls + */ + public CompareToBuilder append(char[] lhs, char[] rhs) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null) { + comparison = -1; + return this; + } + if (rhs == null) { + comparison = +1; + return this; + } + if (lhs.length != rhs.length) { + comparison = (lhs.length < rhs.length) ? -1 : +1; + return this; + } + for (int i = 0; i < lhs.length && comparison == 0; i++) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Appends to the builder the deep comparison of + * two byte arrays.

+ * + *
    + *
  1. Check if arrays are the same using ==
  2. + *
  3. Check if for null, null is less than non-null
  4. + *
  5. Check array length, a shorter length array is less than a longer length array
  6. + *
  7. Check array contents element by element using {@link #append(byte, byte)}
  8. + *
+ * + * @param lhs left-hand array + * @param rhs right-hand array + * @return this - used to chain append calls + */ + public CompareToBuilder append(byte[] lhs, byte[] rhs) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null) { + comparison = -1; + return this; + } + if (rhs == null) { + comparison = +1; + return this; + } + if (lhs.length != rhs.length) { + comparison = (lhs.length < rhs.length) ? -1 : +1; + return this; + } + for (int i = 0; i < lhs.length && comparison == 0; i++) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Appends to the builder the deep comparison of + * two double arrays.

+ * + *
    + *
  1. Check if arrays are the same using ==
  2. + *
  3. Check if for null, null is less than non-null
  4. + *
  5. Check array length, a shorter length array is less than a longer length array
  6. + *
  7. Check array contents element by element using {@link #append(double, double)}
  8. + *
+ * + * @param lhs left-hand array + * @param rhs right-hand array + * @return this - used to chain append calls + */ + public CompareToBuilder append(double[] lhs, double[] rhs) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null) { + comparison = -1; + return this; + } + if (rhs == null) { + comparison = +1; + return this; + } + if (lhs.length != rhs.length) { + comparison = (lhs.length < rhs.length) ? -1 : +1; + return this; + } + for (int i = 0; i < lhs.length && comparison == 0; i++) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Appends to the builder the deep comparison of + * two float arrays.

+ * + *
    + *
  1. Check if arrays are the same using ==
  2. + *
  3. Check if for null, null is less than non-null
  4. + *
  5. Check array length, a shorter length array is less than a longer length array
  6. + *
  7. Check array contents element by element using {@link #append(float, float)}
  8. + *
+ * + * @param lhs left-hand array + * @param rhs right-hand array + * @return this - used to chain append calls + */ + public CompareToBuilder append(float[] lhs, float[] rhs) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null) { + comparison = -1; + return this; + } + if (rhs == null) { + comparison = +1; + return this; + } + if (lhs.length != rhs.length) { + comparison = (lhs.length < rhs.length) ? -1 : +1; + return this; + } + for (int i = 0; i < lhs.length && comparison == 0; i++) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Appends to the builder the deep comparison of + * two boolean arrays.

+ * + *
    + *
  1. Check if arrays are the same using ==
  2. + *
  3. Check if for null, null is less than non-null
  4. + *
  5. Check array length, a shorter length array is less than a longer length array
  6. + *
  7. Check array contents element by element using {@link #append(boolean, boolean)}
  8. + *
+ * + * @param lhs left-hand array + * @param rhs right-hand array + * @return this - used to chain append calls + */ + public CompareToBuilder append(boolean[] lhs, boolean[] rhs) { + if (comparison != 0) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null) { + comparison = -1; + return this; + } + if (rhs == null) { + comparison = +1; + return this; + } + if (lhs.length != rhs.length) { + comparison = (lhs.length < rhs.length) ? -1 : +1; + return this; + } + for (int i = 0; i < lhs.length && comparison == 0; i++) { + append(lhs[i], rhs[i]); + } + return this; + } + + //----------------------------------------------------------------------- + /** + * Returns a negative integer, a positive integer, or zero as + * the builder has judged the "left-hand" side + * as less than, greater than, or equal to the "right-hand" + * side. + * + * @return final comparison result + * @see #build() + */ + public int toComparison() { + return comparison; + } + + /** + * Returns a negative Integer, a positive Integer, or zero as + * the builder has judged the "left-hand" side + * as less than, greater than, or equal to the "right-hand" + * side. + * + * @return final comparison result as an Integer + * @see #toComparison() + * @since 3.0 + */ + public Integer build() { + return Integer.valueOf(toComparison()); + } +} + diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/EqualsBuilder.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/EqualsBuilder.java new file mode 100644 index 00000000..c8a459c5 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/EqualsBuilder.java @@ -0,0 +1,945 @@ +/* + * 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; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + + +import external.org.apache.commons.lang3.ArrayUtils; +import external.org.apache.commons.lang3.tuple.Pair; + +/** + *

Assists in implementing {@link Object#equals(Object)} methods.

+ * + *

This class provides methods to build a good equals method for any + * class. It follows rules laid out in + * Effective Java + * , by Joshua Bloch. In particular the rule for comparing doubles, + * floats, and arrays can be tricky. Also, making sure that + * equals() and hashCode() are consistent can be + * difficult.

+ * + *

Two Objects that compare as equals must generate the same hash code, + * but two Objects with the same hash code do not have to be equal.

+ * + *

All relevant fields should be included in the calculation of equals. + * Derived fields may be ignored. In particular, any field used in + * generating a hash code must be used in the equals method, and vice + * versa.

+ * + *

Typical use for the code is as follows:

+ *
+ * public boolean equals(Object obj) {
+ *   if (obj == null) { return false; }
+ *   if (obj == this) { return true; }
+ *   if (obj.getClass() != getClass()) {
+ *     return false;
+ *   }
+ *   MyClass rhs = (MyClass) obj;
+ *   return new EqualsBuilder()
+ *                 .appendSuper(super.equals(obj))
+ *                 .append(field1, rhs.field1)
+ *                 .append(field2, rhs.field2)
+ *                 .append(field3, rhs.field3)
+ *                 .isEquals();
+ *  }
+ * 
+ * + *

Alternatively, there is a method that uses reflection to determine + * the fields to test. Because these fields are usually private, the method, + * reflectionEquals, uses AccessibleObject.setAccessible to + * change the visibility of the fields. This will fail under a security + * manager, unless the appropriate permissions are set up correctly. It is + * also slower than testing explicitly.

+ * + *

A typical invocation for this method would look like:

+ *
+ * public boolean equals(Object obj) {
+ *   return EqualsBuilder.reflectionEquals(this, obj);
+ * }
+ * 
+ * + * @since 1.0 + * @version $Id: EqualsBuilder.java 1091531 2011-04-12 18:29:49Z ggregory $ + */ +public class EqualsBuilder implements Builder { + + /** + *

+ * A registry of objects used by reflection methods to detect cyclical object references and avoid infinite loops. + *

+ * + * @since 3.0 + */ + private static final ThreadLocal>> REGISTRY = new ThreadLocal>>(); + + /* + * NOTE: we cannot store the actual objects in a HashSet, as that would use the very hashCode() + * we are in the process of calculating. + * + * So we generate a one-to-one mapping from the original object to a new object. + * + * Now HashSet uses equals() to determine if two elements with the same hashcode really + * are equal, so we also need to ensure that the replacement objects are only equal + * if the original objects are identical. + * + * The original implementation (2.4 and before) used the System.indentityHashCode() + * method - however this is not guaranteed to generate unique ids (e.g. LANG-459) + * + * We now use the IDKey helper class (adapted from org.apache.axis.utils.IDKey) + * to disambiguate the duplicate ids. + */ + + /** + *

+ * Returns the registry of object pairs being traversed by the reflection + * methods in the current thread. + *

+ * + * @return Set the registry of objects being traversed + * @since 3.0 + */ + static Set> getRegistry() { + return REGISTRY.get(); + } + + /** + *

+ * Converters value pair into a register pair. + *

+ * + * @param lhs this object + * @param rhs the other object + * + * @return the pair + */ + static Pair getRegisterPair(Object lhs, Object rhs) { + IDKey left = new IDKey(lhs); + IDKey right = new IDKey(rhs); + return Pair.of(left, right); + } + + /** + *

+ * Returns true if the registry contains the given object pair. + * Used by the reflection methods to avoid infinite loops. + * Objects might be swapped therefore a check is needed if the object pair + * is registered in given or swapped order. + *

+ * + * @param lhs this object to lookup in registry + * @param rhs the other object to lookup on registry + * @return boolean true if the registry contains the given object. + * @since 3.0 + */ + static boolean isRegistered(Object lhs, Object rhs) { + Set> registry = getRegistry(); + Pair pair = getRegisterPair(lhs, rhs); + Pair swappedPair = Pair.of(pair.getLeft(), pair.getRight()); + + return registry != null + && (registry.contains(pair) || registry.contains(swappedPair)); + } + + /** + *

+ * Registers the given object pair. + * Used by the reflection methods to avoid infinite loops. + *

+ * + * @param lhs this object to register + * @param rhs the other object to register + */ + static void register(Object lhs, Object rhs) { + synchronized (EqualsBuilder.class) { + if (getRegistry() == null) { + REGISTRY.set(new HashSet>()); + } + } + + Set> registry = getRegistry(); + Pair pair = getRegisterPair(lhs, rhs); + registry.add(pair); + } + + /** + *

+ * Unregisters the given object pair. + *

+ * + *

+ * Used by the reflection methods to avoid infinite loops. + * + * @param lhs this object to unregister + * @param rhs the other object to unregister + * @since 3.0 + */ + static void unregister(Object lhs, Object rhs) { + Set> registry = getRegistry(); + if (registry != null) { + Pair pair = getRegisterPair(lhs, rhs); + registry.remove(pair); + synchronized (EqualsBuilder.class) { + //read again + registry = getRegistry(); + if (registry != null && registry.isEmpty()) { + REGISTRY.remove(); + } + } + } + } + + /** + * If the fields tested are equals. + * The default value is true. + */ + private boolean isEquals = true; + + /** + *

Constructor for EqualsBuilder.

+ * + *

Starts off assuming that equals is true.

+ * @see Object#equals(Object) + */ + public EqualsBuilder() { + // do nothing for now. + } + + //------------------------------------------------------------------------- + + /** + *

This method uses reflection to determine if the two Objects + * are equal.

+ * + *

It uses AccessibleObject.setAccessible to gain access to private + * fields. This means that it will throw a security exception if run under + * a security manager, if the permissions are not set up correctly. It is also + * not as efficient as testing explicitly.

+ * + *

Transient members will be not be tested, as they are likely derived + * fields, and not part of the value of the Object.

+ * + *

Static fields will not be tested. Superclass fields will be included.

+ * + * @param lhs this object + * @param rhs the other object + * @param excludeFields Collection of String field names to exclude from testing + * @return true if the two Objects have tested equals. + */ + public static boolean reflectionEquals(Object lhs, Object rhs, Collection excludeFields) { + return reflectionEquals(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields)); + } + + /** + *

This method uses reflection to determine if the two Objects + * are equal.

+ * + *

It uses AccessibleObject.setAccessible to gain access to private + * fields. This means that it will throw a security exception if run under + * a security manager, if the permissions are not set up correctly. It is also + * not as efficient as testing explicitly.

+ * + *

Transient members will be not be tested, as they are likely derived + * fields, and not part of the value of the Object.

+ * + *

Static fields will not be tested. Superclass fields will be included.

+ * + * @param lhs this object + * @param rhs the other object + * @param excludeFields array of field names to exclude from testing + * @return true if the two Objects have tested equals. + */ + public static boolean reflectionEquals(Object lhs, Object rhs, String... excludeFields) { + return reflectionEquals(lhs, rhs, false, null, excludeFields); + } + + /** + *

This method uses reflection to determine if the two Objects + * are equal.

+ * + *

It uses AccessibleObject.setAccessible to gain access to private + * fields. This means that it will throw a security exception if run under + * a security manager, if the permissions are not set up correctly. It is also + * not as efficient as testing explicitly.

+ * + *

If the TestTransients parameter is set to true, transient + * members will be tested, otherwise they are ignored, as they are likely + * derived fields, and not part of the value of the Object.

+ * + *

Static fields will not be tested. Superclass fields will be included.

+ * + * @param lhs this object + * @param rhs the other object + * @param testTransients whether to include transient fields + * @return true if the two Objects have tested equals. + */ + public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients) { + return reflectionEquals(lhs, rhs, testTransients, null); + } + + /** + *

This method uses reflection to determine if the two Objects + * are equal.

+ * + *

It uses AccessibleObject.setAccessible to gain access to private + * fields. This means that it will throw a security exception if run under + * a security manager, if the permissions are not set up correctly. It is also + * not as efficient as testing explicitly.

+ * + *

If the testTransients parameter is set to true, transient + * members will be tested, otherwise they are ignored, as they are likely + * derived fields, and not part of the value of the Object.

+ * + *

Static fields will not be included. Superclass fields will be appended + * up to and including the specified superclass. A null superclass is treated + * as java.lang.Object.

+ * + * @param lhs this object + * @param rhs the other object + * @param testTransients whether to include transient fields + * @param reflectUpToClass the superclass to reflect up to (inclusive), + * may be null + * @param excludeFields array of field names to exclude from testing + * @return true if the two Objects have tested equals. + * @since 2.0 + */ + public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class reflectUpToClass, + String... excludeFields) { + if (lhs == rhs) { + return true; + } + if (lhs == null || rhs == null) { + return false; + } + // Find the leaf class since there may be transients in the leaf + // class or in classes between the leaf and root. + // If we are not testing transients or a subclass has no ivars, + // then a subclass can test equals to a superclass. + Class lhsClass = lhs.getClass(); + Class rhsClass = rhs.getClass(); + Class testClass; + if (lhsClass.isInstance(rhs)) { + testClass = lhsClass; + if (!rhsClass.isInstance(lhs)) { + // rhsClass is a subclass of lhsClass + testClass = rhsClass; + } + } else if (rhsClass.isInstance(lhs)) { + testClass = rhsClass; + if (!lhsClass.isInstance(rhs)) { + // lhsClass is a subclass of rhsClass + testClass = lhsClass; + } + } else { + // The two classes are not related. + return false; + } + EqualsBuilder equalsBuilder = new EqualsBuilder(); + try { + reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields); + while (testClass.getSuperclass() != null && testClass != reflectUpToClass) { + testClass = testClass.getSuperclass(); + reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields); + } + } catch (IllegalArgumentException e) { + // In this case, we tried to test a subclass vs. a superclass and + // the subclass has ivars or the ivars are transient and + // we are testing transients. + // If a subclass has ivars that we are trying to test them, we get an + // exception and we know that the objects are not equal. + return false; + } + return equalsBuilder.isEquals(); + } + + /** + *

Appends the fields and values defined by the given object of the + * given Class.

+ * + * @param lhs the left hand object + * @param rhs the right hand object + * @param clazz the class to append details of + * @param builder the builder to append to + * @param useTransients whether to test transient fields + * @param excludeFields array of field names to exclude from testing + */ + private static void reflectionAppend( + Object lhs, + Object rhs, + Class clazz, + EqualsBuilder builder, + boolean useTransients, + String[] excludeFields) { + + if (isRegistered(lhs, rhs)) { + return; + } + + try { + register(lhs, rhs); + Field[] fields = clazz.getDeclaredFields(); + AccessibleObject.setAccessible(fields, true); + for (int i = 0; i < fields.length && builder.isEquals; i++) { + Field f = fields[i]; + if (!ArrayUtils.contains(excludeFields, f.getName()) + && (f.getName().indexOf('$') == -1) + && (useTransients || !Modifier.isTransient(f.getModifiers())) + && (!Modifier.isStatic(f.getModifiers()))) { + try { + builder.append(f.get(lhs), f.get(rhs)); + } catch (IllegalAccessException e) { + //this can't happen. Would get a Security exception instead + //throw a runtime exception in case the impossible happens. + throw new InternalError("Unexpected IllegalAccessException"); + } + } + } + } finally { + unregister(lhs, rhs); + } + } + + //------------------------------------------------------------------------- + + /** + *

Adds the result of super.equals() to this builder.

+ * + * @param superEquals the result of calling super.equals() + * @return EqualsBuilder - used to chain calls. + * @since 2.0 + */ + public EqualsBuilder appendSuper(boolean superEquals) { + if (isEquals == false) { + return this; + } + isEquals = superEquals; + return this; + } + + //------------------------------------------------------------------------- + + /** + *

Test if two Objects are equal using their + * equals method.

+ * + * @param lhs the left hand object + * @param rhs the right hand object + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(Object lhs, Object rhs) { + if (isEquals == false) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null || rhs == null) { + this.setEquals(false); + return this; + } + Class lhsClass = lhs.getClass(); + if (!lhsClass.isArray()) { + // The simple case, not an array, just test the element + isEquals = lhs.equals(rhs); + } else if (lhs.getClass() != rhs.getClass()) { + // Here when we compare different dimensions, for example: a boolean[][] to a boolean[] + this.setEquals(false); + } + // 'Switch' on type of array, to dispatch to the correct handler + // This handles multi dimensional arrays of the same depth + else if (lhs instanceof long[]) { + append((long[]) lhs, (long[]) rhs); + } else if (lhs instanceof int[]) { + append((int[]) lhs, (int[]) rhs); + } else if (lhs instanceof short[]) { + append((short[]) lhs, (short[]) rhs); + } else if (lhs instanceof char[]) { + append((char[]) lhs, (char[]) rhs); + } else if (lhs instanceof byte[]) { + append((byte[]) lhs, (byte[]) rhs); + } else if (lhs instanceof double[]) { + append((double[]) lhs, (double[]) rhs); + } else if (lhs instanceof float[]) { + append((float[]) lhs, (float[]) rhs); + } else if (lhs instanceof boolean[]) { + append((boolean[]) lhs, (boolean[]) rhs); + } else { + // Not an array of primitives + append((Object[]) lhs, (Object[]) rhs); + } + return this; + } + + /** + *

+ * Test if two long s are equal. + *

+ * + * @param lhs + * the left hand long + * @param rhs + * the right hand long + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(long lhs, long rhs) { + if (isEquals == false) { + return this; + } + isEquals = (lhs == rhs); + return this; + } + + /** + *

Test if two ints are equal.

+ * + * @param lhs the left hand int + * @param rhs the right hand int + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(int lhs, int rhs) { + if (isEquals == false) { + return this; + } + isEquals = (lhs == rhs); + return this; + } + + /** + *

Test if two shorts are equal.

+ * + * @param lhs the left hand short + * @param rhs the right hand short + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(short lhs, short rhs) { + if (isEquals == false) { + return this; + } + isEquals = (lhs == rhs); + return this; + } + + /** + *

Test if two chars are equal.

+ * + * @param lhs the left hand char + * @param rhs the right hand char + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(char lhs, char rhs) { + if (isEquals == false) { + return this; + } + isEquals = (lhs == rhs); + return this; + } + + /** + *

Test if two bytes are equal.

+ * + * @param lhs the left hand byte + * @param rhs the right hand byte + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(byte lhs, byte rhs) { + if (isEquals == false) { + return this; + } + isEquals = (lhs == rhs); + return this; + } + + /** + *

Test if two doubles are equal by testing that the + * pattern of bits returned by doubleToLong are equal.

+ * + *

This handles NaNs, Infinities, and -0.0.

+ * + *

It is compatible with the hash code generated by + * HashCodeBuilder.

+ * + * @param lhs the left hand double + * @param rhs the right hand double + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(double lhs, double rhs) { + if (isEquals == false) { + return this; + } + return append(Double.doubleToLongBits(lhs), Double.doubleToLongBits(rhs)); + } + + /** + *

Test if two floats are equal byt testing that the + * pattern of bits returned by doubleToLong are equal.

+ * + *

This handles NaNs, Infinities, and -0.0.

+ * + *

It is compatible with the hash code generated by + * HashCodeBuilder.

+ * + * @param lhs the left hand float + * @param rhs the right hand float + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(float lhs, float rhs) { + if (isEquals == false) { + return this; + } + return append(Float.floatToIntBits(lhs), Float.floatToIntBits(rhs)); + } + + /** + *

Test if two booleanss are equal.

+ * + * @param lhs the left hand boolean + * @param rhs the right hand boolean + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(boolean lhs, boolean rhs) { + if (isEquals == false) { + return this; + } + isEquals = (lhs == rhs); + return this; + } + + /** + *

Performs a deep comparison of two Object arrays.

+ * + *

This also will be called for the top level of + * multi-dimensional, ragged, and multi-typed arrays.

+ * + * @param lhs the left hand Object[] + * @param rhs the right hand Object[] + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(Object[] lhs, Object[] rhs) { + if (isEquals == false) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null || rhs == null) { + this.setEquals(false); + return this; + } + if (lhs.length != rhs.length) { + this.setEquals(false); + return this; + } + for (int i = 0; i < lhs.length && isEquals; ++i) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Deep comparison of array of long. Length and all + * values are compared.

+ * + *

The method {@link #append(long, long)} is used.

+ * + * @param lhs the left hand long[] + * @param rhs the right hand long[] + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(long[] lhs, long[] rhs) { + if (isEquals == false) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null || rhs == null) { + this.setEquals(false); + return this; + } + if (lhs.length != rhs.length) { + this.setEquals(false); + return this; + } + for (int i = 0; i < lhs.length && isEquals; ++i) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Deep comparison of array of int. Length and all + * values are compared.

+ * + *

The method {@link #append(int, int)} is used.

+ * + * @param lhs the left hand int[] + * @param rhs the right hand int[] + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(int[] lhs, int[] rhs) { + if (isEquals == false) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null || rhs == null) { + this.setEquals(false); + return this; + } + if (lhs.length != rhs.length) { + this.setEquals(false); + return this; + } + for (int i = 0; i < lhs.length && isEquals; ++i) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Deep comparison of array of short. Length and all + * values are compared.

+ * + *

The method {@link #append(short, short)} is used.

+ * + * @param lhs the left hand short[] + * @param rhs the right hand short[] + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(short[] lhs, short[] rhs) { + if (isEquals == false) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null || rhs == null) { + this.setEquals(false); + return this; + } + if (lhs.length != rhs.length) { + this.setEquals(false); + return this; + } + for (int i = 0; i < lhs.length && isEquals; ++i) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Deep comparison of array of char. Length and all + * values are compared.

+ * + *

The method {@link #append(char, char)} is used.

+ * + * @param lhs the left hand char[] + * @param rhs the right hand char[] + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(char[] lhs, char[] rhs) { + if (isEquals == false) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null || rhs == null) { + this.setEquals(false); + return this; + } + if (lhs.length != rhs.length) { + this.setEquals(false); + return this; + } + for (int i = 0; i < lhs.length && isEquals; ++i) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Deep comparison of array of byte. Length and all + * values are compared.

+ * + *

The method {@link #append(byte, byte)} is used.

+ * + * @param lhs the left hand byte[] + * @param rhs the right hand byte[] + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(byte[] lhs, byte[] rhs) { + if (isEquals == false) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null || rhs == null) { + this.setEquals(false); + return this; + } + if (lhs.length != rhs.length) { + this.setEquals(false); + return this; + } + for (int i = 0; i < lhs.length && isEquals; ++i) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Deep comparison of array of double. Length and all + * values are compared.

+ * + *

The method {@link #append(double, double)} is used.

+ * + * @param lhs the left hand double[] + * @param rhs the right hand double[] + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(double[] lhs, double[] rhs) { + if (isEquals == false) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null || rhs == null) { + this.setEquals(false); + return this; + } + if (lhs.length != rhs.length) { + this.setEquals(false); + return this; + } + for (int i = 0; i < lhs.length && isEquals; ++i) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Deep comparison of array of float. Length and all + * values are compared.

+ * + *

The method {@link #append(float, float)} is used.

+ * + * @param lhs the left hand float[] + * @param rhs the right hand float[] + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(float[] lhs, float[] rhs) { + if (isEquals == false) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null || rhs == null) { + this.setEquals(false); + return this; + } + if (lhs.length != rhs.length) { + this.setEquals(false); + return this; + } + for (int i = 0; i < lhs.length && isEquals; ++i) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Deep comparison of array of boolean. Length and all + * values are compared.

+ * + *

The method {@link #append(boolean, boolean)} is used.

+ * + * @param lhs the left hand boolean[] + * @param rhs the right hand boolean[] + * @return EqualsBuilder - used to chain calls. + */ + public EqualsBuilder append(boolean[] lhs, boolean[] rhs) { + if (isEquals == false) { + return this; + } + if (lhs == rhs) { + return this; + } + if (lhs == null || rhs == null) { + this.setEquals(false); + return this; + } + if (lhs.length != rhs.length) { + this.setEquals(false); + return this; + } + for (int i = 0; i < lhs.length && isEquals; ++i) { + append(lhs[i], rhs[i]); + } + return this; + } + + /** + *

Returns true if the fields that have been checked + * are all equal.

+ * + * @return boolean + */ + public boolean isEquals() { + return this.isEquals; + } + + /** + *

Returns true if the fields that have been checked + * are all equal.

+ * + * @return true if all of the fields that have been checked + * are equal, false otherwise. + * + * @since 3.0 + */ + public Boolean build() { + return Boolean.valueOf(isEquals()); + } + + /** + * Sets the isEquals value. + * + * @param isEquals The value to set. + * @since 2.1 + */ + protected void setEquals(boolean isEquals) { + this.isEquals = isEquals; + } + + /** + * Reset the EqualsBuilder so you can use the same object again + * @since 2.5 + */ + public void reset() { + this.isEquals = true; + } +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/HashCodeBuilder.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/HashCodeBuilder.java new file mode 100644 index 00000000..093a9661 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/HashCodeBuilder.java @@ -0,0 +1,961 @@ +/* + * 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; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import external.org.apache.commons.lang3.ArrayUtils; + +/** + *

+ * Assists in implementing {@link Object#hashCode()} methods. + *

+ * + *

+ * This class enables a good hashCode method to be built for any class. It follows the rules laid out in + * the book Effective Java by Joshua Bloch. Writing a + * good hashCode method is actually quite difficult. This class aims to simplify the process. + *

+ * + *

+ * The following is the approach taken. When appending a data field, the current total is multiplied by the + * multiplier then a relevant value + * for that data type is added. For example, if the current hashCode is 17, and the multiplier is 37, then + * appending the integer 45 will create a hashcode of 674, namely 17 * 37 + 45. + *

+ * + *

+ * All relevant fields from the object should be included in the hashCode method. Derived fields may be + * excluded. In general, any field used in the equals method must be used in the hashCode + * method. + *

+ * + *

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

+ * + *
+ * public class Person {
+ *   String name;
+ *   int age;
+ *   boolean smoker;
+ *   ...
+ *
+ *   public int hashCode() {
+ *     // you pick a hard-coded, randomly chosen, non-zero, odd number
+ *     // ideally different for each class
+ *     return new HashCodeBuilder(17, 37).
+ *       append(name).
+ *       append(age).
+ *       append(smoker).
+ *       toHashCode();
+ *   }
+ * }
+ * 
+ * + *

+ * If required, the superclass hashCode() can be added using {@link #appendSuper}. + *

+ * + *

+ * Alternatively, there is a method that uses reflection to determine the fields to test. Because these fields are + * usually private, the method, reflectionHashCode, uses AccessibleObject.setAccessible + * to change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions + * are set up correctly. It is also slower than testing explicitly. + *

+ * + *

+ * A typical invocation for this method would look like: + *

+ * + *
+ * public int hashCode() {
+ *   return HashCodeBuilder.reflectionHashCode(this);
+ * }
+ * 
+ * + * @since 1.0 + * @version $Id: HashCodeBuilder.java 1144929 2011-07-10 18:26:16Z ggregory $ + */ +public class HashCodeBuilder implements Builder { + /** + *

+ * A registry of objects used by reflection methods to detect cyclical object references and avoid infinite loops. + *

+ * + * @since 2.3 + */ + private static final ThreadLocal> REGISTRY = new ThreadLocal>(); + + /* + * NOTE: we cannot store the actual objects in a HashSet, as that would use the very hashCode() + * we are in the process of calculating. + * + * So we generate a one-to-one mapping from the original object to a new object. + * + * Now HashSet uses equals() to determine if two elements with the same hashcode really + * are equal, so we also need to ensure that the replacement objects are only equal + * if the original objects are identical. + * + * The original implementation (2.4 and before) used the System.indentityHashCode() + * method - however this is not guaranteed to generate unique ids (e.g. LANG-459) + * + * We now use the IDKey helper class (adapted from org.apache.axis.utils.IDKey) + * to disambiguate the duplicate ids. + */ + + /** + *

+ * Returns the registry of objects being traversed by the reflection methods in the current thread. + *

+ * + * @return Set the registry of objects being traversed + * @since 2.3 + */ + static Set getRegistry() { + return REGISTRY.get(); + } + + /** + *

+ * Returns true if the registry contains the given object. Used by the reflection methods to avoid + * infinite loops. + *

+ * + * @param value + * The object to lookup in the registry. + * @return boolean true if the registry contains the given object. + * @since 2.3 + */ + static boolean isRegistered(Object value) { + Set registry = getRegistry(); + return registry != null && registry.contains(new IDKey(value)); + } + + /** + *

+ * Appends the fields and values defined by the given object of the given Class. + *

+ * + * @param object + * the object to append details of + * @param clazz + * the class to append details of + * @param builder + * the builder to append to + * @param useTransients + * whether to use transient fields + * @param excludeFields + * Collection of String field names to exclude from use in calculation of hash code + */ + private static void reflectionAppend(Object object, Class clazz, HashCodeBuilder builder, boolean useTransients, + String[] excludeFields) { + if (isRegistered(object)) { + return; + } + try { + register(object); + Field[] fields = clazz.getDeclaredFields(); + AccessibleObject.setAccessible(fields, true); + for (Field field : fields) { + if (!ArrayUtils.contains(excludeFields, field.getName()) + && (field.getName().indexOf('$') == -1) + && (useTransients || !Modifier.isTransient(field.getModifiers())) + && (!Modifier.isStatic(field.getModifiers()))) { + try { + Object fieldValue = field.get(object); + builder.append(fieldValue); + } catch (IllegalAccessException e) { + // this can't happen. Would get a Security exception instead + // throw a runtime exception in case the impossible happens. + throw new InternalError("Unexpected IllegalAccessException"); + } + } + } + } finally { + unregister(object); + } + } + + /** + *

+ * This method uses reflection to build a valid hash code. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be used, as they are likely derived fields, and not part of the value of the + * Object. + *

+ * + *

+ * Static fields will not be tested. Superclass fields will be included. + *

+ * + *

+ * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class, + * however this is not vital. Prime numbers are preferred, especially for the multiplier. + *

+ * + * @param initialNonZeroOddNumber + * a non-zero, odd number used as the initial value + * @param multiplierNonZeroOddNumber + * a non-zero, odd number used as the multiplier + * @param object + * the Object to create a hashCode for + * @return int hash code + * @throws IllegalArgumentException + * if the Object is null + * @throws IllegalArgumentException + * if the number is zero or even + */ + public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object) { + return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, false, null); + } + + /** + *

+ * This method uses reflection to build a valid hash code. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the TestTransients parameter is set to true, transient members will be tested, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * Static fields will not be tested. Superclass fields will be included. + *

+ * + *

+ * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class, + * however this is not vital. Prime numbers are preferred, especially for the multiplier. + *

+ * + * @param initialNonZeroOddNumber + * a non-zero, odd number used as the initial value + * @param multiplierNonZeroOddNumber + * a non-zero, odd number used as the multiplier + * @param object + * the Object to create a hashCode for + * @param testTransients + * whether to include transient fields + * @return int hash code + * @throws IllegalArgumentException + * if the Object is null + * @throws IllegalArgumentException + * if the number is zero or even + */ + public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object, + boolean testTransients) { + return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, testTransients, null); + } + + /** + *

+ * This method uses reflection to build a valid hash code. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the TestTransients parameter is set to true, transient members will be tested, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be included up to and including the specified + * superclass. A null superclass is treated as java.lang.Object. + *

+ * + *

+ * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class, + * however this is not vital. Prime numbers are preferred, especially for the multiplier. + *

+ * + * @param + * the type of the object involved + * @param initialNonZeroOddNumber + * a non-zero, odd number used as the initial value + * @param multiplierNonZeroOddNumber + * a non-zero, odd number used as the multiplier + * @param object + * the Object to create a hashCode for + * @param testTransients + * whether to include transient fields + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @param excludeFields + * array of field names to exclude from use in calculation of hash code + * @return int hash code + * @throws IllegalArgumentException + * if the Object is null + * @throws IllegalArgumentException + * if the number is zero or even + * @since 2.0 + */ + public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, T object, + boolean testTransients, Class reflectUpToClass, String... excludeFields) { + + if (object == null) { + throw new IllegalArgumentException("The object to build a hash code for must not be null"); + } + HashCodeBuilder builder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber); + Class clazz = object.getClass(); + reflectionAppend(object, clazz, builder, testTransients, excludeFields); + while (clazz.getSuperclass() != null && clazz != reflectUpToClass) { + clazz = clazz.getSuperclass(); + reflectionAppend(object, clazz, builder, testTransients, excludeFields); + } + return builder.toHashCode(); + } + + /** + *

+ * This method uses reflection to build a valid hash code. + *

+ * + *

+ * This constructor uses two hard coded choices for the constants needed to build a hash code. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the TestTransients parameter is set to true, transient members will be tested, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * Static fields will not be tested. Superclass fields will be included. + *

+ * + * @param object + * the Object to create a hashCode for + * @param testTransients + * whether to include transient fields + * @return int hash code + * @throws IllegalArgumentException + * if the object is null + */ + public static int reflectionHashCode(Object object, boolean testTransients) { + return reflectionHashCode(17, 37, object, testTransients, null); + } + + /** + *

+ * This method uses reflection to build a valid hash code. + *

+ * + *

+ * This constructor uses two hard coded choices for the constants needed to build a hash code. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be used, as they are likely derived fields, and not part of the value of the + * Object. + *

+ * + *

+ * Static fields will not be tested. Superclass fields will be included. + *

+ * + * @param object + * the Object to create a hashCode for + * @param excludeFields + * Collection of String field names to exclude from use in calculation of hash code + * @return int hash code + * @throws IllegalArgumentException + * if the object is null + */ + public static int reflectionHashCode(Object object, Collection excludeFields) { + return reflectionHashCode(object, ReflectionToStringBuilder.toNoNullStringArray(excludeFields)); + } + + // ------------------------------------------------------------------------- + + /** + *

+ * This method uses reflection to build a valid hash code. + *

+ * + *

+ * This constructor uses two hard coded choices for the constants needed to build a hash code. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be used, as they are likely derived fields, and not part of the value of the + * Object. + *

+ * + *

+ * Static fields will not be tested. Superclass fields will be included. + *

+ * + * @param object + * the Object to create a hashCode for + * @param excludeFields + * array of field names to exclude from use in calculation of hash code + * @return int hash code + * @throws IllegalArgumentException + * if the object is null + */ + public static int reflectionHashCode(Object object, String... excludeFields) { + return reflectionHashCode(17, 37, object, false, null, excludeFields); + } + + /** + *

+ * Registers the given object. Used by the reflection methods to avoid infinite loops. + *

+ * + * @param value + * The object to register. + */ + static void register(Object value) { + synchronized (HashCodeBuilder.class) { + if (getRegistry() == null) { + REGISTRY.set(new HashSet()); + } + } + getRegistry().add(new IDKey(value)); + } + + /** + *

+ * Unregisters the given object. + *

+ * + *

+ * Used by the reflection methods to avoid infinite loops. + * + * @param value + * The object to unregister. + * @since 2.3 + */ + static void unregister(Object value) { + Set registry = getRegistry(); + if (registry != null) { + registry.remove(new IDKey(value)); + synchronized (HashCodeBuilder.class) { + //read again + registry = getRegistry(); + if (registry != null && registry.isEmpty()) { + REGISTRY.remove(); + } + } + } + } + + /** + * Constant to use in building the hashCode. + */ + private final int iConstant; + + /** + * Running total of the hashCode. + */ + private int iTotal = 0; + + /** + *

+ * Uses two hard coded choices for the constants needed to build a hashCode. + *

+ */ + public HashCodeBuilder() { + iConstant = 37; + iTotal = 17; + } + + /** + *

+ * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class, + * however this is not vital. + *

+ * + *

+ * Prime numbers are preferred, especially for the multiplier. + *

+ * + * @param initialNonZeroOddNumber + * a non-zero, odd number used as the initial value + * @param multiplierNonZeroOddNumber + * a non-zero, odd number used as the multiplier + * @throws IllegalArgumentException + * if the number is zero or even + */ + public HashCodeBuilder(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber) { + if (initialNonZeroOddNumber == 0) { + throw new IllegalArgumentException("HashCodeBuilder requires a non zero initial value"); + } + if (initialNonZeroOddNumber % 2 == 0) { + throw new IllegalArgumentException("HashCodeBuilder requires an odd initial value"); + } + if (multiplierNonZeroOddNumber == 0) { + throw new IllegalArgumentException("HashCodeBuilder requires a non zero multiplier"); + } + if (multiplierNonZeroOddNumber % 2 == 0) { + throw new IllegalArgumentException("HashCodeBuilder requires an odd multiplier"); + } + iConstant = multiplierNonZeroOddNumber; + iTotal = initialNonZeroOddNumber; + } + + /** + *

+ * Append a hashCode for a boolean. + *

+ *

+ * This adds 1 when true, and 0 when false to the hashCode. + *

+ *

+ * This is in contrast to the standard java.lang.Boolean.hashCode handling, which computes + * a hashCode value of 1231 for java.lang.Boolean instances + * that represent true or 1237 for java.lang.Boolean instances + * that represent false. + *

+ *

+ * This is in accordance with the Effective Java design. + *

+ * + * @param value + * the boolean to add to the hashCode + * @return this + */ + public HashCodeBuilder append(boolean value) { + iTotal = iTotal * iConstant + (value ? 0 : 1); + return this; + } + + /** + *

+ * Append a hashCode for a boolean array. + *

+ * + * @param array + * the array to add to the hashCode + * @return this + */ + public HashCodeBuilder append(boolean[] array) { + if (array == null) { + iTotal = iTotal * iConstant; + } else { + for (boolean element : array) { + append(element); + } + } + return this; + } + + // ------------------------------------------------------------------------- + + /** + *

+ * Append a hashCode for a byte. + *

+ * + * @param value + * the byte to add to the hashCode + * @return this + */ + public HashCodeBuilder append(byte value) { + iTotal = iTotal * iConstant + value; + return this; + } + + // ------------------------------------------------------------------------- + + /** + *

+ * Append a hashCode for a byte array. + *

+ * + * @param array + * the array to add to the hashCode + * @return this + */ + public HashCodeBuilder append(byte[] array) { + if (array == null) { + iTotal = iTotal * iConstant; + } else { + for (byte element : array) { + append(element); + } + } + return this; + } + + /** + *

+ * Append a hashCode for a char. + *

+ * + * @param value + * the char to add to the hashCode + * @return this + */ + public HashCodeBuilder append(char value) { + iTotal = iTotal * iConstant + value; + return this; + } + + /** + *

+ * Append a hashCode for a char array. + *

+ * + * @param array + * the array to add to the hashCode + * @return this + */ + public HashCodeBuilder append(char[] array) { + if (array == null) { + iTotal = iTotal * iConstant; + } else { + for (char element : array) { + append(element); + } + } + return this; + } + + /** + *

+ * Append a hashCode for a double. + *

+ * + * @param value + * the double to add to the hashCode + * @return this + */ + public HashCodeBuilder append(double value) { + return append(Double.doubleToLongBits(value)); + } + + /** + *

+ * Append a hashCode for a double array. + *

+ * + * @param array + * the array to add to the hashCode + * @return this + */ + public HashCodeBuilder append(double[] array) { + if (array == null) { + iTotal = iTotal * iConstant; + } else { + for (double element : array) { + append(element); + } + } + return this; + } + + /** + *

+ * Append a hashCode for a float. + *

+ * + * @param value + * the float to add to the hashCode + * @return this + */ + public HashCodeBuilder append(float value) { + iTotal = iTotal * iConstant + Float.floatToIntBits(value); + return this; + } + + /** + *

+ * Append a hashCode for a float array. + *

+ * + * @param array + * the array to add to the hashCode + * @return this + */ + public HashCodeBuilder append(float[] array) { + if (array == null) { + iTotal = iTotal * iConstant; + } else { + for (float element : array) { + append(element); + } + } + return this; + } + + /** + *

+ * Append a hashCode for an int. + *

+ * + * @param value + * the int to add to the hashCode + * @return this + */ + public HashCodeBuilder append(int value) { + iTotal = iTotal * iConstant + value; + return this; + } + + /** + *

+ * Append a hashCode for an int array. + *

+ * + * @param array + * the array to add to the hashCode + * @return this + */ + public HashCodeBuilder append(int[] array) { + if (array == null) { + iTotal = iTotal * iConstant; + } else { + for (int element : array) { + append(element); + } + } + return this; + } + + /** + *

+ * Append a hashCode for a long. + *

+ * + * @param value + * the long to add to the hashCode + * @return this + */ + // NOTE: This method uses >> and not >>> as Effective Java and + // Long.hashCode do. Ideally we should switch to >>> at + // some stage. There are backwards compat issues, so + // that will have to wait for the time being. cf LANG-342. + public HashCodeBuilder append(long value) { + iTotal = iTotal * iConstant + ((int) (value ^ (value >> 32))); + return this; + } + + /** + *

+ * Append a hashCode for a long array. + *

+ * + * @param array + * the array to add to the hashCode + * @return this + */ + public HashCodeBuilder append(long[] array) { + if (array == null) { + iTotal = iTotal * iConstant; + } else { + for (long element : array) { + append(element); + } + } + return this; + } + + /** + *

+ * Append a hashCode for an Object. + *

+ * + * @param object + * the Object to add to the hashCode + * @return this + */ + public HashCodeBuilder append(Object object) { + if (object == null) { + iTotal = iTotal * iConstant; + + } else { + if(object.getClass().isArray()) { + // 'Switch' on type of array, to dispatch to the correct handler + // This handles multi dimensional arrays + if (object instanceof long[]) { + append((long[]) object); + } else if (object instanceof int[]) { + append((int[]) object); + } else if (object instanceof short[]) { + append((short[]) object); + } else if (object instanceof char[]) { + append((char[]) object); + } else if (object instanceof byte[]) { + append((byte[]) object); + } else if (object instanceof double[]) { + append((double[]) object); + } else if (object instanceof float[]) { + append((float[]) object); + } else if (object instanceof boolean[]) { + append((boolean[]) object); + } else { + // Not an array of primitives + append((Object[]) object); + } + } else { + iTotal = iTotal * iConstant + object.hashCode(); + } + } + return this; + } + + /** + *

+ * Append a hashCode for an Object array. + *

+ * + * @param array + * the array to add to the hashCode + * @return this + */ + public HashCodeBuilder append(Object[] array) { + if (array == null) { + iTotal = iTotal * iConstant; + } else { + for (Object element : array) { + append(element); + } + } + return this; + } + + /** + *

+ * Append a hashCode for a short. + *

+ * + * @param value + * the short to add to the hashCode + * @return this + */ + public HashCodeBuilder append(short value) { + iTotal = iTotal * iConstant + value; + return this; + } + + /** + *

+ * Append a hashCode for a short array. + *

+ * + * @param array + * the array to add to the hashCode + * @return this + */ + public HashCodeBuilder append(short[] array) { + if (array == null) { + iTotal = iTotal * iConstant; + } else { + for (short element : array) { + append(element); + } + } + return this; + } + + /** + *

+ * Adds the result of super.hashCode() to this builder. + *

+ * + * @param superHashCode + * the result of calling super.hashCode() + * @return this HashCodeBuilder, used to chain calls. + * @since 2.0 + */ + public HashCodeBuilder appendSuper(int superHashCode) { + iTotal = iTotal * iConstant + superHashCode; + return this; + } + + /** + *

+ * Return the computed hashCode. + *

+ * + * @return hashCode based on the fields appended + */ + public int toHashCode() { + return iTotal; + } + + /** + * Returns the computed hashCode. + * + * @return hashCode based on the fields appended + * + * @since 3.0 + */ + public Integer build() { + return Integer.valueOf(toHashCode()); + } + + /** + *

+ * The computed hashCode from toHashCode() is returned due to the likelihood + * of bugs in mis-calling toHashCode() and the unlikeliness of it mattering what the hashCode for + * HashCodeBuilder itself is.

+ * + * @return hashCode based on the fields appended + * @since 2.5 + */ + @Override + public int hashCode() { + return toHashCode(); + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/IDKey.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/IDKey.java new file mode 100644 index 00000000..68d93885 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/IDKey.java @@ -0,0 +1,74 @@ +/* + * 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; + +// adapted from org.apache.axis.utils.IDKey + +/** + * Wrap an identity key (System.identityHashCode()) + * so that an object can only be equal() to itself. + * + * This is necessary to disambiguate the occasional duplicate + * identityHashCodes that can occur. + * + */ +final class IDKey { + private final Object value; + private final int id; + + /** + * Constructor for IDKey + * @param _value The value + */ + public IDKey(Object _value) { + // This is the Object hashcode + id = System.identityHashCode(_value); + // There have been some cases (LANG-459) that return the + // same identity hash code for different objects. So + // the value is also added to disambiguate these cases. + value = _value; + } + + /** + * returns hashcode - i.e. the system identity hashcode. + * @return the hashcode + */ + @Override + public int hashCode() { + return id; + } + + /** + * checks if instances are equal + * @param other The other object to compare to + * @return if the instances are for the same object + */ + @Override + public boolean equals(Object other) { + if (!(other instanceof IDKey)) { + return false; + } + IDKey idKey = (IDKey) other; + if (id != idKey.id) { + return false; + } + // Note that identity equals is used. + return value == idKey.value; + } +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java new file mode 100644 index 00000000..a6f41ec6 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java @@ -0,0 +1,691 @@ +/* + * 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; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import external.org.apache.commons.lang3.ArrayUtils; +import external.org.apache.commons.lang3.ClassUtils; + +/** + *

+ * Assists in implementing {@link Object#toString()} methods using reflection. + *

+ *

+ * This class uses reflection to determine the fields to append. Because these fields are usually private, the class + * uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], boolean)} to + * change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are + * set up correctly. + *

+ *

+ * Using reflection to access (private) fields circumvents any synchronization protection guarding access to these + * fields. If a toString method cannot safely read a field, you should exclude it from the toString method, or use + * synchronization consistent with the class' lock management around the invocation of the method. Take special care to + * exclude non-thread-safe collection classes, because these classes may throw ConcurrentModificationException if + * modified while the toString method is executing. + *

+ *

+ * A typical invocation for this method would look like: + *

+ *
+ * public String toString() {
+ *     return ReflectionToStringBuilder.toString(this);
+ * }
+ * 
+ *

+ * You can also use the builder to debug 3rd party objects: + *

+ *
+ * System.out.println("An object: " + ReflectionToStringBuilder.toString(anObject));
+ * 
+ *

+ * A subclass can control field output by overriding the methods: + *

    + *
  • {@link #accept(java.lang.reflect.Field)}
  • + *
  • {@link #getValue(java.lang.reflect.Field)}
  • + *
+ *

+ *

+ * For example, this method does not include the password field in the returned String: + *

+ *
+ * public String toString() {
+ *     return (new ReflectionToStringBuilder(this) {
+ *         protected boolean accept(Field f) {
+ *             return super.accept(f) && !f.getName().equals("password");
+ *         }
+ *     }).toString();
+ * }
+ * 
+ *

+ * The exact format of the toString is determined by the {@link ToStringStyle} passed into the constructor. + *

+ * + * @since 2.0 + * @version $Id: ReflectionToStringBuilder.java 1200177 2011-11-10 06:14:33Z ggregory $ + */ +public class ReflectionToStringBuilder extends ToStringBuilder { + + /** + *

+ * Builds a toString value using the default ToStringStyle through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + * @param object + * the Object to be output + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + */ + public static String toString(Object object) { + return toString(object, null, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object or ToStringStyle is null + */ + public static String toString(Object object, ToStringStyle style) { + return toString(object, style, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient members will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + */ + public static String toString(Object object, ToStringStyle style, boolean outputTransients) { + return toString(object, style, outputTransients, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include transient fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * @since 2.1 + */ + public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics) { + return toString(object, style, outputTransients, outputStatics, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as + * java.lang.Object. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param + * the type of the object + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * @since 2.1 + */ + public static String toString( + T object, ToStringStyle style, boolean outputTransients, + boolean outputStatics, Class reflectUpToClass) { + return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics) + .toString(); + } + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude. Null excludes nothing. + * @return The toString value. + */ + public static String toStringExclude(Object object, Collection excludeFieldNames) { + return toStringExclude(object, toNoNullStringArray(excludeFieldNames)); + } + + /** + * Converts the given Collection into an array of Strings. The returned array does not contain null + * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element + * is null. + * + * @param collection + * The collection to convert + * @return A new array of Strings. + */ + static String[] toNoNullStringArray(Collection collection) { + if (collection == null) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + return toNoNullStringArray(collection.toArray()); + } + + /** + * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists + * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} + * if an array element is null. + * + * @param array + * The array to check + * @return The given array or a new array without null. + */ + static String[] toNoNullStringArray(Object[] array) { + List list = new ArrayList(array.length); + for (Object e : array) { + if (e != null) { + list.add(e.toString()); + } + } + return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY); + } + + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude + * @return The toString value. + */ + public static String toStringExclude(Object object, String... excludeFieldNames) { + return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString(); + } + + /** + * Whether or not to append static fields. + */ + private boolean appendStatics = false; + + /** + * Whether or not to append transient fields. + */ + private boolean appendTransients = false; + + /** + * Which field names to exclude from output. Intended for fields like "password". + * + * @since 3.0 this is protected instead of private + */ + protected String[] excludeFieldNames; + + /** + * The last super class to stop appending fields for. + */ + private Class upToClass = null; + + /** + *

+ * Constructor. + *

+ * + *

+ * This constructor outputs using the default style set with setDefaultStyle. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(Object object) { + super(object); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @param style + * the style of the toString to create, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(Object object, ToStringStyle style) { + super(object, style); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + *

+ * If the buffer is null, a new one is created. + *

+ * + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) { + super(object, style, buffer); + } + + /** + * Constructor. + * + * @param + * the type of the object + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @since 2.1 + */ + public ReflectionToStringBuilder( + T object, ToStringStyle style, StringBuffer buffer, + Class reflectUpToClass, boolean outputTransients, boolean outputStatics) { + super(object, style, buffer); + this.setUpToClass(reflectUpToClass); + this.setAppendTransients(outputTransients); + this.setAppendStatics(outputStatics); + } + + /** + * Returns whether or not to append the given Field. + *
    + *
  • Transient fields are appended only if {@link #isAppendTransients()} returns true. + *
  • Static fields are appended only if {@link #isAppendStatics()} returns true. + *
  • Inner class fields are not appened.
  • + *
+ * + * @param field + * The Field to test. + * @return Whether or not to append the given Field. + */ + protected boolean accept(Field field) { + if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) { + // Reject field from inner class. + return false; + } + if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) { + // Reject transient fields. + return false; + } + if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) { + // Reject static fields. + return false; + } + if (this.excludeFieldNames != null + && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) { + // Reject fields from the getExcludeFieldNames list. + return false; + } + return true; + } + + /** + *

+ * Appends the fields and values defined by the given object of the given Class. + *

+ * + *

+ * If a cycle is detected as an object is "toString()'ed", such an object is rendered as if + * Object.toString() had been called and not implemented by the object. + *

+ * + * @param clazz + * The class of object parameter + */ + protected void appendFieldsIn(Class clazz) { + if (clazz.isArray()) { + this.reflectionAppendArray(this.getObject()); + return; + } + Field[] fields = clazz.getDeclaredFields(); + AccessibleObject.setAccessible(fields, true); + for (Field field : fields) { + String fieldName = field.getName(); + if (this.accept(field)) { + try { + // Warning: Field.get(Object) creates wrappers objects + // for primitive types. + Object fieldValue = this.getValue(field); + this.append(fieldName, fieldValue); + } catch (IllegalAccessException ex) { + //this can't happen. Would get a Security exception + // instead + //throw a runtime exception in case the impossible + // happens. + throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage()); + } + } + } + } + + /** + * @return Returns the excludeFieldNames. + */ + public String[] getExcludeFieldNames() { + return this.excludeFieldNames.clone(); + } + + /** + *

+ * Gets the last super class to stop appending fields for. + *

+ * + * @return The last super class to stop appending fields for. + */ + public Class getUpToClass() { + return this.upToClass; + } + + /** + *

+ * Calls java.lang.reflect.Field.get(Object). + *

+ * + * @param field + * The Field to query. + * @return The Object from the given Field. + * + * @throws IllegalArgumentException + * see {@link java.lang.reflect.Field#get(Object)} + * @throws IllegalAccessException + * see {@link java.lang.reflect.Field#get(Object)} + * + * @see java.lang.reflect.Field#get(Object) + */ + protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException { + return field.get(this.getObject()); + } + + /** + *

+ * Gets whether or not to append static fields. + *

+ * + * @return Whether or not to append static fields. + * @since 2.1 + */ + public boolean isAppendStatics() { + return this.appendStatics; + } + + /** + *

+ * Gets whether or not to append transient fields. + *

+ * + * @return Whether or not to append transient fields. + */ + public boolean isAppendTransients() { + return this.appendTransients; + } + + /** + *

+ * Append to the toString an Object array. + *

+ * + * @param array + * the array to add to the toString + * @return this + */ + public ReflectionToStringBuilder reflectionAppendArray(Object array) { + this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array); + return this; + } + + /** + *

+ * Sets whether or not to append static fields. + *

+ * + * @param appendStatics + * Whether or not to append static fields. + * @since 2.1 + */ + public void setAppendStatics(boolean appendStatics) { + this.appendStatics = appendStatics; + } + + /** + *

+ * Sets whether or not to append transient fields. + *

+ * + * @param appendTransients + * Whether or not to append transient fields. + */ + public void setAppendTransients(boolean appendTransients) { + this.appendTransients = appendTransients; + } + + /** + * Sets the field names to exclude. + * + * @param excludeFieldNamesParam + * The excludeFieldNames to excluding from toString or null. + * @return this + */ + public ReflectionToStringBuilder setExcludeFieldNames(String... excludeFieldNamesParam) { + if (excludeFieldNamesParam == null) { + this.excludeFieldNames = null; + } else { + //clone and remove nulls + this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam); + Arrays.sort(this.excludeFieldNames); + } + return this; + } + + /** + *

+ * Sets the last super class to stop appending fields for. + *

+ * + * @param clazz + * The last super class to stop appending fields for. + */ + public void setUpToClass(Class clazz) { + if (clazz != null) { + Object object = getObject(); + if (object != null && clazz.isInstance(object) == false) { + throw new IllegalArgumentException("Specified class is not a superclass of the object"); + } + } + this.upToClass = clazz; + } + + /** + *

+ * Gets the String built by this builder. + *

+ * + * @return the built string + */ + @Override + public String toString() { + if (this.getObject() == null) { + return this.getStyle().getNullText(); + } + Class clazz = this.getObject().getClass(); + this.appendFieldsIn(clazz); + while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) { + clazz = clazz.getSuperclass(); + this.appendFieldsIn(clazz); + } + return super.toString(); + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ToStringBuilder.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ToStringBuilder.java new file mode 100644 index 00000000..1cb42b5d --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ToStringBuilder.java @@ -0,0 +1,1079 @@ +/* + * 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; + +import external.org.apache.commons.lang3.ObjectUtils; + +/** + *

Assists in implementing {@link Object#toString()} methods.

+ * + *

This class enables a good and consistent toString() to be built for any + * class or object. This class aims to simplify the process by:

+ *
    + *
  • allowing field names
  • + *
  • handling all types consistently
  • + *
  • handling nulls consistently
  • + *
  • outputting arrays and multi-dimensional arrays
  • + *
  • enabling the detail level to be controlled for Objects and Collections
  • + *
  • handling class hierarchies
  • + *
+ * + *

To use this class write code as follows:

+ * + *
+ * public class Person {
+ *   String name;
+ *   int age;
+ *   boolean smoker;
+ *
+ *   ...
+ *
+ *   public String toString() {
+ *     return new ToStringBuilder(this).
+ *       append("name", name).
+ *       append("age", age).
+ *       append("smoker", smoker).
+ *       toString();
+ *   }
+ * }
+ * 
+ * + *

This will produce a toString of the format: + * Person@7f54[name=Stephen,age=29,smoker=false]

+ * + *

To add the superclass toString, use {@link #appendSuper}. + * To append the toString from an object that is delegated + * to (or any other object), use {@link #appendToString}.

+ * + *

Alternatively, there is a method that uses reflection to determine + * the fields to test. Because these fields are usually private, the method, + * reflectionToString, uses AccessibleObject.setAccessible to + * change the visibility of the fields. This will fail under a security manager, + * unless the appropriate permissions are set up correctly. It is also + * slower than testing explicitly.

+ * + *

A typical invocation for this method would look like:

+ * + *
+ * public String toString() {
+ *   return ToStringBuilder.reflectionToString(this);
+ * }
+ * 
+ * + *

You can also use the builder to debug 3rd party objects:

+ * + *
+ * System.out.println("An object: " + ToStringBuilder.reflectionToString(anObject));
+ * 
+ * + *

The exact format of the toString is determined by + * the {@link ToStringStyle} passed into the constructor.

+ * + * @since 1.0 + * @version $Id: ToStringBuilder.java 1088899 2011-04-05 05:31:27Z bayard $ + */ +public class ToStringBuilder implements Builder { + + /** + * The default style of output to use, not null. + */ + private static volatile ToStringStyle defaultStyle = ToStringStyle.DEFAULT_STYLE; + + //---------------------------------------------------------------------------- + + /** + *

Gets the default ToStringStyle to use.

+ * + *

This method gets a singleton default value, typically for the whole JVM. + * Changing this default should generally only be done during application startup. + * It is recommended to pass a ToStringStyle to the constructor instead + * of using this global default.

+ * + *

This method can be used from multiple threads. + * Internally, a volatile variable is used to provide the guarantee + * that the latest value set using {@link #setDefaultStyle} is the value returned. + * It is strongly recommended that the default style is only changed during application startup.

+ * + *

One reason for changing the default could be to have a verbose style during + * development and a compact style in production.

+ * + * @return the default ToStringStyle, never null + */ + public static ToStringStyle getDefaultStyle() { + return defaultStyle; + } + + /** + *

Sets the default ToStringStyle to use.

+ * + *

This method sets a singleton default value, typically for the whole JVM. + * Changing this default should generally only be done during application startup. + * It is recommended to pass a ToStringStyle to the constructor instead + * of changing this global default.

+ * + *

This method is not intended for use from multiple threads. + * Internally, a volatile variable is used to provide the guarantee + * that the latest value set is the value returned from {@link #getDefaultStyle}.

+ * + * @param style the default ToStringStyle + * @throws IllegalArgumentException if the style is null + */ + public static void setDefaultStyle(ToStringStyle style) { + if (style == null) { + throw new IllegalArgumentException("The style must not be null"); + } + defaultStyle = style; + } + + //---------------------------------------------------------------------------- + /** + *

Uses ReflectionToStringBuilder to generate a + * toString for the specified object.

+ * + * @param object the Object to be output + * @return the String result + * @see ReflectionToStringBuilder#toString(Object) + */ + public static String reflectionToString(Object object) { + return ReflectionToStringBuilder.toString(object); + } + + /** + *

Uses ReflectionToStringBuilder to generate a + * toString for the specified object.

+ * + * @param object the Object to be output + * @param style the style of the toString to create, may be null + * @return the String result + * @see ReflectionToStringBuilder#toString(Object,ToStringStyle) + */ + public static String reflectionToString(Object object, ToStringStyle style) { + return ReflectionToStringBuilder.toString(object, style); + } + + /** + *

Uses ReflectionToStringBuilder to generate a + * toString for the specified object.

+ * + * @param object the Object to be output + * @param style the style of the toString to create, may be null + * @param outputTransients whether to include transient fields + * @return the String result + * @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean) + */ + public static String reflectionToString(Object object, ToStringStyle style, boolean outputTransients) { + return ReflectionToStringBuilder.toString(object, style, outputTransients, false, null); + } + + /** + *

Uses ReflectionToStringBuilder to generate a + * toString for the specified object.

+ * + * @param the type of the object + * @param object the Object to be output + * @param style the style of the toString to create, may be null + * @param outputTransients whether to include transient fields + * @param reflectUpToClass the superclass to reflect up to (inclusive), may be null + * @return the String result + * @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean,boolean,Class) + * @since 2.0 + */ + public static String reflectionToString( + T object, + ToStringStyle style, + boolean outputTransients, + Class reflectUpToClass) { + return ReflectionToStringBuilder.toString(object, style, outputTransients, false, reflectUpToClass); + } + + //---------------------------------------------------------------------------- + + /** + * Current toString buffer, not null. + */ + private final StringBuffer buffer; + /** + * The object being output, may be null. + */ + private final Object object; + /** + * The style of output to use, not null. + */ + private final ToStringStyle style; + + /** + *

Constructs a builder for the specified object using the default output style.

+ * + *

This default style is obtained from {@link #getDefaultStyle()}.

+ * + * @param object the Object to build a toString for, not recommended to be null + */ + public ToStringBuilder(Object object) { + this(object, null, null); + } + + /** + *

Constructs a builder for the specified object using the a defined output style.

+ * + *

If the style is null, the default style is used.

+ * + * @param object the Object to build a toString for, not recommended to be null + * @param style the style of the toString to create, null uses the default style + */ + public ToStringBuilder(Object object, ToStringStyle style) { + this(object, style, null); + } + + /** + *

Constructs a builder for the specified object.

+ * + *

If the style is null, the default style is used.

+ * + *

If the buffer is null, a new one is created.

+ * + * @param object the Object to build a toString for, not recommended to be null + * @param style the style of the toString to create, null uses the default style + * @param buffer the StringBuffer to populate, may be null + */ + public ToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) { + if (style == null) { + style = getDefaultStyle(); + } + if (buffer == null) { + buffer = new StringBuffer(512); + } + this.buffer = buffer; + this.style = style; + this.object = object; + + style.appendStart(buffer, object); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a boolean + * value.

+ * + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(boolean value) { + style.append(buffer, null, value); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a boolean + * array.

+ * + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(boolean[] array) { + style.append(buffer, null, array, null); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a byte + * value.

+ * + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(byte value) { + style.append(buffer, null, value); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a byte + * array.

+ * + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(byte[] array) { + style.append(buffer, null, array, null); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a char + * value.

+ * + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(char value) { + style.append(buffer, null, value); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a char + * array.

+ * + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(char[] array) { + style.append(buffer, null, array, null); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a double + * value.

+ * + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(double value) { + style.append(buffer, null, value); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a double + * array.

+ * + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(double[] array) { + style.append(buffer, null, array, null); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a float + * value.

+ * + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(float value) { + style.append(buffer, null, value); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a float + * array.

+ * + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(float[] array) { + style.append(buffer, null, array, null); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString an int + * value.

+ * + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(int value) { + style.append(buffer, null, value); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString an int + * array.

+ * + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(int[] array) { + style.append(buffer, null, array, null); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a long + * value.

+ * + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(long value) { + style.append(buffer, null, value); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a long + * array.

+ * + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(long[] array) { + style.append(buffer, null, array, null); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString an Object + * value.

+ * + * @param obj the value to add to the toString + * @return this + */ + public ToStringBuilder append(Object obj) { + style.append(buffer, null, obj, null); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString an Object + * array.

+ * + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(Object[] array) { + style.append(buffer, null, array, null); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a short + * value.

+ * + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(short value) { + style.append(buffer, null, value); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a short + * array.

+ * + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(short[] array) { + style.append(buffer, null, array, null); + return this; + } + + /** + *

Append to the toString a boolean + * value.

+ * + * @param fieldName the field name + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, boolean value) { + style.append(buffer, fieldName, value); + return this; + } + + /** + *

Append to the toString a boolean + * array.

+ * + * @param fieldName the field name + * @param array the array to add to the hashCode + * @return this + */ + public ToStringBuilder append(String fieldName, boolean[] array) { + style.append(buffer, fieldName, array, null); + return this; + } + + /** + *

Append to the toString a boolean + * array.

+ * + *

A boolean parameter controls the level of detail to show. + * Setting true will output the array in full. Setting + * false will output a summary, typically the size of + * the array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info + * @return this + */ + public ToStringBuilder append(String fieldName, boolean[] array, boolean fullDetail) { + style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail)); + return this; + } + + /** + *

Append to the toString an byte + * value.

+ * + * @param fieldName the field name + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, byte value) { + style.append(buffer, fieldName, value); + return this; + } + + /** + *

Append to the toString a byte array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, byte[] array) { + style.append(buffer, fieldName, array, null); + return this; + } + + /** + *

Append to the toString a byte + * array.

+ * + *

A boolean parameter controls the level of detail to show. + * Setting true will output the array in full. Setting + * false will output a summary, typically the size of + * the array. + * + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info + * @return this + */ + public ToStringBuilder append(String fieldName, byte[] array, boolean fullDetail) { + style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail)); + return this; + } + + /** + *

Append to the toString a char + * value.

+ * + * @param fieldName the field name + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, char value) { + style.append(buffer, fieldName, value); + return this; + } + + /** + *

Append to the toString a char + * array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, char[] array) { + style.append(buffer, fieldName, array, null); + return this; + } + + /** + *

Append to the toString a char + * array.

+ * + *

A boolean parameter controls the level of detail to show. + * Setting true will output the array in full. Setting + * false will output a summary, typically the size of + * the array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info + * @return this + */ + public ToStringBuilder append(String fieldName, char[] array, boolean fullDetail) { + style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail)); + return this; + } + + /** + *

Append to the toString a double + * value.

+ * + * @param fieldName the field name + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, double value) { + style.append(buffer, fieldName, value); + return this; + } + + /** + *

Append to the toString a double + * array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, double[] array) { + style.append(buffer, fieldName, array, null); + return this; + } + + /** + *

Append to the toString a double + * array.

+ * + *

A boolean parameter controls the level of detail to show. + * Setting true will output the array in full. Setting + * false will output a summary, typically the size of + * the array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info + * @return this + */ + public ToStringBuilder append(String fieldName, double[] array, boolean fullDetail) { + style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail)); + return this; + } + + /** + *

Append to the toString an float + * value.

+ * + * @param fieldName the field name + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, float value) { + style.append(buffer, fieldName, value); + return this; + } + + /** + *

Append to the toString a float + * array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, float[] array) { + style.append(buffer, fieldName, array, null); + return this; + } + + /** + *

Append to the toString a float + * array.

+ * + *

A boolean parameter controls the level of detail to show. + * Setting true will output the array in full. Setting + * false will output a summary, typically the size of + * the array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info + * @return this + */ + public ToStringBuilder append(String fieldName, float[] array, boolean fullDetail) { + style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail)); + return this; + } + + /** + *

Append to the toString an int + * value.

+ * + * @param fieldName the field name + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, int value) { + style.append(buffer, fieldName, value); + return this; + } + + /** + *

Append to the toString an int + * array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, int[] array) { + style.append(buffer, fieldName, array, null); + return this; + } + + /** + *

Append to the toString an int + * array.

+ * + *

A boolean parameter controls the level of detail to show. + * Setting true will output the array in full. Setting + * false will output a summary, typically the size of + * the array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info + * @return this + */ + public ToStringBuilder append(String fieldName, int[] array, boolean fullDetail) { + style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail)); + return this; + } + + /** + *

Append to the toString a long + * value.

+ * + * @param fieldName the field name + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, long value) { + style.append(buffer, fieldName, value); + return this; + } + + /** + *

Append to the toString a long + * array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, long[] array) { + style.append(buffer, fieldName, array, null); + return this; + } + + /** + *

Append to the toString a long + * array.

+ * + *

A boolean parameter controls the level of detail to show. + * Setting true will output the array in full. Setting + * false will output a summary, typically the size of + * the array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info + * @return this + */ + public ToStringBuilder append(String fieldName, long[] array, boolean fullDetail) { + style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail)); + return this; + } + + /** + *

Append to the toString an Object + * value.

+ * + * @param fieldName the field name + * @param obj the value to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, Object obj) { + style.append(buffer, fieldName, obj, null); + return this; + } + + /** + *

Append to the toString an Object + * value.

+ * + * @param fieldName the field name + * @param obj the value to add to the toString + * @param fullDetail true for detail, + * false for summary info + * @return this + */ + public ToStringBuilder append(String fieldName, Object obj, boolean fullDetail) { + style.append(buffer, fieldName, obj, Boolean.valueOf(fullDetail)); + return this; + } + + /** + *

Append to the toString an Object + * array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, Object[] array) { + style.append(buffer, fieldName, array, null); + return this; + } + + /** + *

Append to the toString an Object + * array.

+ * + *

A boolean parameter controls the level of detail to show. + * Setting true will output the array in full. Setting + * false will output a summary, typically the size of + * the array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info + * @return this + */ + public ToStringBuilder append(String fieldName, Object[] array, boolean fullDetail) { + style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail)); + return this; + } + + /** + *

Append to the toString an short + * value.

+ * + * @param fieldName the field name + * @param value the value to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, short value) { + style.append(buffer, fieldName, value); + return this; + } + + /** + *

Append to the toString a short + * array.

+ * + * @param fieldName the field name + * @param array the array to add to the toString + * @return this + */ + public ToStringBuilder append(String fieldName, short[] array) { + style.append(buffer, fieldName, array, null); + return this; + } + + /** + *

Append to the toString a short + * array.

+ * + *

A boolean parameter controls the level of detail to show. + * Setting true will output the array in full. Setting + * false will output a summary, typically the size of + * the array. + * + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info + * @return this + */ + public ToStringBuilder append(String fieldName, short[] array, boolean fullDetail) { + style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail)); + return this; + } + + /** + *

Appends with the same format as the default Object toString() + * method. Appends the class name followed by + * {@link System#identityHashCode(java.lang.Object)}.

+ * + * @param object the Object whose class name and id to output + * @return this + * @since 2.0 + */ + public ToStringBuilder appendAsObjectToString(Object object) { + ObjectUtils.identityToString(this.getStringBuffer(), object); + return this; + } + + //---------------------------------------------------------------------------- + + /** + *

Append the toString from the superclass.

+ * + *

This method assumes that the superclass uses the same ToStringStyle + * as this one.

+ * + *

If superToString is null, no change is made.

+ * + * @param superToString the result of super.toString() + * @return this + * @since 2.0 + */ + public ToStringBuilder appendSuper(String superToString) { + if (superToString != null) { + style.appendSuper(buffer, superToString); + } + return this; + } + + /** + *

Append the toString from another object.

+ * + *

This method is useful where a class delegates most of the implementation of + * its properties to another class. You can then call toString() on + * the other class and pass the result into this method.

+ * + *
+     *   private AnotherObject delegate;
+     *   private String fieldInThisClass;
+     *
+     *   public String toString() {
+     *     return new ToStringBuilder(this).
+     *       appendToString(delegate.toString()).
+     *       append(fieldInThisClass).
+     *       toString();
+     *   }
+ * + *

This method assumes that the other object uses the same ToStringStyle + * as this one.

+ * + *

If the toString is null, no change is made.

+ * + * @param toString the result of toString() on another object + * @return this + * @since 2.0 + */ + public ToStringBuilder appendToString(String toString) { + if (toString != null) { + style.appendToString(buffer, toString); + } + return this; + } + + /** + *

Returns the Object being output.

+ * + * @return The object being output. + * @since 2.0 + */ + public Object getObject() { + return object; + } + + /** + *

Gets the StringBuffer being populated.

+ * + * @return the StringBuffer being populated + */ + public StringBuffer getStringBuffer() { + return buffer; + } + + //---------------------------------------------------------------------------- + + /** + *

Gets the ToStringStyle being used.

+ * + * @return the ToStringStyle being used + * @since 2.0 + */ + public ToStringStyle getStyle() { + return style; + } + + /** + *

Returns the built toString.

+ * + *

This method appends the end of data indicator, and can only be called once. + * Use {@link #getStringBuffer} to get the current string state.

+ * + *

If the object is null, return the style's nullText

+ * + * @return the String toString + */ + @Override + public String toString() { + if (this.getObject() == null) { + this.getStringBuffer().append(this.getStyle().getNullText()); + } else { + style.appendEnd(this.getStringBuffer(), this.getObject()); + } + return this.getStringBuffer().toString(); + } + + /** + * Returns the String that was build as an object representation. The + * default implementation utilizes the {@link #toString()} implementation. + * + * @return the String toString + * + * @see #toString() + * + * @since 3.0 + */ + public String build() { + return toString(); + } +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ToStringStyle.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ToStringStyle.java new file mode 100644 index 00000000..783ae6f6 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/ToStringStyle.java @@ -0,0 +1,2271 @@ +/* + * 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; + +import java.io.Serializable; +import java.lang.reflect.Array; +import java.util.Collection; +import java.util.Map; +import java.util.WeakHashMap; + +import external.org.apache.commons.lang3.ClassUtils; +import external.org.apache.commons.lang3.ObjectUtils; +import external.org.apache.commons.lang3.SystemUtils; + +/** + *

Controls String formatting for {@link ToStringBuilder}. + * The main public interface is always via ToStringBuilder.

+ * + *

These classes are intended to be used as Singletons. + * There is no need to instantiate a new style each time. A program + * will generally use one of the predefined constants on this class. + * Alternatively, the {@link StandardToStringStyle} class can be used + * to set the individual settings. Thus most styles can be achieved + * without subclassing.

+ * + *

If required, a subclass can override as many or as few of the + * methods as it requires. Each object type (from boolean + * to long to Object to int[]) has + * its own methods to output it. Most have two versions, detail and summary. + * + *

For example, the detail version of the array based methods will + * output the whole array, whereas the summary method will just output + * the array length.

+ * + *

If you want to format the output of certain objects, such as dates, you + * must create a subclass and override a method. + *

+ * public class MyStyle extends ToStringStyle {
+ *   protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
+ *     if (value instanceof Date) {
+ *       value = new SimpleDateFormat("yyyy-MM-dd").format(value);
+ *     }
+ *     buffer.append(value);
+ *   }
+ * }
+ * 
+ *

+ * + * @since 1.0 + * @version $Id: ToStringStyle.java 1091066 2011-04-11 13:30:11Z mbenson $ + */ +public abstract class ToStringStyle implements Serializable { + + /** + * Serialization version ID. + */ + private static final long serialVersionUID = -2587890625525655916L; + + /** + * The default toString style. Using the Using the Person + * example from {@link ToStringBuilder}, the output would look like this: + * + *
+     * Person@182f0db[name=John Doe,age=33,smoker=false]
+     * 
+ */ + public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle(); + + /** + * The multi line toString style. Using the Using the Person + * example from {@link ToStringBuilder}, the output would look like this: + * + *
+     * Person@182f0db[
+     *   name=John Doe
+     *   age=33
+     *   smoker=false
+     * ]
+     * 
+ */ + public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle(); + + /** + * The no field names toString style. Using the Using the + * Person example from {@link ToStringBuilder}, the output + * would look like this: + * + *
+     * Person@182f0db[John Doe,33,false]
+     * 
+ */ + public static final ToStringStyle NO_FIELD_NAMES_STYLE = new NoFieldNameToStringStyle(); + + /** + * The short prefix toString style. Using the Person example + * from {@link ToStringBuilder}, the output would look like this: + * + *
+     * Person[name=John Doe,age=33,smoker=false]
+     * 
+ * + * @since 2.1 + */ + public static final ToStringStyle SHORT_PREFIX_STYLE = new ShortPrefixToStringStyle(); + + /** + * The simple toString style. Using the Using the Person + * example from {@link ToStringBuilder}, the output would look like this: + * + *
+     * John Doe,33,false
+     * 
+ */ + public static final ToStringStyle SIMPLE_STYLE = new SimpleToStringStyle(); + + /** + *

+ * A registry of objects used by reflectionToString methods + * to detect cyclical object references and avoid infinite loops. + *

+ */ + private static final ThreadLocal> REGISTRY = + new ThreadLocal>(); + + /** + *

+ * Returns the registry of objects being traversed by the reflectionToString + * methods in the current thread. + *

+ * + * @return Set the registry of objects being traversed + */ + static Map getRegistry() { + return REGISTRY.get(); + } + + /** + *

+ * Returns true if the registry contains the given object. + * Used by the reflection methods to avoid infinite loops. + *

+ * + * @param value + * The object to lookup in the registry. + * @return boolean true if the registry contains the given + * object. + */ + static boolean isRegistered(Object value) { + Map m = getRegistry(); + return m != null && m.containsKey(value); + } + + /** + *

+ * Registers the given object. Used by the reflection methods to avoid + * infinite loops. + *

+ * + * @param value + * The object to register. + */ + static void register(Object value) { + if (value != null) { + Map m = getRegistry(); + if (m == null) { + REGISTRY.set(new WeakHashMap()); + } + getRegistry().put(value, null); + } + } + + /** + *

+ * Unregisters the given object. + *

+ * + *

+ * Used by the reflection methods to avoid infinite loops. + *

+ * + * @param value + * The object to unregister. + */ + static void unregister(Object value) { + if (value != null) { + Map m = getRegistry(); + if (m != null) { + m.remove(value); + if (m.isEmpty()) { + REGISTRY.remove(); + } + } + } + } + + /** + * Whether to use the field names, the default is true. + */ + private boolean useFieldNames = true; + + /** + * Whether to use the class name, the default is true. + */ + private boolean useClassName = true; + + /** + * Whether to use short class names, the default is false. + */ + private boolean useShortClassName = false; + + /** + * Whether to use the identity hash code, the default is true. + */ + private boolean useIdentityHashCode = true; + + /** + * The content start '['. + */ + private String contentStart = "["; + + /** + * The content end ']'. + */ + private String contentEnd = "]"; + + /** + * The field name value separator '='. + */ + private String fieldNameValueSeparator = "="; + + /** + * Whether the field separator should be added before any other fields. + */ + private boolean fieldSeparatorAtStart = false; + + /** + * Whether the field separator should be added after any other fields. + */ + private boolean fieldSeparatorAtEnd = false; + + /** + * The field separator ','. + */ + private String fieldSeparator = ","; + + /** + * The array start '{'. + */ + private String arrayStart = "{"; + + /** + * The array separator ','. + */ + private String arraySeparator = ","; + + /** + * The detail for array content. + */ + private boolean arrayContentDetail = true; + + /** + * The array end '}'. + */ + private String arrayEnd = "}"; + + /** + * The value to use when fullDetail is null, + * the default value is true. + */ + private boolean defaultFullDetail = true; + + /** + * The null text '<null>'. + */ + private String nullText = ""; + + /** + * The summary size text start '. + */ + private String sizeStartText = "'>'. + */ + private String sizeEndText = ">"; + + /** + * The summary object text start '<'. + */ + private String summaryObjectStartText = "<"; + + /** + * The summary object text start '>'. + */ + private String summaryObjectEndText = ">"; + + //---------------------------------------------------------------------------- + + /** + *

Constructor.

+ */ + protected ToStringStyle() { + super(); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString the superclass toString.

+ *

NOTE: It assumes that the toString has been created from the same ToStringStyle.

+ * + *

A null superToString is ignored.

+ * + * @param buffer the StringBuffer to populate + * @param superToString the super.toString() + * @since 2.0 + */ + public void appendSuper(StringBuffer buffer, String superToString) { + appendToString(buffer, superToString); + } + + /** + *

Append to the toString another toString.

+ *

NOTE: It assumes that the toString has been created from the same ToStringStyle.

+ * + *

A null toString is ignored.

+ * + * @param buffer the StringBuffer to populate + * @param toString the additional toString + * @since 2.0 + */ + public void appendToString(StringBuffer buffer, String toString) { + if (toString != null) { + int pos1 = toString.indexOf(contentStart) + contentStart.length(); + int pos2 = toString.lastIndexOf(contentEnd); + if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) { + String data = toString.substring(pos1, pos2); + if (fieldSeparatorAtStart) { + removeLastFieldSeparator(buffer); + } + buffer.append(data); + appendFieldSeparator(buffer); + } + } + } + + /** + *

Append to the toString the start of data indicator.

+ * + * @param buffer the StringBuffer to populate + * @param object the Object to build a toString for + */ + public void appendStart(StringBuffer buffer, Object object) { + if (object != null) { + appendClassName(buffer, object); + appendIdentityHashCode(buffer, object); + appendContentStart(buffer); + if (fieldSeparatorAtStart) { + appendFieldSeparator(buffer); + } + } + } + + /** + *

Append to the toString the end of data indicator.

+ * + * @param buffer the StringBuffer to populate + * @param object the Object to build a + * toString for. + */ + public void appendEnd(StringBuffer buffer, Object object) { + if (this.fieldSeparatorAtEnd == false) { + removeLastFieldSeparator(buffer); + } + appendContentEnd(buffer); + unregister(object); + } + + /** + *

Remove the last field separator from the buffer.

+ * + * @param buffer the StringBuffer to populate + * @since 2.0 + */ + protected void removeLastFieldSeparator(StringBuffer buffer) { + int len = buffer.length(); + int sepLen = fieldSeparator.length(); + if (len > 0 && sepLen > 0 && len >= sepLen) { + boolean match = true; + for (int i = 0; i < sepLen; i++) { + if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) { + match = false; + break; + } + } + if (match) { + buffer.setLength(len - sepLen); + } + } + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString an Object + * value, printing the full toString of the + * Object passed in.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param value the value to add to the toString + * @param fullDetail true for detail, false + * for summary info, null for style decides + */ + public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (value == null) { + appendNullText(buffer, fieldName); + + } else { + appendInternal(buffer, fieldName, value, isFullDetail(fullDetail)); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString an Object, + * correctly interpreting its type.

+ * + *

This method performs the main lookup by Class type to correctly + * route arrays, Collections, Maps and + * Objects to the appropriate method.

+ * + *

Either detail or summary views can be specified.

+ * + *

If a cycle is detected, an object will be appended with the + * Object.toString() format.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString, + * not null + * @param detail output detail or not + */ + protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) { + if (isRegistered(value) + && !(value instanceof Number || value instanceof Boolean || value instanceof Character)) { + appendCyclicObject(buffer, fieldName, value); + return; + } + + register(value); + + try { + if (value instanceof Collection) { + if (detail) { + appendDetail(buffer, fieldName, (Collection) value); + } else { + appendSummarySize(buffer, fieldName, ((Collection) value).size()); + } + + } else if (value instanceof Map) { + if (detail) { + appendDetail(buffer, fieldName, (Map) value); + } else { + appendSummarySize(buffer, fieldName, ((Map) value).size()); + } + + } else if (value instanceof long[]) { + if (detail) { + appendDetail(buffer, fieldName, (long[]) value); + } else { + appendSummary(buffer, fieldName, (long[]) value); + } + + } else if (value instanceof int[]) { + if (detail) { + appendDetail(buffer, fieldName, (int[]) value); + } else { + appendSummary(buffer, fieldName, (int[]) value); + } + + } else if (value instanceof short[]) { + if (detail) { + appendDetail(buffer, fieldName, (short[]) value); + } else { + appendSummary(buffer, fieldName, (short[]) value); + } + + } else if (value instanceof byte[]) { + if (detail) { + appendDetail(buffer, fieldName, (byte[]) value); + } else { + appendSummary(buffer, fieldName, (byte[]) value); + } + + } else if (value instanceof char[]) { + if (detail) { + appendDetail(buffer, fieldName, (char[]) value); + } else { + appendSummary(buffer, fieldName, (char[]) value); + } + + } else if (value instanceof double[]) { + if (detail) { + appendDetail(buffer, fieldName, (double[]) value); + } else { + appendSummary(buffer, fieldName, (double[]) value); + } + + } else if (value instanceof float[]) { + if (detail) { + appendDetail(buffer, fieldName, (float[]) value); + } else { + appendSummary(buffer, fieldName, (float[]) value); + } + + } else if (value instanceof boolean[]) { + if (detail) { + appendDetail(buffer, fieldName, (boolean[]) value); + } else { + appendSummary(buffer, fieldName, (boolean[]) value); + } + + } else if (value.getClass().isArray()) { + if (detail) { + appendDetail(buffer, fieldName, (Object[]) value); + } else { + appendSummary(buffer, fieldName, (Object[]) value); + } + + } else { + if (detail) { + appendDetail(buffer, fieldName, value); + } else { + appendSummary(buffer, fieldName, value); + } + } + } finally { + unregister(value); + } + } + + /** + *

Append to the toString an Object + * value that has been detected to participate in a cycle. This + * implementation will print the standard string value of the value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString, + * not null + * + * @since 2.2 + */ + protected void appendCyclicObject(StringBuffer buffer, String fieldName, Object value) { + ObjectUtils.identityToString(buffer, value); + } + + /** + *

Append to the toString an Object + * value, printing the full detail of the Object.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { + buffer.append(value); + } + + /** + *

Append to the toString a Collection.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param coll the Collection to add to the + * toString, not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, Collection coll) { + buffer.append(coll); + } + + /** + *

Append to the toString a Map.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param map the Map to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, Map map) { + buffer.append(map); + } + + /** + *

Append to the toString an Object + * value, printing a summary of the Object.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString, + * not null + */ + protected void appendSummary(StringBuffer buffer, String fieldName, Object value) { + buffer.append(summaryObjectStartText); + buffer.append(getShortClassName(value.getClass())); + buffer.append(summaryObjectEndText); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a long + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param value the value to add to the toString + */ + public void append(StringBuffer buffer, String fieldName, long value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString a long + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString + */ + protected void appendDetail(StringBuffer buffer, String fieldName, long value) { + buffer.append(value); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString an int + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param value the value to add to the toString + */ + public void append(StringBuffer buffer, String fieldName, int value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString an int + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString + */ + protected void appendDetail(StringBuffer buffer, String fieldName, int value) { + buffer.append(value); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a short + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param value the value to add to the toString + */ + public void append(StringBuffer buffer, String fieldName, short value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString a short + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString + */ + protected void appendDetail(StringBuffer buffer, String fieldName, short value) { + buffer.append(value); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a byte + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param value the value to add to the toString + */ + public void append(StringBuffer buffer, String fieldName, byte value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString a byte + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString + */ + protected void appendDetail(StringBuffer buffer, String fieldName, byte value) { + buffer.append(value); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a char + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param value the value to add to the toString + */ + public void append(StringBuffer buffer, String fieldName, char value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString a char + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString + */ + protected void appendDetail(StringBuffer buffer, String fieldName, char value) { + buffer.append(value); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a double + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param value the value to add to the toString + */ + public void append(StringBuffer buffer, String fieldName, double value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString a double + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString + */ + protected void appendDetail(StringBuffer buffer, String fieldName, double value) { + buffer.append(value); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a float + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param value the value to add to the toString + */ + public void append(StringBuffer buffer, String fieldName, float value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString a float + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString + */ + protected void appendDetail(StringBuffer buffer, String fieldName, float value) { + buffer.append(value); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a boolean + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param value the value to add to the toString + */ + public void append(StringBuffer buffer, String fieldName, boolean value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString a boolean + * value.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the toString + */ + protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) { + buffer.append(value); + } + + /** + *

Append to the toString an Object + * array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info, null for style decides + */ + public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString the detail of an + * Object array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + Object item = array[i]; + if (i > 0) { + buffer.append(arraySeparator); + } + if (item == null) { + appendNullText(buffer, fieldName); + + } else { + appendInternal(buffer, fieldName, item, arrayContentDetail); + } + } + buffer.append(arrayEnd); + } + + /** + *

Append to the toString the detail of an array type.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + * @since 2.0 + */ + protected void reflectionAppendArrayDetail(StringBuffer buffer, String fieldName, Object array) { + buffer.append(arrayStart); + int length = Array.getLength(array); + for (int i = 0; i < length; i++) { + Object item = Array.get(array, i); + if (i > 0) { + buffer.append(arraySeparator); + } + if (item == null) { + appendNullText(buffer, fieldName); + + } else { + appendInternal(buffer, fieldName, item, arrayContentDetail); + } + } + buffer.append(arrayEnd); + } + + /** + *

Append to the toString a summary of an + * Object array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a long + * array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info, null for style decides + */ + public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString the detail of a + * long array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

Append to the toString a summary of a + * long array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString an int + * array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info, null for style decides + */ + public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString the detail of an + * int array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

Append to the toString a summary of an + * int array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a short + * array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info, null for style decides + */ + public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString the detail of a + * short array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

Append to the toString a summary of a + * short array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a byte + * array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info, null for style decides + */ + public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString the detail of a + * byte array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

Append to the toString a summary of a + * byte array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a char + * array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info, null for style decides + */ + public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString the detail of a + * char array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

Append to the toString a summary of a + * char array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a double + * array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info, null for style decides + */ + public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString the detail of a + * double array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

Append to the toString a summary of a + * double array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a float + * array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info, null for style decides + */ + public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString the detail of a + * float array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

Append to the toString a summary of a + * float array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString a boolean + * array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail true for detail, false + * for summary info, null for style decides + */ + public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

Append to the toString the detail of a + * boolean array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

Append to the toString a summary of a + * boolean array.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the toString, + * not null + */ + protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + //---------------------------------------------------------------------------- + + /** + *

Append to the toString the class name.

+ * + * @param buffer the StringBuffer to populate + * @param object the Object whose name to output + */ + protected void appendClassName(StringBuffer buffer, Object object) { + if (useClassName && object != null) { + register(object); + if (useShortClassName) { + buffer.append(getShortClassName(object.getClass())); + } else { + buffer.append(object.getClass().getName()); + } + } + } + + /** + *

Append the {@link System#identityHashCode(java.lang.Object)}.

+ * + * @param buffer the StringBuffer to populate + * @param object the Object whose id to output + */ + protected void appendIdentityHashCode(StringBuffer buffer, Object object) { + if (this.isUseIdentityHashCode() && object!=null) { + register(object); + buffer.append('@'); + buffer.append(Integer.toHexString(System.identityHashCode(object))); + } + } + + /** + *

Append to the toString the content start.

+ * + * @param buffer the StringBuffer to populate + */ + protected void appendContentStart(StringBuffer buffer) { + buffer.append(contentStart); + } + + /** + *

Append to the toString the content end.

+ * + * @param buffer the StringBuffer to populate + */ + protected void appendContentEnd(StringBuffer buffer) { + buffer.append(contentEnd); + } + + /** + *

Append to the toString an indicator for null.

+ * + *

The default indicator is '<null>'.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + */ + protected void appendNullText(StringBuffer buffer, String fieldName) { + buffer.append(nullText); + } + + /** + *

Append to the toString the field separator.

+ * + * @param buffer the StringBuffer to populate + */ + protected void appendFieldSeparator(StringBuffer buffer) { + buffer.append(fieldSeparator); + } + + /** + *

Append to the toString the field start.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name + */ + protected void appendFieldStart(StringBuffer buffer, String fieldName) { + if (useFieldNames && fieldName != null) { + buffer.append(fieldName); + buffer.append(fieldNameValueSeparator); + } + } + + /** + *

Append to the toString the field end.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + */ + protected void appendFieldEnd(StringBuffer buffer, String fieldName) { + appendFieldSeparator(buffer); + } + + /** + *

Append to the toString a size summary.

+ * + *

The size summary is used to summarize the contents of + * Collections, Maps and arrays.

+ * + *

The output consists of a prefix, the passed in size + * and a suffix.

+ * + *

The default format is '<size=n>'.

+ * + * @param buffer the StringBuffer to populate + * @param fieldName the field name, typically not used as already appended + * @param size the size to append + */ + protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) { + buffer.append(sizeStartText); + buffer.append(size); + buffer.append(sizeEndText); + } + + /** + *

Is this field to be output in full detail.

+ * + *

This method converts a detail request into a detail level. + * The calling code may request full detail (true), + * but a subclass might ignore that and always return + * false. The calling code may pass in + * null indicating that it doesn't care about + * the detail level. In this case the default detail level is + * used.

+ * + * @param fullDetailRequest the detail level requested + * @return whether full detail is to be shown + */ + protected boolean isFullDetail(Boolean fullDetailRequest) { + if (fullDetailRequest == null) { + return defaultFullDetail; + } + return fullDetailRequest.booleanValue(); + } + + /** + *

Gets the short class name for a class.

+ * + *

The short class name is the classname excluding + * the package name.

+ * + * @param cls the Class to get the short name of + * @return the short name + */ + protected String getShortClassName(Class cls) { + return ClassUtils.getShortClassName(cls); + } + + // Setters and getters for the customizable parts of the style + // These methods are not expected to be overridden, except to make public + // (They are not public so that immutable subclasses can be written) + //--------------------------------------------------------------------- + + /** + *

Gets whether to use the class name.

+ * + * @return the current useClassName flag + */ + protected boolean isUseClassName() { + return useClassName; + } + + /** + *

Sets whether to use the class name.

+ * + * @param useClassName the new useClassName flag + */ + protected void setUseClassName(boolean useClassName) { + this.useClassName = useClassName; + } + + //--------------------------------------------------------------------- + + /** + *

Gets whether to output short or long class names.

+ * + * @return the current useShortClassName flag + * @since 2.0 + */ + protected boolean isUseShortClassName() { + return useShortClassName; + } + + /** + *

Sets whether to output short or long class names.

+ * + * @param useShortClassName the new useShortClassName flag + * @since 2.0 + */ + protected void setUseShortClassName(boolean useShortClassName) { + this.useShortClassName = useShortClassName; + } + + //--------------------------------------------------------------------- + + /** + *

Gets whether to use the identity hash code.

+ * + * @return the current useIdentityHashCode flag + */ + protected boolean isUseIdentityHashCode() { + return useIdentityHashCode; + } + + /** + *

Sets whether to use the identity hash code.

+ * + * @param useIdentityHashCode the new useIdentityHashCode flag + */ + protected void setUseIdentityHashCode(boolean useIdentityHashCode) { + this.useIdentityHashCode = useIdentityHashCode; + } + + //--------------------------------------------------------------------- + + /** + *

Gets whether to use the field names passed in.

+ * + * @return the current useFieldNames flag + */ + protected boolean isUseFieldNames() { + return useFieldNames; + } + + /** + *

Sets whether to use the field names passed in.

+ * + * @param useFieldNames the new useFieldNames flag + */ + protected void setUseFieldNames(boolean useFieldNames) { + this.useFieldNames = useFieldNames; + } + + //--------------------------------------------------------------------- + + /** + *

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

+ * + * @return the current defaultFullDetail flag + */ + protected boolean isDefaultFullDetail() { + return defaultFullDetail; + } + + /** + *

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

+ * + * @param defaultFullDetail the new defaultFullDetail flag + */ + protected void setDefaultFullDetail(boolean defaultFullDetail) { + this.defaultFullDetail = defaultFullDetail; + } + + //--------------------------------------------------------------------- + + /** + *

Gets whether to output array content detail.

+ * + * @return the current array content detail setting + */ + protected boolean isArrayContentDetail() { + return arrayContentDetail; + } + + /** + *

Sets whether to output array content detail.

+ * + * @param arrayContentDetail the new arrayContentDetail flag + */ + protected void setArrayContentDetail(boolean arrayContentDetail) { + this.arrayContentDetail = arrayContentDetail; + } + + //--------------------------------------------------------------------- + + /** + *

Gets the array start text.

+ * + * @return the current array start text + */ + protected String getArrayStart() { + return arrayStart; + } + + /** + *

Sets the array start text.

+ * + *

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

+ * + * @param arrayStart the new array start text + */ + protected void setArrayStart(String arrayStart) { + if (arrayStart == null) { + arrayStart = ""; + } + this.arrayStart = arrayStart; + } + + //--------------------------------------------------------------------- + + /** + *

Gets the array end text.

+ * + * @return the current array end text + */ + protected String getArrayEnd() { + return arrayEnd; + } + + /** + *

Sets the array end text.

+ * + *

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

+ * + * @param arrayEnd the new array end text + */ + protected void setArrayEnd(String arrayEnd) { + if (arrayEnd == null) { + arrayEnd = ""; + } + this.arrayEnd = arrayEnd; + } + + //--------------------------------------------------------------------- + + /** + *

Gets the array separator text.

+ * + * @return the current array separator text + */ + protected String getArraySeparator() { + return arraySeparator; + } + + /** + *

Sets the array separator text.

+ * + *

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

+ * + * @param arraySeparator the new array separator text + */ + protected void setArraySeparator(String arraySeparator) { + if (arraySeparator == null) { + arraySeparator = ""; + } + this.arraySeparator = arraySeparator; + } + + //--------------------------------------------------------------------- + + /** + *

Gets the content start text.

+ * + * @return the current content start text + */ + protected String getContentStart() { + return contentStart; + } + + /** + *

Sets the content start text.

+ * + *

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

+ * + * @param contentStart the new content start text + */ + protected void setContentStart(String contentStart) { + if (contentStart == null) { + contentStart = ""; + } + this.contentStart = contentStart; + } + + //--------------------------------------------------------------------- + + /** + *

Gets the content end text.

+ * + * @return the current content end text + */ + protected String getContentEnd() { + return contentEnd; + } + + /** + *

Sets the content end text.

+ * + *

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

+ * + * @param contentEnd the new content end text + */ + protected void setContentEnd(String contentEnd) { + if (contentEnd == null) { + contentEnd = ""; + } + this.contentEnd = contentEnd; + } + + //--------------------------------------------------------------------- + + /** + *

Gets the field name value separator text.

+ * + * @return the current field name value separator text + */ + protected String getFieldNameValueSeparator() { + return fieldNameValueSeparator; + } + + /** + *

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 + */ + protected void setFieldNameValueSeparator(String fieldNameValueSeparator) { + if (fieldNameValueSeparator == null) { + fieldNameValueSeparator = ""; + } + this.fieldNameValueSeparator = fieldNameValueSeparator; + } + + //--------------------------------------------------------------------- + + /** + *

Gets the field separator text.

+ * + * @return the current field separator text + */ + protected String getFieldSeparator() { + return fieldSeparator; + } + + /** + *

Sets the field separator text.

+ * + *

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

+ * + * @param fieldSeparator the new field separator text + */ + protected void setFieldSeparator(String fieldSeparator) { + if (fieldSeparator == null) { + fieldSeparator = ""; + } + this.fieldSeparator = fieldSeparator; + } + + //--------------------------------------------------------------------- + + /** + *

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

+ * + * @return the fieldSeparatorAtStart flag + * @since 2.0 + */ + protected boolean isFieldSeparatorAtStart() { + return fieldSeparatorAtStart; + } + + /** + *

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

+ * + * @param fieldSeparatorAtStart the fieldSeparatorAtStart flag + * @since 2.0 + */ + protected void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) { + this.fieldSeparatorAtStart = fieldSeparatorAtStart; + } + + //--------------------------------------------------------------------- + + /** + *

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

+ * + * @return fieldSeparatorAtEnd flag + * @since 2.0 + */ + protected boolean isFieldSeparatorAtEnd() { + return fieldSeparatorAtEnd; + } + + /** + *

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

+ * + * @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag + * @since 2.0 + */ + protected void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) { + this.fieldSeparatorAtEnd = fieldSeparatorAtEnd; + } + + //--------------------------------------------------------------------- + + /** + *

Gets the text to output when null found.

+ * + * @return the current text to output when null found + */ + protected String getNullText() { + return nullText; + } + + /** + *

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 + */ + protected void setNullText(String nullText) { + if (nullText == null) { + nullText = ""; + } + this.nullText = nullText; + } + + //--------------------------------------------------------------------- + + /** + *

Gets the start 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 + */ + protected String getSizeStartText() { + return sizeStartText; + } + + /** + *

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 + */ + protected void setSizeStartText(String sizeStartText) { + if (sizeStartText == null) { + sizeStartText = ""; + } + this.sizeStartText = 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 + */ + protected String getSizeEndText() { + return sizeEndText; + } + + /** + *

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 + */ + protected void setSizeEndText(String sizeEndText) { + if (sizeEndText == null) { + sizeEndText = ""; + } + this.sizeEndText = 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 + */ + protected String getSummaryObjectStartText() { + return summaryObjectStartText; + } + + /** + *

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 + */ + protected void setSummaryObjectStartText(String summaryObjectStartText) { + if (summaryObjectStartText == null) { + summaryObjectStartText = ""; + } + this.summaryObjectStartText = 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 + */ + protected String getSummaryObjectEndText() { + return summaryObjectEndText; + } + + /** + *

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 + */ + protected void setSummaryObjectEndText(String summaryObjectEndText) { + if (summaryObjectEndText == null) { + summaryObjectEndText = ""; + } + this.summaryObjectEndText = summaryObjectEndText; + } + + //---------------------------------------------------------------------------- + + /** + *

Default ToStringStyle.

+ * + *

This is an inner class rather than using + * StandardToStringStyle to ensure its immutability.

+ */ + private static final class DefaultToStringStyle extends ToStringStyle { + + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + *

Constructor.

+ * + *

Use the static constant rather than instantiating.

+ */ + DefaultToStringStyle() { + super(); + } + + /** + *

Ensure Singleton after serialization.

+ * + * @return the singleton + */ + private Object readResolve() { + return ToStringStyle.DEFAULT_STYLE; + } + + } + + //---------------------------------------------------------------------------- + + /** + *

ToStringStyle that does not print out + * the field names.

+ * + *

This is an inner class rather than using + * StandardToStringStyle to ensure its immutability. + */ + private static final class NoFieldNameToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + /** + *

Constructor.

+ * + *

Use the static constant rather than instantiating.

+ */ + NoFieldNameToStringStyle() { + super(); + this.setUseFieldNames(false); + } + + /** + *

Ensure Singleton after serialization.

+ * + * @return the singleton + */ + private Object readResolve() { + return ToStringStyle.NO_FIELD_NAMES_STYLE; + } + + } + + //---------------------------------------------------------------------------- + + /** + *

ToStringStyle that prints out the short + * class name and no identity hashcode.

+ * + *

This is an inner class rather than using + * StandardToStringStyle to ensure its immutability.

+ */ + private static final class ShortPrefixToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + /** + *

Constructor.

+ * + *

Use the static constant rather than instantiating.

+ */ + ShortPrefixToStringStyle() { + super(); + this.setUseShortClassName(true); + this.setUseIdentityHashCode(false); + } + + /** + *

Ensure Singleton after serialization.

+ * @return the singleton + */ + private Object readResolve() { + return ToStringStyle.SHORT_PREFIX_STYLE; + } + + } + + /** + *

ToStringStyle that does not print out the + * classname, identity hashcode, content start or field name.

+ * + *

This is an inner class rather than using + * StandardToStringStyle to ensure its immutability.

+ */ + private static final class SimpleToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + /** + *

Constructor.

+ * + *

Use the static constant rather than instantiating.

+ */ + SimpleToStringStyle() { + super(); + this.setUseClassName(false); + this.setUseIdentityHashCode(false); + this.setUseFieldNames(false); + this.setContentStart(""); + this.setContentEnd(""); + } + + /** + *

Ensure Singleton after serialization.

+ * @return the singleton + */ + private Object readResolve() { + return ToStringStyle.SIMPLE_STYLE; + } + + } + + //---------------------------------------------------------------------------- + + /** + *

ToStringStyle that outputs on multiple lines.

+ * + *

This is an inner class rather than using + * StandardToStringStyle to ensure its immutability.

+ */ + private static final class MultiLineToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + /** + *

Constructor.

+ * + *

Use the static constant rather than instantiating.

+ */ + MultiLineToStringStyle() { + super(); + this.setContentStart("["); + this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + " "); + this.setFieldSeparatorAtStart(true); + this.setContentEnd(SystemUtils.LINE_SEPARATOR + "]"); + } + + /** + *

Ensure Singleton after serialization.

+ * + * @return the singleton + */ + private Object readResolve() { + return ToStringStyle.MULTI_LINE_STYLE; + } + + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/package.html b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/package.html new file mode 100644 index 00000000..dd40682d --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/builder/package.html @@ -0,0 +1,28 @@ + + + +Assists in creating consistent equals(Object), toString(), +hashCode(), and compareTo(Object) methods. +@see java.lang.Object#equals(Object) +@see java.lang.Object#toString() +@see java.lang.Object#hashCode() +@see java.lang.Comparable#compareTo(Object) +@since 1.0 +

These classes are not thread-safe.

+ + diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/exception/CloneFailedException.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/exception/CloneFailedException.java new file mode 100644 index 00000000..edd2d775 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/exception/CloneFailedException.java @@ -0,0 +1,62 @@ +/* + * 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; + +/** + * Exception thrown when a clone cannot be created. In contrast to + * {@link CloneNotSupportedException} this is a {@link RuntimeException}. + * + * @since 3.0 + */ +public class CloneFailedException extends RuntimeException { + // ~ Static fields/initializers --------------------------------------------- + + private static final long serialVersionUID = 20091223L; + + // ~ Constructors ----------------------------------------------------------- + + /** + * Constructs a CloneFailedException. + * + * @param message description of the exception + * @since upcoming + */ + public CloneFailedException(final String message) { + super(message); + } + + /** + * Constructs a CloneFailedException. + * + * @param cause cause of the exception + * @since upcoming + */ + public CloneFailedException(final Throwable cause) { + super(cause); + } + + /** + * Constructs a CloneFailedException. + * + * @param message description of the exception + * @param cause cause of the exception + * @since upcoming + */ + public CloneFailedException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/exception/package.html b/edxp-core/src/main/java/external/org/apache/commons/lang3/exception/package.html new file mode 100644 index 00000000..b9d94036 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/exception/package.html @@ -0,0 +1,27 @@ + + + +Provides functionality for Exceptions. +

Contains the concept of an exception with context i.e. such an exception +will contain a map with keys and values. This provides an easy way to pass valuable +state information at exception time in useful form to a calling process.

+

Lastly, {@link org.apache.commons.lang3.exception.ExceptionUtils} +also contains Throwable manipulation and examination routines.

+@since 1.0 + + diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/Mutable.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/Mutable.java new file mode 100644 index 00000000..aa733e50 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/Mutable.java @@ -0,0 +1,54 @@ +/* + * 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; + +/** + * Provides mutable access to a value. + *

+ * Mutable is used as a generic interface to the implementations in this package. + *

+ * A typical use case would be to enable a primitive or string to be passed to a method and allow that method to + * effectively change the value of the primitive/string. Another use case is to store a frequently changing primitive in + * a collection (for example a total in a map) without needing to create new Integer/Long wrapper objects. + * + * @since 2.1 + * @param the type to set and get + * @version $Id: Mutable.java 1153213 2011-08-02 17:35:39Z ggregory $ + */ +public interface Mutable { + + /** + * Gets the value of this mutable. + * + * @return the stored value + */ + T getValue(); + + /** + * Sets the value of this mutable. + * + * @param value + * the value to store + * @throws NullPointerException + * if the object is null and null is invalid + * @throws ClassCastException + * if the type is invalid + */ + void setValue(T value); + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/MutableInt.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/MutableInt.java new file mode 100644 index 00000000..d7e83d9b --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/MutableInt.java @@ -0,0 +1,273 @@ +/* + * 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 int wrapper. + *

+ * Note that as MutableInt does not extend Integer, it is not treated by String.format as an Integer parameter. + * + * @see Integer + * @since 2.1 + * @version $Id: MutableInt.java 1160571 2011-08-23 07:36:08Z bayard $ + */ +public class MutableInt extends Number implements Comparable, Mutable { + + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 512176391864L; + + /** The mutable value. */ + private int value; + + /** + * Constructs a new MutableInt with the default value of zero. + */ + public MutableInt() { + super(); + } + + /** + * Constructs a new MutableInt with the specified value. + * + * @param value the initial value to store + */ + public MutableInt(int value) { + super(); + this.value = value; + } + + /** + * Constructs a new MutableInt with the specified value. + * + * @param value the initial value to store, not null + * @throws NullPointerException if the object is null + */ + public MutableInt(Number value) { + super(); + this.value = value.intValue(); + } + + /** + * Constructs a new MutableInt parsing the given string. + * + * @param value the string to parse, not null + * @throws NumberFormatException if the string cannot be parsed into an int + * @since 2.5 + */ + public MutableInt(String value) throws NumberFormatException { + super(); + this.value = Integer.parseInt(value); + } + + //----------------------------------------------------------------------- + /** + * Gets the value as a Integer instance. + * + * @return the value as a Integer, never null + */ + public Integer getValue() { + return Integer.valueOf(this.value); + } + + /** + * Sets the value. + * + * @param value the value to set + */ + public void setValue(int 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.intValue(); + } + + //----------------------------------------------------------------------- + /** + * 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(int 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.intValue(); + } + + /** + * 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(int 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.intValue(); + } + + //----------------------------------------------------------------------- + // shortValue and byteValue rely on Number implementation + /** + * Returns the value of this MutableInt 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 MutableInt 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 MutableInt 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 MutableInt 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 Integer. + * + * @return a Integer instance containing the value from this mutable, never null + */ + public Integer toInteger() { + return Integer.valueOf(intValue()); + } + + //----------------------------------------------------------------------- + /** + * Compares this object to the specified object. The result is true if and only if the argument is + * not null and is a MutableInt object that contains the same int 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 MutableInt) { + return value == ((MutableInt) obj).intValue(); + } + 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(MutableInt other) { + int 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/edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/package.html b/edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/package.html new file mode 100644 index 00000000..2f7436af --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/mutable/package.html @@ -0,0 +1,29 @@ + + + + + + + +Provides typed mutable wrappers to primitive values and Object. +@since 2.1 +

These classes are not thread-safe.

+ + diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/overview.html b/edxp-core/src/main/java/external/org/apache/commons/lang3/overview.html new file mode 100644 index 00000000..f8433aae --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/overview.html @@ -0,0 +1,23 @@ + + + +

+This document is the API specification for the Apache Commons Lang library. +

+ + diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/package.html b/edxp-core/src/main/java/external/org/apache/commons/lang3/package.html new file mode 100644 index 00000000..1625c62d --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/package.html @@ -0,0 +1,25 @@ + + + +Provides highly reusable static utility methods, chiefly concerned +with adding value to the {@link java.lang} classes. +@since 1.0 +

Most of these classes are immutable and thus thread-safe. +However Charset is not currently guaranteed thread-safe under all circumstances.

+ + diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/MemberUtils.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/MemberUtils.java new file mode 100644 index 00000000..c268fd76 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/MemberUtils.java @@ -0,0 +1,185 @@ +/* + * 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.AccessibleObject; +import java.lang.reflect.Member; +import java.lang.reflect.Modifier; + +import external.org.apache.commons.lang3.ClassUtils; + +/** + * Contains common code for working with Methods/Constructors, extracted and + * refactored from MethodUtils when it was imported from Commons + * BeanUtils. + * + * @since 2.5 + * @version $Id: MemberUtils.java 1143537 2011-07-06 19:30:22Z joehni $ + */ +public abstract class MemberUtils { + // TODO extract an interface to implement compareParameterSets(...)? + + private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; + + /** Array of primitive number types ordered by "promotability" */ + private static final Class[] ORDERED_PRIMITIVE_TYPES = { Byte.TYPE, Short.TYPE, + Character.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE }; + + /** + * XXX Default access superclass workaround + * + * When a public class has a default access superclass with public members, + * these members are accessible. Calling them from compiled code works fine. + * Unfortunately, on some JVMs, using reflection to invoke these members + * seems to (wrongly) prevent access even when the modifier is public. + * Calling setAccessible(true) solves the problem but will only work from + * sufficiently privileged code. Better workarounds would be gratefully + * accepted. + * @param o the AccessibleObject to set as accessible + */ + static void setAccessibleWorkaround(AccessibleObject o) { + if (o == null || o.isAccessible()) { + return; + } + Member m = (Member) o; + if (Modifier.isPublic(m.getModifiers()) + && isPackageAccess(m.getDeclaringClass().getModifiers())) { + try { + o.setAccessible(true); + } catch (SecurityException e) { // NOPMD + // ignore in favor of subsequent IllegalAccessException + } + } + } + + /** + * Returns whether a given set of modifiers implies package access. + * @param modifiers to test + * @return true unless package/protected/private modifier detected + */ + static boolean isPackageAccess(int modifiers) { + return (modifiers & ACCESS_TEST) == 0; + } + + /** + * Returns whether a Member is accessible. + * @param m Member to check + * @return true if m is accessible + */ + static boolean isAccessible(Member m) { + return m != null && Modifier.isPublic(m.getModifiers()) && !m.isSynthetic(); + } + + /** + * Compares the relative fitness of two sets of parameter types in terms of + * matching a third set of runtime parameter types, such that a list ordered + * by the results of the comparison would return the best match first + * (least). + * + * @param left the "left" parameter set + * @param right the "right" parameter set + * @param actual the runtime parameter types to match against + * left/right + * @return int consistent with compare semantics + */ + public static int compareParameterTypes(Class[] left, Class[] right, Class[] actual) { + float leftCost = getTotalTransformationCost(actual, left); + float rightCost = getTotalTransformationCost(actual, right); + return leftCost < rightCost ? -1 : rightCost < leftCost ? 1 : 0; + } + + /** + * Returns the sum of the object transformation cost for each class in the + * source argument list. + * @param srcArgs The source arguments + * @param destArgs The destination arguments + * @return The total transformation cost + */ + private static float getTotalTransformationCost(Class[] srcArgs, Class[] destArgs) { + float totalCost = 0.0f; + for (int i = 0; i < srcArgs.length; i++) { + Class srcClass, destClass; + srcClass = srcArgs[i]; + destClass = destArgs[i]; + totalCost += getObjectTransformationCost(srcClass, destClass); + } + return totalCost; + } + + /** + * Gets the number of steps required needed to turn the source class into + * the destination class. This represents the number of steps in the object + * hierarchy graph. + * @param srcClass The source class + * @param destClass The destination class + * @return The cost of transforming an object + */ + private static float getObjectTransformationCost(Class srcClass, Class destClass) { + if (destClass.isPrimitive()) { + return getPrimitivePromotionCost(srcClass, destClass); + } + float cost = 0.0f; + while (srcClass != null && !destClass.equals(srcClass)) { + if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) { + // slight penalty for interface match. + // we still want an exact match to override an interface match, + // but + // an interface match should override anything where we have to + // get a superclass. + cost += 0.25f; + break; + } + cost++; + srcClass = srcClass.getSuperclass(); + } + /* + * If the destination class is null, we've travelled all the way up to + * an Object match. We'll penalize this by adding 1.5 to the cost. + */ + if (srcClass == null) { + cost += 1.5f; + } + return cost; + } + + /** + * Gets the number of steps required to promote a primitive number to another + * type. + * @param srcClass the (primitive) source class + * @param destClass the (primitive) destination class + * @return The cost of promoting the primitive + */ + private static float getPrimitivePromotionCost(final Class srcClass, final Class destClass) { + float cost = 0.0f; + Class cls = srcClass; + if (!cls.isPrimitive()) { + // slight unwrapping penalty + cost += 0.1f; + cls = ClassUtils.wrapperToPrimitive(cls); + } + for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) { + if (cls == ORDERED_PRIMITIVE_TYPES[i]) { + cost += 0.1f; + if (i < ORDERED_PRIMITIVE_TYPES.length - 1) { + cls = ORDERED_PRIMITIVE_TYPES[i + 1]; + } + } + } + return cost; + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/MethodUtils.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/MethodUtils.java new file mode 100644 index 00000000..d72a1ebe --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/MethodUtils.java @@ -0,0 +1,537 @@ +/* + * 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.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import external.org.apache.commons.lang3.ArrayUtils; +import external.org.apache.commons.lang3.ClassUtils; + +/** + *

Utility reflection methods focused on methods, originally from Commons BeanUtils. + * Differences from the BeanUtils version may be noted, especially where similar functionality + * already existed within Lang. + *

+ * + *

Known Limitations

+ *

Accessing Public Methods In A Default Access Superclass

+ *

There is an issue when invoking public methods contained in a default access superclass on JREs prior to 1.4. + * Reflection locates these methods fine and correctly assigns them as public. + * However, an IllegalAccessException is thrown if the method is invoked.

+ * + *

MethodUtils contains a workaround for this situation. + * It will attempt to call setAccessible on this method. + * 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 the method may fail.

+ * + * @since 2.5 + * @version $Id: MethodUtils.java 1166253 2011-09-07 16:27:42Z ggregory $ + */ +public class MethodUtils { + + /** + *

MethodUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as + * MethodUtils.getAccessibleMethod(method).

+ * + *

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

+ */ + public MethodUtils() { + super(); + } + + /** + *

Invokes a named method whose parameter type matches the object type.

+ * + *

This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.

+ * + *

This method supports calls to methods taking primitive parameters + * via passing in wrapping classes. So, for example, a Boolean object + * would match a boolean primitive.

+ * + *

This is a convenient wrapper for + * {@link #invokeMethod(Object object,String methodName, Object[] args, Class[] parameterTypes)}. + *

+ * + * @param object invoke method on this object + * @param methodName get method with this name + * @param args use these arguments - treat null as empty array + * @return The value returned by the invoked method + * + * @throws NoSuchMethodException if there is no such accessible method + * @throws InvocationTargetException wraps an exception thrown by the method invoked + * @throws IllegalAccessException if the requested method is not accessible via reflection + */ + public static Object invokeMethod(Object object, String methodName, + Object... args) throws NoSuchMethodException, + IllegalAccessException, InvocationTargetException { + 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 invokeMethod(object, methodName, args, parameterTypes); + } + + /** + *

Invokes a named method whose parameter type matches the object type.

+ * + *

This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.

+ * + *

This method supports calls to methods taking primitive parameters + * via passing in wrapping classes. So, for example, a Boolean object + * would match a boolean primitive.

+ * + * @param object invoke method on this object + * @param methodName get method with this name + * @param args use these arguments - treat null as empty array + * @param parameterTypes match these parameters - treat null as empty array + * @return The value returned by the invoked method + * + * @throws NoSuchMethodException if there is no such accessible method + * @throws InvocationTargetException wraps an exception thrown by the method invoked + * @throws IllegalAccessException if the requested method is not accessible via reflection + */ + public static Object invokeMethod(Object object, String methodName, + Object[] args, Class[] parameterTypes) + throws NoSuchMethodException, IllegalAccessException, + InvocationTargetException { + if (parameterTypes == null) { + parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; + } + if (args == null) { + args = ArrayUtils.EMPTY_OBJECT_ARRAY; + } + Method method = getMatchingAccessibleMethod(object.getClass(), + methodName, parameterTypes); + if (method == null) { + throw new NoSuchMethodException("No such accessible method: " + + methodName + "() on object: " + + object.getClass().getName()); + } + return method.invoke(object, args); + } + + /** + *

Invokes a method whose parameter types match exactly the object + * types.

+ * + *

This uses reflection to invoke the method obtained from a call to + * getAccessibleMethod().

+ * + * @param object invoke method on this object + * @param methodName get method with this name + * @param args use these arguments - treat null as empty array + * @return The value returned by the invoked method + * + * @throws NoSuchMethodException if there is no such accessible method + * @throws InvocationTargetException wraps an exception thrown by the + * method invoked + * @throws IllegalAccessException if the requested method is not accessible + * via reflection + */ + public static Object invokeExactMethod(Object object, String methodName, + Object... args) throws NoSuchMethodException, + IllegalAccessException, InvocationTargetException { + 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 invokeExactMethod(object, methodName, args, parameterTypes); + } + + /** + *

Invokes a method whose parameter types match exactly the parameter + * types given.

+ * + *

This uses reflection to invoke the method obtained from a call to + * getAccessibleMethod().

+ * + * @param object invoke method on this object + * @param methodName get method with this name + * @param args use these arguments - treat null as empty array + * @param parameterTypes match these parameters - treat null as empty array + * @return The value returned by the invoked method + * + * @throws NoSuchMethodException if there is no such accessible method + * @throws InvocationTargetException wraps an exception thrown by the + * method invoked + * @throws IllegalAccessException if the requested method is not accessible + * via reflection + */ + public static Object invokeExactMethod(Object object, String methodName, + Object[] args, Class[] parameterTypes) + throws NoSuchMethodException, IllegalAccessException, + InvocationTargetException { + if (args == null) { + args = ArrayUtils.EMPTY_OBJECT_ARRAY; + } + if (parameterTypes == null) { + parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; + } + Method method = getAccessibleMethod(object.getClass(), methodName, + parameterTypes); + if (method == null) { + throw new NoSuchMethodException("No such accessible method: " + + methodName + "() on object: " + + object.getClass().getName()); + } + return method.invoke(object, args); + } + + /** + *

Invokes a static method whose parameter types match exactly the parameter + * types given.

+ * + *

This uses reflection to invoke the method obtained from a call to + * {@link #getAccessibleMethod(Class, String, Class[])}.

+ * + * @param cls invoke static method on this class + * @param methodName get method with this name + * @param args use these arguments - treat null as empty array + * @param parameterTypes match these parameters - treat null as empty array + * @return The value returned by the invoked method + * + * @throws NoSuchMethodException if there is no such accessible method + * @throws InvocationTargetException wraps an exception thrown by the + * method invoked + * @throws IllegalAccessException if the requested method is not accessible + * via reflection + */ + public static Object invokeExactStaticMethod(Class cls, String methodName, + Object[] args, Class[] parameterTypes) + throws NoSuchMethodException, IllegalAccessException, + InvocationTargetException { + if (args == null) { + args = ArrayUtils.EMPTY_OBJECT_ARRAY; + } + if (parameterTypes == null) { + parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; + } + Method method = getAccessibleMethod(cls, methodName, parameterTypes); + if (method == null) { + throw new NoSuchMethodException("No such accessible method: " + + methodName + "() on class: " + cls.getName()); + } + return method.invoke(null, args); + } + + /** + *

Invokes a named static method whose parameter type matches the object type.

+ * + *

This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.

+ * + *

This method supports calls to methods taking primitive parameters + * via passing in wrapping classes. So, for example, a Boolean class + * would match a boolean primitive.

+ * + *

This is a convenient wrapper for + * {@link #invokeStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes)}. + *

+ * + * @param cls invoke static method on this class + * @param methodName get method with this name + * @param args use these arguments - treat null as empty array + * @return The value returned by the invoked method + * + * @throws NoSuchMethodException if there is no such accessible method + * @throws InvocationTargetException wraps an exception thrown by the + * method invoked + * @throws IllegalAccessException if the requested method is not accessible + * via reflection + */ + public static Object invokeStaticMethod(Class cls, String methodName, + Object... args) throws NoSuchMethodException, + IllegalAccessException, InvocationTargetException { + 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 invokeStaticMethod(cls, methodName, args, parameterTypes); + } + + /** + *

Invokes a named static method whose parameter type matches the object type.

+ * + *

This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.

+ * + *

This method supports calls to methods taking primitive parameters + * via passing in wrapping classes. So, for example, a Boolean class + * would match a boolean primitive.

+ * + * + * @param cls invoke static method on this class + * @param methodName get method with this name + * @param args use these arguments - treat null as empty array + * @param parameterTypes match these parameters - treat null as empty array + * @return The value returned by the invoked method + * + * @throws NoSuchMethodException if there is no such accessible method + * @throws InvocationTargetException wraps an exception thrown by the + * method invoked + * @throws IllegalAccessException if the requested method is not accessible + * via reflection + */ + public static Object invokeStaticMethod(Class cls, String methodName, + Object[] args, Class[] parameterTypes) + throws NoSuchMethodException, IllegalAccessException, + InvocationTargetException { + if (parameterTypes == null) { + parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; + } + if (args == null) { + args = ArrayUtils.EMPTY_OBJECT_ARRAY; + } + Method method = getMatchingAccessibleMethod(cls, methodName, + parameterTypes); + if (method == null) { + throw new NoSuchMethodException("No such accessible method: " + + methodName + "() on class: " + cls.getName()); + } + return method.invoke(null, args); + } + + /** + *

Invokes a static method whose parameter types match exactly the object + * types.

+ * + *

This uses reflection to invoke the method obtained from a call to + * {@link #getAccessibleMethod(Class, String, Class[])}.

+ * + * @param cls invoke static method on this class + * @param methodName get method with this name + * @param args use these arguments - treat null as empty array + * @return The value returned by the invoked method + * + * @throws NoSuchMethodException if there is no such accessible method + * @throws InvocationTargetException wraps an exception thrown by the + * method invoked + * @throws IllegalAccessException if the requested method is not accessible + * via reflection + */ + public static Object invokeExactStaticMethod(Class cls, String methodName, + Object... args) throws NoSuchMethodException, + IllegalAccessException, InvocationTargetException { + 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 invokeExactStaticMethod(cls, methodName, args, parameterTypes); + } + + /** + *

Returns an accessible method (that is, one that can be invoked via + * reflection) with given name and parameters. If no such method + * can be found, return null. + * This is just a convenient wrapper for + * {@link #getAccessibleMethod(Method method)}.

+ * + * @param cls get method from this class + * @param methodName get method with this name + * @param parameterTypes with these parameters types + * @return The accessible method + */ + public static Method getAccessibleMethod(Class cls, String methodName, + Class... parameterTypes) { + try { + return getAccessibleMethod(cls.getMethod(methodName, + parameterTypes)); + } catch (NoSuchMethodException e) { + return null; + } + } + + /** + *

Returns an accessible method (that is, one that can be invoked via + * reflection) that implements the specified Method. If no such method + * can be found, return null.

+ * + * @param method The method that we wish to call + * @return The accessible method + */ + public static Method getAccessibleMethod(Method method) { + if (!MemberUtils.isAccessible(method)) { + return null; + } + // If the declaring class is public, we are done + Class cls = method.getDeclaringClass(); + if (Modifier.isPublic(cls.getModifiers())) { + return method; + } + String methodName = method.getName(); + Class[] parameterTypes = method.getParameterTypes(); + + // Check the implemented interfaces and subinterfaces + method = getAccessibleMethodFromInterfaceNest(cls, methodName, + parameterTypes); + + // Check the superclass chain + if (method == null) { + method = getAccessibleMethodFromSuperclass(cls, methodName, + parameterTypes); + } + return method; + } + + /** + *

Returns an accessible method (that is, one that can be invoked via + * reflection) by scanning through the superclasses. If no such method + * can be found, return null.

+ * + * @param cls Class to be checked + * @param methodName Method name of the method we wish to call + * @param parameterTypes The parameter type signatures + * @return the accessible method or null if not found + */ + private static Method getAccessibleMethodFromSuperclass(Class cls, + String methodName, Class... parameterTypes) { + Class parentClass = cls.getSuperclass(); + while (parentClass != null) { + if (Modifier.isPublic(parentClass.getModifiers())) { + try { + return parentClass.getMethod(methodName, parameterTypes); + } catch (NoSuchMethodException e) { + return null; + } + } + parentClass = parentClass.getSuperclass(); + } + return null; + } + + /** + *

Returns an accessible method (that is, one that can be invoked via + * reflection) that implements the specified method, by scanning through + * all implemented interfaces and subinterfaces. If no such method + * can be found, return null.

+ * + *

There isn't any good reason why this method must be private. + * It is because there doesn't seem any reason why other classes should + * call this rather than the higher level methods.

+ * + * @param cls Parent class for the interfaces to be checked + * @param methodName Method name of the method we wish to call + * @param parameterTypes The parameter type signatures + * @return the accessible method or null if not found + */ + private static Method getAccessibleMethodFromInterfaceNest(Class cls, + String methodName, Class... parameterTypes) { + Method method = null; + + // Search up the superclass chain + for (; cls != null; cls = cls.getSuperclass()) { + + // Check the implemented interfaces of the parent class + Class[] interfaces = cls.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) { + // Is this interface public? + if (!Modifier.isPublic(interfaces[i].getModifiers())) { + continue; + } + // Does the method exist on this interface? + try { + method = interfaces[i].getDeclaredMethod(methodName, + parameterTypes); + } catch (NoSuchMethodException e) { // NOPMD + /* + * Swallow, if no method is found after the loop then this + * method returns null. + */ + } + if (method != null) { + break; + } + // Recursively check our parent interfaces + method = getAccessibleMethodFromInterfaceNest(interfaces[i], + methodName, parameterTypes); + if (method != null) { + break; + } + } + } + return method; + } + + /** + *

Finds an accessible method that matches the given name and has compatible parameters. + * Compatible parameters mean that every method parameter is assignable from + * the given parameters. + * In other words, it finds a method with the given name + * that will take the parameters given.

+ * + *

This method is used by + * {@link + * #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}. + * + *

This method can match primitive parameter by passing in wrapper classes. + * For example, a Boolean will match a primitive boolean + * parameter. + * + * @param cls find method in this class + * @param methodName find method with this name + * @param parameterTypes find method with most compatible parameters + * @return The accessible method + */ + public static Method getMatchingAccessibleMethod(Class cls, + String methodName, Class... parameterTypes) { + try { + Method method = cls.getMethod(methodName, parameterTypes); + MemberUtils.setAccessibleWorkaround(method); + return method; + } catch (NoSuchMethodException e) { // NOPMD - Swallow the exception + } + // search through all methods + Method bestMatch = null; + Method[] methods = cls.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 + Method accessibleMethod = getAccessibleMethod(method); + if (accessibleMethod != null && (bestMatch == null || MemberUtils.compareParameterTypes( + accessibleMethod.getParameterTypes(), + bestMatch.getParameterTypes(), + parameterTypes) < 0)) { + bestMatch = accessibleMethod; + } + } + } + if (bestMatch != null) { + MemberUtils.setAccessibleWorkaround(bestMatch); + } + return bestMatch; + } +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/package.html b/edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/package.html new file mode 100644 index 00000000..618b07a8 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/reflect/package.html @@ -0,0 +1,29 @@ + + + + + + + +Accumulates common high-level uses of the java.lang.reflect APIs. +@since 3.0 +

These classes are immutable, and therefore thread-safe.

+ + diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/ImmutablePair.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/ImmutablePair.java new file mode 100644 index 00000000..d3085be1 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/ImmutablePair.java @@ -0,0 +1,103 @@ +/* + * 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.tuple; + +/** + *

An immutable pair consisting of two {@code Object} elements.

+ * + *

Although the implementation is immutable, there is no restriction on the objects + * that may be stored. If mutable objects are stored in the pair, then the pair + * itself effectively becomes mutable. The class is also not {@code final}, so a subclass + * could add undesirable behaviour.

+ * + *

#ThreadSafe# if the objects are threadsafe

+ * + * @param the left element type + * @param the right element type + * + * @since Lang 3.0 + * @version $Id: ImmutablePair.java 1127544 2011-05-25 14:35:42Z scolebourne $ + */ +public final class ImmutablePair extends Pair { + + /** Serialization version */ + private static final long serialVersionUID = 4954918890077093841L; + + /** Left object */ + public final L left; + /** Right object */ + public final R right; + + /** + *

Obtains an immutable pair of from two objects inferring the generic types.

+ * + *

This factory allows the pair to be created using inference to + * obtain the generic types.

+ * + * @param the left element type + * @param the right element type + * @param left the left element, may be null + * @param right the right element, may be null + * @return a pair formed from the two parameters, not null + */ + public static ImmutablePair of(L left, R right) { + return new ImmutablePair(left, right); + } + + /** + * Create a new pair instance. + * + * @param left the left value, may be null + * @param right the right value, may be null + */ + public ImmutablePair(L left, R right) { + super(); + this.left = left; + this.right = right; + } + + //----------------------------------------------------------------------- + /** + * {@inheritDoc} + */ + @Override + public L getLeft() { + return left; + } + + /** + * {@inheritDoc} + */ + @Override + public R getRight() { + return right; + } + + /** + *

Throws {@code UnsupportedOperationException}.

+ * + *

This pair is immutable, so this operation is not supported.

+ * + * @param value the value to set + * @return never + * @throws UnsupportedOperationException as this operation is not supported + */ + public R setValue(R value) { + throw new UnsupportedOperationException(); + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/Pair.java b/edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/Pair.java new file mode 100644 index 00000000..e43bd8ab --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/Pair.java @@ -0,0 +1,177 @@ +/* + * 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.tuple; + +import java.io.Serializable; +import java.util.Map; + + +import external.org.apache.commons.lang3.ObjectUtils; +import external.org.apache.commons.lang3.builder.CompareToBuilder; + +/** + *

A pair consisting of two elements.

+ * + *

This class is an abstract implementation defining the basic API. + * It refers to the elements as 'left' and 'right'. It also implements the + * {@code Map.Entry} interface where the key is 'left' and the value is 'right'.

+ * + *

Subclass implementations may be mutable or immutable. + * However, there is no restriction on the type of the stored objects that may be stored. + * If mutable objects are stored in the pair, then the pair itself effectively becomes mutable.

+ * + * @param the left element type + * @param the right element type + * + * @since Lang 3.0 + * @version $Id: Pair.java 1142401 2011-07-03 08:30:12Z bayard $ + */ +public abstract class Pair implements Map.Entry, Comparable>, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 4954918890077093841L; + + /** + *

Obtains an immutable pair of from two objects inferring the generic types.

+ * + *

This factory allows the pair to be created using inference to + * obtain the generic types.

+ * + * @param the left element type + * @param the right element type + * @param left the left element, may be null + * @param right the right element, may be null + * @return a pair formed from the two parameters, not null + */ + public static Pair of(L left, R right) { + return new ImmutablePair(left, right); + } + + //----------------------------------------------------------------------- + /** + *

Gets the left element from this pair.

+ * + *

When treated as a key-value pair, this is the key.

+ * + * @return the left element, may be null + */ + public abstract L getLeft(); + + /** + *

Gets the right element from this pair.

+ * + *

When treated as a key-value pair, this is the value.

+ * + * @return the right element, may be null + */ + public abstract R getRight(); + + /** + *

Gets the key from this pair.

+ * + *

This method implements the {@code Map.Entry} interface returning the + * left element as the key.

+ * + * @return the left element as the key, may be null + */ + public final L getKey() { + return getLeft(); + } + + /** + *

Gets the value from this pair.

+ * + *

This method implements the {@code Map.Entry} interface returning the + * right element as the value.

+ * + * @return the right element as the value, may be null + */ + public R getValue() { + return getRight(); + } + + //----------------------------------------------------------------------- + /** + *

Compares the pair based on the left element followed by the right element. + * The types must be {@code Comparable}.

+ * + * @param other the other pair, not null + * @return negative if this is less, zero if equal, positive if greater + */ + public int compareTo(Pair other) { + return new CompareToBuilder().append(getLeft(), other.getLeft()) + .append(getRight(), other.getRight()).toComparison(); + } + + /** + *

Compares this pair to another based on the two elements.

+ * + * @param obj the object to compare to, null returns false + * @return true if the elements of the pair are equal + */ + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof Map.Entry) { + Map.Entry other = (Map.Entry) obj; + return ObjectUtils.equals(getKey(), other.getKey()) + && ObjectUtils.equals(getValue(), other.getValue()); + } + return false; + } + + /** + *

Returns a suitable hash code. + * The hash code follows the definition in {@code Map.Entry}.

+ * + * @return the hash code + */ + @Override + public int hashCode() { + // see Map.Entry API specification + return (getKey() == null ? 0 : getKey().hashCode()) ^ + (getValue() == null ? 0 : getValue().hashCode()); + } + + /** + *

Returns a String representation of this pair using the format {@code ($left,$right)}.

+ * + * @return a string describing this object, not null + */ + @Override + public String toString() { + return new StringBuilder().append('(').append(getLeft()).append(',').append(getRight()).append(')').toString(); + } + + /** + *

Formats the receiver using the given format.

+ * + *

This uses {@link java.util.Formattable} to perform the formatting. Two variables may + * be used to embed the left and right elements. Use {@code %1$s} for the left + * element (key) and {@code %2$s} for the right element (value). + * The default format used by {@code toString()} is {@code (%1$s,%2$s)}.

+ * + * @param format the format string, optionally containing {@code %1$s} and {@code %2$s}, not null + * @return the formatted string, not null + */ + public String toString(String format) { + return String.format(format, getLeft(), getRight()); + } + +} diff --git a/edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/package.html b/edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/package.html new file mode 100644 index 00000000..db858539 --- /dev/null +++ b/edxp-core/src/main/java/external/org/apache/commons/lang3/tuple/package.html @@ -0,0 +1,22 @@ + + + +Tuple classes, starting with a Pair class in version 3.0. +@since 3.0 + + diff --git a/edxp-core/src/main/java/pxb/android/ResConst.java b/edxp-core/src/main/java/pxb/android/ResConst.java new file mode 100644 index 00000000..be0d87a8 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/ResConst.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android; + +public interface ResConst { + int RES_STRING_POOL_TYPE = 0x0001; + int RES_TABLE_TYPE = 0x0002; + int RES_TABLE_PACKAGE_TYPE = 0x0200; + int RES_TABLE_TYPE_SPEC_TYPE = 0x0202; + int RES_TABLE_TYPE_TYPE = 0x0201; + + int RES_XML_TYPE = 0x0003; + int RES_XML_RESOURCE_MAP_TYPE = 0x0180; + int RES_XML_END_NAMESPACE_TYPE = 0x0101; + int RES_XML_END_ELEMENT_TYPE = 0x0103; + int RES_XML_START_NAMESPACE_TYPE = 0x0100; + int RES_XML_START_ELEMENT_TYPE = 0x0102; + int RES_XML_CDATA_TYPE = 0x0104; + +} diff --git a/edxp-core/src/main/java/pxb/android/StringItem.java b/edxp-core/src/main/java/pxb/android/StringItem.java new file mode 100644 index 00000000..7f99ecba --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/StringItem.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android; + +public class StringItem { + public String data; + public int dataOffset; + public int index; + + public StringItem() { + super(); + } + + public StringItem(String data) { + super(); + this.data = data; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + StringItem other = (StringItem) obj; + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((data == null) ? 0 : data.hashCode()); + return result; + } + + public String toString() { + return String.format("S%04d %s", index, data); + } + +} diff --git a/edxp-core/src/main/java/pxb/android/StringItems.java b/edxp-core/src/main/java/pxb/android/StringItems.java new file mode 100644 index 00000000..edf026a6 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/StringItems.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +@SuppressWarnings("serial") +public class StringItems extends ArrayList { + private static final int UTF8_FLAG = 0x00000100; + + + public static String[] read(ByteBuffer in) throws IOException { + int trunkOffset = in.position() - 8; + int stringCount = in.getInt(); + int styleOffsetCount = in.getInt(); + int flags = in.getInt(); + int stringDataOffset = in.getInt(); + int stylesOffset = in.getInt(); + int offsets[] = new int[stringCount]; + String strings[] = new String[stringCount]; + for (int i = 0; i < stringCount; i++) { + offsets[i] = in.getInt(); + } + + int base = trunkOffset + stringDataOffset; + for (int i = 0; i < offsets.length; i++) { + in.position(base + offsets[i]); + String s; + + if (0 != (flags & UTF8_FLAG)) { + u8length(in); // ignored + int u8len = u8length(in); + int start = in.position(); + int blength = u8len; + while (in.get(start + blength) != 0) { + blength++; + } + s = new String(in.array(), start, blength, "UTF-8"); + } else { + int length = u16length(in); + s = new String(in.array(), in.position(), length * 2, "UTF-16LE"); + } + strings[i] = s; + } + return strings; + } + + static int u16length(ByteBuffer in) { + int length = in.getShort() & 0xFFFF; + if (length > 0x7FFF) { + length = ((length & 0x7FFF) << 8) | (in.getShort() & 0xFFFF); + } + return length; + } + + static int u8length(ByteBuffer in) { + int len = in.get() & 0xFF; + if ((len & 0x80) != 0) { + len = ((len & 0x7F) << 8) | (in.get() & 0xFF); + } + return len; + } + + byte[] stringData; + + public int getSize() { + return 5 * 4 + this.size() * 4 + stringData.length + 0;// TODO + } + + public void prepare() throws IOException { + for (StringItem s : this) { + if (s.data.length() > 0x7FFF) { + useUTF8 = false; + } + } + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + int i = 0; + int offset = 0; + baos.reset(); + Map map = new HashMap(); + for (StringItem item : this) { + item.index = i++; + String stringData = item.data; + Integer of = map.get(stringData); + if (of != null) { + item.dataOffset = of; + } else { + item.dataOffset = offset; + map.put(stringData, offset); + if (useUTF8) { + int length = stringData.length(); + byte[] data = stringData.getBytes("UTF-8"); + int u8lenght = data.length; + + if (length > 0x7F) { + offset++; + baos.write((length >> 8) | 0x80); + } + baos.write(length); + + if (u8lenght > 0x7F) { + offset++; + baos.write((u8lenght >> 8) | 0x80); + } + baos.write(u8lenght); + baos.write(data); + baos.write(0); + offset += 3 + u8lenght; + } else { + int length = stringData.length(); + byte[] data = stringData.getBytes("UTF-16LE"); + if (length > 0x7FFF) { + int x = (length >> 16) | 0x8000; + baos.write(x); + baos.write(x >> 8); + offset += 2; + } + baos.write(length); + baos.write(length >> 8); + baos.write(data); + baos.write(0); + baos.write(0); + offset += 4 + data.length; + } + } + } + // TODO + stringData = baos.toByteArray(); + } + + private boolean useUTF8 = true; + + public void write(ByteBuffer out) throws IOException { + out.putInt(this.size()); + out.putInt(0);// TODO style count + out.putInt(useUTF8 ? UTF8_FLAG : 0); + out.putInt(7 * 4 + this.size() * 4); + out.putInt(0); + for (StringItem item : this) { + out.putInt(item.dataOffset); + } + out.put(stringData); + // TODO + } +} diff --git a/edxp-core/src/main/java/pxb/android/arsc/ArscDumper.java b/edxp-core/src/main/java/pxb/android/arsc/ArscDumper.java new file mode 100644 index 00000000..1e5760d2 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/arsc/ArscDumper.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.arsc; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import pxb.android.axml.Util; + +/** + * dump an arsc file + * + * @author bob + * + */ +public class ArscDumper { + public static void dump(List pkgs) { + for (int x = 0; x < pkgs.size(); x++) { + Pkg pkg = pkgs.get(x); + + System.out.println(String.format(" Package %d id=%d name=%s typeCount=%d", x, pkg.id, pkg.name, + pkg.types.size())); + for (Type type : pkg.types.values()) { + System.out.println(String.format(" type %d %s", type.id - 1, type.name)); + + int resPrefix = pkg.id << 24 | type.id << 16; + for (int i = 0; i < type.specs.length; i++) { + ResSpec spec = type.getSpec(i); + System.out.println(String.format(" spec 0x%08x 0x%08x %s", resPrefix | spec.id, spec.flags, + spec.name)); + } + for (int i = 0; i < type.configs.size(); i++) { + Config config = type.configs.get(i); + System.out.println(" config"); + + List entries = new ArrayList(config.resources.values()); + for (int j = 0; j < entries.size(); j++) { + ResEntry entry = entries.get(j); + System.out.println(String.format(" resource 0x%08x %-20s: %s", + resPrefix | entry.spec.id, entry.spec.name, entry.value)); + } + } + } + } + } + + public static void main(String... args) throws IOException { + if (args.length == 0) { + System.err.println("asrc-dump file.arsc"); + return; + } + byte[] data = Util.readFile(new File(args[0])); + List pkgs = new ArscParser(data).parse(); + + dump(pkgs); + + } +} diff --git a/edxp-core/src/main/java/pxb/android/arsc/ArscParser.java b/edxp-core/src/main/java/pxb/android/arsc/ArscParser.java new file mode 100644 index 00000000..721c1406 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/arsc/ArscParser.java @@ -0,0 +1,317 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.arsc; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import pxb.android.ResConst; +import pxb.android.StringItems; + +/** + * + * Read the resources.arsc inside an Android apk. + * + * Usage: + * + *
+ * byte[] oldArscFile= ... ; //
+ * List<Pkg> pkgs = new ArscParser(oldArscFile).parse(); // read the file
+ * modify(pkgs); // do what you want here
+ * byte[] newArscFile = new ArscWriter(pkgs).toByteArray(); // build a new file
+ * 
+ * + * The format of arsc is described here (gingerbread) + *
    + *
  • frameworks/base/libs/utils/ResourceTypes.cpp
  • + *
  • frameworks/base/include/utils/ResourceTypes.h
  • + *
+ * and the cmd line aapt d resources abc.apk is also good for debug + * (available in android sdk) + * + *

+ * Todos: + *

    + * TODO add support to read styled strings + *
+ * + *

+ * Thanks to the the following projects + *

    + *
  • android4me https://code.google.com/p/android4me/
  • + *
  • Apktool https://code.google.com/p/android-apktool
  • + *
  • Android http://source.android.com/
  • + *
+ * + * @author bob + * + */ +public class ArscParser implements ResConst { + + /* pkg */class Chunk { + + public final int headSize; + public final int location; + public final int size; + public final int type; + + public Chunk() { + location = in.position(); + type = in.getShort() & 0xFFFF; + headSize = in.getShort() & 0xFFFF; + size = in.getInt(); + } + } + + /** + * If set, this resource has been declared public, so libraries are allowed + * to reference it. + */ + static final int ENGRY_FLAG_PUBLIC = 0x0002; + + /** + * If set, this is a complex entry, holding a set of name/value mappings. It + * is followed by an array of ResTable_map structures. + */ + final static short ENTRY_FLAG_COMPLEX = 0x0001; + public static final int TYPE_STRING = 0x03; + + private int fileSize = -1; + private ByteBuffer in; + private String[] keyNamesX; + private Pkg pkg; + private List pkgs = new ArrayList(); + private String[] strings; + private String[] typeNamesX; + + public ArscParser(byte[] b) { + this.in = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN); + } + + public List parse() throws IOException { + if (fileSize < 0) { + Chunk head = new Chunk(); + if (head.type != RES_TABLE_TYPE) { + throw new RuntimeException(); + } + fileSize = head.size; + in.getInt();// packagecount + } + while (in.hasRemaining()) { + Chunk chunk = new Chunk(); + switch (chunk.type) { + case RES_STRING_POOL_TYPE: + strings = StringItems.read(in); + break; + case RES_TABLE_PACKAGE_TYPE: + readPackage(in); + } + in.position(chunk.location + chunk.size); + } + return pkgs; + } + + // private void readConfigFlags() { + // int size = in.getInt(); + // if (size < 28) { + // throw new RuntimeException(); + // } + // short mcc = in.getShort(); + // short mnc = in.getShort(); + // + // char[] language = new char[] { (char) in.get(), (char) in.get() }; + // char[] country = new char[] { (char) in.get(), (char) in.get() }; + // + // byte orientation = in.get(); + // byte touchscreen = in.get(); + // short density = in.getShort(); + // + // byte keyboard = in.get(); + // byte navigation = in.get(); + // byte inputFlags = in.get(); + // byte inputPad0 = in.get(); + // + // short screenWidth = in.getShort(); + // short screenHeight = in.getShort(); + // + // short sdkVersion = in.getShort(); + // short minorVersion = in.getShort(); + // + // byte screenLayout = 0; + // byte uiMode = 0; + // short smallestScreenWidthDp = 0; + // if (size >= 32) { + // screenLayout = in.get(); + // uiMode = in.get(); + // smallestScreenWidthDp = in.getShort(); + // } + // + // short screenWidthDp = 0; + // short screenHeightDp = 0; + // + // if (size >= 36) { + // screenWidthDp = in.getShort(); + // screenHeightDp = in.getShort(); + // } + // + // short layoutDirection = 0; + // if (size >= 38 && sdkVersion >= 17) { + // layoutDirection = in.getShort(); + // } + // + // } + + private void readEntry(Config config, ResSpec spec) { + int size = in.getShort(); + + int flags = in.getShort(); // ENTRY_FLAG_PUBLIC + int keyStr = in.getInt(); + spec.updateName(keyNamesX[keyStr]); + + ResEntry resEntry = new ResEntry(flags, spec); + + if (0 != (flags & ENTRY_FLAG_COMPLEX)) { + + int parent = in.getInt(); + int count = in.getInt(); + BagValue bag = new BagValue(parent); + for (int i = 0; i < count; i++) { + Map.Entry entry = new AbstractMap.SimpleEntry(in.getInt(), readValue()); + bag.map.add(entry); + } + resEntry.value = bag; + } else { + resEntry.value = readValue(); + } + config.resources.put(spec.id, resEntry); + } + + private void readPackage(ByteBuffer in) throws IOException { + int pid = in.getInt() % 0xFF; + + String name; + { + int nextPisition = in.position() + 128 * 2; + StringBuilder sb = new StringBuilder(32); + for (int i = 0; i < 128; i++) { + int s = in.getShort(); + if (s == 0) { + break; + } else { + sb.append((char) s); + } + } + name = sb.toString(); + in.position(nextPisition); + } + + pkg = new Pkg(pid, name); + pkgs.add(pkg); + + int typeStringOff = in.getInt(); + int typeNameCount = in.getInt(); + int keyStringOff = in.getInt(); + int specNameCount = in.getInt(); + + { + Chunk chunk = new Chunk(); + if (chunk.type != RES_STRING_POOL_TYPE) { + throw new RuntimeException(); + } + typeNamesX = StringItems.read(in); + in.position(chunk.location + chunk.size); + } + { + Chunk chunk = new Chunk(); + if (chunk.type != RES_STRING_POOL_TYPE) { + throw new RuntimeException(); + } + keyNamesX = StringItems.read(in); + in.position(chunk.location + chunk.size); + } + + out: while (in.hasRemaining()) { + Chunk chunk = new Chunk(); + switch (chunk.type) { + case RES_TABLE_TYPE_SPEC_TYPE: { + int tid = in.get() & 0xFF; + in.get(); // res0 + in.getShort();// res1 + int entryCount = in.getInt(); + + Type t = pkg.getType(tid, typeNamesX[tid - 1], entryCount); + for (int i = 0; i < entryCount; i++) { + t.getSpec(i).flags = in.getInt(); + } + } + break; + case RES_TABLE_TYPE_TYPE: { + int tid = in.get() & 0xFF; + in.get(); // res0 + in.getShort();// res1 + int entryCount = in.getInt(); + Type t = pkg.getType(tid, typeNamesX[tid - 1], entryCount); + int entriesStart = in.getInt(); + + int p = in.position(); + int size = in.getInt(); + // readConfigFlags(); + byte[] data = new byte[size]; + in.position(p); + in.get(data); + Config config = new Config(data, entryCount); + + in.position(chunk.location + chunk.headSize); + + int[] entrys = new int[entryCount]; + for (int i = 0; i < entryCount; i++) { + entrys[i] = in.getInt(); + } + for (int i = 0; i < entrys.length; i++) { + if (entrys[i] != -1) { + in.position(chunk.location + entriesStart + entrys[i]); + ResSpec spec = t.getSpec(i); + readEntry(config, spec); + } + } + + t.addConfig(config); + } + break; + default: + break out; + } + in.position(chunk.location + chunk.size); + } + } + + private Object readValue() { + int size1 = in.getShort();// 8 + int zero = in.get();// 0 + int type = in.get() & 0xFF; // TypedValue.* + int data = in.getInt(); + String raw = null; + if (type == TYPE_STRING) { + raw = strings[data]; + } + return new Value(type, data, raw); + } +} diff --git a/edxp-core/src/main/java/pxb/android/arsc/ArscWriter.java b/edxp-core/src/main/java/pxb/android/arsc/ArscWriter.java new file mode 100644 index 00000000..082c42f9 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/arsc/ArscWriter.java @@ -0,0 +1,400 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.arsc; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import pxb.android.ResConst; +import pxb.android.StringItem; +import pxb.android.StringItems; +import pxb.android.axml.Util; + +/** + * Write pkgs to an arsc file + * + * @see ArscParser + * @author bob + * + */ +public class ArscWriter implements ResConst { + private static class PkgCtx { + Map keyNames = new HashMap(); + StringItems keyNames0 = new StringItems(); + public int keyStringOff; + int offset; + Pkg pkg; + int pkgSize; + List typeNames = new ArrayList(); + + StringItems typeNames0 = new StringItems(); + int typeStringOff; + + public void addKeyName(String name) { + if (keyNames.containsKey(name)) { + return; + } + StringItem stringItem = new StringItem(name); + keyNames.put(name, stringItem); + keyNames0.add(stringItem); + } + + public void addTypeName(int id, String name) { + while (typeNames.size() <= id) { + typeNames.add(null); + } + + StringItem item = typeNames.get(id); + if (item == null) { + typeNames.set(id, new StringItem(name)); + } else { + throw new RuntimeException(); + } + } + } + + private static void D(String fmt, Object... args) { + + } + + private List ctxs = new ArrayList(5); + private List pkgs; + private Map strTable = new TreeMap(); + private StringItems strTable0 = new StringItems(); + + public ArscWriter(List pkgs) { + this.pkgs = pkgs; + } + + public static void main(String... args) throws IOException { + if (args.length < 2) { + System.err.println("asrc-write-test in.arsc out.arsc"); + return; + } + byte[] data = Util.readFile(new File(args[0])); + List pkgs = new ArscParser(data).parse(); + // ArscDumper.dump(pkgs); + byte[] data2 = new ArscWriter(pkgs).toByteArray(); + // ArscDumper.dump(new ArscParser(data2).parse()); + Util.writeFile(data2, new File(args[1])); + } + + private void addString(String str) { + if (strTable.containsKey(str)) { + return; + } + StringItem stringItem = new StringItem(str); + strTable.put(str, stringItem); + strTable0.add(stringItem); + } + + private int count() { + + int size = 0; + + size += 8 + 4;// chunk, pkgcount + { + int stringSize = strTable0.getSize(); + if (stringSize % 4 != 0) { + stringSize += 4 - stringSize % 4; + } + size += 8 + stringSize;// global strings + } + for (PkgCtx ctx : ctxs) { + ctx.offset = size; + int pkgSize = 0; + pkgSize += 8 + 4 + 256;// chunk,pid+name + pkgSize += 4 * 4; + + ctx.typeStringOff = pkgSize; + { + int stringSize = ctx.typeNames0.getSize(); + if (stringSize % 4 != 0) { + stringSize += 4 - stringSize % 4; + } + pkgSize += 8 + stringSize;// type names + } + + ctx.keyStringOff = pkgSize; + + { + int stringSize = ctx.keyNames0.getSize(); + if (stringSize % 4 != 0) { + stringSize += 4 - stringSize % 4; + } + pkgSize += 8 + stringSize;// key names + } + + for (Type type : ctx.pkg.types.values()) { + type.wPosition = size + pkgSize; + pkgSize += 8 + 4 + 4 + 4 * type.specs.length; // trunk,id,entryCount, + // configs + + for (Config config : type.configs) { + config.wPosition = pkgSize + size; + int configBasePostion = pkgSize; + pkgSize += 8 + 4 + 4 + 4; // trunk,id,entryCount,entriesStart + int size0 = config.id.length; + if (size0 % 4 != 0) { + size0 += 4 - size0 % 4; + } + pkgSize += size0;// config + + if (pkgSize - configBasePostion > 0x0038) { + throw new RuntimeException("config id too big"); + } else { + pkgSize = configBasePostion + 0x0038; + } + + pkgSize += 4 * config.entryCount;// offset + config.wEntryStart = pkgSize - configBasePostion; + int entryBase = pkgSize; + for (ResEntry e : config.resources.values()) { + e.wOffset = pkgSize - entryBase; + pkgSize += 8;// size,flag,keyString + if (e.value instanceof BagValue) { + BagValue big = (BagValue) e.value; + pkgSize += 8 + big.map.size() * 12; + } else { + pkgSize += 8; + } + } + config.wChunkSize = pkgSize - configBasePostion; + } + } + ctx.pkgSize = pkgSize; + size += pkgSize; + } + + return size; + } + + private List prepare() throws IOException { + for (Pkg pkg : pkgs) { + PkgCtx ctx = new PkgCtx(); + ctx.pkg = pkg; + ctxs.add(ctx); + + for (Type type : pkg.types.values()) { + ctx.addTypeName(type.id - 1, type.name); + for (ResSpec spec : type.specs) { + ctx.addKeyName(spec.name); + } + for (Config config : type.configs) { + for (ResEntry e : config.resources.values()) { + Object object = e.value; + if (object instanceof BagValue) { + travelBagValue((BagValue) object); + } else { + travelValue((Value) object); + } + } + } + } + ctx.keyNames0.prepare(); + ctx.typeNames0.addAll(ctx.typeNames); + ctx.typeNames0.prepare(); + } + strTable0.prepare(); + return ctxs; + } + + public byte[] toByteArray() throws IOException { + prepare(); + int size = count(); + ByteBuffer out = ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN); + write(out, size); + return out.array(); + } + + private void travelBagValue(BagValue bag) { + for (Map.Entry e : bag.map) { + travelValue(e.getValue()); + } + } + + private void travelValue(Value v) { + if (v.raw != null) { + addString(v.raw); + } + } + + private void write(ByteBuffer out, int size) throws IOException { + out.putInt(RES_TABLE_TYPE | (0x000c << 16)); + out.putInt(size); + out.putInt(ctxs.size()); + + { + int stringSize = strTable0.getSize(); + int padding = 0; + if (stringSize % 4 != 0) { + padding = 4 - stringSize % 4; + } + out.putInt(RES_STRING_POOL_TYPE | (0x001C << 16)); + out.putInt(stringSize + padding + 8); + strTable0.write(out); + out.put(new byte[padding]); + } + + for (PkgCtx pctx : ctxs) { + if (out.position() != pctx.offset) { + throw new RuntimeException(); + } + final int basePosition = out.position(); + out.putInt(RES_TABLE_PACKAGE_TYPE | (0x011c << 16)); + out.putInt(pctx.pkgSize); + out.putInt(pctx.pkg.id); + int p = out.position(); + out.put(pctx.pkg.name.getBytes("UTF-16LE")); + out.position(p + 256); + + out.putInt(pctx.typeStringOff); + out.putInt(pctx.typeNames0.size()); + + out.putInt(pctx.keyStringOff); + out.putInt(pctx.keyNames0.size()); + + { + if (out.position() - basePosition != pctx.typeStringOff) { + throw new RuntimeException(); + } + int stringSize = pctx.typeNames0.getSize(); + int padding = 0; + if (stringSize % 4 != 0) { + padding = 4 - stringSize % 4; + } + out.putInt(RES_STRING_POOL_TYPE | (0x001C << 16)); + out.putInt(stringSize + padding + 8); + pctx.typeNames0.write(out); + out.put(new byte[padding]); + } + + { + if (out.position() - basePosition != pctx.keyStringOff) { + throw new RuntimeException(); + } + int stringSize = pctx.keyNames0.getSize(); + int padding = 0; + if (stringSize % 4 != 0) { + padding = 4 - stringSize % 4; + } + out.putInt(RES_STRING_POOL_TYPE | (0x001C << 16)); + out.putInt(stringSize + padding + 8); + pctx.keyNames0.write(out); + out.put(new byte[padding]); + } + + for (Type t : pctx.pkg.types.values()) { + D("[%08x]write spec", out.position(), t.name); + if (t.wPosition != out.position()) { + throw new RuntimeException(); + } + out.putInt(RES_TABLE_TYPE_SPEC_TYPE | (0x0010 << 16)); + out.putInt(4 * 4 + 4 * t.specs.length);// size + + out.putInt(t.id); + out.putInt(t.specs.length); + for (ResSpec spec : t.specs) { + out.putInt(spec.flags); + } + + for (Config config : t.configs) { + D("[%08x]write config", out.position()); + int typeConfigPosition = out.position(); + if (config.wPosition != typeConfigPosition) { + throw new RuntimeException(); + } + out.putInt(RES_TABLE_TYPE_TYPE | (0x0038 << 16)); + out.putInt(config.wChunkSize);// size + + out.putInt(t.id); + out.putInt(t.specs.length); + out.putInt(config.wEntryStart); + + D("[%08x]write config ids", out.position()); + out.put(config.id); + + int size0 = config.id.length; + int padding = 0; + if (size0 % 4 != 0) { + padding = 4 - size0 % 4; + } + out.put(new byte[padding]); + + out.position(typeConfigPosition + 0x0038); + + D("[%08x]write config entry offsets", out.position()); + for (int i = 0; i < config.entryCount; i++) { + ResEntry entry = config.resources.get(i); + if (entry == null) { + out.putInt(-1); + } else { + out.putInt(entry.wOffset); + } + } + + if (out.position() - typeConfigPosition != config.wEntryStart) { + throw new RuntimeException(); + } + D("[%08x]write config entrys", out.position()); + for (ResEntry e : config.resources.values()) { + D("[%08x]ResTable_entry", out.position()); + boolean isBag = e.value instanceof BagValue; + out.putShort((short) (isBag ? 16 : 8)); + int flag = e.flag; + if (isBag) { // add complex flag + flag |= ArscParser.ENTRY_FLAG_COMPLEX; + } else { // remove + flag &= ~ArscParser.ENTRY_FLAG_COMPLEX; + } + out.putShort((short) flag); + out.putInt(pctx.keyNames.get(e.spec.name).index); + if (isBag) { + BagValue bag = (BagValue) e.value; + out.putInt(bag.parent); + out.putInt(bag.map.size()); + for (Map.Entry entry : bag.map) { + out.putInt(entry.getKey()); + writeValue(entry.getValue(), out); + } + } else { + writeValue((Value) e.value, out); + } + } + } + } + } + } + + private void writeValue(Value value, ByteBuffer out) { + out.putShort((short) 8); + out.put((byte) 0); + out.put((byte) value.type); + if (value.type == ArscParser.TYPE_STRING) { + out.putInt(strTable.get(value.raw).index); + } else { + out.putInt(value.data); + } + } + +} diff --git a/edxp-core/src/main/java/pxb/android/arsc/BagValue.java b/edxp-core/src/main/java/pxb/android/arsc/BagValue.java new file mode 100644 index 00000000..f75ddd08 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/arsc/BagValue.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.arsc; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public class BagValue { + public List> map = new ArrayList>(); + public final int parent; + + public BagValue(int parent) { + this.parent = parent; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof BagValue)) + return false; + BagValue other = (BagValue) obj; + if (map == null) { + if (other.map != null) + return false; + } else if (!map.equals(other.map)) + return false; + if (parent != other.parent) + return false; + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((map == null) ? 0 : map.hashCode()); + result = prime * result + parent; + return result; + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(String.format("{bag%08x", parent)); + for (Map.Entry e : map) { + sb.append(",").append(String.format("0x%08x", e.getKey())); + sb.append("="); + sb.append(e.getValue()); + } + + return sb.append("}").toString(); + } +} diff --git a/edxp-core/src/main/java/pxb/android/arsc/Config.java b/edxp-core/src/main/java/pxb/android/arsc/Config.java new file mode 100644 index 00000000..66ec1048 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/arsc/Config.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.arsc; + +import java.util.Map; +import java.util.TreeMap; + +public class Config { + public final int entryCount; + public final byte[] id; + public Map resources = new TreeMap(); + /* package */int wChunkSize; + /* package */int wEntryStart; + /* package */int wPosition; + + public Config(byte[] id, int entryCount) { + super(); + this.id = id; + this.entryCount = entryCount; + } +} \ No newline at end of file diff --git a/edxp-core/src/main/java/pxb/android/arsc/Pkg.java b/edxp-core/src/main/java/pxb/android/arsc/Pkg.java new file mode 100644 index 00000000..909003cb --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/arsc/Pkg.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.arsc; + +import java.util.TreeMap; + +public class Pkg { + public final int id; + public String name; + public TreeMap types = new TreeMap(); + + public Pkg(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + public Type getType(int tid, String name, int entrySize) { + Type type = types.get(tid); + if (type != null) { + if (name != null) { + if (type.name == null) { + type.name = name; + } else if (!name.endsWith(type.name)) { + throw new RuntimeException(); + } + if (type.specs.length != entrySize) { + throw new RuntimeException(); + } + } + } else { + type = new Type(); + type.id = tid; + type.name = name; + type.specs = new ResSpec[entrySize]; + types.put(tid, type); + } + return type; + } + +} \ No newline at end of file diff --git a/edxp-core/src/main/java/pxb/android/arsc/ResEntry.java b/edxp-core/src/main/java/pxb/android/arsc/ResEntry.java new file mode 100644 index 00000000..bb45007e --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/arsc/ResEntry.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.arsc; + +public class ResEntry { + public final int flag; + + public final ResSpec spec; + /** + * {@link BagValue} or {@link Value} + */ + public Object value; + + /* package */int wOffset; + + public ResEntry(int flag, ResSpec spec) { + super(); + this.flag = flag; + this.spec = spec; + } + +} \ No newline at end of file diff --git a/edxp-core/src/main/java/pxb/android/arsc/ResSpec.java b/edxp-core/src/main/java/pxb/android/arsc/ResSpec.java new file mode 100644 index 00000000..92193a2b --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/arsc/ResSpec.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.arsc; + +public class ResSpec { + public int flags; + public final int id; + public String name; + + public ResSpec(int id) { + super(); + this.id = id; + } + + public void updateName(String s) { + String name = this.name; + if (name == null) { + this.name = s; + } else if (!s.equals(name)) { + throw new RuntimeException(); + } + } +} \ No newline at end of file diff --git a/edxp-core/src/main/java/pxb/android/arsc/Type.java b/edxp-core/src/main/java/pxb/android/arsc/Type.java new file mode 100644 index 00000000..5f35d3d3 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/arsc/Type.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.arsc; + +import java.util.ArrayList; +import java.util.List; + +public class Type { + public List configs = new ArrayList(); + public int id; + public String name; + public ResSpec[] specs; + /* package */int wPosition; + + public void addConfig(Config config) { + if (config.entryCount != specs.length) { + throw new RuntimeException(); + } + configs.add(config); + } + + public ResSpec getSpec(int resId) { + ResSpec res = specs[resId]; + if (res == null) { + res = new ResSpec(resId); + specs[resId] = res; + } + return res; + } + +} \ No newline at end of file diff --git a/edxp-core/src/main/java/pxb/android/arsc/Value.java b/edxp-core/src/main/java/pxb/android/arsc/Value.java new file mode 100644 index 00000000..56f90dba --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/arsc/Value.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.arsc; + +public class Value { + public final int data; + public String raw; + public final int type; + + public Value(int type, int data, String raw) { + super(); + this.type = type; + this.data = data; + this.raw = raw; + } + + public String toString() { + if (type == 0x03) { + return raw; + } + return String.format("{t=0x%02x d=0x%08x}", type, data); + } + +} diff --git a/edxp-core/src/main/java/pxb/android/axml/Axml.java b/edxp-core/src/main/java/pxb/android/axml/Axml.java new file mode 100644 index 00000000..49879f7a --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/axml/Axml.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.axml; + +import java.util.ArrayList; +import java.util.List; + +public class Axml extends AxmlVisitor { + + public static class Node extends NodeVisitor { + public static class Attr { + public String ns, name; + public int resourceId, type; + public Object value; + + public void accept(NodeVisitor nodeVisitor) { + nodeVisitor.attr(ns, name, resourceId, type, value); + } + } + + public static class Text { + public int ln; + public String text; + + public void accept(NodeVisitor nodeVisitor) { + nodeVisitor.text(ln, text); + } + } + + public List attrs = new ArrayList(); + public List children = new ArrayList(); + public Integer ln; + public String ns, name; + public Text text; + + public void accept(NodeVisitor nodeVisitor) { + NodeVisitor nodeVisitor2 = nodeVisitor.child(ns, name); + acceptB(nodeVisitor2); + nodeVisitor2.end(); + } + + public void acceptB(NodeVisitor nodeVisitor) { + if (text != null) { + text.accept(nodeVisitor); + } + for (Attr a : attrs) { + a.accept(nodeVisitor); + } + if (ln != null) { + nodeVisitor.line(ln); + } + for (Node c : children) { + c.accept(nodeVisitor); + } + } + + @Override + public void attr(String ns, String name, int resourceId, int type, Object obj) { + Attr attr = new Attr(); + attr.name = name; + attr.ns = ns; + attr.resourceId = resourceId; + attr.type = type; + attr.value = obj; + attrs.add(attr); + } + + @Override + public NodeVisitor child(String ns, String name) { + Node node = new Node(); + node.name = name; + node.ns = ns; + children.add(node); + return node; + } + + @Override + public void line(int ln) { + this.ln = ln; + } + + @Override + public void text(int lineNumber, String value) { + Text text = new Text(); + text.ln = lineNumber; + text.text = value; + this.text = text; + } + } + + public static class Ns { + public int ln; + public String prefix, uri; + + public void accept(AxmlVisitor visitor) { + visitor.ns(prefix, uri, ln); + } + } + + public List firsts = new ArrayList(); + public List nses = new ArrayList(); + + public void accept(final AxmlVisitor visitor) { + for (Ns ns : nses) { + ns.accept(visitor); + } + for (Node first : firsts) { + first.accept(visitor); + } + } + + @Override + public NodeVisitor child(String ns, String name) { + Node node = new Node(); + node.name = name; + node.ns = ns; + firsts.add(node); + return node; + } + + @Override + public void ns(String prefix, String uri, int ln) { + Ns ns = new Ns(); + ns.prefix = prefix; + ns.uri = uri; + ns.ln = ln; + nses.add(ns); + } +} diff --git a/edxp-core/src/main/java/pxb/android/axml/AxmlParser.java b/edxp-core/src/main/java/pxb/android/axml/AxmlParser.java new file mode 100644 index 00000000..d3802451 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/axml/AxmlParser.java @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.axml; + +import static pxb.android.axml.NodeVisitor.TYPE_INT_BOOLEAN; +import static pxb.android.axml.NodeVisitor.TYPE_STRING; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; + +import pxb.android.ResConst; +import pxb.android.StringItems; + +/** + * a class to read android axml + * + * @author Panxiaobo + */ +public class AxmlParser implements ResConst { + + public static final int END_FILE = 7; + public static final int END_NS = 5; + public static final int END_TAG = 3; + public static final int START_FILE = 1; + public static final int START_NS = 4; + public static final int START_TAG = 2; + public static final int TEXT = 6; + // private int attrName[]; + // private int attrNs[]; + // private int attrResId[]; + // private int attrType[]; + // private Object attrValue[]; + + private int attributeCount; + + private IntBuffer attrs; + + private int classAttribute; + private int fileSize = -1; + private int idAttribute; + private ByteBuffer in; + private int lineNumber; + private int nameIdx; + private int nsIdx; + + private int prefixIdx; + + private int[] resourceIds; + + private String[] strings; + + private int styleAttribute; + + private int textIdx; + + public AxmlParser(byte[] data) { + this(ByteBuffer.wrap(data)); + } + + public AxmlParser(ByteBuffer in) { + super(); + this.in = in.order(ByteOrder.LITTLE_ENDIAN); + } + + public int getAttrCount() { + return attributeCount; + } + + public int getAttributeCount() { + return attributeCount; + } + + public String getAttrName(int i) { + int idx = attrs.get(i * 5 + 1); + return strings[idx]; + + } + + public String getAttrNs(int i) { + int idx = attrs.get(i * 5 + 0); + return idx >= 0 ? strings[idx] : null; + } + + String getAttrRawString(int i) { + int idx = attrs.get(i * 5 + 2); + if (idx >= 0) { + return strings[idx]; + } + return null; + } + + public int getAttrResId(int i) { + if (resourceIds != null) { + int idx = attrs.get(i * 5 + 1); + if (idx >= 0 && idx < resourceIds.length) { + return resourceIds[idx]; + } + } + return -1; + } + + public int getAttrType(int i) { + return attrs.get(i * 5 + 3) >> 24; + } + + public Object getAttrValue(int i) { + int v = attrs.get(i * 5 + 4); + + if (i == idAttribute) { + return ValueWrapper.wrapId(v, getAttrRawString(i)); + } else if (i == styleAttribute) { + return ValueWrapper.wrapStyle(v, getAttrRawString(i)); + } else if (i == classAttribute) { + return ValueWrapper.wrapClass(v, getAttrRawString(i)); + } + + switch (getAttrType(i)) { + case TYPE_STRING: + return strings[v]; + case TYPE_INT_BOOLEAN: + return v != 0; + default: + return v; + } + } + + public int getLineNumber() { + return lineNumber; + } + + public String getName() { + return strings[nameIdx]; + } + + public String getNamespacePrefix() { + return strings[prefixIdx]; + } + + public String getNamespaceUri() { + return nsIdx >= 0 ? strings[nsIdx] : null; + } + + public String getText() { + return strings[textIdx]; + } + + public int next() throws IOException { + if (fileSize < 0) { + int type = in.getInt() & 0xFFFF; + if (type != RES_XML_TYPE) { + throw new RuntimeException(); + } + fileSize = in.getInt(); + return START_FILE; + } + int event = -1; + for (int p = in.position(); p < fileSize; p = in.position()) { + int type = in.getInt() & 0xFFFF; + int size = in.getInt(); + switch (type) { + case RES_XML_START_ELEMENT_TYPE: { + { + lineNumber = in.getInt(); + in.getInt();/* skip, 0xFFFFFFFF */ + nsIdx = in.getInt(); + nameIdx = in.getInt(); + int flag = in.getInt();// 0x00140014 ? + if (flag != 0x00140014) { + throw new RuntimeException(); + } + } + + attributeCount = in.getShort() & 0xFFFF; + idAttribute = (in.getShort() & 0xFFFF) - 1; + classAttribute = (in.getShort() & 0xFFFF) - 1; + styleAttribute = (in.getShort() & 0xFFFF) - 1; + + attrs = in.asIntBuffer(); + + // attrResId = new int[attributeCount]; + // attrName = new int[attributeCount]; + // attrNs = new int[attributeCount]; + // attrType = new int[attributeCount]; + // attrValue = new Object[attributeCount]; + // for (int i = 0; i < attributeCount; i++) { + // int attrNsIdx = in.getInt(); + // int attrNameIdx = in.getInt(); + // int raw = in.getInt(); + // int aValueType = in.getInt() >>> 24; + // int aValue = in.getInt(); + // Object value = null; + // switch (aValueType) { + // case TYPE_STRING: + // value = strings[aValue]; + // break; + // case TYPE_INT_BOOLEAN: + // value = aValue != 0; + // break; + // default: + // value = aValue; + // } + // int resourceId = attrNameIdx < this.resourceIds.length ? + // resourceIds[attrNameIdx] : -1; + // attrNs[i] = attrNsIdx; + // attrName[i] = attrNameIdx; + // attrType[i] = aValueType; + // attrResId[i] = resourceId; + // attrValue[i] = value; + // } + event = START_TAG; + } + break; + case RES_XML_END_ELEMENT_TYPE: { + in.position(p + size); + event = END_TAG; + } + break; + case RES_XML_START_NAMESPACE_TYPE: + lineNumber = in.getInt(); + in.getInt();/* 0xFFFFFFFF */ + prefixIdx = in.getInt(); + nsIdx = in.getInt(); + event = START_NS; + break; + case RES_XML_END_NAMESPACE_TYPE: + in.position(p + size); + event = END_NS; + break; + case RES_STRING_POOL_TYPE: + strings = StringItems.read(in); + in.position(p + size); + continue; + case RES_XML_RESOURCE_MAP_TYPE: + int count = size / 4 - 2; + resourceIds = new int[count]; + for (int i = 0; i < count; i++) { + resourceIds[i] = in.getInt(); + } + in.position(p + size); + continue; + case RES_XML_CDATA_TYPE: + lineNumber = in.getInt(); + in.getInt();/* 0xFFFFFFFF */ + textIdx = in.getInt(); + + in.getInt();/* 00000008 00000000 */ + in.getInt(); + + event = TEXT; + break; + default: + throw new RuntimeException("Unsupported type: " + type); + } + in.position(p + size); + return event; + } + return END_FILE; + } +} diff --git a/edxp-core/src/main/java/pxb/android/axml/AxmlReader.java b/edxp-core/src/main/java/pxb/android/axml/AxmlReader.java new file mode 100644 index 00000000..11c17613 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/axml/AxmlReader.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.axml; + +import static pxb.android.axml.AxmlParser.END_FILE; +import static pxb.android.axml.AxmlParser.END_NS; +import static pxb.android.axml.AxmlParser.END_TAG; +import static pxb.android.axml.AxmlParser.START_FILE; +import static pxb.android.axml.AxmlParser.START_NS; +import static pxb.android.axml.AxmlParser.START_TAG; +import static pxb.android.axml.AxmlParser.TEXT; + +import java.io.IOException; +import java.util.Stack; + +import de.robv.android.xposed.XposedBridge; + +/** + * a class to read android axml + * + * @author Panxiaobo + */ +public class AxmlReader { + public static final NodeVisitor EMPTY_VISITOR = new NodeVisitor() { + + @Override + public NodeVisitor child(String ns, String name) { + return this; + } + + }; + final AxmlParser parser; + + public AxmlReader(byte[] data) { + super(); + this.parser = new AxmlParser(data); + } + + public void accept(final AxmlVisitor av) throws IOException { + Stack nvs = new Stack(); + NodeVisitor tos = av; + while (true) { + int type = parser.next(); + switch (type) { + case START_FILE: + break; + case START_TAG: + nvs.push(tos); + tos = tos.child(parser.getNamespaceUri(), parser.getName()); + if (tos != null) { + if (tos != EMPTY_VISITOR) { + tos.line(parser.getLineNumber()); + for (int i = 0; i < parser.getAttrCount(); i++) { + tos.attr(parser.getAttrNs(i), parser.getAttrName(i), parser.getAttrResId(i), + parser.getAttrType(i), parser.getAttrValue(i)); + } + } + } else { + tos = EMPTY_VISITOR; + } + break; + case END_TAG: + tos.end(); + tos = nvs.pop(); + break; + case START_NS: + av.ns(parser.getNamespacePrefix(), parser.getNamespaceUri(), parser.getLineNumber()); + break; + case END_NS: + break; + case TEXT: + tos.text(parser.getLineNumber(), parser.getText()); + break; + case END_FILE: + return; + default: + XposedBridge.log("Unsupported tag: " + type); + } + } + } +} diff --git a/edxp-core/src/main/java/pxb/android/axml/AxmlVisitor.java b/edxp-core/src/main/java/pxb/android/axml/AxmlVisitor.java new file mode 100644 index 00000000..3856d9d7 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/axml/AxmlVisitor.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.axml; + +/** + * visitor to visit an axml + * + * @author Panxiaobo + */ +public class AxmlVisitor extends NodeVisitor { + + public AxmlVisitor() { + super(); + + } + + public AxmlVisitor(NodeVisitor av) { + super(av); + } + + /** + * create a ns + * + * @param prefix + * @param uri + * @param ln + */ + public void ns(String prefix, String uri, int ln) { + if (nv != null && nv instanceof AxmlVisitor) { + ((AxmlVisitor) nv).ns(prefix, uri, ln); + } + } + +} diff --git a/edxp-core/src/main/java/pxb/android/axml/AxmlWriter.java b/edxp-core/src/main/java/pxb/android/axml/AxmlWriter.java new file mode 100644 index 00000000..d5daeedf --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/axml/AxmlWriter.java @@ -0,0 +1,442 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.axml; + +import static pxb.android.ResConst.RES_STRING_POOL_TYPE; +import static pxb.android.ResConst.RES_XML_CDATA_TYPE; +import static pxb.android.ResConst.RES_XML_END_ELEMENT_TYPE; +import static pxb.android.ResConst.RES_XML_END_NAMESPACE_TYPE; +import static pxb.android.ResConst.RES_XML_RESOURCE_MAP_TYPE; +import static pxb.android.ResConst.RES_XML_START_ELEMENT_TYPE; +import static pxb.android.ResConst.RES_XML_START_NAMESPACE_TYPE; +import static pxb.android.ResConst.RES_XML_TYPE; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Stack; +import java.util.TreeSet; + +import pxb.android.StringItem; +import pxb.android.StringItems; + +/** + * a class to write android axml + * + * @author Panxiaobo + */ +public class AxmlWriter extends AxmlVisitor { + static final Comparator ATTR_CMP = new Comparator() { + + @Override + public int compare(Attr a, Attr b) { + int x = a.resourceId - b.resourceId; + if (x == 0) { + x = a.name.data.compareTo(b.name.data); + if (x == 0) { + boolean aNsIsnull = a.ns == null; + boolean bNsIsnull = b.ns == null; + if (aNsIsnull) { + if (bNsIsnull) { + x = 0; + } else { + x = -1; + } + } else { + if (bNsIsnull) { + x = 1; + } else { + x = a.ns.data.compareTo(b.ns.data); + } + } + + } + } + return x; + } + }; + + static class Attr { + + public int index; + public StringItem name; + public StringItem ns; + public int resourceId; + public int type; + public Object value; + public StringItem raw; + + public Attr(StringItem ns, StringItem name, int resourceId) { + super(); + this.ns = ns; + this.name = name; + this.resourceId = resourceId; + } + + public void prepare(AxmlWriter axmlWriter) { + ns = axmlWriter.updateNs(ns); + if (this.name != null) { + if (resourceId != -1) { + this.name = axmlWriter.updateWithResourceId(this.name, this.resourceId); + } else { + this.name = axmlWriter.update(this.name); + } + } + if (value instanceof StringItem) { + value = axmlWriter.update((StringItem) value); + } + if (raw != null) { + raw = axmlWriter.update(raw); + } + } + + } + + static class NodeImpl extends NodeVisitor { + private Set attrs = new TreeSet(ATTR_CMP); + private List children = new ArrayList(); + private int line; + private StringItem name; + private StringItem ns; + private StringItem text; + private int textLineNumber; + Attr id; + Attr style; + Attr clz; + + public NodeImpl(String ns, String name) { + super(null); + this.ns = ns == null ? null : new StringItem(ns); + this.name = name == null ? null : new StringItem(name); + } + + @Override + public void attr(String ns, String name, int resourceId, int type, Object value) { + if (name == null) { + throw new RuntimeException("name can't be null"); + } + Attr a = new Attr(ns == null ? null : new StringItem(ns), new StringItem(name), resourceId); + a.type = type; + + if (value instanceof ValueWrapper) { + ValueWrapper valueWrapper = (ValueWrapper) value; + if (valueWrapper.raw != null) { + a.raw = new StringItem(valueWrapper.raw); + } + a.value = valueWrapper.ref; + switch (valueWrapper.type) { + case ValueWrapper.CLASS: + clz = a; + break; + case ValueWrapper.ID: + id = a; + break; + case ValueWrapper.STYLE: + style = a; + break; + } + } else if (type == TYPE_STRING) { + StringItem raw = new StringItem((String) value); + a.raw = raw; + a.value = raw; + + } else { + a.raw = null; + a.value = value; + } + + attrs.add(a); + } + + @Override + public NodeVisitor child(String ns, String name) { + NodeImpl child = new NodeImpl(ns, name); + this.children.add(child); + return child; + } + + @Override + public void end() { + } + + @Override + public void line(int ln) { + this.line = ln; + } + + public int prepare(AxmlWriter axmlWriter) { + ns = axmlWriter.updateNs(ns); + name = axmlWriter.update(name); + + int attrIndex = 0; + for (Attr attr : attrs) { + attr.index = attrIndex++; + attr.prepare(axmlWriter); + } + + text = axmlWriter.update(text); + int size = 24 + 36 + attrs.size() * 20;// 24 for end tag,36+x*20 for + // start tag + for (NodeImpl child : children) { + size += child.prepare(axmlWriter); + } + if (text != null) { + size += 28; + } + return size; + } + + @Override + public void text(int ln, String value) { + this.text = new StringItem(value); + this.textLineNumber = ln; + } + + void write(ByteBuffer out) throws IOException { + // start tag + out.putInt(RES_XML_START_ELEMENT_TYPE | (0x0010 << 16)); + out.putInt(36 + attrs.size() * 20); + out.putInt(line); + out.putInt(0xFFFFFFFF); + out.putInt(ns != null ? this.ns.index : -1); + out.putInt(name.index); + out.putInt(0x00140014);// TODO + out.putShort((short) this.attrs.size()); + out.putShort((short) (id == null ? 0 : id.index + 1)); + out.putShort((short) (clz == null ? 0 : clz.index + 1)); + out.putShort((short) (style == null ? 0 : style.index + 1)); + for (Attr attr : attrs) { + out.putInt(attr.ns == null ? -1 : attr.ns.index); + out.putInt(attr.name.index); + out.putInt(attr.raw != null ? attr.raw.index : -1); + out.putInt((attr.type << 24) | 0x000008); + Object v = attr.value; + if (v instanceof StringItem) { + out.putInt(((StringItem) attr.value).index); + } else if (v instanceof Boolean) { + out.putInt(Boolean.TRUE.equals(v) ? -1 : 0); + } else if (v instanceof Float) { + out.putInt(Float.floatToIntBits((float) v)); + } else { + out.putInt((Integer) attr.value); + } + } + + if (this.text != null) { + out.putInt(RES_XML_CDATA_TYPE | (0x0010 << 16)); + out.putInt(28); + out.putInt(textLineNumber); + out.putInt(0xFFFFFFFF); + out.putInt(text.index); + out.putInt(0x00000008); + out.putInt(0x00000000); + } + + // children + for (NodeImpl child : children) { + child.write(out); + } + + // end tag + out.putInt(RES_XML_END_ELEMENT_TYPE | (0x0010 << 16)); + out.putInt(24); + out.putInt(-1); + out.putInt(0xFFFFFFFF); + out.putInt(ns != null ? this.ns.index : -1); + out.putInt(name.index); + } + } + + static class Ns { + int ln; + StringItem prefix; + StringItem uri; + + public Ns(StringItem prefix, StringItem uri, int ln) { + super(); + this.prefix = prefix; + this.uri = uri; + this.ln = ln; + } + } + + private List firsts = new ArrayList(3); + + private Map nses = new HashMap(); + + private List otherString = new ArrayList(); + + private Map resourceId2Str = new HashMap(); + + private List resourceIds = new ArrayList(); + + private List resourceString = new ArrayList(); + + private StringItems stringItems = new StringItems(); + + // TODO add style support + // private List styleItems = new ArrayList(); + + @Override + public NodeVisitor child(String ns, String name) { + NodeImpl first = new NodeImpl(ns, name); + this.firsts.add(first); + return first; + } + + @Override + public void end() { + } + + @Override + public void ns(String prefix, String uri, int ln) { + nses.put(uri, new Ns(prefix == null ? null : new StringItem(prefix), new StringItem(uri), ln)); + } + + private int prepare() throws IOException { + int size = 0; + + for (NodeImpl first : firsts) { + size += first.prepare(this); + } + { + int a = 0; + for (Map.Entry e : nses.entrySet()) { + Ns ns = e.getValue(); + if (ns == null) { + ns = new Ns(null, new StringItem(e.getKey()), 0); + e.setValue(ns); + } + if (ns.prefix == null) { + ns.prefix = new StringItem(String.format("axml_auto_%02d", a++)); + } + ns.prefix = update(ns.prefix); + ns.uri = update(ns.uri); + } + } + + size += nses.size() * 24 * 2; + + this.stringItems.addAll(resourceString); + resourceString = null; + this.stringItems.addAll(otherString); + otherString = null; + this.stringItems.prepare(); + int stringSize = this.stringItems.getSize(); + if (stringSize % 4 != 0) { + stringSize += 4 - stringSize % 4; + } + size += 8 + stringSize; + size += 8 + resourceIds.size() * 4; + return size; + } + + public byte[] toByteArray() throws IOException { + + int size = 8 + prepare(); + ByteBuffer out = ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN); + + out.putInt(RES_XML_TYPE | (0x0008 << 16)); + out.putInt(size); + + int stringSize = this.stringItems.getSize(); + int padding = 0; + if (stringSize % 4 != 0) { + padding = 4 - stringSize % 4; + } + out.putInt(RES_STRING_POOL_TYPE | (0x001C << 16)); + out.putInt(stringSize + padding + 8); + this.stringItems.write(out); + out.put(new byte[padding]); + + out.putInt(RES_XML_RESOURCE_MAP_TYPE | (0x0008 << 16)); + out.putInt(8 + this.resourceIds.size() * 4); + for (Integer i : resourceIds) { + out.putInt(i); + } + + Stack stack = new Stack(); + for (Map.Entry e : this.nses.entrySet()) { + Ns ns = e.getValue(); + stack.push(ns); + out.putInt(RES_XML_START_NAMESPACE_TYPE | (0x0010 << 16)); + out.putInt(24); + out.putInt(-1); + out.putInt(0xFFFFFFFF); + out.putInt(ns.prefix.index); + out.putInt(ns.uri.index); + } + + for (NodeImpl first : firsts) { + first.write(out); + } + + while (stack.size() > 0) { + Ns ns = stack.pop(); + out.putInt(RES_XML_END_NAMESPACE_TYPE | (0x0010 << 16)); + out.putInt(24); + out.putInt(ns.ln); + out.putInt(0xFFFFFFFF); + out.putInt(ns.prefix.index); + out.putInt(ns.uri.index); + } + return out.array(); + } + + StringItem update(StringItem item) { + if (item == null) + return null; + int i = this.otherString.indexOf(item); + if (i < 0) { + StringItem copy = new StringItem(item.data); + this.otherString.add(copy); + return copy; + } else { + return this.otherString.get(i); + } + } + + StringItem updateNs(StringItem item) { + if (item == null) { + return null; + } + String ns = item.data; + if (!this.nses.containsKey(ns)) { + this.nses.put(ns, null); + } + return update(item); + } + + StringItem updateWithResourceId(StringItem name, int resourceId) { + String key = name.data + resourceId; + StringItem item = this.resourceId2Str.get(key); + if (item != null) { + return item; + } else { + StringItem copy = new StringItem(name.data); + resourceIds.add(resourceId); + resourceString.add(copy); + resourceId2Str.put(key, copy); + return copy; + } + } +} diff --git a/edxp-core/src/main/java/pxb/android/axml/DumpAdapter.java b/edxp-core/src/main/java/pxb/android/axml/DumpAdapter.java new file mode 100644 index 00000000..b68fee2e --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/axml/DumpAdapter.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.axml; + +import java.util.HashMap; +import java.util.Map; + +/** + * dump axml to stdout + * + * @author Panxiaobo + */ +public class DumpAdapter extends AxmlVisitor { + protected int deep; + protected Map nses; + + public DumpAdapter() { + this(null); + } + + public DumpAdapter(NodeVisitor nv) { + this(nv, 0, new HashMap()); + } + + public DumpAdapter(NodeVisitor nv, int x, Map nses) { + super(nv); + this.deep = x; + this.nses = nses; + } + + @Override + public void attr(String ns, String name, int resourceId, int type, Object obj) { + for (int i = 0; i < deep; i++) { + System.out.print(" "); + } + if (ns != null) { + System.out.print(String.format("%s:", getPrefix(ns))); + } + System.out.print(name); + if (resourceId != -1) { + System.out.print(String.format("(%08x)", resourceId)); + } + if (obj instanceof String) { + System.out.print(String.format("=[%08x]\"%s\"", type, obj)); + } else if (obj instanceof Boolean) { + System.out.print(String.format("=[%08x]\"%b\"", type, obj)); + } else if (obj instanceof ValueWrapper) { + ValueWrapper w = (ValueWrapper) obj; + System.out.print(String.format("=[%08x]@%08x, raw: \"%s\"", type, w.ref, w.raw)); + } else if (type == TYPE_REFERENCE) { + System.out.print(String.format("=[%08x]@%08x", type, obj)); + } else { + System.out.print(String.format("=[%08x]%08x", type, obj)); + } + System.out.println(); + super.attr(ns, name, resourceId, type, obj); + } + + @Override + public NodeVisitor child(String ns, String name) { + for (int i = 0; i < deep; i++) { + System.out.print(" "); + } + System.out.print("<"); + if (ns != null) { + System.out.print(getPrefix(ns) + ":"); + } + System.out.println(name); + NodeVisitor nv = super.child(ns, name); + if (nv != null) { + return new DumpAdapter(nv, deep + 1, nses); + } + return null; + } + + protected String getPrefix(String uri) { + if (nses != null) { + String prefix = nses.get(uri); + if (prefix != null) { + return prefix; + } + } + return uri; + } + + @Override + public void ns(String prefix, String uri, int ln) { + System.out.println(prefix + "=" + uri); + this.nses.put(uri, prefix); + super.ns(prefix, uri, ln); + } + + @Override + public void text(int ln, String value) { + for (int i = 0; i < deep + 1; i++) { + System.out.print(" "); + } + System.out.print("T: "); + System.out.println(value); + super.text(ln, value); + } + +} diff --git a/edxp-core/src/main/java/pxb/android/axml/NodeVisitor.java b/edxp-core/src/main/java/pxb/android/axml/NodeVisitor.java new file mode 100644 index 00000000..fe6179bc --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/axml/NodeVisitor.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.axml; + +public abstract class NodeVisitor { + + public static final int TYPE_FIRST_INT = 0x10; + public static final int TYPE_INT_BOOLEAN = 0x12; + public static final int TYPE_INT_HEX = 0x11; + public static final int TYPE_REFERENCE = 0x01; + public static final int TYPE_STRING = 0x03; + protected NodeVisitor nv; + + public NodeVisitor() { + super(); + } + + public NodeVisitor(NodeVisitor nv) { + super(); + this.nv = nv; + } + + /** + * add attribute to the node + * + * @param ns + * @param name + * @param resourceId + * @param type + * {@link #TYPE_STRING} or others + * @param obj + * a string for {@link #TYPE_STRING} ,and Integer for others + */ + public void attr(String ns, String name, int resourceId, int type, Object obj) { + if (nv != null) { + nv.attr(ns, name, resourceId, type, obj); + } + } + + /** + * create a child node + * + * @param ns + * @param name + * @return + */ + public NodeVisitor child(String ns, String name) { + if (nv != null) { + return nv.child(ns, name); + } + return null; + } + + /** + * end the visit + */ + public void end() { + if (nv != null) { + nv.end(); + } + } + + /** + * line number in the .xml + * + * @param ln + */ + public void line(int ln) { + if (nv != null) { + nv.line(ln); + } + } + + /** + * the node text + * + * @param value + */ + public void text(int lineNumber, String value) { + if (nv != null) { + nv.text(lineNumber, value); + } + } +} diff --git a/edxp-core/src/main/java/pxb/android/axml/Util.java b/edxp-core/src/main/java/pxb/android/axml/Util.java new file mode 100644 index 00000000..992f39d5 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/axml/Util.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2009-2013 Panxiaobo + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pxb.android.axml; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.util.HashMap; +import java.util.Map; + +public class Util { + public static byte[] readFile(File in) throws IOException { + InputStream is = new FileInputStream(in); + byte[] xml = new byte[is.available()]; + is.read(xml); + is.close(); + return xml; + } + + public static byte[] readIs(InputStream is) throws IOException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + copy(is, os); + return os.toByteArray(); + } + + public static void writeFile(byte[] data, File out) throws IOException { + FileOutputStream fos = new FileOutputStream(out); + fos.write(data); + fos.close(); + } + + public static Map readProguardConfig(File config) throws IOException { + Map clzMap = new HashMap(); + BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(config), "utf8")); + try { + for (String ln = r.readLine(); ln != null; ln = r.readLine()) { + if (ln.startsWith("#") || ln.startsWith(" ")) { + continue; + } + // format a.pt.Main -> a.a.a: + int i = ln.indexOf("->"); + if (i > 0) { + clzMap.put(ln.substring(0, i).trim(), ln.substring(i + 2, ln.length() - 1).trim()); + } + } + } finally { + r.close(); + } + return clzMap; + } + + public static void copy(InputStream is, OutputStream os) throws IOException { + byte[] xml = new byte[10 * 1024]; + for (int c = is.read(xml); c > 0; c = is.read(xml)) { + os.write(xml, 0, c); + } + } + +} diff --git a/edxp-core/src/main/java/pxb/android/axml/ValueWrapper.java b/edxp-core/src/main/java/pxb/android/axml/ValueWrapper.java new file mode 100644 index 00000000..c9da562b --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/axml/ValueWrapper.java @@ -0,0 +1,34 @@ +package pxb.android.axml; + +public class ValueWrapper { + + public static final int ID = 1; + public static final int STYLE = 2; + public static final int CLASS = 3; + public final int type; + public final String raw; + public final int ref; + + private ValueWrapper(int type, int ref, String raw) { + super(); + this.type = type; + this.raw = raw; + this.ref = ref; + } + + public ValueWrapper replaceRaw(String raw) { + return new ValueWrapper(type, ref, raw); + } + + public static ValueWrapper wrapId(int ref, String raw) { + return new ValueWrapper(ID, ref, raw); + } + + public static ValueWrapper wrapStyle(int ref, String raw) { + return new ValueWrapper(STYLE, ref, raw); + } + + public static ValueWrapper wrapClass(int ref, String raw) { + return new ValueWrapper(CLASS, ref, raw); + } +} diff --git a/edxp-core/src/main/java/pxb/android/package.html b/edxp-core/src/main/java/pxb/android/package.html new file mode 100644 index 00000000..ede50bf2 --- /dev/null +++ b/edxp-core/src/main/java/pxb/android/package.html @@ -0,0 +1,2 @@ +

Source code of axml project.

+

Revision 2394d02d86bb - Apr 22, 2014

\ No newline at end of file diff --git a/edxp-core/template_override/customize.sh b/edxp-core/template_override/customize.sh index dd347f93..817e3c58 100644 --- a/edxp-core/template_override/customize.sh +++ b/edxp-core/template_override/customize.sh @@ -143,9 +143,6 @@ extract "${ZIPFILE}" 'sepolicy.rule' "${MODPATH}" extract "${ZIPFILE}" 'post-fs-data.sh' "${MODPATH}" extract "${ZIPFILE}" 'uninstall.sh' "${MODPATH}" -extract "${ZIPFILE}" 'system/framework/eddalvikdx.dex' "${MODPATH}" -extract "${ZIPFILE}" 'system/framework/eddexmaker.dex' "${MODPATH}" -extract "${ZIPFILE}" 'system/framework/edservice.dex' "${MODPATH}" extract "${ZIPFILE}" 'system/framework/edxp.dex' "${MODPATH}" if [ "$ARCH" = "x86" ] || [ "$ARCH" = "x64" ]; then diff --git a/edxp-core/template_override/verify.sh b/edxp-core/template_override/verify.sh index b99291d4..f3c8b97b 100644 --- a/edxp-core/template_override/verify.sh +++ b/edxp-core/template_override/verify.sh @@ -22,10 +22,10 @@ extract() { hash_path="" if [ $junk_paths = true ]; then file_path="$dir/$(basename "$file")" - hash_path="$TMPDIR_FOR_VERIFY/$(basename "$file").s" + hash_path="$TMPDIR_FOR_VERIFY/$(basename "$file").sha256" else file_path="$dir/$file" - hash_path="$TMPDIR_FOR_VERIFY/$file.s" + hash_path="$TMPDIR_FOR_VERIFY/$file.sha256" fi unzip $opts "$zip" "$file" -d "$dir" >&2 diff --git a/edxp-core/tpl/edconfig.tpl b/edxp-core/tpl/edconfig.tpl index e61bd7b3..1f717293 100644 --- a/edxp-core/tpl/edconfig.tpl +++ b/edxp-core/tpl/edconfig.tpl @@ -1,4 +1,4 @@ -version=$apiCode-$version ($backend) +version=$apiCode-$version arch=arm64 minsdk=26 maxsdk=30 diff --git a/edxp-core/tpl/module.prop.tpl b/edxp-core/tpl/module.prop.tpl index 32f415e9..42f0a305 100644 --- a/edxp-core/tpl/module.prop.tpl +++ b/edxp-core/tpl/module.prop.tpl @@ -1,8 +1,8 @@ id=${moduleId} -name=Riru - EdXposed +name=Riru - Lsposed version=${versionName} versionCode=${versionCode} author=${authorList} api=${apiCode} -description=Another enhanced implementation of Xposed Framework. Supports Android 8.0, 8.1, 9, 10, 11 or above. Requires Riru v23 or above installed. Telegram: @EdXposed +description=Another enhanced implementation of Xposed Framework. Supports Android 8.0, 8.1, 9, 10, 11 or above. Requires Riru v23 or above installed. minApi=${minApi} \ No newline at end of file diff --git a/edxp-sandhook/.gitignore b/edxp-sandhook/.gitignore deleted file mode 100644 index 3a66a198..00000000 --- a/edxp-sandhook/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build -/template_override/system/framework \ No newline at end of file diff --git a/edxp-sandhook/build.gradle b/edxp-sandhook/build.gradle deleted file mode 100644 index 2dffc4d5..00000000 --- a/edxp-sandhook/build.gradle +++ /dev/null @@ -1,81 +0,0 @@ -apply plugin: 'com.android.application' - -sourceCompatibility = "7" -targetCompatibility = "7" - -android { - compileSdkVersion androidCompileSdkVersion.toInteger() - - defaultConfig { - applicationId "com.elderdrivers.riru.edxp.sandhook" - minSdkVersion androidMinSdkVersion.toInteger() - targetSdkVersion androidTargetSdkVersion.toInteger() - versionCode 1 - versionName "1.0" - multiDexEnabled false - } - - buildTypes { - release { - minifyEnabled true - proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' - } - } - - ndkVersion androidCompileNdkVersion -} - -dependencies { - compileOnly project(':hiddenapi-stubs') - implementation project(':edxp-common') - implementation project(':sandhook-hooklib') - compileOnly files(project(":dexmaker").tasks.getByName("makeJarRelease").outputs) -} - - -preBuild.doLast { - def imlFile = file(project.name + ".iml") - try { - def parsedXml = (new groovy.util.XmlParser()).parse(imlFile) - def jdkNode = parsedXml.component[1].orderEntry.find { it.'@type' == 'jdk' } - parsedXml.component[1].remove(jdkNode) - def sdkString = "Android API " + android.compileSdkVersion.substring("android-".length()) + " Platform" - new groovy.util.Node(parsedXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': sdkString, 'jdkType': 'Android SDK']) - groovy.xml.XmlUtil.serialize(parsedXml, new FileOutputStream(imlFile)) - } catch (FileNotFoundException e) { - // nop, iml not found - } -} - -afterEvaluate { - - tasks.withType(JavaCompile) { - options.compilerArgs.add("-Xbootclasspath/p:${hiddenApiStubJarFilePath}") - } - - android.applicationVariants.all { variant -> - - def variantNameCapped = variant.name.capitalize() - def variantNameLowered = variant.name.toLowerCase() - def myTemplatePath = "${projectDir}/template_override/" - - task("copyDex${variantNameCapped}", type: Copy) { - dependsOn "assemble${variantNameCapped}" - dependsOn tasks.getByPath(":edxp-common:copyCommonProperties") - dependsOn tasks.getByPath(":sandhook-hooklib:copySandHook${variantNameCapped}LibraryToMagiskTemplate") - def dexOutPath = variant.name.contains("release") ? - "${buildDir}/intermediates/dex/${variantNameLowered}/minify${variantNameCapped}WithR8" : - "${buildDir}/intermediates/dex/${variantNameLowered}/mergeDex${variantNameCapped}" - from(dexOutPath) { - rename "classes.dex", "edxp.dex" - } - destinationDir file(zipPathMagiskReleasePath + "system/framework/") - doLast { - copy { - from file(myTemplatePath) - into file(zipPathMagiskReleasePath) - } - } - } - } -} \ No newline at end of file diff --git a/edxp-sandhook/genhookstubs.py b/edxp-sandhook/genhookstubs.py deleted file mode 100644 index f3cd9b7a..00000000 --- a/edxp-sandhook/genhookstubs.py +++ /dev/null @@ -1,196 +0,0 @@ -#!/usr/bin/python - -import os - -STUB_FILE_NAME = "MethodHookerStubs" - -TEMP_STUB_CLASS_WRAPPER = """package com.swift.sandhook.xposedcompat.hookstub; - -import static com.swift.sandhook.xposedcompat.hookstub.HookStubManager.hookBridge; -import static com.swift.sandhook.xposedcompat.hookstub.HookStubManager.getMethodId; -import static com.swift.sandhook.xposedcompat.hookstub.HookStubManager.originMethods; -import static com.swift.sandhook.xposedcompat.utils.DexLog.printCallOriginError; - -/** -* this file is auto gen by genhookstubs.py -* it is for sandhook internal hooker & backup methods -**/ -public class MethodHookerStubs%d { -%s -} -""" - -TEMP_STUB_HOOK_METHOD_NAME = """stub_hook_%d""" -TEMP_STUB_HOOK_BACKUP_NAME = """stub_backup_%d""" -TEMP_STUB_CALL_ORIGIN_NAME = """call_origin_%d_%d""" - -TEMP_STUB_GET_METHOD_ID_NAME = """getMethodId(%d, %d)""" - -JAVA_TYPE_INT = "int" -JAVA_CAST_INT = "(int)" -JAVA_TYPE_LONG = "long" - -TEMP_STUB_HOOK_METHOD = """ - public static %s %s(%s) throws Throwable { - return %s hookBridge(%s, %s %s); - } -""" - -TEMP_STUB_BACKUP_METHOD = """ - public static %s %s(%s) throws Throwable { - try { - printCallOriginError(originMethods[%s]); - } catch (Throwable throwable) {} - return 0; - } -""" - -TEMP_STUB_CALL_ORIGIN_CLASS = """ - static class %s implements CallOriginCallBack { - @Override - public long call(long... args) throws Throwable { - return %s(%s); - } - } -""" - -TEMP_STUB_INFO = """ - public static boolean hasStubBackup = %s; - public static int[] stubSizes = {%s}; -""" - - -STUB_SIZES_32 = [10,20,30,30,30,30,30,20,10,10,5,5,3] -STUB_SIZES_64 = [10,20,30,30,30,30,50,50] -HAS_BACKUP = False - - -def getMethodId(args, index): - return TEMP_STUB_GET_METHOD_ID_NAME % (args, index) - -def getMethodHookName(index): - return TEMP_STUB_HOOK_METHOD_NAME % index - -def getMethodBackupName(index): - return TEMP_STUB_HOOK_BACKUP_NAME % index - -def getCallOriginClassName(args, index): - return TEMP_STUB_CALL_ORIGIN_NAME % (args, index) - - -def genArgsList(is64Bit, isDefine, length): - args_list = "" - for i in range(length): - if (i != 0): - args_list += ", " - if isDefine: - if (is64Bit): - args_list += (JAVA_TYPE_LONG + " " + "a" + str(i)) - else: - args_list += (JAVA_TYPE_INT + " " + "a" + str(i)) - else: - args_list += ("a" + str(i)) - return args_list - - -def genArgsListForCallOriginMethod(is64Bit, length): - arg_name = """args[%s]""" - args_list = "" - for i in range(length): - if (i != 0): - args_list += ", " - if (is64Bit): - args_list += arg_name % i - else: - args_list += (JAVA_CAST_INT + arg_name % i) - return args_list - - -def genHookMethod(is64Bit, args, index): - java_type = JAVA_TYPE_LONG if is64Bit else JAVA_TYPE_INT - cast = "" if is64Bit else JAVA_CAST_INT - args_list_pre = ", " if args > 0 else "" - args_list = genArgsList(is64Bit, False, args) - args_list_def = genArgsList(is64Bit, True, args) - call_origin_obj = ("new " + getCallOriginClassName(args, index) + "()") if HAS_BACKUP else "null" - method = TEMP_STUB_HOOK_METHOD % (java_type, getMethodHookName(index), args_list_def, cast, getMethodId(args, index), call_origin_obj, args_list_pre + args_list) - return method - - -def genBackupMethod(is64Bit, args, index): - java_type = JAVA_TYPE_LONG if is64Bit else JAVA_TYPE_INT - args_list_def = genArgsList(is64Bit, True, args) - method = TEMP_STUB_BACKUP_METHOD % (java_type, getMethodBackupName(index), args_list_def, getMethodId(args, index)) - return method - -def genCallOriginClass(is64Bit, args, index): - method = TEMP_STUB_CALL_ORIGIN_CLASS % (getCallOriginClassName(args, index), getMethodBackupName(index), genArgsListForCallOriginMethod(is64Bit, args)) - return method - -def genStubInfo32(): - hasStub = "true" if HAS_BACKUP else "false" - stubSizes = "" - for args in range(len(STUB_SIZES_32)): - if (args != 0): - stubSizes += ", " - stubSizes += str(STUB_SIZES_32[args]) - return TEMP_STUB_INFO % (hasStub, stubSizes) - -def genStubInfo64(): - hasStub = "true" if HAS_BACKUP else "false" - stubSizes = "" - for args in range(len(STUB_SIZES_64)): - if (args != 0): - stubSizes += ", " - stubSizes += str(STUB_SIZES_64[args]) - return TEMP_STUB_INFO % (hasStub, stubSizes) - -def gen32Stub(packageDir): - class_content = genStubInfo32() - class_name = STUB_FILE_NAME + "32" - for args in range(len(STUB_SIZES_32)): - for index in range(STUB_SIZES_32[args]): - class_content += """\n\n\t//stub of arg size %d, index %d""" % (args, index) - class_content += genHookMethod(False, args, index) - if HAS_BACKUP: - class_content += "\n" - class_content += genCallOriginClass(False, args, index) - class_content += "\n" - class_content += genBackupMethod(False, args, index) - class_content += "\n" - class_str = TEMP_STUB_CLASS_WRAPPER % (32, class_content) - javaFile = open(os.path.join(packageDir, class_name + ".java"), "w") - javaFile.write(class_str) - javaFile.close() - - -def gen64Stub(packageDir): - class_content = genStubInfo64() - class_name = STUB_FILE_NAME + "64" - for args in range(len(STUB_SIZES_64)): - for index in range(STUB_SIZES_64[args]): - class_content += """\n\n\t//stub of arg size %d, index %d""" % (args, index) - class_content += genHookMethod(True, args, index) - if HAS_BACKUP: - class_content += "\n" - class_content += genCallOriginClass(True, args, index) - class_content += "\n" - class_content += genBackupMethod(True, args, index) - class_content += "\n" - class_str = TEMP_STUB_CLASS_WRAPPER % (64, class_content) - javaFile = open(os.path.join(packageDir, class_name + ".java"), "w") - javaFile.write(class_str) - javaFile.close() - - -def genStub(packageDir): - for fileName in os.listdir(packageDir): - if fileName.startswith(STUB_FILE_NAME): - os.remove(os.path.join(packageDir, fileName)) - gen32Stub(packageDir) - gen64Stub(packageDir) - - -if __name__ == "__main__": - genStub(os.path.join(os.path.dirname(os.path.realpath(__file__)), - "src/main/java/com/swift/sandhook/xposedcompat/hookstub")) diff --git a/edxp-sandhook/proguard-rules.pro b/edxp-sandhook/proguard-rules.pro deleted file mode 100644 index 45557ede..00000000 --- a/edxp-sandhook/proguard-rules.pro +++ /dev/null @@ -1,38 +0,0 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile - --dontoptimize --dontobfuscate --keep class de.robv.android.xposed.** {*;} --keep class android.** { *; } - --keep interface com.elderdrivers.riru.common.KeepAll --keep interface com.elderdrivers.riru.common.KeepMembers - --keep class * implements com.elderdrivers.riru.common.KeepAll { *; } --keepclassmembers class * implements com.elderdrivers.riru.common.KeepMembers { *; } - --keep class com.swift.sandhook.** {*;} - --keepclasseswithmembers class * { - native ; -} \ No newline at end of file diff --git a/edxp-sandhook/src/main/AndroidManifest.xml b/edxp-sandhook/src/main/AndroidManifest.xml deleted file mode 100644 index 4d54a3c5..00000000 --- a/edxp-sandhook/src/main/AndroidManifest.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/edxp-service/.gitignore b/edxp-service/.gitignore deleted file mode 100644 index 3a66a198..00000000 --- a/edxp-service/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build -/template_override/system/framework \ No newline at end of file diff --git a/edxp-service/build.gradle b/edxp-service/build.gradle deleted file mode 100644 index 4ff94376..00000000 --- a/edxp-service/build.gradle +++ /dev/null @@ -1,73 +0,0 @@ -apply plugin: 'com.android.application' - -sourceCompatibility = "7" -targetCompatibility = "7" - -android { - compileSdkVersion androidCompileSdkVersion.toInteger() - - defaultConfig { - applicationId "com.elderdrivers.riru.edxp.yahfa" - minSdkVersion androidMinSdkVersion.toInteger() - targetSdkVersion androidTargetSdkVersion.toInteger() - versionCode 1 - versionName "1.0" - multiDexEnabled false - } - - buildTypes { - release { - minifyEnabled true - proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' - } - } - - ndkVersion androidCompileNdkVersion -} - -dependencies { - compileOnly project(':hiddenapi-stubs') - implementation project(':edxp-common') -} - - -preBuild.doLast { - def imlFile = file(project.name + ".iml") - try { - def parsedXml = (new groovy.util.XmlParser()).parse(imlFile) - def jdkNode = parsedXml.component[1].orderEntry.find { it.'@type' == 'jdk' } - parsedXml.component[1].remove(jdkNode) - def sdkString = "Android API " + android.compileSdkVersion.substring("android-".length()) + " Platform" - new groovy.util.Node(parsedXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': sdkString, 'jdkType': 'Android SDK']) - groovy.xml.XmlUtil.serialize(parsedXml, new FileOutputStream(imlFile)) - } catch (FileNotFoundException e) { - // nop, iml not found - } -} - -afterEvaluate { - - tasks.withType(JavaCompile) { - options.compilerArgs << "-Xbootclasspath/p:${hiddenApiStubJarFilePath}" - } - - android.applicationVariants.all { variant -> - - def variantNameCapped = variant.name.capitalize() - def variantNameLowered = variant.name.toLowerCase() - - task("copyDex${variantNameCapped}", type: Copy) { - dependsOn "assemble${variantNameCapped}" - dependsOn tasks.getByPath(":edxp-common:copyCommonProperties") - def dexOutPath = variant.name.contains("release") ? - "${buildDir}/intermediates/dex/${variantNameLowered}/minify${variantNameCapped}WithR8" : - "${buildDir}/intermediates/dex/${variantNameLowered}/mergeDex${variantNameCapped}" - from (dexOutPath){ - rename("classes.dex", "edservice.dex") - } - destinationDir file(templateRootPath + "system/framework/") - outputs.upToDateWhen { false } - } - - } -} \ No newline at end of file diff --git a/edxp-service/proguard-rules.pro b/edxp-service/proguard-rules.pro deleted file mode 100644 index 784e5ec2..00000000 --- a/edxp-service/proguard-rules.pro +++ /dev/null @@ -1,34 +0,0 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile - --dontoptimize --dontobfuscate - --keep interface com.elderdrivers.riru.common.KeepAll --keep interface com.elderdrivers.riru.common.KeepMembers - --keep class * implements com.elderdrivers.riru.common.KeepAll { *; } --keepclassmembers class * implements com.elderdrivers.riru.common.KeepMembers { *; } - --keepclasseswithmembers class * { - native ; -} diff --git a/edxp-service/src/main/AndroidManifest.xml b/edxp-service/src/main/AndroidManifest.xml deleted file mode 100644 index c41a679e..00000000 --- a/edxp-service/src/main/AndroidManifest.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/edxp-yahfa/.gitignore b/edxp-yahfa/.gitignore deleted file mode 100644 index 3a66a198..00000000 --- a/edxp-yahfa/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build -/template_override/system/framework \ No newline at end of file diff --git a/edxp-yahfa/build.gradle b/edxp-yahfa/build.gradle deleted file mode 100644 index f5996d63..00000000 --- a/edxp-yahfa/build.gradle +++ /dev/null @@ -1,74 +0,0 @@ -apply plugin: 'com.android.application' - -sourceCompatibility = "7" -targetCompatibility = "7" - -android { - compileSdkVersion androidCompileSdkVersion.toInteger() - - defaultConfig { - applicationId "com.elderdrivers.riru.edxp.yahfa" - minSdkVersion androidMinSdkVersion.toInteger() - targetSdkVersion androidTargetSdkVersion.toInteger() - versionCode 1 - versionName "1.0" - multiDexEnabled false - } - - buildTypes { - release { - minifyEnabled true - proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' - } - } - - ndkVersion androidCompileNdkVersion -} - -dependencies { - compileOnly project(':hiddenapi-stubs') - implementation project(':edxp-common') - compileOnly files(project(":dexmaker").tasks.getByName("makeJarRelease").outputs) -} - - -preBuild.doLast { - def imlFile = file(project.name + ".iml") - try { - def parsedXml = (new groovy.util.XmlParser()).parse(imlFile) - def jdkNode = parsedXml.component[1].orderEntry.find { it.'@type' == 'jdk' } - parsedXml.component[1].remove(jdkNode) - def sdkString = "Android API " + android.compileSdkVersion.substring("android-".length()) + " Platform" - new groovy.util.Node(parsedXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': sdkString, 'jdkType': 'Android SDK']) - groovy.xml.XmlUtil.serialize(parsedXml, new FileOutputStream(imlFile)) - } catch (FileNotFoundException e) { - // nop, iml not found - } -} - -afterEvaluate { - - tasks.withType(JavaCompile) { - options.compilerArgs << "-Xbootclasspath/p:${hiddenApiStubJarFilePath}" - } - - android.applicationVariants.all { variant -> - - def variantNameCapped = variant.name.capitalize() - def variantNameLowered = variant.name.toLowerCase() - - task("copyDex${variantNameCapped}", type: Copy) { - dependsOn "assemble${variantNameCapped}" - dependsOn tasks.getByPath(":edxp-common:copyCommonProperties") - def dexOutPath = variant.name.contains("release") ? - "${buildDir}/intermediates/dex/${variantNameLowered}/minify${variantNameCapped}WithR8" : - "${buildDir}/intermediates/dex/${variantNameLowered}/mergeDex${variantNameCapped}" - from (dexOutPath){ - rename("classes.dex", "edxp.dex") - } - destinationDir file(zipPathMagiskReleasePath + "system/framework/") - outputs.upToDateWhen { false } - } - - } -} \ No newline at end of file diff --git a/edxp-yahfa/proguard-rules.pro b/edxp-yahfa/proguard-rules.pro deleted file mode 100644 index 50e9b797..00000000 --- a/edxp-yahfa/proguard-rules.pro +++ /dev/null @@ -1,36 +0,0 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile - --dontoptimize --dontobfuscate --keep class de.robv.android.xposed.** {*;} --keep class android.** { *; } - --keep interface com.elderdrivers.riru.common.KeepAll --keep interface com.elderdrivers.riru.common.KeepMembers - --keep class * implements com.elderdrivers.riru.common.KeepAll { *; } --keepclassmembers class * implements com.elderdrivers.riru.common.KeepMembers { *; } - --keepclasseswithmembers class * { - native ; -} diff --git a/edxp-yahfa/src/main/AndroidManifest.xml b/edxp-yahfa/src/main/AndroidManifest.xml deleted file mode 100644 index 7998b31b..00000000 --- a/edxp-yahfa/src/main/AndroidManifest.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/settings.gradle b/settings.gradle index ae4c3cf5..198220fc 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1 @@ -include ':edxp-core', ':xposed-bridge', ':hiddenapi-stubs', ':dexmaker', ':dalvikdx', ':edxp-common', ':edxp-yahfa', ':edxp-sandhook', ':edxp-service', ':sandhook-hooklib', ':sandhook-annotation' \ No newline at end of file +include ':edxp-core', ':hiddenapi-stubs', ':sandhook-hooklib', ':sandhook-annotation' \ No newline at end of file diff --git a/xposed-bridge/build.gradle b/xposed-bridge/build.gradle index 506545be..8471f005 100644 --- a/xposed-bridge/build.gradle +++ b/xposed-bridge/build.gradle @@ -45,7 +45,6 @@ preBuild.doLast { } dependencies { - compileOnly files(project(":dexmaker").tasks.getByName("makeJarRelease").outputs) compileOnly files(project(":hiddenapi-stubs").tasks.getByName("makeStubJar").outputs) }