This is an automated email from the git hooks/post-receive script. New change to branch develop in repository nuiton-version. See http://git.nuiton.org/nuiton-version.git from 4d0e450 Fixes #3797 Merge branch 'feature/3797_javadoc_8' into develop new 5aa78df Remove nuiton-util sutff + update configuration + rename package The 1 revisions listed above as "new" are entirely new to this repository and will be described in separate emails. The revisions listed as "adds" were already present in the repository and have only been added to this reference. Detailed log of new commits: commit 5aa78df0d8e4552f5db13892d2825a1cef2b8a2c Author: Tony CHEMIT <chemit@codelutin.com> Date: Sun Jan 10 14:24:54 2016 +0100 Remove nuiton-util sutff + update configuration + rename package Summary of changes: pom.xml | 141 +- src/license/THIRD-PARTY.properties | 20 - src/main/java/org/nuiton/util/AliasMap.java | 273 --- src/main/java/org/nuiton/util/ArrayUtil.java | 175 -- src/main/java/org/nuiton/util/BoundedList.java | 235 -- .../util/BoundedListOutOfBoundsException.java | 56 - src/main/java/org/nuiton/util/CallAnalyse.java | 360 --- .../java/org/nuiton/util/CardinalityHelper.java | 259 --- .../org/nuiton/util/CategorisedListenerSet.java | 258 --- src/main/java/org/nuiton/util/ClassLoaderUtil.java | 140 -- src/main/java/org/nuiton/util/CollectionUtil.java | 260 --- src/main/java/org/nuiton/util/DateUtil.java | 554 ----- src/main/java/org/nuiton/util/DesktopUtil.java | 174 -- src/main/java/org/nuiton/util/DigestGenerator.java | 385 ---- .../nuiton/util/FasterCachedResourceResolver.java | 101 - src/main/java/org/nuiton/util/FileUtil.java | 1370 ------------ src/main/java/org/nuiton/util/GZUtil.java | 134 -- src/main/java/org/nuiton/util/GZUtilException.java | 49 - src/main/java/org/nuiton/util/HashList.java | 148 -- src/main/java/org/nuiton/util/LRUMapMultiKey.java | 225 -- src/main/java/org/nuiton/util/ListenerSet.java | 224 -- .../java/org/nuiton/util/LoggingException.java | 49 - .../org/nuiton/util/LoggingPatternFormatter.java | 512 ----- src/main/java/org/nuiton/util/MD5InputStream.java | 168 -- src/main/java/org/nuiton/util/MD5OutputStream.java | 57 - src/main/java/org/nuiton/util/MatrixMap.java | 2357 -------------------- src/main/java/org/nuiton/util/MonthEnum.java | 82 - src/main/java/org/nuiton/util/NumberUtil.java | 162 -- src/main/java/org/nuiton/util/ObjectUtil.java | 806 ------- src/main/java/org/nuiton/util/PagerBean.java | 122 - src/main/java/org/nuiton/util/PagerBeanUtil.java | 131 -- src/main/java/org/nuiton/util/PeriodDates.java | 264 --- .../util/PropertiesDateRemoveFilterStream.java | 62 - .../java/org/nuiton/util/RecursiveProperties.java | 94 - src/main/java/org/nuiton/util/ReflectUtil.java | 722 ------ src/main/java/org/nuiton/util/Resource.java | 917 -------- .../java/org/nuiton/util/ResourceException.java | 49 - .../org/nuiton/util/ResourceNotFoundException.java | 49 - .../java/org/nuiton/util/ResourceResolver.java | 307 --- .../java/org/nuiton/util/ReverseFileReader.java | 133 -- src/main/java/org/nuiton/util/SemVer.java | 676 ------ .../java/org/nuiton/util/SortedProperties.java | 66 - src/main/java/org/nuiton/util/StringUtil.java | 771 ------- .../java/org/nuiton/util/StringUtilException.java | 34 - src/main/java/org/nuiton/util/TimeLog.java | 246 -- .../org/nuiton/util/TransparenteSoftReference.java | 139 -- .../org/nuiton/util/TransparenteWeakReference.java | 141 -- src/main/java/org/nuiton/util/Version.java | 350 --- src/main/java/org/nuiton/util/VersionUtil.java | 568 ----- .../java/org/nuiton/util/ZipStreamEncoder.java | 98 - src/main/java/org/nuiton/util/ZipUtil.java | 603 ----- .../java/org/nuiton/util/beans/BeanMonitor.java | 280 --- src/main/java/org/nuiton/util/beans/BeanUtil.java | 451 ---- src/main/java/org/nuiton/util/beans/Binder.java | 1086 --------- .../java/org/nuiton/util/beans/BinderFactory.java | 522 ----- .../org/nuiton/util/beans/BinderModelBuilder.java | 651 ------ .../org/nuiton/util/beans/InstanceFactory.java | 31 - .../java/org/nuiton/util/beans/PropertyDiff.java | 97 - .../java/org/nuiton/util/beans/package-info.java | 100 - .../org/nuiton/util/converter/ColorConverter.java | 81 - .../org/nuiton/util/converter/ConverterUtil.java | 206 -- .../org/nuiton/util/converter/EnumConverter.java | 152 -- .../org/nuiton/util/converter/FormatConverter.java | 94 - .../util/converter/FormatConverterFactory.java | 192 -- .../java/org/nuiton/util/converter/FormatMap.java | 191 -- .../nuiton/util/converter/KeyStrokeConverter.java | 75 - .../org/nuiton/util/converter/URIConverter.java | 93 - .../org/nuiton/util/converter/URLConverter.java | 95 - .../nuiton/util/converter/VersionConverter.java | 88 - .../org/nuiton/util/converter/package-info.java | 40 - src/main/java/org/nuiton/util/package-info.java | 30 - .../nuiton/util/pagination/PaginationOrder.java | 61 - .../util/pagination/PaginationParameter.java | 317 --- .../nuiton/util/pagination/PaginationResult.java | 149 -- .../org/nuiton/util/pagination/package-info.java | 32 - .../org/nuiton/util/rmi/RemoteMethodExecutor.java | 47 - .../nuiton/util/rmi/RemoteMethodExecutorImpl.java | 81 - .../org/nuiton/util/rmi/RemoteProxyFactory.java | 137 -- .../java/org/nuiton/util/rmi/ServiceExporter.java | 159 -- .../java/org/nuiton/util/rmi/package-info.java | 34 - .../java/org/nuiton/{util => }/version/SemVer.java | 8 +- .../org/nuiton/{util => }/version/Version.java | 8 +- .../nuiton/{util => }/version/VersionBuilder.java | 8 +- .../{util => }/version/VersionComparator.java | 8 +- .../{util => }/version/VersionConverter.java | 8 +- .../org/nuiton/{util => }/version/Versions.java | 8 +- .../org.apache.commons.beanutils.Converter | 3 +- .../services/org.nuiton.converter.NuitonConverter | 3 +- .../resources/i18n/nuiton-utils_en_GB.properties | 40 - .../resources/i18n/nuiton-utils_es_ES.properties | 40 - .../resources/i18n/nuiton-utils_fr_FR.properties | 40 - src/site/apt/index.apt | 170 +- src/site/apt/versions.apt | 34 - src/site/site.xml | 10 +- src/test/java/org/nuiton/util/AliasMapTest.java | 77 - src/test/java/org/nuiton/util/CallAnalyseTest.java | 84 - .../org/nuiton/util/CardinalityHelperTest.java | 180 -- .../nuiton/util/CategorisedListenerSetTest.java | 101 - .../java/org/nuiton/util/CollectionUtilTest.java | 60 - src/test/java/org/nuiton/util/DateUtilTest.java | 343 --- src/test/java/org/nuiton/util/DesktopUtilTest.java | 36 - src/test/java/org/nuiton/util/FileUtilTest.java | 295 --- .../java/org/nuiton/util/LRUMapMultiKeyTest.java | 107 - src/test/java/org/nuiton/util/ListenerSetTest.java | 160 -- .../java/org/nuiton/util/MD5InputStreamTest.java | 1008 --------- src/test/java/org/nuiton/util/MatrixMapTest.java | 123 - src/test/java/org/nuiton/util/NumberUtilTest.java | 95 - src/test/java/org/nuiton/util/ObjectUtilTest.java | 202 -- .../java/org/nuiton/util/PagerBeanUtilTest.java | 78 - src/test/java/org/nuiton/util/PeriodDatesTest.java | 132 -- .../org/nuiton/util/RecursivePropertiesTest.java | 64 - src/test/java/org/nuiton/util/ReflectUtilTest.java | 391 ---- src/test/java/org/nuiton/util/ResourceTest.java | 282 --- .../org/nuiton/util/ReverseFileReaderTest.java | 60 - src/test/java/org/nuiton/util/SemVerTest.java | 231 -- src/test/java/org/nuiton/util/StringUtilTest.java | 248 -- .../org/nuiton/util/TransparenteReferenceTest.java | 62 - src/test/java/org/nuiton/util/VersionTest.java | 156 -- src/test/java/org/nuiton/util/VersionUtilTest.java | 471 ---- src/test/java/org/nuiton/util/ZipUtilTest.java | 265 --- src/test/java/org/nuiton/util/beans/BeanA.java | 140 -- src/test/java/org/nuiton/util/beans/BeanAA.java | 140 -- src/test/java/org/nuiton/util/beans/BeanB.java | 110 - src/test/java/org/nuiton/util/beans/BeanC.java | 106 - .../org/nuiton/util/beans/BeanMonitorTest.java | 145 -- .../java/org/nuiton/util/beans/BeanUtilTest.java | 317 --- .../org/nuiton/util/beans/BinderFactoryTest.java | 140 -- .../nuiton/util/beans/BinderModelBuilderTest.java | 588 ----- .../java/org/nuiton/util/beans/BinderTest.java | 394 ---- .../java/org/nuiton/util/beans/Destination.java | 39 - src/test/java/org/nuiton/util/beans/Source.java | 39 - .../nuiton/util/converter/ConverterUtilTest.java | 81 - .../util/converter/UnregistreableConverter.java | 41 - .../util/converter/VersionConverterTest.java | 101 - .../util/pagination/PaginationParameterTest.java | 91 - .../util/pagination/PaginationResultTest.java | 124 - .../java/org/nuiton/util/rmi/AnyException.java | 33 - .../nuiton/util/rmi/RmiExporterAndProxyTest.java | 138 -- src/test/java/org/nuiton/util/rmi/SomeBean.java | 85 - src/test/java/org/nuiton/util/rmi/SomeService.java | 54 - .../java/org/nuiton/util/rmi/SomeServiceImpl.java | 52 - .../org/nuiton/{util => }/version/SemVerTest.java | 6 +- .../{util => }/version/VersionBuilderTest.java | 6 +- .../{util => }/version/VersionComparatorTest.java | 6 +- .../org/nuiton/{util => }/version/VersionTest.java | 6 +- .../nuiton/{util => }/version/VersionsTest.java | 6 +- .../org.apache.commons.beanutils.Converter | 1 - src/test/resources/log4j.properties | 7 +- .../resources/org/nuiton/util/fileUtilData.txt | 1421 ------------ src/test/resources/org/nuiton/util/reverseread.txt | 4 - src/test/resources/properties/recursive.properties | 23 - src/test/resources/properties/windows.properties | 27 - src/test/resources/zip/not-a-zip.zip | 1 - src/test/resources/zip/test-uncompress.zip | Bin 60825 -> 0 bytes src/test/resources/zip/this-is-a-zip.zap | Bin 910 -> 0 bytes 155 files changed, 63 insertions(+), 31956 deletions(-) delete mode 100644 src/license/THIRD-PARTY.properties delete mode 100644 src/main/java/org/nuiton/util/AliasMap.java delete mode 100644 src/main/java/org/nuiton/util/ArrayUtil.java delete mode 100644 src/main/java/org/nuiton/util/BoundedList.java delete mode 100644 src/main/java/org/nuiton/util/BoundedListOutOfBoundsException.java delete mode 100644 src/main/java/org/nuiton/util/CallAnalyse.java delete mode 100644 src/main/java/org/nuiton/util/CardinalityHelper.java delete mode 100644 src/main/java/org/nuiton/util/CategorisedListenerSet.java delete mode 100644 src/main/java/org/nuiton/util/ClassLoaderUtil.java delete mode 100644 src/main/java/org/nuiton/util/CollectionUtil.java delete mode 100644 src/main/java/org/nuiton/util/DateUtil.java delete mode 100644 src/main/java/org/nuiton/util/DesktopUtil.java delete mode 100644 src/main/java/org/nuiton/util/DigestGenerator.java delete mode 100644 src/main/java/org/nuiton/util/FasterCachedResourceResolver.java delete mode 100644 src/main/java/org/nuiton/util/FileUtil.java delete mode 100644 src/main/java/org/nuiton/util/GZUtil.java delete mode 100644 src/main/java/org/nuiton/util/GZUtilException.java delete mode 100644 src/main/java/org/nuiton/util/HashList.java delete mode 100644 src/main/java/org/nuiton/util/LRUMapMultiKey.java delete mode 100644 src/main/java/org/nuiton/util/ListenerSet.java delete mode 100644 src/main/java/org/nuiton/util/LoggingException.java delete mode 100644 src/main/java/org/nuiton/util/LoggingPatternFormatter.java delete mode 100644 src/main/java/org/nuiton/util/MD5InputStream.java delete mode 100644 src/main/java/org/nuiton/util/MD5OutputStream.java delete mode 100644 src/main/java/org/nuiton/util/MatrixMap.java delete mode 100644 src/main/java/org/nuiton/util/MonthEnum.java delete mode 100644 src/main/java/org/nuiton/util/NumberUtil.java delete mode 100644 src/main/java/org/nuiton/util/ObjectUtil.java delete mode 100644 src/main/java/org/nuiton/util/PagerBean.java delete mode 100644 src/main/java/org/nuiton/util/PagerBeanUtil.java delete mode 100644 src/main/java/org/nuiton/util/PeriodDates.java delete mode 100644 src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java delete mode 100644 src/main/java/org/nuiton/util/RecursiveProperties.java delete mode 100644 src/main/java/org/nuiton/util/ReflectUtil.java delete mode 100644 src/main/java/org/nuiton/util/Resource.java delete mode 100644 src/main/java/org/nuiton/util/ResourceException.java delete mode 100644 src/main/java/org/nuiton/util/ResourceNotFoundException.java delete mode 100644 src/main/java/org/nuiton/util/ResourceResolver.java delete mode 100644 src/main/java/org/nuiton/util/ReverseFileReader.java delete mode 100644 src/main/java/org/nuiton/util/SemVer.java delete mode 100644 src/main/java/org/nuiton/util/SortedProperties.java delete mode 100644 src/main/java/org/nuiton/util/StringUtil.java delete mode 100644 src/main/java/org/nuiton/util/StringUtilException.java delete mode 100644 src/main/java/org/nuiton/util/TimeLog.java delete mode 100644 src/main/java/org/nuiton/util/TransparenteSoftReference.java delete mode 100644 src/main/java/org/nuiton/util/TransparenteWeakReference.java delete mode 100644 src/main/java/org/nuiton/util/Version.java delete mode 100644 src/main/java/org/nuiton/util/VersionUtil.java delete mode 100644 src/main/java/org/nuiton/util/ZipStreamEncoder.java delete mode 100644 src/main/java/org/nuiton/util/ZipUtil.java delete mode 100644 src/main/java/org/nuiton/util/beans/BeanMonitor.java delete mode 100644 src/main/java/org/nuiton/util/beans/BeanUtil.java delete mode 100644 src/main/java/org/nuiton/util/beans/Binder.java delete mode 100644 src/main/java/org/nuiton/util/beans/BinderFactory.java delete mode 100644 src/main/java/org/nuiton/util/beans/BinderModelBuilder.java delete mode 100644 src/main/java/org/nuiton/util/beans/InstanceFactory.java delete mode 100644 src/main/java/org/nuiton/util/beans/PropertyDiff.java delete mode 100644 src/main/java/org/nuiton/util/beans/package-info.java delete mode 100644 src/main/java/org/nuiton/util/converter/ColorConverter.java delete mode 100644 src/main/java/org/nuiton/util/converter/ConverterUtil.java delete mode 100644 src/main/java/org/nuiton/util/converter/EnumConverter.java delete mode 100644 src/main/java/org/nuiton/util/converter/FormatConverter.java delete mode 100644 src/main/java/org/nuiton/util/converter/FormatConverterFactory.java delete mode 100644 src/main/java/org/nuiton/util/converter/FormatMap.java delete mode 100644 src/main/java/org/nuiton/util/converter/KeyStrokeConverter.java delete mode 100644 src/main/java/org/nuiton/util/converter/URIConverter.java delete mode 100644 src/main/java/org/nuiton/util/converter/URLConverter.java delete mode 100644 src/main/java/org/nuiton/util/converter/VersionConverter.java delete mode 100644 src/main/java/org/nuiton/util/converter/package-info.java delete mode 100644 src/main/java/org/nuiton/util/package-info.java delete mode 100644 src/main/java/org/nuiton/util/pagination/PaginationOrder.java delete mode 100644 src/main/java/org/nuiton/util/pagination/PaginationParameter.java delete mode 100644 src/main/java/org/nuiton/util/pagination/PaginationResult.java delete mode 100644 src/main/java/org/nuiton/util/pagination/package-info.java delete mode 100644 src/main/java/org/nuiton/util/rmi/RemoteMethodExecutor.java delete mode 100644 src/main/java/org/nuiton/util/rmi/RemoteMethodExecutorImpl.java delete mode 100644 src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java delete mode 100644 src/main/java/org/nuiton/util/rmi/ServiceExporter.java delete mode 100644 src/main/java/org/nuiton/util/rmi/package-info.java rename src/main/java/org/nuiton/{util => }/version/SemVer.java (99%) rename src/main/java/org/nuiton/{util => }/version/Version.java (99%) rename src/main/java/org/nuiton/{util => }/version/VersionBuilder.java (99%) rename src/main/java/org/nuiton/{util => }/version/VersionComparator.java (98%) rename src/main/java/org/nuiton/{util => }/version/VersionConverter.java (96%) rename src/main/java/org/nuiton/{util => }/version/Versions.java (98%) delete mode 100644 src/main/resources/i18n/nuiton-utils_en_GB.properties delete mode 100644 src/main/resources/i18n/nuiton-utils_es_ES.properties delete mode 100644 src/main/resources/i18n/nuiton-utils_fr_FR.properties delete mode 100644 src/site/apt/versions.apt delete mode 100644 src/test/java/org/nuiton/util/AliasMapTest.java delete mode 100644 src/test/java/org/nuiton/util/CallAnalyseTest.java delete mode 100644 src/test/java/org/nuiton/util/CardinalityHelperTest.java delete mode 100644 src/test/java/org/nuiton/util/CategorisedListenerSetTest.java delete mode 100644 src/test/java/org/nuiton/util/CollectionUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/DateUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/DesktopUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/FileUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/LRUMapMultiKeyTest.java delete mode 100644 src/test/java/org/nuiton/util/ListenerSetTest.java delete mode 100644 src/test/java/org/nuiton/util/MD5InputStreamTest.java delete mode 100644 src/test/java/org/nuiton/util/MatrixMapTest.java delete mode 100644 src/test/java/org/nuiton/util/NumberUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/ObjectUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/PagerBeanUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/PeriodDatesTest.java delete mode 100644 src/test/java/org/nuiton/util/RecursivePropertiesTest.java delete mode 100644 src/test/java/org/nuiton/util/ReflectUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/ResourceTest.java delete mode 100644 src/test/java/org/nuiton/util/ReverseFileReaderTest.java delete mode 100644 src/test/java/org/nuiton/util/SemVerTest.java delete mode 100644 src/test/java/org/nuiton/util/StringUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/TransparenteReferenceTest.java delete mode 100644 src/test/java/org/nuiton/util/VersionTest.java delete mode 100644 src/test/java/org/nuiton/util/VersionUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/ZipUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/beans/BeanA.java delete mode 100644 src/test/java/org/nuiton/util/beans/BeanAA.java delete mode 100644 src/test/java/org/nuiton/util/beans/BeanB.java delete mode 100644 src/test/java/org/nuiton/util/beans/BeanC.java delete mode 100644 src/test/java/org/nuiton/util/beans/BeanMonitorTest.java delete mode 100644 src/test/java/org/nuiton/util/beans/BeanUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/beans/BinderFactoryTest.java delete mode 100644 src/test/java/org/nuiton/util/beans/BinderModelBuilderTest.java delete mode 100644 src/test/java/org/nuiton/util/beans/BinderTest.java delete mode 100644 src/test/java/org/nuiton/util/beans/Destination.java delete mode 100644 src/test/java/org/nuiton/util/beans/Source.java delete mode 100644 src/test/java/org/nuiton/util/converter/ConverterUtilTest.java delete mode 100644 src/test/java/org/nuiton/util/converter/UnregistreableConverter.java delete mode 100644 src/test/java/org/nuiton/util/converter/VersionConverterTest.java delete mode 100644 src/test/java/org/nuiton/util/pagination/PaginationParameterTest.java delete mode 100644 src/test/java/org/nuiton/util/pagination/PaginationResultTest.java delete mode 100644 src/test/java/org/nuiton/util/rmi/AnyException.java delete mode 100644 src/test/java/org/nuiton/util/rmi/RmiExporterAndProxyTest.java delete mode 100644 src/test/java/org/nuiton/util/rmi/SomeBean.java delete mode 100644 src/test/java/org/nuiton/util/rmi/SomeService.java delete mode 100644 src/test/java/org/nuiton/util/rmi/SomeServiceImpl.java rename src/test/java/org/nuiton/{util => }/version/SemVerTest.java (98%) rename src/test/java/org/nuiton/{util => }/version/VersionBuilderTest.java (97%) rename src/test/java/org/nuiton/{util => }/version/VersionComparatorTest.java (96%) rename src/test/java/org/nuiton/{util => }/version/VersionTest.java (95%) rename src/test/java/org/nuiton/{util => }/version/VersionsTest.java (97%) delete mode 100644 src/test/resources/META-INF/services/org.apache.commons.beanutils.Converter delete mode 100644 src/test/resources/org/nuiton/util/fileUtilData.txt delete mode 100644 src/test/resources/org/nuiton/util/reverseread.txt delete mode 100644 src/test/resources/properties/recursive.properties delete mode 100644 src/test/resources/properties/windows.properties delete mode 100644 src/test/resources/zip/not-a-zip.zip delete mode 100644 src/test/resources/zip/test-uncompress.zip delete mode 100644 src/test/resources/zip/this-is-a-zip.zap -- To stop receiving notification emails like this one, please contact nuiton.org SCM administrator <admin+scm@nuiton.org>.
This is an automated email from the git hooks/post-receive script. New commit to branch develop in repository nuiton-version. See http://git.nuiton.org/nuiton-version.git commit 5aa78df0d8e4552f5db13892d2825a1cef2b8a2c Author: Tony CHEMIT <chemit@codelutin.com> Date: Sun Jan 10 14:24:54 2016 +0100 Remove nuiton-util sutff + update configuration + rename package --- pom.xml | 141 +- src/license/THIRD-PARTY.properties | 20 - src/main/java/org/nuiton/util/AliasMap.java | 273 --- src/main/java/org/nuiton/util/ArrayUtil.java | 175 -- src/main/java/org/nuiton/util/BoundedList.java | 235 -- .../util/BoundedListOutOfBoundsException.java | 56 - src/main/java/org/nuiton/util/CallAnalyse.java | 360 --- .../java/org/nuiton/util/CardinalityHelper.java | 259 --- .../org/nuiton/util/CategorisedListenerSet.java | 258 --- src/main/java/org/nuiton/util/ClassLoaderUtil.java | 140 -- src/main/java/org/nuiton/util/CollectionUtil.java | 260 --- src/main/java/org/nuiton/util/DateUtil.java | 554 ----- src/main/java/org/nuiton/util/DesktopUtil.java | 174 -- src/main/java/org/nuiton/util/DigestGenerator.java | 385 ---- .../nuiton/util/FasterCachedResourceResolver.java | 101 - src/main/java/org/nuiton/util/FileUtil.java | 1370 ------------ src/main/java/org/nuiton/util/GZUtil.java | 134 -- src/main/java/org/nuiton/util/GZUtilException.java | 49 - src/main/java/org/nuiton/util/HashList.java | 148 -- src/main/java/org/nuiton/util/LRUMapMultiKey.java | 225 -- src/main/java/org/nuiton/util/ListenerSet.java | 224 -- .../java/org/nuiton/util/LoggingException.java | 49 - .../org/nuiton/util/LoggingPatternFormatter.java | 512 ----- src/main/java/org/nuiton/util/MD5InputStream.java | 168 -- src/main/java/org/nuiton/util/MD5OutputStream.java | 57 - src/main/java/org/nuiton/util/MatrixMap.java | 2357 -------------------- src/main/java/org/nuiton/util/MonthEnum.java | 82 - src/main/java/org/nuiton/util/NumberUtil.java | 162 -- src/main/java/org/nuiton/util/ObjectUtil.java | 806 ------- src/main/java/org/nuiton/util/PagerBean.java | 122 - src/main/java/org/nuiton/util/PagerBeanUtil.java | 131 -- src/main/java/org/nuiton/util/PeriodDates.java | 264 --- .../util/PropertiesDateRemoveFilterStream.java | 62 - .../java/org/nuiton/util/RecursiveProperties.java | 94 - src/main/java/org/nuiton/util/ReflectUtil.java | 722 ------ src/main/java/org/nuiton/util/Resource.java | 917 -------- .../java/org/nuiton/util/ResourceException.java | 49 - .../org/nuiton/util/ResourceNotFoundException.java | 49 - .../java/org/nuiton/util/ResourceResolver.java | 307 --- .../java/org/nuiton/util/ReverseFileReader.java | 133 -- src/main/java/org/nuiton/util/SemVer.java | 676 ------ .../java/org/nuiton/util/SortedProperties.java | 66 - src/main/java/org/nuiton/util/StringUtil.java | 771 ------- .../java/org/nuiton/util/StringUtilException.java | 34 - src/main/java/org/nuiton/util/TimeLog.java | 246 -- .../org/nuiton/util/TransparenteSoftReference.java | 139 -- .../org/nuiton/util/TransparenteWeakReference.java | 141 -- src/main/java/org/nuiton/util/Version.java | 350 --- src/main/java/org/nuiton/util/VersionUtil.java | 568 ----- .../java/org/nuiton/util/ZipStreamEncoder.java | 98 - src/main/java/org/nuiton/util/ZipUtil.java | 603 ----- .../java/org/nuiton/util/beans/BeanMonitor.java | 280 --- src/main/java/org/nuiton/util/beans/BeanUtil.java | 451 ---- src/main/java/org/nuiton/util/beans/Binder.java | 1086 --------- .../java/org/nuiton/util/beans/BinderFactory.java | 522 ----- .../org/nuiton/util/beans/BinderModelBuilder.java | 651 ------ .../org/nuiton/util/beans/InstanceFactory.java | 31 - .../java/org/nuiton/util/beans/PropertyDiff.java | 97 - .../java/org/nuiton/util/beans/package-info.java | 100 - .../org/nuiton/util/converter/ColorConverter.java | 81 - .../org/nuiton/util/converter/ConverterUtil.java | 206 -- .../org/nuiton/util/converter/EnumConverter.java | 152 -- .../org/nuiton/util/converter/FormatConverter.java | 94 - .../util/converter/FormatConverterFactory.java | 192 -- .../java/org/nuiton/util/converter/FormatMap.java | 191 -- .../nuiton/util/converter/KeyStrokeConverter.java | 75 - .../org/nuiton/util/converter/URIConverter.java | 93 - .../org/nuiton/util/converter/URLConverter.java | 95 - .../nuiton/util/converter/VersionConverter.java | 88 - .../org/nuiton/util/converter/package-info.java | 40 - src/main/java/org/nuiton/util/package-info.java | 30 - .../nuiton/util/pagination/PaginationOrder.java | 61 - .../util/pagination/PaginationParameter.java | 317 --- .../nuiton/util/pagination/PaginationResult.java | 149 -- .../org/nuiton/util/pagination/package-info.java | 32 - .../org/nuiton/util/rmi/RemoteMethodExecutor.java | 47 - .../nuiton/util/rmi/RemoteMethodExecutorImpl.java | 81 - .../org/nuiton/util/rmi/RemoteProxyFactory.java | 137 -- .../java/org/nuiton/util/rmi/ServiceExporter.java | 159 -- .../java/org/nuiton/util/rmi/package-info.java | 34 - .../java/org/nuiton/{util => }/version/SemVer.java | 8 +- .../org/nuiton/{util => }/version/Version.java | 8 +- .../nuiton/{util => }/version/VersionBuilder.java | 8 +- .../{util => }/version/VersionComparator.java | 8 +- .../{util => }/version/VersionConverter.java | 8 +- .../org/nuiton/{util => }/version/Versions.java | 8 +- .../org.apache.commons.beanutils.Converter | 3 +- .../services/org.nuiton.converter.NuitonConverter | 3 +- .../resources/i18n/nuiton-utils_en_GB.properties | 40 - .../resources/i18n/nuiton-utils_es_ES.properties | 40 - .../resources/i18n/nuiton-utils_fr_FR.properties | 40 - src/site/apt/index.apt | 170 +- src/site/apt/versions.apt | 34 - src/site/site.xml | 10 +- src/test/java/org/nuiton/util/AliasMapTest.java | 77 - src/test/java/org/nuiton/util/CallAnalyseTest.java | 84 - .../org/nuiton/util/CardinalityHelperTest.java | 180 -- .../nuiton/util/CategorisedListenerSetTest.java | 101 - .../java/org/nuiton/util/CollectionUtilTest.java | 60 - src/test/java/org/nuiton/util/DateUtilTest.java | 343 --- src/test/java/org/nuiton/util/DesktopUtilTest.java | 36 - src/test/java/org/nuiton/util/FileUtilTest.java | 295 --- .../java/org/nuiton/util/LRUMapMultiKeyTest.java | 107 - src/test/java/org/nuiton/util/ListenerSetTest.java | 160 -- .../java/org/nuiton/util/MD5InputStreamTest.java | 1008 --------- src/test/java/org/nuiton/util/MatrixMapTest.java | 123 - src/test/java/org/nuiton/util/NumberUtilTest.java | 95 - src/test/java/org/nuiton/util/ObjectUtilTest.java | 202 -- .../java/org/nuiton/util/PagerBeanUtilTest.java | 78 - src/test/java/org/nuiton/util/PeriodDatesTest.java | 132 -- .../org/nuiton/util/RecursivePropertiesTest.java | 64 - src/test/java/org/nuiton/util/ReflectUtilTest.java | 391 ---- src/test/java/org/nuiton/util/ResourceTest.java | 282 --- .../org/nuiton/util/ReverseFileReaderTest.java | 60 - src/test/java/org/nuiton/util/SemVerTest.java | 231 -- src/test/java/org/nuiton/util/StringUtilTest.java | 248 -- .../org/nuiton/util/TransparenteReferenceTest.java | 62 - src/test/java/org/nuiton/util/VersionTest.java | 156 -- src/test/java/org/nuiton/util/VersionUtilTest.java | 471 ---- src/test/java/org/nuiton/util/ZipUtilTest.java | 265 --- src/test/java/org/nuiton/util/beans/BeanA.java | 140 -- src/test/java/org/nuiton/util/beans/BeanAA.java | 140 -- src/test/java/org/nuiton/util/beans/BeanB.java | 110 - src/test/java/org/nuiton/util/beans/BeanC.java | 106 - .../org/nuiton/util/beans/BeanMonitorTest.java | 145 -- .../java/org/nuiton/util/beans/BeanUtilTest.java | 317 --- .../org/nuiton/util/beans/BinderFactoryTest.java | 140 -- .../nuiton/util/beans/BinderModelBuilderTest.java | 588 ----- .../java/org/nuiton/util/beans/BinderTest.java | 394 ---- .../java/org/nuiton/util/beans/Destination.java | 39 - src/test/java/org/nuiton/util/beans/Source.java | 39 - .../nuiton/util/converter/ConverterUtilTest.java | 81 - .../util/converter/UnregistreableConverter.java | 41 - .../util/converter/VersionConverterTest.java | 101 - .../util/pagination/PaginationParameterTest.java | 91 - .../util/pagination/PaginationResultTest.java | 124 - .../java/org/nuiton/util/rmi/AnyException.java | 33 - .../nuiton/util/rmi/RmiExporterAndProxyTest.java | 138 -- src/test/java/org/nuiton/util/rmi/SomeBean.java | 85 - src/test/java/org/nuiton/util/rmi/SomeService.java | 54 - .../java/org/nuiton/util/rmi/SomeServiceImpl.java | 52 - .../org/nuiton/{util => }/version/SemVerTest.java | 6 +- .../{util => }/version/VersionBuilderTest.java | 6 +- .../{util => }/version/VersionComparatorTest.java | 6 +- .../org/nuiton/{util => }/version/VersionTest.java | 6 +- .../nuiton/{util => }/version/VersionsTest.java | 6 +- .../org.apache.commons.beanutils.Converter | 1 - src/test/resources/log4j.properties | 7 +- .../resources/org/nuiton/util/fileUtilData.txt | 1421 ------------ src/test/resources/org/nuiton/util/reverseread.txt | 4 - src/test/resources/properties/recursive.properties | 23 - src/test/resources/properties/windows.properties | 27 - src/test/resources/zip/not-a-zip.zip | 1 - src/test/resources/zip/test-uncompress.zip | Bin 60825 -> 0 bytes src/test/resources/zip/this-is-a-zip.zap | Bin 910 -> 0 bytes 155 files changed, 63 insertions(+), 31956 deletions(-) diff --git a/pom.xml b/pom.xml index 3ead646..edc668e 100644 --- a/pom.xml +++ b/pom.xml @@ -29,29 +29,17 @@ <version>5-rc-2</version> </parent> - <artifactId>nuiton-utils</artifactId> - <version>3.0-SNAPSHOT</version> + <artifactId>nuiton-version</artifactId> + <version>1.0-SNAPSHOT</version> - <name>Nuiton Utils</name> - <description>Library of usefull class to be used in any project.</description> - <url>http://nuiton-utils.nuiton.org</url> - <inceptionYear>2004</inceptionYear> + <name>Nuiton Version</name> + <description>Library of usefull class around version topic.</description> + <url>http://nuiton-version.nuiton.org</url> + <inceptionYear>2016</inceptionYear> <developers> <developer> - <name>Brendan Le Ny</name> - <id>bleny</id> - <email>bleny@codelutin.com</email> - <organization>CodeLutin</organization> - <organizationUrl>http://www.codelutin.com/</organizationUrl> - <timezone>Europe/Paris</timezone> - <roles> - <role>developer</role> - </roles> - </developer> - - <developer> <name>Benjamin Poussin</name> <id>bpoussin</id> <email>poussin@codelutin.com</email> @@ -87,42 +75,12 @@ </roles> </developer> - <developer> - <name>Kevin Morin</name> - <id>kmorin</id> - <email>morin@codelutin.com</email> - <organization>CodeLutin</organization> - <organizationUrl>http://www.codelutin.com/</organizationUrl> - <timezone>Europe/Paris</timezone> - <roles> - <role>developer</role> - </roles> - </developer> - </developers> - <contributors> - <contributor> - <name>Sylvain Letellier</name> - <timezone>Europe/Paris</timezone> - <roles> - <role>developer</role> - </roles> - </contributor> - - <contributor> - <name>Florian Desbois</name> - <timezone>Europe/Paris</timezone> - <roles> - <role>developer</role> - </roles> - </contributor> - </contributors> - <scm> - <url>https://gitlab.nuiton.org/codelutin/nuiton-utils</url> - <connection>scm:git:git@gitlab.nuiton.org:codelutin/nuiton-utils.git</connection> - <developerConnection>scm:git:git@gitlab.nuiton.org:codelutin/nuiton-utils.git</developerConnection> + <url>https://gitlab.nuiton.org/nuiton/nuiton-version</url> + <connection>scm:git:git@gitlab.nuiton.org:nuiton/nuiton-version.git</connection> + <developerConnection>scm:git:git@gitlab.nuiton.org:nuiton/nuiton-version.git</developerConnection> </scm> <distributionManagement> @@ -135,15 +93,9 @@ <properties> <!-- redmine project Id --> - <projectId>nuiton-utils</projectId> - - <nuitonI18nVersion>3.3</nuitonI18nVersion> + <projectId>nuiton-version</projectId> - <!-- i18n configuration --> - <i18n.bundles>fr_FR,en_GB,es_ES</i18n.bundles> - - <!-- Documentation is in apt format --> - <siteSourcesType>apt</siteSourcesType> + <!-- Site locale --> <locales>fr</locales> <!-- extra files to include in release --> @@ -169,24 +121,12 @@ </dependency> <dependency> - <groupId>commons-primitives</groupId> - <artifactId>commons-primitives</artifactId> - <version>1.0</version> - </dependency> - - <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.1</version> </dependency> <dependency> - <groupId>commons-io</groupId> - <artifactId>commons-io</artifactId> - <version>2.4</version> - </dependency> - - <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.2</version> @@ -199,12 +139,6 @@ </dependency> <dependency> - <groupId>org.nuiton.i18n</groupId> - <artifactId>nuiton-i18n</artifactId> - <version>${nuitonI18nVersion}</version> - </dependency> - - <dependency> <groupId>org.nuiton</groupId> <artifactId>nuiton-converter</artifactId> <version>1.0</version> @@ -226,59 +160,6 @@ </dependencies> - <build> - <pluginManagement> - <plugins> - - <!-- plugin i18n --> - <plugin> - <groupId>org.nuiton.i18n</groupId> - <artifactId>i18n-maven-plugin</artifactId> - <version>${nuitonI18nVersion}</version> - </plugin> - - </plugins> - </pluginManagement> - <plugins> - - <!-- plugin i18n --> - <plugin> - <groupId>org.nuiton.i18n</groupId> - <artifactId>i18n-maven-plugin</artifactId> - <configuration> - <silent>true</silent> - <bundles>fr_FR,en_GB,es_ES</bundles> - </configuration> - <executions> - <execution> - <goals> - <goal>parserJava</goal> - <goal>gen</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <artifactId>maven-assembly-plugin</artifactId> - <executions> - <execution> - <id>build-jar-with-dependencies</id> - <goals> - <goal>single</goal> - </goals> - <phase>package</phase> - <configuration> - <attach>true</attach> - <descriptorRefs> - <descriptorRef>jar-with-dependencies</descriptorRef> - </descriptorRefs> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - <profiles> <!-- create assemblies at release time --> diff --git a/src/license/THIRD-PARTY.properties b/src/license/THIRD-PARTY.properties deleted file mode 100644 index d98c166..0000000 --- a/src/license/THIRD-PARTY.properties +++ /dev/null @@ -1,20 +0,0 @@ -# Generated by org.codehaus.mojo.license.AddThirdPartyMojo -#------------------------------------------------------------------------------- -# Already used licenses in project : -# - Apache License -# - BSD License -# - COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 -# - Common Public License Version 1.0 -# - Indiana University Extreme! Lab Software License, vesion 1.1.1 -# - Lesser General Public License (LGPL) v 3.0 -# - Lesser General Public License (LPGL) -# - Lesser General Public License (LPGL) v 2.1 -# - MIT License -# - New BSD License -# - The Apache Software License, Version 2.0 -#------------------------------------------------------------------------------- -# Please fill the missing licenses for dependencies : -# -# -#Tue Jul 23 18:43:34 CEST 2013 -commons-primitives--commons-primitives--1.0=The Apache Software License, Version 2.0 diff --git a/src/main/java/org/nuiton/util/AliasMap.java b/src/main/java/org/nuiton/util/AliasMap.java deleted file mode 100644 index 62a82ac..0000000 --- a/src/main/java/org/nuiton/util/AliasMap.java +++ /dev/null @@ -1,273 +0,0 @@ -package org.nuiton.util; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.map.MultiValueMap; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.UUID; - -/** - * Une map base sur une HashMap qui permet pour une valeur d'ajouter d'autres - * cles. Cette nouvelle cle est un alias, un alias peut-etre utilise pour - * plusieurs valeurs. Si l'on demande la valeur associe a un Alias, cela - * retourne une liste contenant toutes les valeurs pour lequel cette Alias est - * utilise. - * - * Cela permet de stocker des objets avec une cle principale et unique, puis - * avec des alias. - * - * Et ainsi recherche les valeurs qui ont un ensemble d'alias via la methode - * {@link #getValueAlias(java.lang.Object[]) } ou supprimer les valeurs qui - * ont un ensemble d'Alias en commun via la methode {@link #removeValue} - * - * Si la cle ne vous importe que peu, vous pouvez par exemple utiliser - * {@link UUID#randomUUID()} pour generer une cle unique. - * - * @author Benjamin Poussin - poussin@codelutin.com - * @since 3.6.9 - */ -public class AliasMap<K, V, A> extends HashMap<K, V> { - - /** Logger. */ - static private Log log = LogFactory.getLog(AliasMap.class); - private static final long serialVersionUID = 1L; - - /** key: alias, value: key */ - protected MultiValueMap aliases; - /** key: key, value: alias */ - protected MultiValueMap keys; - - public AliasMap() { - aliases = MultiValueMap.multiValueMap(new HashMap(), HashSet.class); - keys = MultiValueMap.multiValueMap(new HashMap(), HashSet.class); - } - - /** - * Ajoute une valeur dans la map avec un ensemble d'alias associe - * - * @param key identifiant unique pour cette valeur - * @param value la valeur - * @param alias1 le premier alias à saisir - * @param alias les alias de la valeur - * @return FIXME - */ - public V put(K key, V value, A alias1, A ... alias) { - V result = put(key, value); - putAlias(key, alias1, alias); - - return result; - } - - /** - * Ajoute des alias a une cle - * @param key FIXME - * @param alias1 FIXME - * @param alias FIXME - */ - protected void putAlias(K key, A alias1, A ... alias) { - aliases.put(alias1, key); - keys.put(key, alias1); - for (Object a : alias) { - aliases.put(a, key); - keys.put(key, a); - } - } - - /** - * Retoure les cles en commun de tous les alias. Les cles retournees sont - * celle qui ont tous les alias. - * <pre> - * K1: a, b, c - * K2: b, c, d - * K3: c, d, e - * - * getKeyAlias(a, b, c) retourne [K1] - * getKeyAlias(b, c) retourne [K1, K2] - * getKeyAlias(c) retourne [K1, K2, K3] - * getKeyAlias(d) retourne [K2, K3] - * getKeyAlias(z) retourne [] - * </pre> - * - * - * @param alias FIXME - * @return une liste vide si aucune valeur ne correspond au alias en argument - */ - public Collection<K> getKeyAlias(A ... alias) { - Collection result = null; - for (Object a : alias) { - Collection tmp = aliases.getCollection(a); - if (tmp != null) { - if (result == null) { - result = new HashSet(tmp); - } else { - result.retainAll(tmp); - } - } - } - if (result == null) { - result = Collections.emptySet(); - } - return result; - } - - /** - * Retoure les valeurs en commun de tous les alias. Les valeurs retournees sont - * celle qui ont tous les alias. - * <pre> - * V1: a, b, c - * V2: b, c, d - * V3: c, d, e - * - * getKeyAlias(a, b, c) retourne [V1] - * getKeyAlias(b, c) retourne [V1, V2] - * getKeyAlias(c) retourne [V1, V2, V3] - * getKeyAlias(d) retourne [V2, V3] - * getKeyAlias(z) retourne [] - * </pre> - * - * - * @param alias FIXME - * @return une liste vide si aucune valeur ne correspond au alias en argument - */ - public Collection<V> getValueAlias(A ... alias) { - Collection keys = getKeyAlias(alias); - Collection result = new HashSet(keys.size()); - for (Object k : keys) { - result.add(get(k)); - } - return result; - } - - /** - * Retourne la liste d'alias associee avec une cle - * - * <pre> - * K1: a, b, c - * K2: b, c, d - * K3: c, d, e - * - * getAlias(K1) retourne [a, b, c] - * getAlias(k3) retourne [c, d, e] - * getKeyAlias(k9) retourne [] - * </pre> - * - * @param key FIXME - * @return FIXME - */ - public Collection<A> getAlias(K key) { - Collection result = keys.getCollection(key); - if (result == null) { - result = Collections.emptySet(); - } - return result; - } - - /** - * Retire une cle ainsi que tous ses alias - * - * <pre> - * K1: a, b, c - * K2: b, c, d - * K3: c, d, e - * - * remove(K1) il reste K2: [b, c, d], K3: [c, d, e] - * </pre> - * - * @param key FIXME - * @return FIXME - */ - @Override - public V remove(Object key) { - V result = super.remove(key); - Collection alias = getAlias((K)key); - keys.remove(key); - if (alias != null) { - for (Object a : alias) { - aliases.removeMapping(a, key); - if (CollectionUtils.isEmpty(aliases.getCollection(a))) { - aliases.remove(a); - } - } - } - return result; - } - - /** - * Supprime toutes les valeurs et leur cle associe aux alias - * - * <pre> - * K1: a, b, c - * K2: b, c, d - * K3: c, d, e - * - * removeValue(b, c) il reste K3: [c, d, e] - * </pre> - * - * @param alias FIXME - * @return la liste de valeur qui a ete supprime de la map - */ - public Collection<V> removeValue(A ... alias) { - Collection keys = getKeyAlias(alias); - Collection result = new ArrayList(keys.size()); - for (Object k : keys) { - result.add(remove(k)); - } - return result; - } - - /** - * Supprime des alias quelque soit leur cle - * - * <pre> - * K1: a, b, c - * K2: b, c, d - * K3: c, d, e - * - * removeAlias(a, b) alors K1: [c], k2: [c, d], k3: [c, d, e] - * removeAlias(c) alors K1: [a, b], k2: [b, d], k3: [d, e] - * getKeyAlias(z) alors rien ne change car cette alias n'existe pas - * </pre> - * - * @param alias FIXME - */ - public void removeAlias(A ... alias) { - for (Object a : alias) { - Collection ks = aliases.getCollection(a); - aliases.remove(a); - if (ks != null) { - for (Object k : ks) { - keys.removeMapping(k, a); - } - } - } - } -} diff --git a/src/main/java/org/nuiton/util/ArrayUtil.java b/src/main/java/org/nuiton/util/ArrayUtil.java deleted file mode 100644 index a6870cc..0000000 --- a/src/main/java/org/nuiton/util/ArrayUtil.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - - -/** - * ArrayUtil.java - * <p> - * Created: 31 oct. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - */ - -package org.nuiton.util; - -import java.lang.reflect.Array; -import java.util.Collection; - -public class ArrayUtil { // ArrayUtil - - public static int[] asIntArray(String[] a) { - int[] result = new int[a.length]; - for (int i = 0; i < a.length; i++) { - result[i] = StringUtil.toInt(a[i]); - } - return result; - } - - - /** - * Fait la somme des 2 tableaux et retourne un nouveau tableau, les - * 2 tableaux passés en argument ne sont pas modifiés. Les deux tableaux - * doivent être non null et avoir la même taille. - * - * @param a le premier tableau - * @param b le second tableau - * @return le tableau des sommes - */ - public static int[] sum(int[] a, int[] b) { - if (a == null || b == null || a.length != b.length) { - throw new IllegalArgumentException("Au moins des tableaux est null ou les tableaux ne font pas la même taille"); - } - int[] result = new int[a.length]; - for (int i = 0; i < a.length; i++) { - result[i] = a[i] + b[i]; - } - return result; - } - - public static int[] concat(int[]... tabs) { - int length = 0; - for (int[] tab : tabs) { - if (tab != null) { - length += tab.length; - } - } - int[] result = new int[length]; - length = 0; - for (int[] tab : tabs) { - if (tab != null) { - System.arraycopy(tab, 0, result, length, tab.length); - length += tab.length; - } - } - return result; - } - - /** - * Retourne un nouveau tableau qui est la concatenation des deux autres. - * Essai de garder pour le tableau resultat le type des tableaux en entré - * si possible. [Double], [Number] → [Number]; [Double], [Long] → [Object] - * - * @param tabs les tableaux - * @return le nouveau tableau ou null, si les deux tableaux sont null - * todo essayer de retourner le meilleur type de tableau possible - * [Double], [Long] → [Number] - */ - public static Object[] concat(Object[]... tabs) { - Object[] result = null; - Class<?> clazz = null; - int length = 0; - for (Object[] tab : tabs) { - if (tab != null) { - length += tab.length; - Class<?> tmp = tab.getClass().getComponentType(); - if (clazz == null) { - clazz = tmp; - } else if (tmp.isAssignableFrom(clazz)) { - clazz = tmp; - } else if (clazz.isAssignableFrom(tmp)) { - // do nothing, because clazz can't be better - } else { - clazz = Object.class; - } - } - } - - if (clazz != null) { - result = (Object[]) Array.newInstance(clazz, length); - length = 0; - for (Object[] tab : tabs) { - if (tab != null) { - System.arraycopy(tab, 0, result, length, tab.length); - length += tab.length; - } - } - } - return result; - } - - /** - * Ajoute a un tableau un ensemble d'element. Le type du tableau retourné - * est le meilleur possible. - * - * @param <E> FIXME - * @param <F> FIXME - * @param tab les valeurs initiales du tableau - * @param elems les elemements a ajouter - * @return un nouveau tableau contenant a la fin les elements souhaites - */ - @SuppressWarnings("unchecked") - public static <E, F extends E> E[] concatElems(E[] tab, F... elems) { - E[] result; - result = (E[]) concat(tab, elems); - return result; - } - - /** - * Recherche dans le table le 1er element qui correspond a la classe - * passée en argument. - * - * @param <A> FIXME - * @param tab le tableau dans lequel il faut chercher - * @param clazz la classe de l'objet souhaité - * @return un objet de la classe demandé, ou null si aucun ne correspond - */ - public static <A> A search(Object[] tab, Class<A> clazz) { - A result = null; - for (Object o : tab) { - if (clazz.isInstance(o)) { - result = clazz.cast(o); - } - } - return result; - } - - @SuppressWarnings({"unchecked"}) - public static <T> T[] toArray(Collection list, Class<T> clazz) { - T[] result = (T[]) Array.newInstance(clazz, list == null ? 0 : list.size()); - int i = 0; - for (Object o : list) { - result[i++] = (T) o; - } - return result; - } -} // ArrayUtil - diff --git a/src/main/java/org/nuiton/util/BoundedList.java b/src/main/java/org/nuiton/util/BoundedList.java deleted file mode 100644 index 18d8893..0000000 --- a/src/main/java/org/nuiton/util/BoundedList.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * ArrayList with minimum and maximum sizes. For each operation, the size is - * checked and the BoundedList to ensure that it is kept in the range. - * - * Created: 10 juin 2005 - * - * @author Arnaud Thimel - thimel@codelutin.com - * - */ -public class BoundedList<E> extends ArrayList<E> { - /** */ - private static final long serialVersionUID = -3211387041114409849L; - - //By defaut, maxSize is set to -1 (infinite) - private int minSize = 0; - - private int maxSize = -1; - - /** - * Indicates if the list size is at the maximum - * - * @return true is the maximum size has been reached - */ - public boolean isFull() { - return (maxSize == -1 || size() >= maxSize); - } - - /** - * Indicates if the list size is to the minimum - * - * @return true is the list size is the minimum size - */ - public boolean isToMinimum() { - return (size() <= minSize); - } - - /** - * Creates a new BoundedList with the specified initialCapacity. The min size is set to 0 and the max size to the infinite. - * - * @param initialCapacity FIXME - */ - public BoundedList(int initialCapacity) { - super(initialCapacity); - } - - /** Creates a new BoundedList with the default capacity. The min size is set to 0 and the max size to the infinite. */ - public BoundedList() { - super(); - } - - /** - * Creates a new BoundedList with the specified collection of elements. The min size is set to 0 and the max size to the infinite. - * - * @param arg0 FIXME - */ - public BoundedList(Collection<E> arg0) { - super(arg0); - } - - /** - * Creates a new empty BoundedList with the specified min and max sizes. Please be informed that -1 represents the infinite. - * - * @param minSize FIXME - * @param maxSize FIXME - */ - public BoundedList(int minSize, int maxSize) { - super(); - if (minSize > 0) - this.minSize = minSize; - if (minSize > -1) - this.maxSize = maxSize; - } - - /** - * Appends the specified element to the end of this list. - * - * @param o the Object to be added - */ - @Override - public boolean add(E o) { - if (checkNewSize(1)) - return super.add(o); - else - throw getException("Cannot add element. Use set to replace element or remove to free space or addAll"); - } - - /** - * Inserts the specified element at the specified position in this list. - * - * @param index the position where to add the Object - * @param o the Object to be added - */ - @Override - public void add(int index, E o) { - if (checkNewSize(1)) - super.add(index, o); - else - throw getException("Cannot add element. Use set to replace element or remove to free space or addAll"); - } - - /** - * Appends all of the elements in the specified Collection to the end of this list, in the order that they are returned by the specified Collection's Iterator. - * - * @param c the collection of Objects to be added - */ - @Override - public boolean addAll(Collection<? extends E> c) { - if (checkNewSize(c.size())) - return super.addAll(c); - else - throw getException("Cannot add element. Use set to replace element or remove to free space or addAll"); - } - - /** - * Inserts all of the elements in the specified Collection into this list, starting at the specified position. - * - * @param index the index where to start adding the collection of objects - * @param c the collection of Objects to be added - */ - @Override - public boolean addAll(int index, Collection<? extends E> c) { - if (checkNewSize(c.size())) - return super.addAll(index, c); - else - throw getException("Cannot add element. Use set to replace element or remove to free space or addAll"); - } - - /** Returns a shallow copy of this BoundedList instance */ - @SuppressWarnings("unchecked") - @Override - public Object clone() { - BoundedList<E> bL = (BoundedList<E>) super.clone(); - bL.minSize = minSize; - bL.maxSize = maxSize; - return bL; - } - - /* - public Object set(int index, Object o) { - //Pas d'action particulière à priori - return super.set(index, o); - } - */ - - /** - * Removes the element at the specified position in this list. - * - * @param index the position of the element to be removed - */ - @Override - public E remove(int index) { - if (checkNewSize(-1)) - return super.remove(index); - else - throw getException("Cannot remove element, minSize is " + minSize); - } - - /** - * Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive. - * - * @param fromIndex index of first element to be removed - * @param toIndex index after last element to be removed - */ - @Override - protected void removeRange(int fromIndex, int toIndex) { - if (checkNewSize(-(toIndex - fromIndex))) - super.removeRange(fromIndex, toIndex); - else - throw getException("Cannot remove element, minSize is " + minSize); - } - - /** Removes a single instance of the specified element from this list, if it is present (optional operation). */ - @Override - public boolean remove(Object o) { - if (checkNewSize(-1) || !contains(o)) - return super.remove(o); - else - throw getException("Cannot remove element, minSize is " + minSize); - } - - /** Removes from this collection all of its elements that are contained in the specified collection (optional operation). */ - @Override - public boolean removeAll(Collection<?> c) { - //On ne sait pas si les éléments de la Collection sont contenus dans la liste. - //De plus, on ne sait pas si les instances sont présentes un ou plusieurs fois (Si elles y sont +sieurs fois elles sont supprimées +sieurs fois) - if (checkNewSize(-c.size())) - return super.removeAll(c); - else - throw getException("Cannot remove element, minSize is " + minSize); - } - - private boolean checkNewSize(int size) { - if (size == 0) //Pas de changement de taille ! - return (((size()) >= minSize) && ((maxSize == -1) || (size() <= maxSize))); - else if (size > 0) //Ajout d'un elem - vérification qu'on ne dépasse pas la borne max - return ((maxSize == -1) || ((size() + size) <= maxSize)); - return ((size() + size) >= minSize); //Suppression d'un élem - on vérifie qu'on ne descend pas en dessous de la borne min - } - - private RuntimeException getException(String msg) { - return new BoundedListOutOfBoundsException(msg); - } - - @Override - public String toString() { - return /*"(" + minSize + ", " + maxSize + ") " +*/ super.toString(); - } -} diff --git a/src/main/java/org/nuiton/util/BoundedListOutOfBoundsException.java b/src/main/java/org/nuiton/util/BoundedListOutOfBoundsException.java deleted file mode 100644 index bca1a89..0000000 --- a/src/main/java/org/nuiton/util/BoundedListOutOfBoundsException.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * -* BoundedListOfBoundsException.java -* -* Created: 30 mai 2005 -* -* @author Arnaud Thimel - thimel@codelutin.com -* -*/ - - -package org.nuiton.util; - - -public class BoundedListOutOfBoundsException extends RuntimeException { - - private static final long serialVersionUID = 7006384682459926080L; - - public BoundedListOutOfBoundsException() { - super(); - } - - public BoundedListOutOfBoundsException(String message) { - super(message); - } - - public BoundedListOutOfBoundsException(String message, Throwable cause) { - super(message, cause); - } - - public BoundedListOutOfBoundsException(Throwable cause) { - super(cause); - } - -} diff --git a/src/main/java/org/nuiton/util/CallAnalyse.java b/src/main/java/org/nuiton/util/CallAnalyse.java deleted file mode 100644 index 8a4b934..0000000 --- a/src/main/java/org/nuiton/util/CallAnalyse.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.collections.primitives.ArrayLongList; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * Cette classe permet de faire des analyses sur les appels de methode - * En debut de methode on appelle la methode {@link #enter}, et en fin de methode - * la methode {@link #exit}. - * <p> - * Ensuite on peut récuperer les statistiques par Thread ou de tous les threads - * <p> - * On a comme statistique - * <ul> - * <li> le temps d'execution - * <li> la memore utilisé - * <li> le nombre d'appels - * </ul> - * - * @author Benjamin Poussin - poussin@codelutin.com - * @see TimeLog - * Created: 25 aout 2005 14:09:22 CEST - */ -public class CallAnalyse { // CallAnalyse - - /** - * Logger. - */ - static private Log log = LogFactory.getLog(CallAnalyse.class); - - static private List<ThreadStatistics> listThreadStatistics = - new ArrayList<ThreadStatistics>(); - - static private ThreadLocal<ThreadStatistics> stats = - new ThreadLocal<ThreadStatistics>() { - @Override - protected synchronized ThreadStatistics initialValue() { - ThreadStatistics result = new ThreadStatistics(); - listThreadStatistics.add(result); - return result; - } - }; - - /** - * Permet d'activer les statistiques, pour le thread courant - */ - public static void activate() { - stats.get().setActivated(true); - } - - /** - * Permet de desactiver les statistiques, pour le thread courant - */ - public static void desactivate() { - stats.get().setActivated(false); - } - - /** - * Permet de savoir si les statistiques sont activées ou non, pour le - * thread courant - * @return FIXME - */ - public static boolean isActivate() { - return stats.get().getActivated(); - } - - /** - * @param name le nom de l'appel a monitorer - */ - public static void enter(String name) { - ThreadStatistics t = stats.get(); - if (t.getActivated()) { - t.get(name).enter(); - } - } - - /** - * Indique la sortie de l'appel, name doit avoir ete utilisé lors d'un enter - * - * @param name le nom de l'appel a monitorer, doit etre identique a - * celui utilisé pour la methode enter - */ - public static void exit(String name) { - ThreadStatistics t = stats.get(); - if (t.getActivated()) { - t.get(name).exit(); - } - } - - /** - * @return the statistics for the current thread - */ - public static ThreadStatistics getThreadStatistics() { - return stats.get(); - } - - /** - * @return the statistics for all threads - */ - public static List<ThreadStatistics> getAllThreadStatistics() { - return listThreadStatistics; - } - - public static class ThreadStatistics extends TreeMap<String, CallStatistics> { - /** */ - private static final long serialVersionUID = -36051448464013504L; - - protected boolean activated = false; - - public boolean getActivated() { - return activated; - } - - public void setActivated(boolean activated) { - this.activated = activated; - } - - public CallStatistics get(String name) { - CallStatistics result = super.get(name); - if (result == null) { - put(name, result = new CallStatistics(name)); - } - return result; - } - - public String toString() { - return values().toString(); - } - } - - /** - * This method will get all the statistics from all the threads and put it - * all together in a {@link Map} which key is the name of the watched - * element and the value is its instance of {@link CallStatisticsSummary} - * - * @return A map with all collected statistics - */ - public static Map<String, CallStatisticsSummary> getSummary() { - Map<String, CallStatisticsSummary> results = new HashMap<String, CallStatisticsSummary>(); - for (ThreadStatistics stats : CallAnalyse.getAllThreadStatistics()) { - for (String name : stats.keySet()) { - CallStatisticsSummary stat = results.get(name); - if (stat == null) { - stat = new CallStatisticsSummary(name); - results.put(name, stat); - } - stat.addCallStats(stats.get(name)); - } - } - return results; - } - - /** - * CallStatistics is the class which handles values on excecution time and - * memory usage. - * Each CallStatistics object is for one particular name. - * - * @author bpoussin - */ - public static class CallStatistics implements Cloneable { - protected String name = null; - - protected long calls = 0; - - protected long minTime = Long.MAX_VALUE; - - protected long maxTime = Long.MIN_VALUE; - - protected long sumTime = 0; - - protected long minMemory = Long.MAX_VALUE; - - protected long maxMemory = Long.MIN_VALUE; - - protected long sumMemory = 0; - - /** - * pile contenant le temps de appel, util pour les appels recursifs - */ - protected ArrayLongList times = new ArrayLongList(); - - protected ArrayLongList memories = new ArrayLongList(); - - protected Runtime runtime = Runtime.getRuntime(); - - public CallStatistics(String name) { - this.name = name; - } - - public void enter() { - times.add(System.nanoTime()); - memories.add(getMemory()); - } - - public void exit() { - calls++; - - if (times.size() == 0) { - log.info("To many exit call for " + name); - return; - } - long time = times.removeElementAt(times.size() - 1); - time = System.nanoTime() - time; - if (time < minTime || minTime == Long.MAX_VALUE) { - minTime = time; - } - if (time > maxTime) { - maxTime = time; - } - sumTime += time; - - long memory = memories.removeElementAt(memories.size() - 1); - memory = getMemory() - memory; - if (memory < minMemory || minMemory == Long.MAX_VALUE) { - minMemory = memory; - } - if (memory > maxMemory) { - maxMemory = memory; - } - sumMemory += memory; - } - - public String getName() { - return name; - } - - public long getCalls() { - return calls; - } - - public long getMinTime() { - return minTime; - } - - public long getMaxTime() { - return maxTime; - } - - public long getSumTime() { - return sumTime; - } - - public long getAvgTime() { - if (calls == 0) { - return 0; - } else { - return sumTime / calls; - } - } - - public long getMinMemory() { - return minMemory; - } - - public long getMaxMemory() { - return maxMemory; - } - - public long getSumMemory() { - return sumMemory; - } - - public long getAvgMemory() { - if (calls == 0) { - return 0; - } else { - return sumMemory / calls; - } - } - - protected long getMemory() { - // runtime.gc(); - return runtime.totalMemory() - runtime.freeMemory(); - } - - @Override - public String toString() { - return getName() + " calls=" + getCalls() - + " time=" + StringUtil.convertTime(getSumTime()) - + "(" + StringUtil.convertTime(getMinTime()) + "/" + StringUtil.convertTime(getAvgTime()) + "/" + StringUtil.convertTime(getMaxTime()) + ")" - + " memory=" + StringUtil.convertMemory(getSumMemory()) - + "(" + StringUtil.convertMemory(getMinMemory()) + "/" + StringUtil.convertMemory(getAvgMemory()) + "/" + StringUtil.convertMemory(getMaxMemory()) + ")" - ; - } - - } //CallStatistics - - /** - * This class is collecting data from different CallStatistics classes by - * using the method {@link #addCallStats(org.nuiton.util.CallAnalyse.CallStatistics)}. - * - * @author thimel - */ - public static class CallStatisticsSummary extends CallStatistics { - - public CallStatisticsSummary(String name) { - super(name); - } - - /** - * This methods read the given {@link CallStatistics} and add values to - * its own - * - * @param other an other CallStatistics object - */ - public void addCallStats(CallStatistics other) { - if (other == null || this.equals(other)) { - return; - } - calls += other.getCalls(); - if (other.getMinTime() < minTime || minTime == Long.MAX_VALUE) { - minTime = other.getMinTime(); - } - if (other.getMaxTime() > maxTime) { - maxTime = other.getMaxTime(); - } - - sumTime += other.getSumTime(); - - if (other.getMinMemory() < minMemory || minMemory == Long.MAX_VALUE) { - minMemory = other.getMinMemory(); - } - if (other.getMaxMemory() > maxMemory) { - maxMemory = other.getMaxMemory(); - } - sumMemory += other.getSumMemory(); - } - } //CallStatisticsSummary - -} // CallAnalyse - diff --git a/src/main/java/org/nuiton/util/CardinalityHelper.java b/src/main/java/org/nuiton/util/CardinalityHelper.java deleted file mode 100644 index 0e183d5..0000000 --- a/src/main/java/org/nuiton/util/CardinalityHelper.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Une classe avec des méthodes utiles sur les cardinalités : - * - * parser une cardinalité {@link #parseCardinalite(String, boolean)} - * - * afficher une cardinité {@link #printCardinalite(StringBuilder, String, int, int, boolean, String, String, String, String)} - * - * et pour tester des cardinalités : - * - * {@link #isMandatory(int)}, savoir si une cardinalité est obligatoire à - * partir de son min. - * - * {@link #isRepetable(int)}, savoir si une cardinalité est répétable à partir - * de son max. - * - * {@link #isMaxBounded(int)}, savoir si une cardinalité est bornée sur son max - * à partir de son max. - * - * {@link #isDefaultMandatory(int, int)}, savoir si la cardinalité est la - * cardinalité obligatoire par défaut {1}. - * - * {@link #isDefaultOptional(int, int)}, savoir si la cardinalité est la - * cardinalité optionel par défaut {0,1}. - * - * {@link #isAvailable(int, int)}, savoir si il reste encore des occurrences - * disponibles sur une cardianlité à partir d'un nombre d'oocurrence et du max - * de la cardinalité. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class CardinalityHelper { - - static final Pattern PATTERN_OPTIONAL = Pattern.compile("\\[.*\\]"); - - static final Pattern PATTERN_MANDATORY = Pattern.compile("\\<.*\\>"); - - /** XXX + ou XXX * */ - public static final Pattern PATTERN_NO_MAX_BOUND = Pattern.compile("(.*)(\\+|\\*)"); - - /** XXX {n} n est un entier */ - public static final Pattern PATTERN_EXTACLY = Pattern.compile("(.*)\\{([0-9]+)\\}"); - - /** XXX {n,m} n est un entier, m est un entier ou * */ - public static final Pattern PATTERN_BOUNDED = Pattern.compile("(.*)\\{([0-9]+),([0-9]+|\\*)\\}"); - - /** - * Indique si une cardinalité est la cardinalité obligatoire par défaut {1} - * - * @param min le min de la cardinalité à tester - * @param max le max de la cardinalité à tester - * @return {@code true} si min==1 et max=1 - */ - public static boolean isDefaultMandatory(int min, int max) { - return min == 1 && max == 1; - } - - /** - * Indique si une cardinalité est la cardinalité optionel par défaut {0,1} - * - * @param min le min de la cardinalité à tester - * @param max le max de la cardinalité à tester - * @return {@code true} si min==0 et max==1 - */ - public static boolean isDefaultOptional(int min, int max) { - return min == 0 && max == 1; - } - - /** - * Indique si une cardinalité est obligatoire à partir de son min - * - * @param min le min de la cardinalité à tester - * @return {@code true} si min>0 - */ - public static boolean isMandatory(int min) { - return min > 0; - } - - /** - * Indique si une cardinalité est majorée à partir de son max - * - * @param max le max de la cardinalité à tester - * @return {@code true} si max≠-1 - */ - public static boolean isMaxBounded(int max) { - return max != -1; - } - - /** - * Indique si une cardinalité est répétable à partir de son max - * - * @param max le max de la cardinalité à tester - * @return {@code true} si max>0 || max==-1 - */ - public static boolean isRepetable(int max) { - return !isMaxBounded(max) || max > 1; - } - - /** - * Indique si on n'a pas encore atteint la borne max d'une cardinalité à - * partir de son max et d'un nombre d'occurrences déjà atteint. - * - * @param current le nombre d'occurence actuel - * @param max la borne max de la cardinalité - * @return {@code true} si la cardinalité n'a pas atteint sa borne max - */ - - public static boolean isAvailable(int current, int max) { - return !isMaxBounded(max) || current < max; - } - - /** - * Retourne le min par défault d'une cardinalité à partir du critère - * obligatoire ou non. - * - * @param mandatory le critère à tester - * @return {@code 1} si obligatoire, 0 sinon. - */ - public static int getDefaultMin(boolean mandatory) { - return mandatory ? 1 : 0; - } - - /** - * Parse la cardinalite à la fin d'un texte. - * - * @param txt la valeur dont on cherche la cardinalité - * @param mandatory si vrai, valeurs par default {1}, sinon {0,1} - * @return un tableau contenant 3 object : le texte donné sans les - * informations de cardinalité, la répétitionMin, la répétitionMax. - */ - public static Object[] parseCardinalite(String txt, boolean mandatory) { - - Object[] result = new Object[3]; - Matcher matcher; - - // always trim the text - txt = txt.trim(); - if ((matcher = PATTERN_NO_MAX_BOUND.matcher(txt)).matches()) { - // find a no max cardinalite *|+ - result[0] = matcher.group(1).trim(); - result[1] = getDefaultMin(matcher.group(2).equals("+")); - result[2] = -1; - } else if ((matcher = PATTERN_EXTACLY.matcher(txt)).matches()) { - // found a exactly cardinalite {n} - result[0] = matcher.group(1).trim(); - result[1] = Integer.valueOf(matcher.group(2)); - result[2] = result[1]; - } else if ((matcher = PATTERN_BOUNDED.matcher(txt)).matches()) { - // found a bounded cardinalite {n,m} - result[0] = matcher.group(1).trim(); - result[1] = Integer.valueOf(matcher.group(2)); - String max = matcher.group(3); - result[2] = max.equals("*") ? -1 : Integer.valueOf(max); - } else { - // no cardinalite was found, use default values - result[0] = txt.trim(); - result[1] = getDefaultMin(mandatory); - result[2] = 1; - } - return result; - } - - /** - * Imprime dans le builder, le txt + une cardinalité. - * - * @param sb le builder - * @param txt le txt à imprimer - * @param min la caridnalité min - * @param max la cardinalité max - * @param mandatory pour indiquer dans quel cas on affiche la cardinalité : - * si elle correspond aux valeurs par défaut - * de mandatory {1} ou optionel {0,1}, pas d'impression. - * @param mo le caractère ouvrant pour un object obligatoire - * @param mc le caractère fermant pour un object obligatoire - * @param oo le caractère ouvrant pour un object optionel - * @param oc le caractère fermant pour un object optionel - */ - public static void printCardinalite(StringBuilder sb, String txt, int min, int max, boolean mandatory, String mo, String mc, String oo, String oc) { - // flag pour indiquer s'il faut ou non imprimer les bordures - boolean print = false; - - boolean maxBounded = isMaxBounded(max); - if (isMandatory(min)) { - sb.append(mo).append(txt).append(mc); - if (isDefaultMandatory(min, max)) { - if (mandatory || mo.length() > 0) { - // rien a faire on a la valeur par defaut attendue, ou la - // bordure existe et remplace la valeur par defaut - } else { - // pas de bordure, ou valeur optionel attendue, on doit imprimer la cardinalite - print = true; - } - } else { - if (!maxBounded && min == 1) { - sb.append('+'); - } else { - print = true; - } - } - } else { - sb.append(oo).append(txt).append(oc); - if (isDefaultOptional(min, max)) { - if (!mandatory || oo.length() > 0) { - // rien a faire on a la valeur par defaut attendue, ou la - // bordure existe et remplace la valeur par defaut - } else { - // pas de bordure, ou valeur optionel attendue, on doit imprimer la cardinalite - print = true; - } - } else { - if (!maxBounded) { - sb.append('*'); - } else { - print = true; - } - } - } - if (print) { - sb.append('{'); - sb.append(min); - if (max != min) { - sb.append(','); - sb.append(maxBounded ? max : "*"); - } - sb.append('}'); - } - } - - protected CardinalityHelper() { - // do not instanciate - } - -} diff --git a/src/main/java/org/nuiton/util/CategorisedListenerSet.java b/src/main/java/org/nuiton/util/CategorisedListenerSet.java deleted file mode 100644 index 0d5f13d..0000000 --- a/src/main/java/org/nuiton/util/CategorisedListenerSet.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - - -/* * - * CategorisedListenerSet.java - * - * Created: 13 mai 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * Copyright Code Lutin - * - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.beans.Statement; -import java.util.Iterator; -import java.util.WeakHashMap; - -/** - * Objet permettant de géré plusieurs liste de listener de facon simple. - * Chaque liste de listener est rangé en fonction d'une cle (categorie) - * Une categorie peut avoir un pere, dans ce cas si un event doit etre lancé - * sur une categorie il est aussi lancer sur le pere de la categorie. - * Mais attention l'inverse n'est pas vrai, un event lancé sur un père n'est - * jamais lancé sur ses fils. - * Il existe une Category spéciale {@link #ALL} qui permet d'envoyer un event - * a tous les listeners. - * Si cette classe est la derniere classe a conserver l'objet categorie - * alors la categorie est libere et ainsi que les listeners si c'etait aussi - * leur derniers referencements - * - * <p> Si les categories sont representees par des Class, alors vous pouvez - * utiliser la hierachie de classe pour creer de facon automatique les peres. - * - * @param <L> listener type - * @see ListenerSet - */ -public class CategorisedListenerSet<L> { // CategorisedListenerSet - - /** Logger. */ - private static Log log = LogFactory.getLog(CategorisedListenerSet.class); - - /** - * permet de remplacer toutes les categories. - * Si on utilise cette category, alors tous les listeners present - * seront utilisé. - */ - public static final Object ALL = new Object(); - - /** - * HashMap de ListenerSet, en cle l'objet qui caracterise la categorie - * en valeur un ListenerSet - */ - protected WeakHashMap<Object, ListenerSet<L>> listeners = new WeakHashMap<Object, ListenerSet<L>>(); - - protected WeakHashMap<Object, Object> categoryParent = new WeakHashMap<Object, Object>(); - - protected boolean isClassCategory = true; - - /** Empty constructor. */ - public CategorisedListenerSet() { - - } - - /** - * @param isClassCategory si vrai et que les categorie passé en arguement - * lors de l'ajout sont de type Class alors lors du fire on recherche aussi - * les peres dans la hierarchie d'heritage de la classe (Super class et - * interfaces) - */ - public CategorisedListenerSet(boolean isClassCategory) { - this(); - this.isClassCategory = isClassCategory; - } - - protected void checkCategory(Object category) { - if (ALL.equals(category)) { - throw new IllegalArgumentException( - "ALL category can't be use to add listener or add Category"); - } - } - - /** - * Ajoute une categorie en indiquant sont pere. Une categorie ne peut - * avoir qu'un seul pere, si la nouvelle categorie existait deja - * alors l'appel a cette methode change son pere. - * - * @param parent le pere de la categorie, null si on ne souhaite pas de pere - * @param newCategory la nouvelle caterogie - */ - public void addCategory(Object parent, Object newCategory) { - checkCategory(parent); - checkCategory(newCategory); - categoryParent.put(newCategory, parent); - } - - /** - * Ajoute un listener sur une certaine categorie, si la categorie n'existe - * alors on la crée en ne lui affectant pas de père - * - * @param category la categorie dans lequel il faut ajouter le listener - * @param l le listener a ajouter - */ - public void add(Object category, L l) { - checkCategory(category); - ListenerSet<L> listeners = getListeners(category); - listeners.add(l); - } - - /** - * Supprime un listener d'une categorie, si la categorie ou le listener - * n'existe pas, rien ne se passe. - * - * @param category la categorie dans lequel il faut supprimer le listener - * @param l le listener a supprimer - */ - public void remove(Object category, L l) { - ListenerSet<L> listeners = getListeners(category); - listeners.remove(l); - } - - /** - * Permet de lancer un event dans une categorie, l'event est aussi propagé - * sur les ancètres de la categorie - * - * @param category la categorie a partir duquel il faut lancer l'evenement - * @param methodName le nom de la méthode de la classe listener - * @param event l'objet event a passer en paramètre de la methode du - * listener - * @throws Exception if event can't be fired - */ - public void fire(Object category, String methodName, Object event) - throws Exception { - if (log.isTraceEnabled()) { - log.trace("fire category: " + category + " method: " + methodName); - } - ListenerSet<L> ls = getAllListeners(category); - ls.fire(methodName, event); - } - - /** - * Permet de lancer un event dans une categorie, l'event est aussi propagé - * sur les ancètres de la categorie, si un meme objet etait listener - * dans plusieurs categories alors il ne recevra qu'une seul notification - * - * @param category la categorie a partir duquel il faut lancer l'evenement - * @param methodName le nom de la méthode de la classe listener - * @throws Exception if event can't be fired - */ - public void fire(Object category, String methodName) throws Exception { - for (L l : getAllListeners(category)) { - Statement stm = new Statement(l, methodName, null); - stm.execute(); - } - } - - /** - * Retourne un Iterator sur tous les listeners qu'il faut prevenir si on - * souhaite prevenir une certaine categorie. Ceci inclue les ancetre de la - * categorie - * - * @param category category to get iterator on - * @return iterator - */ - public Iterator<L> iterator(Object category) { - return getAllListeners(category).iterator(); - } - - /** - * @param category categorie demandee - * @return un ListenerSet contenant tous les listeners c'est à dire les - * listener de la categorie demandé mais aussi les listeners des ancetres - */ - protected ListenerSet<L> getAllListeners(Object category) { - ListenerSet<L> result = new ListenerSet<L>(); - if (ALL.equals(category)) { - for (ListenerSet<L> ls : listeners.values()) { - result.addAll(ls); - } - } else { - Object parentCategory = category; - while (parentCategory != null) { - result.addAll(getListeners(parentCategory)); - if (isClassCategory && parentCategory instanceof Class) { - result.addAll(getListenersClass((Class<?>) parentCategory)); - } - parentCategory = categoryParent.get(parentCategory); - } - } - if (log.isTraceEnabled()) { - log.trace("getAllListeners category: " + category + " result: " - + result); - } - return result; - } - - protected ListenerSet<L> getListenersClass(Class<?> category) { - ListenerSet<L> result = new ListenerSet<L>(); - Class<?> superClass = category.getSuperclass(); - if (superClass != null) { - result.addAll(getAllListeners(superClass)); - } - for (Class<?> c : category.getInterfaces()) { - result.addAll(getAllListeners(c)); - } - return result; - } - - /** - * @param category categorie demandee - * @return un ListenerSet contenant seulement les listener de la categorie - * demandé. Si la categorie n'existe pas alors elle est créé. - */ - protected ListenerSet<L> getListeners(Object category) { - ListenerSet<L> result = listeners.get(category); - if (result == null) { - listeners.put(category, result = new ListenerSet<L>()); - } - if (log != null && log.isTraceEnabled()) { - log.trace("getListeners category: " + category + " result: " - + result); - } - return result; - } - - public String toString() { - return "Listeners Category: " + categoryParent + "\nListener: " - + listeners; - } - -} // CategorisedListenerSet - diff --git a/src/main/java/org/nuiton/util/ClassLoaderUtil.java b/src/main/java/org/nuiton/util/ClassLoaderUtil.java deleted file mode 100644 index d305232..0000000 --- a/src/main/java/org/nuiton/util/ClassLoaderUtil.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Stack; - -/** - * A usefull class with method for ClassLoader - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class ClassLoaderUtil { - - - /** Logger. */ - private static final Log log = LogFactory.getLog(ClassLoaderUtil.class); - - /** - * Returns the all urls to be used in a {@link URLClassLoader}. - * - * If classloader has only one url and the url is a jar, try to load in - * manifest class-path. - * - * @param loader the classloader (if null will use system one) - * @return all the url found in the classloader - */ - public static URL[] getDeepURLs(URLClassLoader loader) { - Stack<URL> urlToTreate = new Stack<URL>(); - List<URL> urlTreated = new ArrayList<URL>(); - - // first get the urls from classloader - URL[] result = getURLs(loader); - - urlToTreate.addAll(Arrays.asList(result)); - while (!urlToTreate.isEmpty()) { - URL currentUrl = urlToTreate.pop(); - // save the url - urlTreated.add(currentUrl); - if (Resource.isJar(currentUrl.toString())) { - // jar invocation - try { - URL[] newArrayURLs = - Resource.getClassPathURLsFromJarManifest( - currentUrl); - if (newArrayURLs == null) { - continue; - } - List<URL> newURLs = Arrays.asList(newArrayURLs); - for (URL newURL : newURLs) { - if (!urlTreated.contains(newURL) && - !urlToTreate.contains(newURL)) { - urlToTreate.add(newURL); - } - } - } catch (Exception e) { - if (log.isDebugEnabled()) { - // this is not a such error, but some jar can not be - log.debug("error with url" + currentUrl + - " for reason : " + e.getMessage()); - } - } - } - } - return urlTreated.toArray(new URL[urlToTreate.size()]); - } - - /** - * Recupere la liste des urls d'un {@link URLClassLoader}. - * - * Note : Un cas particulier est positionné pour JBoss qui utilise - * la method getAllURLs. - * - * @param classLoader le class loader a scanner - * @return les urls du classloade. - */ - public static URL[] getURLs(URLClassLoader classLoader) { - if (classLoader == null) { - classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); - } - Method m; - try { - // Essai de récupération de la méthode getAllURLs() de - // RepositoryClassLoader (JBoss) - m = classLoader.getClass().getMethod("getAllURLs"); - } catch (Exception e) { - m = null; - } - URL[] result; - if (m == null) { - result = classLoader.getURLs(); - } else { - try { - result = (URL[]) m.invoke(classLoader); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - return result; - } - - public static void printLoader(ClassLoader loader) { - log.info(loader); - if (loader instanceof URLClassLoader) { - URL[] urls = getURLs((URLClassLoader) loader); - for (URL url : urls) { - log.info(url); - } - } - } - -} diff --git a/src/main/java/org/nuiton/util/CollectionUtil.java b/src/main/java/org/nuiton/util/CollectionUtil.java deleted file mode 100644 index ce6cee2..0000000 --- a/src/main/java/org/nuiton/util/CollectionUtil.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Set; - - -/** - * Created: 23 févr. 2006 09:03:39 - * - * @author Benjamin Poussin - poussin@codelutin.com - */ - -public class CollectionUtil { - - /** - * Ajoute a la collection tous les elements passés en parametre - * - * @param <A> FIXME - * @param <E> FIXME - * @param col la collection - * @param e les elements a ajouter - * @return la collection passé en parametre - */ - public static <A, E extends Collection<A>> E addAll(E col, A... e) { - Collections.addAll(col, e); - return col; - } - - /** - * Ajoute a la liste tous les elements passés en parametre - * - * @param <A> FIXME - * @param <E> FIXME - * @param col la liste - * @param pos le premier index où insérer les données - * @param e les elements a ajouter - * @return la liste passé en parametre - */ - public static <A, E extends List<A>> E addAll(E col, int pos, A... e) { - col.addAll(pos, Arrays.asList(e)); - return col; - } - - /** - * Permet de convertir une liste non typée, en une liste typée. - * <p> - * La liste en entrée en juste bien castée. - * <p> - * On effectue une vérification sur le typage des élements de la liste. - * <p> - * Note : <b>Aucune liste n'est créee, ni recopiée</b> - * - * @param <O> data type - * @param list la liste à convertir - * @param type le type des éléments de la liste - * @return la liste typée - * @throws IllegalArgumentException si un élément de la liste en entrée n'est - * pas en adéquation avec le type voulue. - */ - @SuppressWarnings({"unchecked"}) - public static <O> List<O> toGenericList( - List<?> list, Class<O> type) throws IllegalArgumentException { - if (list.isEmpty()) { - return (List<O>) list; - } - for (Object o : list) { - if (!type.isAssignableFrom(o.getClass())) { - throw new IllegalArgumentException( - "can not cast List with object of type " + - o.getClass() + " to " + type + " type!"); - } - } - return (List<O>) list; - } - - /** - * Permet de convertir une collection non typée, en une collection typée. - * <p> - * La collection en entrée en juste bien castée. - * <p> - * On effectue une vérification sur le typage des élements de la collection. - * <p> - * Note : <b>Aucune collection n'est créee, ni recopiée</b> - * - * @param <O> data type - * @param list la collection à convertir - * @param type le type des éléments de la collection - * @return la collection typée - * @throws IllegalArgumentException si un élément de la collection en entrée n'est - * pas en adéquation avec le type voulue. - */ - @SuppressWarnings({"unchecked"}) - public static <O> Collection<O> toGenericCollection( - Collection<?> list, Class<O> type) throws IllegalArgumentException { - if (list.isEmpty()) { - return (Collection<O>) list; - } - for (Object o : list) { - if (!type.isAssignableFrom(o.getClass())) { - throw new IllegalArgumentException( - "can not cast Collection with object of type " + - o.getClass() + " to " + type + " type!"); - } - } - return (Collection<O>) list; - } - - /** - * Permet de convertir un ensemble non typée, en un ensemble typée. - * <p> - * L'ensemble en entrée en juste bien castée. - * <p> - * On effectue une vérification sur le typage des élements de la collection. - * <p> - * Note : <b>Aucun ensemble n'est créee, ni recopiée</b> - * - * @param <O> data type - * @param list l'ensemble à convertir - * @param type le type des éléments de l'ensemble - * @return l'ensemble typée - * @throws IllegalArgumentException si un élément de l'ensemble en entrée n'est - * pas en adéquation avec le type voulue. - */ - @SuppressWarnings({"unchecked"}) - public static <O> Set<O> toGenericSet( - Set<?> list, Class<O> type) throws IllegalArgumentException { - if (list.isEmpty()) { - return (Set<O>) list; - } - for (Object o : list) { - if (!type.isAssignableFrom(o.getClass())) { - throw new IllegalArgumentException( - "can not cast Set with object of type " + - o.getClass() + " to " + type + " type!"); - } - } - return (Set<O>) list; - } - - /** - * Get data at given {@code index} from the given collection or - * {@code null} if no element at given position. - * - * @param collection the collection to scan - * @param index index to seek - * @param <T> type of data in collection - * @return the data found at given index, or {@code null} if not found - * @since 2.6.4 - */ - public static <T> T getOrNull(Collection<T> collection, int index) { - T result = null; - if (collection != null) { - int i = 0; - for (T t : collection) { - if (index == i) { - result = t; - break; - } - i++; - } - } - return result; - } - - /** - * Get data at given {@code index} from the given collection. - * - * @param collection the collection to scan - * @param index index to seek - * @param <T> type of data in collection - * @return the data found at given index - * @throws IndexOutOfBoundsException if there is such index in collection - * @since 2.6.4 - */ - public static <T> T get(Collection<T> collection, int index) throws IndexOutOfBoundsException { - T result = null; - if (collection != null) { - int i = 0; - for (T t : collection) { - if (index == i) { - result = t; - break; - } - i++; - } - if (i != index) { - throw new IndexOutOfBoundsException("No element at index " + index); - } - } - return result; - } - - /** - * Get data at given {@code index} from the given list. - * - * @param list the list to scan - * @param index index to seek - * @param <T> type of data in collection - * @return the data found at given index - * @throws IndexOutOfBoundsException if there is such index in list - * @since 2.6.4 - */ - public static <T> T get(List<T> list, int index) throws IndexOutOfBoundsException { - T result = null; - if (list != null) { - if (index >= list.size()) { - throw new IndexOutOfBoundsException("No element at index " + index); - } - result = list.get(index); - } - return result; - } - - /** - * Get data at given {@code index} from the given list or {@code null} if - * no such index in list. - * - * @param list the list to scan - * @param index index to seek - * @param <T> type of data in collection - * @return the data found at given index or {@code null} if no such index in list - * @since 2.6.4 - */ - public static <T> T getOrNull(List<T> list, int index) { - T result = null; - if (list != null) { - if (index < list.size()) { - result = list.get(index); - } - } - return result; - } -} - - diff --git a/src/main/java/org/nuiton/util/DateUtil.java b/src/main/java/org/nuiton/util/DateUtil.java deleted file mode 100644 index fbc836b..0000000 --- a/src/main/java/org/nuiton/util/DateUtil.java +++ /dev/null @@ -1,554 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.text.DateFormat; -import java.text.DateFormatSymbols; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -/** - * Library for manipulating dates. - * <p> - * <b>Note: </b> - * - * @author fdesbois - * @since 1.4.1 - */ -public class DateUtil { - - public static final String DEFAULT_PATTERN = "dd/MM/yyyy"; - - public static final String MONTH_PATTERN = "MM/yyyy"; - - /** - * Format a date using the pattern in argument. The pattern is the same using - * for DateFormat object. - * - * @param date the date to format - * @param pattern the pattern to use - * @return a String corresponding to the date formatted - * @see DateFormat - */ - public static String formatDate(Date date, String pattern) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); - return simpleDateFormat.format(date); - } - - public static String formatDate(Date date, String pattern, Locale locale) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, locale); - return simpleDateFormat.format(date); - } - - /** - * Parse a date using the pattern in argument. The pattern is the same using - * for DateFormat object. - * - * @param date the String to parse - * @param pattern the pattern to use - * @return a Date corresponding to the String argument parsed - * @throws ParseException for parsing errors - * @see DateFormat - */ - public static Date parseDate(String date, String pattern) throws ParseException { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); - Date result = simpleDateFormat.parse(date); - return result; - } - - /** - * Create a new date from day, month and year (French version). - * The month is the real month of the year and not the one which is stored - * in Calendar object. - * - * @param s value of the seconds 1-60 - * @param m value of the minutes 1-60 - * @param h value of the hours 1-24 - * @param dd value of the day 1-31 - * @param mm value of the month 1-12 - * @param yy value of the year 0-9999 - * @return a new date - */ - public static Date createDate(int s, int m, int h, int dd, int mm, int yy) { - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(0L); - calendar.set(Calendar.YEAR, yy); - calendar.set(Calendar.MONTH, mm - 1); - calendar.set(Calendar.DAY_OF_MONTH, dd); - calendar.set(Calendar.HOUR_OF_DAY, h); - calendar.set(Calendar.MINUTE, m); - calendar.set(Calendar.SECOND, s); - return calendar.getTime(); - } - - /** - * Create a new date from day, month and year (French version). - * The month is the real month of the year and not the one which is stored - * in Calendar object. Time is set to 00:00:00.000 - * - * @param dd value of the day 1-31 - * @param mm value of the month 1-12 - * @param yy value of the year 0-9999 - * @return a new date - */ - public static Date createDate(int dd, int mm, int yy) { - Calendar calendar = Calendar.getInstance(); - calendar.set(Calendar.YEAR, yy); - calendar.set(Calendar.MONTH, mm - 1); - calendar.set(Calendar.DAY_OF_MONTH, dd); - return setMinTimeOfDay(calendar.getTime()); - } - - /** - * Create a new date after the current date (today) with modification on day, month and year. - * You can use negative values on arguments to have a date before today. - * - * @param ddStep nb days you want to increase from the current date - * @param mmStep nb months you want to increase from the current date - * @param yyStep nb years you want to increase from the current date - * @return a new date from the current date increase by days, months and years. - */ - public static Date createDateAfterToday(int ddStep, int mmStep, int yyStep) { - Calendar calendar = getDefaultCalendar(new Date()); - calendar.add(Calendar.DAY_OF_MONTH, ddStep); - calendar.add(Calendar.MONTH, mmStep); - calendar.add(Calendar.YEAR, yyStep); - return calendar.getTime(); - } - - /** - * Set the last day of month to the date in argument. - * The value depends on the month of the date. (30 april, 28 february, ...) - * - * @param date Date to modify - * @return the date with day of month modified - */ - public static Date setLastDayOfMonth(Date date) { - Calendar calendar = getDefaultCalendar(date); - int maximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); - calendar.set(Calendar.DAY_OF_MONTH, maximum); - Date lastDay = calendar.getTime(); - return lastDay; - } - - /** - * Set the first day of month to the date in argument. - * - * @param date Date to modify - * @return the date with day of month modified - */ - public static Date setFirstDayOfMonth(Date date) { - Calendar calendar = getDefaultCalendar(date); - calendar.set(Calendar.DAY_OF_MONTH, 1); - Date firstDay = calendar.getTime(); - return firstDay; - } - - /** - * Set the last day of year to the date in argument. - * - * @param date Date to modify - * @return the date with day of year modified - */ - public static Date setLastDayOfYear(Date date) { - Calendar calendar = getDefaultCalendar(date); - int maximum = calendar.getActualMaximum(Calendar.DAY_OF_YEAR); - calendar.set(Calendar.DAY_OF_YEAR, maximum); - Date lastDay = calendar.getTime(); - return lastDay; - } - - /** - * Set the first day of year to the date in argument. - * - * @param date Date to modify - * @return the date with day of year modified - */ - public static Date setFirstDayOfYear(Date date) { - Calendar calendar = getDefaultCalendar(date); - calendar.set(Calendar.DAY_OF_YEAR, 1); - Date firstDay = calendar.getTime(); - return firstDay; - } - - /** - * Set the min time of the day : 00:00:00.000. - * - * @param date to modify - * @return Date with the time set to the minimum in the day - */ - public static Date setMinTimeOfDay(Date date) { - Calendar calendar = getDefaultCalendar(date); - calendar.set(Calendar.AM_PM, Calendar.AM); - calendar.set(Calendar.HOUR, 0); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MILLISECOND, 0); - return calendar.getTime(); - } - - /** - * Set the max time of the day. EUROPE : 23:59:59.999. - * - * @param date to modify - * @return Date with the time set to the maximum in the day - */ - public static Date setMaxTimeOfDay(Date date) { - Calendar calendar = getDefaultCalendar(date); - calendar.set(Calendar.AM_PM, Calendar.PM); - calendar.set(Calendar.HOUR, 11); - calendar.set(Calendar.MINUTE, 59); - calendar.set(Calendar.SECOND, 59); - calendar.set(Calendar.MILLISECOND, 999); - return calendar.getTime(); - } - - /** - * Check if the first date in argument is included between the two other - * dates. The argument myDate can be equals to beforeDate or afterDate to - * validate the includes. - * - * @param myDate the date to test - * @param beforeDate the first date of the period to test - * @param afterDate the second date of the period to test - * @return true if myDate is included between beforeDate and afterDate - */ - public static boolean between(Date myDate, Date beforeDate, Date afterDate) { - if (myDate == null) { - return false; - } - boolean result = true; - result &= myDate.after(beforeDate) || myDate.compareTo(beforeDate) == 0; - result &= afterDate == null || myDate.before(afterDate) || - myDate.compareTo(afterDate) == 0; - return result; - } - - /** - * Check if the current date is between the two dates in argument. - * - * @param beforeDate the first date of the period - * @param afterDate the second date of the period - * @return true if the current date is included between the two dates, - * false otherwise - * @see #between(Date, Date, Date) - */ - public static boolean currentPeriod(Date beforeDate, Date afterDate) { - return between(new Date(), beforeDate, afterDate); - } - - /** - * Get the month value from a date (between 0 and 11). - * - * @param date the date to extract month - * @return the month value of the date - */ - public static int getMonth(Date date) { - Calendar calendar = getDefaultCalendar(date); - return calendar.get(Calendar.MONTH); - } - - /** - * Do the difference between the two dates in argument. The result is a number - * of seconds between the two dates. - * - * @param beginDate first date - * @param endDate second date - * @return a number of seconds between beginDate and endDate - */ - public static int getDifferenceInSeconds(Date beginDate, Date endDate) { - long begin = beginDate.getTime(); - long end = endDate.getTime(); - return (int) Math.ceil((end - begin) / 1000); - } - - /** - * Do the difference between the two dates in argument. The result is a number - * of minutes between the two dates. - * - * @param beginDate first date - * @param endDate second date - * @return a number of minutes between beginDate and endDate - */ - public static int getDifferenceInMinutes(Date beginDate, Date endDate) { - long begin = beginDate.getTime(); - long end = endDate.getTime(); - // 60000 = 60 * 1000 - return (int) Math.ceil((end - begin) / 60000); - } - - /** - * Do the difference between the two dates in argument. The result is a number - * of hours between the two dates. - * - * @param beginDate first date - * @param endDate second date - * @return a number of hours between beginDate and endDate - */ - public static int getDifferenceInHours(Date beginDate, Date endDate) { - long begin = beginDate.getTime(); - long end = endDate.getTime(); - // 3600000 = 60 * 60 * 1000 - return (int) Math.ceil((end - begin) / 3600000); - } - - /** - * Do the difference between the two dates in argument. The result is a number - * of days between the two dates. - * Ex : 28/01/2009 and 08/02/2009 return 11. - * - * @param beginDate first date - * @param endDate second date - * @return a number of days between beginDate and endDate - */ - public static int getDifferenceInDays(Date beginDate, Date endDate) { - long begin = beginDate.getTime(); - long end = endDate.getTime(); - // 86400000 = 24 * 60 * 60 * 1000 - return (int) Math.ceil((end - begin) / 86400000); - } - - /** - * Do the difference between the two dates in argument. The result is a number - * of months between the two dates. - * Ex : 01/01/2009 and 28/02/2009 return 2 months. - * Warning, if beginDate is inferior to endDate, the result will be 1 minimum - * - * @param beginDate first date - * @param endDate second date - * @return a number of months between beginDate and endDate - */ - public static int getDifferenceInMonths(Date beginDate, Date endDate) { - int count = 0; - Calendar fromCalendar = getDefaultCalendar(beginDate); - Calendar thruCalendar = getDefaultCalendar(endDate); - - while (fromCalendar.before(thruCalendar)) { - fromCalendar.add(Calendar.MONTH, 1); - count++; - } - return count; - } - - /** - * Get the age of a person born on the date in argument. The result is a number - * of years between the birth date and now. - * Ex : 01/01/2000 returns 11 years (now date is 26/10/2011). - * - * @param birthDate birth date - * @return a number of years between birthDate and now - */ - public static int getAge(Date birthDate) { - int count = 0; - Calendar fromCalendar = getDefaultCalendar(birthDate); - Calendar thruCalendar = getDefaultCalendar(new Date()); - - fromCalendar.add(Calendar.YEAR, 1); - while (fromCalendar.before(thruCalendar)) { - count++; - fromCalendar.add(Calendar.YEAR, 1); - } - return count; - } - - /** - * Get libelle of the month corresponding to the number given in argument. - * - * @param monthNumber between 1-12 - * @param locale Locale for language support - * @return a String corresponding to the libelle of the month - */ - public static String getMonthLibelle(int monthNumber, Locale locale) { - return new DateFormatSymbols(locale).getMonths()[monthNumber - 1]; - } - - /** - * Get libelle of the month corresponding to the number given in argument. - * - * @param monthNumber between 1-12 - * @return a String corresponding to the libelle of the month - */ - public static String getMonthLibelle(int monthNumber) { - return getMonthLibelle(monthNumber, Locale.getDefault()); - } - - /** - * Get the date before today - * - * @param date concerned - * @return Date before today - */ - public static Date getYesterday(Date date) { - Calendar cal = getDefaultCalendar(date); - if (cal.get(Calendar.MONTH) == Calendar.JANUARY && cal.get(Calendar.DAY_OF_MONTH) == 1) { - cal.roll(Calendar.YEAR, false); - } - if (cal.get(Calendar.DAY_OF_MONTH) == 1) { - cal.roll(Calendar.MONTH, false); - } - cal.roll(Calendar.DAY_OF_MONTH, false); - return cal.getTime(); - } - - /** - * Get the calendar corresponding to the {@code date}. The default calendar - * will be returned (default time zone and locale). - * - * @param date used to set the calendar time - * @return the default calendar with time corresponding to the {@code date} - */ - public static Calendar getDefaultCalendar(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - return calendar; - } - - /** - * Truncate a date to its week (to monday). It's equivalent to a call to - * {@link org.apache.commons.lang3.time.DateUtils#truncate(java.util.Date, int)} - * and giving {@link java.util.Calendar#DAY_OF_WEEK} argument, but such a call - * raise an exception showing that this field is not supported. This method - * allows you to bypass this limitation. - * - * @param date any date - * @return a date in the same week as given date, a monday. All field below - * (hours, secondes, ms) are zeroed. - */ - public static Date truncateToDayOfWeek(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - calendar.set(Calendar.HOUR_OF_DAY, 0); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MILLISECOND, 0); - return calendar.getTime(); - } - - - /** - * Enleve les données des heures (hour, minute, second, milli = 0). - * - * @param date la date a modifier - * @return la date d'un jour - */ - public static Date getDay(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - calendar.set(Calendar.MILLISECOND, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.HOUR_OF_DAY, 0); - date = calendar.getTime(); - return date; - } - - /** - * Positionne une date sur la fin d'un jour - * - * @param date la date a modifier - * @return la date d'un jour - */ - public static Date getEndOfDay(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - calendar.set(Calendar.MILLISECOND, 999); - calendar.set(Calendar.SECOND, 59); - calendar.set(Calendar.MINUTE, 59); - calendar.set(Calendar.HOUR_OF_DAY, 23); - date = calendar.getTime(); - return date; - } - - /** - * Créer la date qui utilise le jour donné dans {@code day} et l'heure - * donnée dans {@code time}. - * - * @param day le jour à utiliser - * @param time l'heure a utiliser - * @param useSecond FIXME - * @param useMiliSecond FIXME - * @return la date donnée avec l'heure courante - */ - public static Date getDateAndTime(Date day, Date time, boolean useSecond, boolean useMiliSecond) { - - Calendar calendar = Calendar.getInstance(); - - // recuperation de l'heure - calendar.setTime(time); - int h = calendar.get(Calendar.HOUR_OF_DAY); - int m = calendar.get(Calendar.MINUTE); - int s = useSecond ? calendar.get(Calendar.SECOND) : 0; - int ms = useMiliSecond ? calendar.get(Calendar.MILLISECOND) : 0; - - calendar.setTime(day); - - // appliquer l'heure - calendar.set(Calendar.HOUR_OF_DAY, h); - calendar.set(Calendar.MINUTE, m); - calendar.set(Calendar.SECOND, s); - calendar.set(Calendar.MILLISECOND, ms); - - return calendar.getTime(); - - } - - /** - * Créer la date qui utilise uniquement l'heure - * donnée dans {@code dayTime}. - * - * @param dayTime l'heure a utiliser - * @param useSecond FIXME - * @param useMiliSecond FIXME - * @return la date donnée avec uniquement l'heure courante - */ - public static Date getTime(Date dayTime, boolean useSecond, boolean useMiliSecond) { - Calendar calendar = Calendar.getInstance(); - - // recuperation de l'heure - calendar.setTime(dayTime); - int h = calendar.get(Calendar.HOUR_OF_DAY); - int m = calendar.get(Calendar.MINUTE); - int s = calendar.get(Calendar.SECOND); - int ms = calendar.get(Calendar.MILLISECOND); - - - // on part d'une date vide - calendar.setTimeInMillis(0); - - // appliquer l'heure - calendar.set(Calendar.HOUR_OF_DAY, h); - calendar.set(Calendar.MINUTE, m); - if (useSecond) { - calendar.set(Calendar.SECOND, s); - } - if (useMiliSecond) { - calendar.set(Calendar.MILLISECOND, ms); - } - - return calendar.getTime(); - } -} diff --git a/src/main/java/org/nuiton/util/DesktopUtil.java b/src/main/java/org/nuiton/util/DesktopUtil.java deleted file mode 100644 index 8634b64..0000000 --- a/src/main/java/org/nuiton/util/DesktopUtil.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.awt.Desktop; -import java.io.File; -import java.io.IOException; -import java.net.URI; - -/** - * Utility class for methods to interact with Desktop Environment - * - * @author Jean Couteau - couteau@codelutin.com - * @since 2.4.3 - */ -public class DesktopUtil { - - /** Logger. */ - static private Log log = LogFactory.getLog(DesktopUtil.class); - - /** - * Method to open an URI in the user default web browser. It uses the Java - * Desktop API on Windows and Gnome environment and xdg-open on other - * platforms (non-gnome linux distribution for example). - * - * A Bug report have been opened in 2006 so that java.awt.Desktop can - * support all environments but it is not fixed yet : - * http://bugs.sun.com/view_bug.do?bug_id=6486393 this utility method should - * be removed when the bug is fixed. - * - * @param uri the URI to open - */ - public static void browse(URI uri) { - boolean useXdg = true; - try { - if (Desktop.isDesktopSupported()) { - Desktop desktop = Desktop.getDesktop(); - if (desktop.isSupported(Desktop.Action.BROWSE)) { - useXdg = false; - desktop.browse(uri); - } - } - } catch (IOException ioe) { - // ignore - } - - if (useXdg) { - if (log.isDebugEnabled()) { - log.debug("Desktop API not supported, launching xdg-open"); - } - ProcessBuilder pb = new ProcessBuilder("xdg-open", uri.toString()); - try { - pb.start(); - } catch (IOException e) { - if (log.isDebugEnabled()) { - log.debug("Could not launch browser, there is maybe no " + - "default browser configured on the system", e); - } - } - } - } - - /** - * Method to open an URI in the user default open client. It uses the Java - * Desktop API on Windows and Gnome environment and xdg-open on other - * platforms (non-gnome linux distribution for example). - * - * A Bug report have been opened in 2006 so that java.awt.Desktop can - * support all environments but it is not fixed yet : - * http://bugs.sun.com/view_bug.do?bug_id=6486393 this utility method should - * be removed when the bug is fixed. - * - * @param file the file to open - */ - public static void open(File file) { - boolean useXdg = true; - try { - if (Desktop.isDesktopSupported()) { - Desktop desktop = Desktop.getDesktop(); - if (desktop.isSupported(Desktop.Action.OPEN)) { - useXdg = false; - desktop.open(file); - } - } - } catch (IOException ioe) { - - } - - if (useXdg) { - if (log.isDebugEnabled()) { - log.debug("Desktop API not supported, launching xdg-open"); - } - - ProcessBuilder pb = new ProcessBuilder("xdg-open", file.toURI().toString()); - try { - pb.start(); - } catch (IOException e) { - if (log.isDebugEnabled()) { - log.debug("Could not open file, there is maybe no " + - "default viewer configured on the system", e); - } - } - - } - - } - - /** - * Method to open an URI in the user default mail client. It uses the Java - * Desktop API on Windows and Gnome environment and xdg-email on other - * platforms (non-gnome linux distribution for example). - * - * A Bug report have been opened in 2006 so that java.awt.Desktop can - * support all environments but it is not fixed yet : - * http://bugs.sun.com/view_bug.do?bug_id=6486393 this utility method should - * be removed when the bug is fixed. - * - * @param uri the uri to open - */ - public static void mail(URI uri) { - boolean useXdg = true; - try { - if (Desktop.isDesktopSupported()) { - Desktop desktop = Desktop.getDesktop(); - if (desktop.isSupported(Desktop.Action.MAIL)) { - useXdg = false; - desktop.mail(uri); - } - } - } catch (IOException ioe) { - - } - - if (useXdg) { - if (log.isDebugEnabled()) { - log.debug("Desktop API not supported, launching xdg-open"); - } - - ProcessBuilder pb = new ProcessBuilder("xdg-email", uri.toString()); - try { - pb.start(); - } catch (IOException e) { - if (log.isDebugEnabled()) { - log.debug("Could not open file, there is maybe no " + - "default viewer configured on the system", e); - } - } - - } - - } -} diff --git a/src/main/java/org/nuiton/util/DigestGenerator.java b/src/main/java/org/nuiton/util/DigestGenerator.java deleted file mode 100644 index aa16592..0000000 --- a/src/main/java/org/nuiton/util/DigestGenerator.java +++ /dev/null @@ -1,385 +0,0 @@ -/* - * Nuiton Utils %%Ignore-License - * - * - * $HeadURL$ - * - * 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. - */ - -/* -* Modified by Landais Gabriel, Code Lutin 2008 -* -* Works with standard org.w3c.dom XML classes -* -*/ - -package org.nuiton.util; - -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.ProcessingInstruction; -import org.w3c.dom.Text; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.SortedMap; -import java.util.TreeMap; - -/** - * Helper class to provide the functionality of the digest value generation. This is an implementation of the DHASH - * algorithm on . - * - * TODO tchemit 2010-08-25 : This class is a nightmare ? we talk about digest mixed with dom nodes ? - * TODO tchemit 2010-08-25 : Should have more to explain the purpose (javadoc, author, since...) or (rename | split) this class. - */ -public class DigestGenerator { - public static final String UNICODE_BIG_UNMARKED = "UnicodeBigUnmarked"; - - /** - * This method is an overloaded method for the digest generation for Document - * - * @param document FIXME - * @param digestAlgorithm FIXME - * @return Returns a byte array representing the calculated digest - * @throws Exception FIXME - */ - public byte[] getDigest(Document document, String digestAlgorithm) - throws Exception { - byte[] digest; - try { - MessageDigest md = MessageDigest.getInstance(digestAlgorithm); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - dos.writeInt(9); - Collection childNodes = getValidElements(document); - dos.writeInt(childNodes.size()); - for (Object childNode : childNodes) { - Node node = (Node) childNode; - if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - dos.write(getDigest((ProcessingInstruction) node, - digestAlgorithm)); - } else if (node.getNodeType() == Node.ELEMENT_NODE) { - dos.write(getDigest((Element) node, digestAlgorithm)); - } - } - dos.close(); - md.update(baos.toByteArray()); - digest = md.digest(); - } catch (NoSuchAlgorithmException e) { - throw new Exception(e); - } catch (IOException e) { - throw new Exception(e); - } - return digest; - } - - /** - * This method is an overloaded method for the digest generation for Node - * - * @param node FIXME - * @param digestAlgorithm FIXME - * @return Returns a byte array representing the calculated digest value - * @throws Exception FIXME - */ - public byte[] getDigest(Node node, String digestAlgorithm) throws Exception { - if (node.getNodeType() == Node.ELEMENT_NODE) { - return getDigest((Element) node, digestAlgorithm); - } - if (node.getNodeType() == Node.TEXT_NODE) { - return getDigest((Text) node, digestAlgorithm); - } - if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - return getDigest((ProcessingInstruction) node, digestAlgorithm); - } - return new byte[0]; - } - - /** - * This method is an overloaded method for the digest generation for Element - * - * @param element FIXME - * @param digestAlgorithm FIXME - * @return Returns a byte array representing the calculated digest value - * @throws Exception FIXME - */ - public byte[] getDigest(Element element, String digestAlgorithm) - throws Exception { - byte[] digest; - try { - MessageDigest md = MessageDigest.getInstance(digestAlgorithm); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - dos.writeInt(1); - dos.write(getExpandedName(element).getBytes(UNICODE_BIG_UNMARKED)); - dos.write((byte) 0); - dos.write((byte) 0); - Collection attrs = getAttributesWithoutNS(element); - dos.writeInt(attrs.size()); - for (Object attr : attrs) { - dos.write(getDigest((Attr) attr, digestAlgorithm)); - } - Node node = element.getFirstChild(); - // adjoining Texts are merged, - // there is no 0-length Text, and - // comment nodes are removed. - int length = element.getChildNodes().getLength(); - dos.writeInt(length); - while (node != null) { - dos.write(getDigest(node, digestAlgorithm)); - node = node.getNextSibling(); - } - dos.close(); - md.update(baos.toByteArray()); - digest = md.digest(); - } catch (NoSuchAlgorithmException e) { - throw new Exception(e); - } catch (IOException e) { - throw new Exception(e); - } - return digest; - } - - /** - * This method is an overloaded method for the digest generation for ProcessingInstruction - * - * @param pi FIXME - * @param digestAlgorithm FIXME - * @return Returns a byte array representing the calculated digest value - * @throws Exception FIXME - */ - public byte[] getDigest(ProcessingInstruction pi, String digestAlgorithm) - throws Exception { - byte[] digest; - try { - MessageDigest md = MessageDigest.getInstance(digestAlgorithm); - md.update((byte) 0); - md.update((byte) 0); - md.update((byte) 0); - md.update((byte) 7); - md.update(pi.getTarget().getBytes(UNICODE_BIG_UNMARKED)); - md.update((byte) 0); - md.update((byte) 0); - md.update(pi.getNodeValue().getBytes(UNICODE_BIG_UNMARKED)); - digest = md.digest(); - } catch (NoSuchAlgorithmException e) { - throw new Exception(e); - } catch (UnsupportedEncodingException e) { - throw new Exception(e); - } - return digest; - } - - /** - * This method is an overloaded method for the digest generation for Attr - * - * @param attribute FIXME - * @param digestAlgorithm FIXME - * @return Returns a byte array representing the calculated digest value - * @throws Exception FIXME - */ - public byte[] getDigest(Attr attribute, String digestAlgorithm) - throws Exception { - byte[] digest = new byte[0]; - if (!(attribute.getLocalName().equals("xmlns") || attribute - .getLocalName().startsWith("xmlns:"))) { - try { - MessageDigest md = MessageDigest.getInstance(digestAlgorithm); - md.update((byte) 0); - md.update((byte) 0); - md.update((byte) 0); - md.update((byte) 2); - md.update(getExpandedName(attribute).getBytes( - UNICODE_BIG_UNMARKED)); - md.update((byte) 0); - md.update((byte) 0); - md.update(attribute.getValue().getBytes(UNICODE_BIG_UNMARKED)); - digest = md.digest(); - } catch (NoSuchAlgorithmException e) { - throw new Exception(e); - } catch (UnsupportedEncodingException e) { - throw new Exception(e); - } - } - return digest; - } - - /** - * This method is an overloaded method for the digest generation for Text - * - * @param text FIXME - * @param digestAlgorithm FIXME - * @return Returns a byte array representing the calculated digest value - * @throws Exception FIXME - */ - public byte[] getDigest(Text text, String digestAlgorithm) throws Exception { - byte[] digest; - try { - MessageDigest md = MessageDigest.getInstance(digestAlgorithm); - md.update((byte) 0); - md.update((byte) 0); - md.update((byte) 0); - md.update((byte) 3); - md.update(text.getTextContent().getBytes(UNICODE_BIG_UNMARKED)); - digest = md.digest(); - } catch (NoSuchAlgorithmException e) { - throw new Exception(e); - } catch (UnsupportedEncodingException e) { - throw new Exception(e); - } - return digest; - } - - /** - * This method is an overloaded method for getting the expanded name namespaceURI followed by the local name for - * Element - * - * @param element FIXME - * @return Returns the expanded name of Element - */ - public String getExpandedName(Element element) { - return element.getNamespaceURI() + ":" + element.getLocalName(); - } - - /** - * This method is an overloaded method for getting the expanded name namespaceURI followed by the local name for - * Attr - * - * @param attribute FIXME - * @return Returns the expanded name of the Attr - */ - public String getExpandedName(Attr attribute) { - return attribute.getNamespaceURI() + ":" + attribute.getLocalName(); - } - - /** - * Gets the collection of attributes which are none namespace declarations for an Element - * - * @param element FIXME - * @return Returns the collection of attributes which are none namespace declarations - */ - public Collection getAttributesWithoutNS(Element element) { - SortedMap map = new TreeMap(); - for (int i = 0; i < element.getAttributes().getLength(); i++) { - Attr attribute = (Attr) element.getAttributes().item(i); - if (!(attribute.getLocalName().equals("xmlns") || attribute - .getLocalName().startsWith("xmlns:"))) { - map.put(getExpandedName(attribute), attribute); - } - } - return map.values(); - } - - /** - * Gets the valid element collection of an Document. Element and ProcessingInstruction only - * - * @param document FIXME - * @return Returns a collection of ProcessingInstructions and Elements - */ - public Collection getValidElements(Document document) { - ArrayList list = new ArrayList(); - NodeList childNodes = document.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - Node node = childNodes.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE - || node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - list.add(node); - } - } - return list; - } - - /** - * Gets the String representation of the byte array - * - * @param array FIXME - * @return Returns the String of the byte - */ - public String getStringRepresentation(byte[] array) { - String str = ""; - for (byte anArray : array) { - str += anArray; - } - return str; - } - - /** - * Compares two Nodes for the XML equality - * - * @param node FIXME - * @param comparingNode FIXME - * @param digestAlgorithm FIXME - * @return Returns true if the Node XML contents are equal - * @throws Exception FIXME - */ - public boolean compareNode(Node node, Node comparingNode, - String digestAlgorithm) throws Exception { - return Arrays.equals(getDigest(node, digestAlgorithm), getDigest( - comparingNode, digestAlgorithm)); - } - - /** - * Compares two Documents for the XML equality - * - * @param document FIXME - * @param comparingDocument FIXME - * @param digestAlgorithm FIXME - * @return Returns true if the Document XML content are equal - * @throws Exception FIXME - */ - public boolean compareDocument(Document document, - Document comparingDocument, String digestAlgorithm) - throws Exception { - return Arrays.equals(getDigest(document, digestAlgorithm), getDigest( - comparingDocument, digestAlgorithm)); - } - - /** - * Compares two Attributes for the XML equality - * - * @param attribute FIXME - * @param comparingAttribute FIXME - * @param digestAlgorithm FIXME - * @return Returns true if the Document XML content are equal - * @throws Exception FIXME - */ - public boolean compareAttribute(Attr attribute, Attr comparingAttribute, - String digestAlgorithm) throws Exception { - return Arrays.equals(getDigest(attribute, digestAlgorithm), getDigest( - comparingAttribute, digestAlgorithm)); - } - - /** String representing the MD5 digest algorithm */ - public static final String md5DigestAlgorithm = "MD5"; - - /** String representing the SHA digest algorithm */ - public static final String shaDigestAlgorithm = "SHA"; - - /** String representing the SHA1 digest algorithm */ - public static final String sha1DigestAlgorithm = "SHA1"; -} diff --git a/src/main/java/org/nuiton/util/FasterCachedResourceResolver.java b/src/main/java/org/nuiton/util/FasterCachedResourceResolver.java deleted file mode 100644 index ecd059d..0000000 --- a/src/main/java/org/nuiton/util/FasterCachedResourceResolver.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.xml.transform.Source; -import javax.xml.transform.stream.StreamSource; -import java.net.URL; - -/** - * FasterCachedResourceResolver is a URIResolver using a optimized search time algorithm. - * <p> - * For a given href, will try to search the exact path in classp-ath in the exact directory META-INF/cache. - * </p> - * The fact of using META-INF directory is optimized (special jvm directory). - * - * The other fact of using an exact directory makes also decrease dramaticly time search. - * - * Finally, we spend ten times less time in searching; moreover using the path of - * searched resource resolve the probleme of name colision and this is also a good thing... - * - * Exemple : - * <pre> - * href = http://foo/bar/file.txt - * search resource : /META-INF/cache/foo/bar/file.txt - * </pre> - * - * @author chorlet - */ -public class FasterCachedResourceResolver extends ResourceResolver { - - /** log. */ - private static final Log log = LogFactory.getLog(FasterCachedResourceResolver.class); - - protected boolean offline; - - public FasterCachedResourceResolver() { - this(null); - } - - public FasterCachedResourceResolver(String base) { - super(base); - } - - public void setOffline(boolean offline) { - this.offline = offline; - } - - @Override - protected Source findHrefSource(String path) { - long t0 = System.nanoTime(); - String resource = "META-INF/cache/" + path; - - if (verbose) { - log.info("will discover " + resource); - } - - URL url = cl.getResource(resource); - - Source source = null; - - if (url != null) { - if (verbose) { - log.info(url.toString()); - } - source = new StreamSource(url.toString()); - } - if (source == null) { - if (offline) { - throw new IllegalStateException("offline - could not find extact resource at location " + resource); - } - log.warn("could not find extact resource at location " + resource); - } - if (verbose) { - log.info("resolved in " + StringUtil.convertTime(System.nanoTime() - t0)); - } - return source; - } -} diff --git a/src/main/java/org/nuiton/util/FileUtil.java b/src/main/java/org/nuiton/util/FileUtil.java deleted file mode 100644 index 7799ef0..0000000 --- a/src/main/java/org/nuiton/util/FileUtil.java +++ /dev/null @@ -1,1370 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.SystemUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JFileChooser; -import java.awt.Component; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileFilter; -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.io.OutputStreamWriter; -import java.io.PrintStream; -import java.nio.CharBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Opérations sur des fichiers. Copie, suppression, renommage, - * recherche, fichiers d'un répertoire, sous-répertoires d'un répertoire, - * récupération du basename ou de l'extension, création d'un fichier - * temporaire, comparaison de dates de création, récupération d'une chaîne, - * d'un Reader ou d'un Writer à partir d'un fichier, récupération du fichier - * saisi dans une boîte de dialogue, conversions en byte[], en Stream... - * <p> - * Created: 22 novembre 2004 - * - * @author Benjamin Poussin - poussin@codelutin.com - * @author Tony Chemit - chemit@codelutin.com - */ -public class FileUtil { // FileUtil - - /** - * Logger. - */ - static private Log log = LogFactory.getLog(FileUtil.class); - - /** - * Encoding utilisé (peut être redéfini) - */ - // TODO fdesbois 2011-04-16 : Perhaps change ISO encoding by UTF-8 - public static String ENCODING = "ISO-8859-1"; - - /** - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - protected static File currentDirectory = new File("."); - - /** - * @param dir FIXME - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static void setCurrentDirectory(File dir) { - currentDirectory = dir; - } - - /** - * @return FIXME - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static File getCurrentDirectory() { - return currentDirectory; - } - - /** - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static class PatternChooserFilter extends javax.swing.filechooser.FileFilter { - protected String pattern; - - protected String description; - - public PatternChooserFilter(String pattern, String description) { - this.pattern = pattern; - this.description = description; - } - - @Override - public boolean accept(File f) { - return f.isDirectory() || f.getAbsolutePath().matches(pattern); - } - - @Override - public String getDescription() { - return description; - } - - } - - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données - * par deux, le pattern du filtre + la description du filtre - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - * @see #getFile(javax.swing.filechooser.FileFilter...) - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static File getFile(String... patternOrDescriptionFilters) { - File result; - result = getFile(null, patternOrDescriptionFilters); - return result; - } - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param filters les filtres a ajouter - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static File getFile(javax.swing.filechooser.FileFilter... filters) { - File result = getFile(null, filters); - return result; - } - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param parent le component parent du dialog - * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données - * par deux, le pattern du filtre + la description du filtre - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - * @see #getFile(javax.swing.filechooser.FileFilter...) - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static File getFile(Component parent, - String... patternOrDescriptionFilters) { - File result; - result = getFile("Ok", "Ok", parent, patternOrDescriptionFilters); - return result; - } - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param title le titre de la boite de dialogue - * @param approvalText le label du boutton d'acceptation - * @param parent le component parent du dialog - * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données - * par deux, le pattern du filtre + la description du filtre - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - * @see #getFile(javax.swing.filechooser.FileFilter...) - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static File getFile(String title, - String approvalText, - Component parent, - String... patternOrDescriptionFilters) { - - if (patternOrDescriptionFilters.length % 2 != 0) { - throw new IllegalArgumentException( - "Arguments must be (pattern, description) couple"); - } - javax.swing.filechooser.FileFilter[] filters = - new javax.swing.filechooser.FileFilter[ - patternOrDescriptionFilters.length / 2]; - for (int i = 0; i < filters.length; i++) { - String pattern = patternOrDescriptionFilters[i * 2]; - String description = patternOrDescriptionFilters[i * 2 + 1]; - filters[i] = new PatternChooserFilter(pattern, description); - } - File result; - result = getFile(title, approvalText, parent, filters); - return result; - } - - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param parent le component parent du dialog - * @param filters les filtres a ajouter - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static File getFile(Component parent, - javax.swing.filechooser.FileFilter... filters) { - File result = getFile("Ok", "Ok", parent, filters); - return result; - } - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param title le titre de la boite de dialogue - * @param approvalText le label du boutton d'acceptation - * @param parent le component parent du dialog - * @param filters les filtres a ajouter - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static File getFile(String title, - String approvalText, - Component parent, - javax.swing.filechooser.FileFilter... filters) { - try { - JFileChooser chooser = new JFileChooser(currentDirectory); - - chooser.setDialogType(JFileChooser.CUSTOM_DIALOG); - if (filters.length > 0) { - if (filters.length == 1) { - chooser.setFileFilter(filters[0]); - } else { - for (javax.swing.filechooser.FileFilter filter : filters) { - chooser.addChoosableFileFilter(filter); - } - } - } - chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - chooser.setDialogTitle(title); - int returnVal = chooser.showDialog(parent, approvalText); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File theFile = chooser.getSelectedFile(); - if (theFile != null) { - currentDirectory = theFile; - return theFile.getAbsoluteFile(); - } - } - } catch (Exception eee) { - log.warn("Erreur:", eee); - } - return null; - } - - /** - * @return le nom du repertoire entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne - * null. - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static String getDirectory() { - return getDirectory(null, "Ok", "Ok"); - } - - /** - * @param title le nom de la boite de dialogue - * @param approvalText le texte de l'action d'acceptation du répertoire dans le file chooser - * @return le nom du repertoire entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne - * null. - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static String getDirectory(String title, String approvalText) { - String result = getDirectory(null, title, approvalText); - return result; - } - - /** - * @param parent le component parent du dialog - * @param title le nom de la boite de dialogue - * @param approvalText le texte de l'action d'acceptation du répertoire dans le file chooser - * @return le nom du repertoire entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne - * null. - * @deprecated since 2.6.13, prefer use same method in - * jaxx.runtime.FileChooserUtil class in jaxx-runtime project - * (see http://svn.nuiton.org/svn/jaxx/trunk/jaxx-runtime/src/main/java/jaxx/runtime/FileChooserUtil} - */ - @Deprecated - public static String getDirectory(Component parent, - String title, - String approvalText) { - try { - JFileChooser chooser = new JFileChooser(currentDirectory); - chooser.setDialogType(JFileChooser.CUSTOM_DIALOG); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setDialogTitle(title); - int returnVal = chooser.showDialog(parent, approvalText); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File theFile = chooser.getSelectedFile(); - if (theFile != null) { - currentDirectory = theFile; - if (theFile.isDirectory()) { - return theFile.getAbsolutePath(); - } - } - } else { - return null; - } - } catch (Exception eee) { - log.warn("Erreur:", eee); - } - return null; - } - - /** - * Permet de convertir des bytes en fichier, le fichier sera automatiquement - * supprimé a la fin de la JVM. - * - * @param bytes the array of bytes to copy in dstination file - * @return le fichier temporaire contenant les bytes - * @throws IOException if any io pb - */ - public static File byteToFile(byte[] bytes) throws IOException { - File file = File.createTempFile("FileUtil-byteToFile", ".tmp"); - byteToFile(bytes, file); - return file; - } - - /** - * Permet de convertir des bytes en fichier - * - * @param bytes the array of bytes to put in the given destination file - * @param file le fichier dans lequel il faut ecrire les bytes - * @return le fichier passé en parametre - * @throws IOException if any io pb - * @deprecated since 2.4.6, prefer use method {@link FileUtils#writeByteArrayToFile(File, byte[])} - */ - @Deprecated - public static File byteToFile(byte[] bytes, - File file) throws IOException { - OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); - try { - out.write(bytes); - } finally { - out.close(); - } - return file; - } - - /** - * Retourne un Reader utilisant l'encoding par defaut {@link #ENCODING}. - * - * @param file the given reader - * @return the reader on the given file - * @throws IOException if any io pb - */ - public static BufferedReader getReader(File file) throws IOException { - return getReader(file, ENCODING); - } - - /** - * Retourne un reader utilisant l'encoding choisi et placé dans un - * BufferedReader - * - * @param file the given file - * @param encoding (ISO-8859-1, UTF-8, ...) - * @return the buffered reader in the given encoding - * @throws IOException if any io pb - */ - public static BufferedReader getReader(File file, - String encoding) throws IOException { - FileInputStream inf = new FileInputStream(file); - InputStreamReader in = new InputStreamReader(inf, encoding); - BufferedReader result = new BufferedReader(in); - return result; - } - - /** - * Retourne un Writer utilisant l'encoding par defaut {@link #ENCODING}. - * - * @param file the given file - * @return the writer on the given file - * @throws IOException if any io pb - */ - public static BufferedWriter getWriter(File file) throws IOException { - return getWriter(file, ENCODING); - } - - /** - * Retourne un writer utilisant l'encoding choisi et placé dans un - * BufferedWriter - * - * @param file the given file - * @param encoding (ISO-8859-1, UTF-8, ...) - * @return the buffered writer on the given file with given encoding - * @throws IOException if any io pb - */ - public static BufferedWriter getWriter(File file, - String encoding) throws IOException { - FileOutputStream outf = new FileOutputStream(file); - OutputStreamWriter out = new OutputStreamWriter(outf, encoding); - BufferedWriter result = new BufferedWriter(out); - return result; - } - - - /** - * Permet de creer un nouveu repertoire temporaire, l'effacement du - * répertoire est a la charge de l'appelant - * - * @param prefix le prefix du fichier - * @param suffix le suffix du fichier - * @param tmpdir le répertoire temporaire ou il faut creer le repertoire - * si null on utilise java.io.tmpdir - * @return le fichier pointant sur le nouveau repertoire - * @throws IOException if any io pb - */ - public static File createTempDirectory(String prefix, - String suffix, - File tmpdir) throws IOException { - if (tmpdir == null) { - tmpdir = new File(System.getProperty("java.io.tmpdir")); - } - File result = new File(tmpdir, prefix + System.currentTimeMillis() + suffix); - while (result.exists()) { - result = new File(tmpdir, prefix + System.currentTimeMillis() + suffix); - } - if (!result.mkdirs()) { - throw new IOException("Can't create temporary directory: " + result); - } - return result; - } - - /** - * Permet de creer un nouveu repertoire temporaire, l'effacement du - * répertoire est a la charge de l'appelant - * - * @param prefix le prefix du repertoire a creer - * @param suffix le suffix du repertoire a creer. - * @return the temprary created file - * @throws IOException if any io pb - */ - public static File createTempDirectory(String prefix, - String suffix) throws IOException { - return createTempDirectory(prefix, suffix, null); - } - - /** - * Permet de sauver une chaine directement dans un fichier - * - * @param file Le fichier dans lequel il faut ecrire la chaine - * @param content Le texte a ecrire dans le fichier - * @param encoding encoding to use - * @throws IOException if any pb while writing - * @deprecated since 2.4.6, prefer use method {@link FileUtils#writeStringToFile(File, String, String)}. - */ - @Deprecated - public static void writeString(File file, - String content, - String encoding) throws IOException { - //fixme on doit tester le retour de la méthode, car il se peut que le répertoire - // ne puisse être crée. - File parentFile = file.getParentFile(); - //TODO tchemit 2011-05-15 Must test if directory was created (use - // the #createDirectoryIfNecessary method). - if (parentFile != null) { - parentFile.mkdirs(); - } - - BufferedWriter out = getWriter(file, encoding); - out.write(content); - out.close(); - } - - /** - * Permet de donner une representation fichier pour une chaine de caractere. - * Le fichier sera automatiquement effacé à la fin de la JVM. - * - * @param content le contenu du fichier temporaire - * @return le fichier qui contient content - * @throws IOException if any io pb - */ - public static File getTempFile(String content) throws IOException { - return getTempFile(content, ""); - } - - /** - * Permet de donner une representation fichier pour une chaine de caractere. - * Le fichier sera automatiquement effacé à la fin de la JVM. - * - * @param content le contenu du fichier temporaire - * @param fileSuffix l'extension du fichier créé - * @return le fichier qui contient content - * @throws IOException if any io pb - */ - public static File getTempFile(String content, - String fileSuffix) throws IOException { - File result = File.createTempFile("tmp-" + FileUtil.class.getName(), - fileSuffix); - result.deleteOnExit(); - FileUtils.write(result, content); - return result; - } - - /** - * Equivalent de la methode basename unix. - * basename("/tmp/toto.xml", ".xml") → "toto" - * - * @param file le fichier dont on souhaite le nom sans le chemin - * @param suffixes si present represente le suffixe a eliminer du fichier - * s'il est trouvé - * @return le nom du fichier sans le suffixe si trouvé. - */ - public static String basename(File file, String... suffixes) { - String result = basename(file.getName(), suffixes); - return result; - } - - /** - * Equivalent de la methode basename unix. - * basename("/tmp/toto.xml", ".xml") → "toto" - * - * @param name le nom du fichier dont on souhaite le nom sans le chemin - * @param suffixes si present represente le suffixe a eliminer du fichier - * s'il est trouvé - * @return le nom du fichier sans le suffixe si trouvé. - * @since 1.4.2 - */ - public static String basename(String name, String... suffixes) { - String result = name; - for (String suffixe : suffixes) { - if (result.endsWith(suffixe)) { - result = result.substring(0, - result.length() - suffixe.length()); - break; - } - } - return result; - } - - /** - * Permet de récupérer l'extension d'un fichier - * - * @param file le fichier dont on souhaite l'extension - * @param extchars la liste des caracteres pouvant former l'extension - * dans l'ordre de preference. Si vide on utilise ".". - * @return l'extension ou la chaine vide si le fichier n'a pas d'extension - * l'extension ne contient pas le chaine de delimitation - */ - public static String extension(File file, String... extchars) { - String name = file.getName(); - String result = extension(name, extchars); - return result; - } - - /** - * Permet de récupérer l'extension d'un nom de fichier - * - * @param name le nom du fichier dont on souhaite l'extension - * @param extchars la liste des caracteres pouvant former l'extension - * dans l'ordre de preference. Si vide on utilise ".". - * @return l'extension ou la chaine vide si le fichier n'a pas d'extension - * l'extension ne contient pas le chaine de delimitation - * @since 1.4.2 - */ - public static String extension(String name, String... extchars) { - String result = ""; - - if (extchars.length == 0) { - extchars = new String[]{"."}; - } - for (String extchar : extchars) { - int pos = name.lastIndexOf(extchar); - if (pos != -1) { - result = name.substring(pos + extchar.length()); - break; - } - } - return result; - } - - /** - * Recupère le fichier dans le même répertoire que le fichier donné et dont - * on a changé l'extension. - * - * @param file le fichier d'origine - * @param newExtension la nouvelle extension à utiliser - * @param extchars la liste des extensions possibles - * @return le fichier dont on a changé l'extension - * @throws IOException si aucune extension trouvé dans le fichier d'origine - * @since 1.4.2 - */ - public static File changeExtension(File file, - String newExtension, - String... extchars) throws IOException { - String name = file.getName(); - String newName = changeExtension(name, newExtension, extchars); - File newFile = new File(file.getParentFile(), newName); - return newFile; - } - - /** - * Change l'extension du fichier en entrée avec la nouvelle extension - * - * @param name le nom de fichier à transformer - * @param newExtension la nouvelle extension à utiliser - * @param extchars la liste des extensions possibles - * @return le nouveau nom de fichier - * @throws IOException si aucune extension trouvé dans le fichier d'origine - * @since 1.4.2 - */ - public static String changeExtension(String name, - String newExtension, - String... extchars) throws IOException { - String extension = extension(name, extchars); - if (extension == null) { - throw new IOException("Could not find extension for name " + - name + " within " + Arrays.toString(extchars)); - } - String nameWithoutExtension = name.substring( - 0, name.length() - extension.length()); - String newName = nameWithoutExtension + newExtension; - return newName; - } - - /** - * Recupère le fichier mirroir du fichier {@code file} donnée qui est dans - * l'arborescence de {@code inputDirectory} dans le répertoire - * {@code ouputDirectory}. - * - * @param inputDirectory le répertoire de départ - * @param outputDirectory le répertoire cible - * @param file le fichier - * @return le fichier mirroir dans le répertoire cible - * @since 1.4.2 - */ - public static File getRelativeFile(File inputDirectory, - File outputDirectory, - File file) { - String inputPath = inputDirectory.getAbsolutePath(); - String s = file.getAbsolutePath(); - int index = s.indexOf(inputPath); - if (index == -1) { - throw new IllegalArgumentException( - "File " + file + " is not in " + inputDirectory); - } - String relativePath = s.substring(inputPath.length()); - File result = new File(outputDirectory, relativePath); - return result; - } - - public interface FileAction { - boolean doAction(File f); - } - - /** - * Retourne tous les sous répertoires du répertoire passé en argument. - * - * @param directory un répertoire - * @return une liste d'objet {@link File} de répertoires et ceci - * recursivement à partir de directory, si directory - * n'est pas un répertoire la liste est vide. - */ - public static List<File> getSubDirectories(File directory) { - class DirectoryFilter implements FileFilter { - @Override - public boolean accept(File f) { - return f.isDirectory(); - } - } - return getFilteredElements(directory, new DirectoryFilter(), true); - } - - /** - * Retourne tous les fichiers du répertoire passé en argument. - * - * @param directory un répertoire - * @return une liste d'objet {@link File} des fichiers et ceci - * recursivement à partir de directory, si directory n'est pas un - * répertoire la liste est vide - */ - public static List<File> getFiles(File directory) { - class NormalFileFilter implements FileFilter { - @Override - public boolean accept(File f) { - return f.isFile(); - } - } - return getFilteredElements(directory, new NormalFileFilter(), true); - } - - /** - * Retourne les fichiers d'un répertoire qui satisfont un certain pattern. - * La recherche est faite récursivement dans les sous répertoires - * - * @param directory le répertoire à partir duquel il faut faire la recherche - * @param pattern le pattern que doit respecter le fichier pour être dans la - * liste résultante - * @param recursively flag pour indiquer si on doit descendre dans les sous répertoires - * @return une liste d'objet {@link File} qui ont s'attisfait le - * pattern. - */ - public static List<File> find(File directory, - final String pattern, - boolean recursively) { - final String root = directory.getAbsolutePath(); - final int rootLength = root.length(); - - return getFilteredElements(directory, new FileFilter() { - @Override - public boolean accept(File f) { - String longFilename = f.getAbsolutePath(); - // + 1 to remove the first / or \ - String filename = longFilename.substring(rootLength + 1); - return filename.matches(pattern); - } - }, recursively); - } - - /** - * Retourne la liste de toutes les fichiers ou répertoire qui s'attisfont - * le filtre - * - * @param directory repertoire à partir duquel il faut faire la recherche - * @param ff le filtre à appliquer pour savoir si le fichier parcouru doit - * être conservé dans les résultats, ou null pour tous les fichiers - * @param recursively un flag pour indiquer si on doit descendre dans les répertoires - * @return une liste d'objet {@link File}, qui s'attisfont le filtre - */ - public static List<File> getFilteredElements(File directory, - FileFilter ff, - boolean recursively) { - ArrayList<File> result = new ArrayList<File>(); - LinkedList<File> todo = new LinkedList<File>(); - if (directory.isDirectory()) { - todo.addAll(Arrays.asList(directory.listFiles())); - } - while (todo.size() > 0) { - File file = todo.removeFirst(); - if (recursively && file.isDirectory()) { - File[] childs = file.listFiles(); - if (childs != null) { - // null if we don't have access to directory - todo.addAll(Arrays.asList(childs)); - } - } - if (ff == null || ff.accept(file)) { - result.add(file); - } - } - return result; - } - - /** - * Permet de faire une action avant le parcours des fichiers, c-a-d que - * l'on fera l'action sur les fichiers contenu dans un répertoire - * après l'action sur le répertoire lui même. - * - * @param f le fichier ou répertoire à partir duquel il faut commencer - * @param fileAction l'action à effectuer sur chaque fichier - * @return le résultat des fileAction executé sur les fichiers, chaque - * résultat de FileAction sont assemblé par un ET logique pour donner - * le résultat final - */ - public static boolean walkAfter(File f, FileAction fileAction) { - boolean result = fileAction.doAction(f); - if (f.isDirectory()) { - File list[] = f.listFiles(); - for (File aList : list) { - result = result && walkAfter(aList, fileAction); - } - } - return result; - } - - /** - * Permet de faire une action apès le parcours des fichiers, c-a-d que - * l'on fera l'action sur les fichiers contenu dans un répertoire - * avant l'action sur le répertoire lui même. - * - * @param f le fichier ou répertoire à partir duquel il faut commencer - * @param fileAction l'action à effectuer sur chaque fichier - * @return le résultat des fileAction executé sur les fichiers, chaque - * résultat de FileAction sont assemblé par un ET logique pour donner - * le résultat final - */ - public static boolean walkBefore(File f, FileAction fileAction) { - boolean result = true; - if (f.isDirectory()) { - File list[] = f.listFiles(); - for (File aList : list) { - result = result && walkBefore(aList, fileAction); - } - } - return result && fileAction.doAction(f); - } - - /** - * Copie recursivement le repertoire source dans le repertoire destination - * <p> - * copyRecursively("/truc/titi", "/var/tmp") donnera le repertoire - * "/var/tmp/titi" - * - * @param srcDir le répertoire source à copier - * @param destDir le répertoire destination où copier - * @param includePatterns les patterns que doivent resperter les - * fichiers/repertoires pour etre copié. Si vide alors tout est copié - * @throws IOException if any io pb - */ - public static void copyRecursively(File srcDir, - File destDir, - String... includePatterns) throws IOException { - copyAndRenameRecursively(srcDir, destDir, null, null, includePatterns); - } - - /** - * Copie recursivement le repertoire source dans le repertoire destination - * <p> - * copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire - * "/var/tmp/bidulle", 'bidulle' remplacant 'titi' - * - * @param srcDir le répertoire source à copier - * @param destDir le répertoire destination où copier - * @param renameFrom pattern to permit rename file before uncompress it - * @param renameTo new name for file if renameFrom is applicable to it - * you can use $1, $2, ... if you have '(' ')' in renameFrom - * @param includePatterns les patterns que doivent resperter les - * fichiers/repertoires pour etre copié. Si vide alors tout est copié - * @throws IOException if any io pb - */ - public static void copyAndRenameRecursively(File srcDir, File destDir, - String renameFrom, - String renameTo, - String... includePatterns) throws IOException { - copyAndRenameRecursively(srcDir, - destDir, - true, - renameFrom, - renameTo, - false, - includePatterns - ); - } - - /** - * Copie recursivement le repertoire source dans le repertoire destination - * <p> - * copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire - * "/var/tmp/bidulle", 'bidulle' remplacant 'titi' - * - * @param srcDir le répertoire source à copier - * @param destDir le répertoire destination où copier - * @param includeSrcDir si vrai alors le repertoire source est copie dans le - * repertoire destination et non pas seulement les fichiers qu'il contient - * @param renameFrom pattern to permit rename file before uncompress it - * @param renameTo new name for file if renameFrom is applicable to it - * you can use $1, $2, ... if you have '(' ')' in renameFrom - * @param exclude inverse include pattern interpretation - * @param includePatterns les patterns que doivent resperter les - * fichiers/repertoires pour etre copié. Si vide alors tout est copié - * @throws IOException if any io pb - */ - public static void copyAndRenameRecursively(File srcDir, - File destDir, - boolean includeSrcDir, - String renameFrom, - String renameTo, - boolean exclude, - String... includePatterns) throws IOException { - String rootSrc; - if (includeSrcDir) { - rootSrc = srcDir.getParent(); - } else { - rootSrc = srcDir.getPath(); - } - List<File> files = getFilteredElements(srcDir, null, true); - log.debug("copyRecursively: " + files); - for (File file : files) { - boolean doCopy = copyRecursivelyAccept(file, includePatterns); - if (exclude ^ doCopy) { - String path = file.getPath().substring(rootSrc.length()); - if (renameFrom != null && renameTo != null) { - String tmp = path.replaceAll(renameFrom, renameTo); - if (log.isDebugEnabled()) { - log.debug("rename " + path + " → " + tmp); - } - path = tmp; - } - - File destFile = new File(destDir, path); - if (file.isDirectory()) { - log.debug("create directory: " + destFile); - //fixme on doit tester le retour de la méthode, car il se peut que le répertoire - // ne puisse être copié. - createDirectoryIfNecessary(destFile); - } else { - log.debug("copy " + path + " to " + destFile); - FileUtils.copyFile(file, destFile); - } - } - } - } - - /** - * Get a ByteArrayOutputStream containing all data that could be read from the given InputStream - * - * @param inputStream the stream to read - * @param defaultBufferSize the buffer size - * @return the input stream read for input - * @throws IOException if any pb while reading or writing - */ - public static ByteArrayOutputStream readBytesFrom(InputStream inputStream, - int defaultBufferSize) throws IOException { - - ByteArrayOutputStream outputStream = new ByteArrayOutputStream( - defaultBufferSize); - byte[] buffer = new byte[defaultBufferSize]; - - int readBytes = inputStream.read(buffer); - while (readBytes > 0) { - outputStream.write(buffer, 0, readBytes); - readBytes = inputStream.read(buffer); - } - - return outputStream; - } - - /** - * @param file le fichier à tester. - * @param includePatterns les patterns pour accepeter le fichier depuis son nom - * @return {@code true} si le fichier est accepté, <code>false> autrement. - */ - private static boolean copyRecursivelyAccept(File file, - String[] includePatterns) { - boolean result = includePatterns.length == 0; - String filename = file.getAbsolutePath(); - for (String pattern : includePatterns) { - result = filename.matches(pattern); - if (result) { - break; - } - } - return result; - } - - /** - * Use the linePattern to break the given CharBuffer into lines, applying - * the input pattern to each line to see if we have a match - * <p> - * Code taken from : - * <p> - * http://java.sun.com/javase/6/docs/technotes/guides/io/example/Grep.java - * - * @param regex regex to search into file - * @param cb nio buffer - * @return matching lines (or {code null} if no matching lines) - * @since 1.1.2 - */ - protected static List<CharSequence> grep(String regex, - CharBuffer cb) { - - List<CharSequence> linesList = null; - - Pattern pattern = Pattern.compile(regex); - - Pattern linePattern = Pattern.compile(".*\r?\n"); - - Matcher lm = linePattern.matcher(cb); // Line matcher - Matcher pm = null; // Pattern matcher - //int lines = 0; - while (lm.find()) { - //lines++; - CharSequence cs = lm.group(); // The current line - if (pm == null) { - pm = pattern.matcher(cs); - } else { - pm.reset(cs); - } - if (pm.find()) { - // init - if (linesList == null) { - linesList = new ArrayList<CharSequence>(); - } - linesList.add(cs); - } - if (lm.end() == cb.limit()) { - break; - } - } - - return linesList; - } - - /** - * Java implementation for the unix grep command. - * <p> - * Code taken from : - * <p> - * http://java.sun.com/javase/6/docs/technotes/guides/io/example/Grep.java - * <p> - * May fail on windows with error : - * The requested operation cannot be performed on a file with a user-mapped section open - * - * @param searchRegex regex to search into file - * @param f file to search into - * @param encoding encoding to use - * @return matching lines (or {code null} if no matching lines) - * @throws IOException FIXME - * @since 1.1.2 - */ - public static List<CharSequence> grep(String searchRegex, - File f, - String encoding) throws IOException { - - List<CharSequence> lines = null; - - FileInputStream fis = null; - FileChannel fc = null; - - try { - // Open the file and then get a channel from the stream - fis = new FileInputStream(f); - fc = fis.getChannel(); - - // Get the file's size and then map it into memory - int sz = (int) fc.size(); - MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); - - // Decode the file into a char buffer - Charset charset = Charset.forName(encoding); - CharsetDecoder decoder = charset.newDecoder(); - CharBuffer cb = decoder.decode(bb); - - // Perform the search - lines = grep(searchRegex, cb); - } finally { - // Close the channel and the stream - if (fc != null) { - fc.close(); - } - if (fis != null) { - fis.close(); - } - } - - return lines; - } - - /** - * Java implementation for the unix grep command. - * <p> - * May fail on windows with error : - * The requested operation cannot be performed on a file with a user-mapped section open - * - * @param searchRegex regex to search into file - * @param rootDirectory directory to seacrh into - * @param fileRegex regex for file to find in {@code rootDirectory} - * @param encoding encoding to use - * @return all matching lines for each files - * @throws IOException FIXME - * @since 1.1.2 - */ - public static Map<File, List<CharSequence>> grep(String searchRegex, - File rootDirectory, - String fileRegex, - String encoding) throws IOException { - Map<File, List<CharSequence>> results = - new HashMap<File, List<CharSequence>>(); - List<File> files = find(rootDirectory, fileRegex, true); - for (File file : files) { - List<CharSequence> lines = grep(searchRegex, file, encoding); - if (lines != null) { - results.put(file, lines); - } - } - return results; - } - - /** - * Search for files matching regex in current directory. - * <p> - * May fail on windows with error : - * The requested operation cannot be performed on a file with a user-mapped section open - * - * @param searchRegex regex to search into file - * @param fileRegex regex for file to find in current dir - * @param encoding encoding to use - * @return all matching lines for each files - * @throws IOException FIXME - * @since 1.1.2 - */ - public static Map<File, List<CharSequence>> grep(String searchRegex, - String fileRegex, - String encoding) throws IOException { - Map<File, List<CharSequence>> results = grep(searchRegex, - new File("."), - fileRegex, - encoding); - return results; - } - - /** - * Sed implementation for a single file. - * <p> - * Oginal source code from http://kickjava.com/src/org/apache/lenya/util/SED.java.htm. - * <p> - * May fail on windows with error : - * The requested operation cannot be performed on a file with a user-mapped section open - * - * @param searchRegex Prefix which shall be replaced - * @param replace Prefix which is going to replace the original - * @param file File which sed shall be applied - * @param encoding charset encoding - * @throws IOException FIXME - * @since 1.1.2 - */ - public static void sed(String searchRegex, - String replace, - File file, - String encoding) throws IOException { - - Pattern pattern = Pattern.compile(searchRegex); - - String outString = null; - FileInputStream fis = new FileInputStream(file); - try { - // Open the file and then get a channel from the stream - FileChannel fc = fis.getChannel(); - - // Get the file's size and then map it into memory - int sz = (int) fc.size(); - MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); - - // Decode the file into a char buffer - // Charset and decoder for encoding - Charset charset = Charset.forName(encoding); - CharsetDecoder decoder = charset.newDecoder(); - CharBuffer cb = decoder.decode(bb); - - Matcher matcher = pattern.matcher(cb); - outString = matcher.replaceAll(replace); - } finally { - fis.close(); - } - - if (outString != null) { - PrintStream ps = new PrintStream(new FileOutputStream(file)); - try { - ps.print(outString); - } finally { - ps.close(); - } - } - } - - /** - * Java implementation for the unix sed command. - * <p> - * May fail on windows with error : - * The requested operation cannot be performed on a file with a user-mapped section open - * - * @param searchRegex regex to search into file - * @param replace string to replace matching patterns - * @param rootDirectory directory to search into - * @param fileRegex regex for file to find in {@code rootDirectory} - * @param encoding encoding to use - * @throws IOException FIXME - * @since 1.1.2 - */ - public static void sed(String searchRegex, - String replace, - File rootDirectory, - String fileRegex, - String encoding) throws IOException { - List<File> files = find(rootDirectory, fileRegex, true); - for (File file : files) { - sed(searchRegex, replace, file, encoding); - } - } - - /** - * Java implementation for the unix sed command. - * <p> - * May fail on windows with error : - * The requested operation cannot be performed on a file with a user-mapped section open - * - * @param searchRegex regex to search into file - * @param replace string to replace matching patterns - * @param fileRegex regex for file to find in current dir - * @param encoding encoding to use - * @throws IOException FIXME - * @since 1.1.2 - */ - public static void sed(String searchRegex, - String replace, - String fileRegex, - String encoding) throws IOException { - sed(searchRegex, replace, new File("."), fileRegex, encoding); - } - - /** - * Create the directory (and his parents) if necessary. - * - * @param dir the directory to create if not exisiting - * @return {@code true} if directory was created, {@code false} if was no - * need to create it - * @throws IOException if could not create directory - * @since 1.3.2 - */ - public static boolean createDirectoryIfNecessary(File dir) - throws IOException { - if (!dir.exists()) { - // do not throw exception if directory was created by another thread - return dir.mkdirs(); - } - return false; - } - - /** - * Obtain a file from the given {@code rootDirectory}, applying given paths. - * <p> - * For example with paths = a, b and c, then result is : - * <pre> - * root/a/b/c - * </pre> - * - * @param rootDirectory the root directory - * @param paths paths to apply - * @return the final file - * @since 2.2 - */ - public static File getFileFromPaths(File rootDirectory, String... paths) { - File result = rootDirectory; - for (String path : paths) { - result = new File(result, path); - } - return result; - } - - /** - * Obtain a file fro the given {@code rootDirectory}, applying the fqn. - * <p> - * For example with fqn = a.b.c, the result is : - * <pre> - * root/a/b/c - * </pre> - * - * @param rootDirectory the root directory - * @param fqn fqn of searched file - * @return the final file - * @since 2.2 - */ - public static File getFileFromFQN(File rootDirectory, String fqn) { - String[] paths = fqn.split("\\."); - - File result = getFileFromPaths(rootDirectory, paths); - return result; - } - - /** - * Obtain a directory and creates it if required to place some test data. - * <p> - * The directory will be : - * <pre> - * java.io.tmpdir/testclassName.fqn/methodName[/classifier]/timestamp - * </pre> - * - * @param testClassName test class name - * @param methodName method name - * @param classifier optional classifier - * @param timestamp timestamp - * @return the computed and created if required directory. - * @since 2.6.10 - */ - public static File getTestSpecificDirectory(Class<?> testClassName, - String methodName, - String classifier, - long timestamp) { - File tempDirFile = SystemUtils.getJavaIoTmpDir(); - - // create the directory to store database data - String dataBasePath = testClassName.getName() - + File.separator // a directory with the test class name - + methodName; // a sub-directory with the method name - - if (StringUtils.isNotBlank(classifier)) { - dataBasePath += classifier; - } - dataBasePath += '_' - + timestamp; // and a timestamp - File databaseFile = new File(tempDirFile, dataBasePath); - return databaseFile; - } - - /** - * Tests if a file is GZipped. - * - * @param file file to test - * @return {@code true} if file is gzipped, {@code false} otherwise - * @throws IOException if any io errors while reading file - * @since 3.0 - */ - public static boolean isGzipFile(File file) throws IOException { - - try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { - boolean gzip = GZUtil.isGzipStream(in); - return gzip; - } - } - -} // FileUtil diff --git a/src/main/java/org/nuiton/util/GZUtil.java b/src/main/java/org/nuiton/util/GZUtil.java deleted file mode 100644 index 4bc6eec..0000000 --- a/src/main/java/org/nuiton/util/GZUtil.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * - * GZUtil.java - * - * Created: 3 nov. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.io.StringReader; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -public class GZUtil { // GZUtil - - /** - * Tests if an inputStream is GZipped. - * <p> - * <b>Note:</b> the stream is not closed and is reset. - * - * @param inputStream inputStream to test - * @return {@code true} if inputStream is gzipped, {@code false} otherwise - * @throws IOException if any io errors while reading inputStream - * @since 3.0 - */ - public static boolean isGzipStream(InputStream inputStream) throws IOException { - - inputStream.mark(2); - // read header to see if is compressed file - int b = inputStream.read(); - // redundant cast : int magic = ((int) in.read() << 8) | b; - int magic = inputStream.read() << 8 | b; - inputStream.reset(); - boolean gzip = magic == GZIPInputStream.GZIP_MAGIC; - return gzip; - - } - - /** - * @param in FIXME - * @return Retourne la string decompressee - */ - public static StringBuffer bytesToStringBuffer(byte[] in) { - try { - if (in == null || in.length == 0) { - return new StringBuffer(""); - } - GZIPInputStream gz = new GZIPInputStream(new BufferedInputStream(new ByteArrayInputStream(in))); - StringBuffer sb = new StringBuffer(); - int c; - - while ((c = gz.read()) != -1) { - sb.append((char) c); - } - gz.close(); - return sb; - } catch (IOException eee) { - throw new GZUtilException("Probleme dans la decompression", eee); - } - } - - /** - * @param in FIXME - * @return la string decompressee - */ - public static String bytesToString(byte[] in) { - return bytesToStringBuffer(in).toString(); - } - - /** - * @param elem FIXME - * @return Retourne la string compressee - */ - public static byte[] stringBufferToBytes(StringBuffer elem) { - return stringToBytes(elem.toString()); - } - - /** - * @param elem FIXME - * @return Retourne la string compressee - */ - public static byte[] stringToBytes(String elem) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gz = new GZIPOutputStream(new BufferedOutputStream(baos)); - Reader sr = new BufferedReader(new StringReader(elem)); - int c; - while ((c = sr.read()) != -1) { - gz.write((char) c); - } - gz.close(); - - return baos.toByteArray(); - } catch (IOException eee) { - throw new GZUtilException("Probleme dans la compression", eee); - } - } - -} // GZUtil - diff --git a/src/main/java/org/nuiton/util/GZUtilException.java b/src/main/java/org/nuiton/util/GZUtilException.java deleted file mode 100644 index 0c0c0d3..0000000 --- a/src/main/java/org/nuiton/util/GZUtilException.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * - * GZUtilException.java - * - * Created: 3 nov. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -public class GZUtilException extends RuntimeException { // GZUtilException - - /** */ - private static final long serialVersionUID = -3342417793974741697L; - - public GZUtilException(String msg) { - super(msg); - } - - public GZUtilException(String msg, Throwable eee) { - super(msg, eee); - } -} // GZUtilException - diff --git a/src/main/java/org/nuiton/util/HashList.java b/src/main/java/org/nuiton/util/HashList.java deleted file mode 100644 index fe90d8e..0000000 --- a/src/main/java/org/nuiton/util/HashList.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * - * HashList.java - * - * Created: 2 nov. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; - -/** - * Cette objet permet de gerer l'unicité des objets ajouté. - * Lorsque l'on appelle la methode add sur cette objet, il verifie - * en premier que l'objet n'est pas deja dans la liste. S'il y est - * alors il n'est pas ajouter, sinon il est ajouter. - * L'utilisation de la methode set n'est pas permise - * - * FIXME: la serialisation n'est pas modifier, c-a-d que seul le tableau est - * conserve et pas la hashSet, donc apres recuperation, l'uticite n'est plus - * garantie. Il faut donc surcharger readObject et writeObject pour conserver - * le HashSet - */ -public class HashList<E> extends ArrayList<E> { // HashList - - /** */ - private static final long serialVersionUID = -334941610313293930L; - - protected HashSet<E> set = new HashSet<E>(); - - public HashList() { - } - - public HashList(Collection<? extends E> c) { - addAll(c); - } - - public HashList(int initialCapacity) { - super(initialCapacity); - } - - @Override - public E set(int index, E element) { - throw new UnsupportedOperationException("You can't use set method in HashList"); - } - - @Override - public boolean add(E o) { - boolean result = !contains(o); - add(size(), o); - return result; - } - - @Override - public void add(int index, E element) { - if (set.add(element)) { - super.add(index, element); - } - } - - /** - * supprime l'element demandé. Si l'elment n'existe pas alors, null - * est retrouné. - */ - @Override - public E remove(int index) { - if (set.remove(get(index))) { - return super.remove(index); - } - return null; - } - - @Override - public void clear() { - set.clear(); - super.clear(); - } - - @Override - public boolean addAll(Collection<? extends E> c) { - boolean modified = false; - for (E aC : c) { - if (add(aC)) - modified = true; - } - return modified; - - } - - @Override - public boolean addAll(int index, Collection<? extends E> c) { - boolean modified = false; - for (E aC : c) { - add(index++, aC); - modified = true; - } - return modified; - - } - - @Override - protected void removeRange(int fromIndex, int toIndex) { - for (int i = toIndex - 1; i >= fromIndex; i--) { - remove(i); - } - } - - @Override - public boolean contains(Object elem) { - return set.contains(elem); - } - - @Override - public Object clone() { - HashList<E> result = new HashList<E>(this); - return result; - } - -} // HashList - diff --git a/src/main/java/org/nuiton/util/LRUMapMultiKey.java b/src/main/java/org/nuiton/util/LRUMapMultiKey.java deleted file mode 100644 index 23943d6..0000000 --- a/src/main/java/org/nuiton/util/LRUMapMultiKey.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - - -/** Created: 23 mai 2006 04:08:03 - * @author Benjamin Poussin - poussin@codelutin.com */ - -public class LRUMapMultiKey extends LinkedHashMap<LRUMapMultiKey.Key, Object> { - - private static final long serialVersionUID = 1L; - - private static final Log log = LogFactory.getLog(LRUMapMultiKey.class); - - /** @author Benjamin Poussin - poussin@codelutin.com */ - public static class Key extends ArrayList<Object> { - - private static final long serialVersionUID = 1L; - - // protected LRUMapMultiKey map = null; - // protected Reference ref = null; - protected int hash = 0; - - public Key(Object... k) { - Collections.addAll(this, k); - } - - @Override - public int hashCode() { - if (hash == 0) { - hash = super.hashCode(); - } - return hash; - } - -// /* (non-Javadoc) -// * @see java.util.AbstractList#equals(java.lang.Object) -// */ -// @Override -// public boolean equals(Object o) { -// if (o != null && o instanceof Reference) { -// Object ref = ((Reference)o).get(); -// if (ref == null) { -// boolean result = o.hashCode() == hashCode(); -// return result; -// } -// } -// return super.equals(o); -// } - -// /* (non-Javadoc) -// * @see java.lang.Object#finalize() -// */ -// @Override -// protected void finalize() throws Throwable { -// if (map != null) { -// for (Iterator i=iterator(); i.hasNext();) { -// Object k = i.next(); -// Set<Reference<Key>> list = map.keys.get(k); -// if (list != null) { -// Object o = ref; -// if (o == null) { -// o = this; -// } -// boolean ok = list.remove(o); -// if (list.size() == 0) { -// map.keys.remove(k); -// } -// } -// } -// } -// } - - } - - - protected Map<Object, Set<Key>> keys = new HashMap<Object, Set<Key>>(); - - protected int maxSize; - - public LRUMapMultiKey(int maxSize) { - super(maxSize <= 0 ? 1000 : maxSize * 100 / 75, (float) 0.75, true); - this.maxSize = maxSize; - } - - public Key createKey(Object... k) { - return new Key(k); - } - - /* (non-Javadoc) - * @see java.util.WeakHashMap#clear() - */ - @Override - public void clear() { - keys.clear(); - super.clear(); - } - - /* (non-Javadoc) - * @see java.util.WeakHashMap#remove(java.lang.Object) - */ - @Override - public Object remove(Object k) { - if (k instanceof Key) { - return super.remove(k); - } else { - ArrayList<Key> result = new ArrayList<Key>(); - Set<Key> list = keys.remove(k); - if (list != null) { - for (Iterator<Key> i = list.iterator(); i.hasNext(); ) { - Key key = i.next(); - result.add(key); - super.remove(key); - } - list.clear(); // not necessary but perhaps help the garbage - } - return result; - } - } - - /* (non-Javadoc) - * @see java.util.WeakHashMap#put(java.lang.Object, java.lang.Object) - */ - @Override - public Object put(Key key, Object value) { -// if (!(akey instanceof Key)) { -// throw new IllegalArgumentException("key must be Key object"); -// } -// Key key = (Key)akey; - for (Iterator i = key.iterator(); i.hasNext(); ) { - Object k = i.next(); - Set<Key> list = keys.get(k); - if (list == null) { - list = new HashSet<Key>(); - keys.put(k, list); - } - list.add(key); -//System.out.println("+++++++++++++++++++ put key: " + key + " list("+k+") == " + list.size()); - } -//System.out.println("++++++++++++++++++++++++++++ LRU size = " + size() + " maxSize: " + maxSize); - Object result = super.put(key, value); -//System.out.println("+++++++++++++++++ LRU size = " + size()); - return result; - } - - /* (non-Javadoc) - * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry) - */ - @Override - protected boolean removeEldestEntry(Map.Entry<Key, Object> eldest) { - if (this.maxSize > 0 && size() > this.maxSize) { - Key key = (Key) eldest.getKey(); - for (Iterator i = key.iterator(); i.hasNext(); ) { - Object k = i.next(); - Set<Key> list = keys.get(k); - if (list != null) { - list.remove(key); - if (list.size() == 0) { - keys.remove(k); - } - } - } - - if (!containsKey(eldest.getKey())) { - log.warn("possible memory leak !!! removeEldestEntry (" + eldest.getKey().getClass() + ")" + eldest.getKey() + " size " + size() + " maxSize" + maxSize); - } - return true; - } - return false; - } - -// /* (non-Javadoc) -// * @see org.apache.commons.collections.map.LRUMap#removeLRU(org.apache.commons.collections.map.AbstractLinkedMap.LinkEntry) -// */ -// @Override -// protected boolean removeLRU(AbstractLinkedMap.LinkEntry entry) { -// Key key = (Key)entry.getKey(); -// for (Iterator i=key.iterator(); i.hasNext();) { -// Object k = i.next(); -// Set<Key> list = keys.get(k); -// if (list != null) { -// boolean ok = list.remove(key); -// if (list.size() == 0) { -// keys.remove(k); -// } -// } -// } -// return true; -// } - -} - - diff --git a/src/main/java/org/nuiton/util/ListenerSet.java b/src/main/java/org/nuiton/util/ListenerSet.java deleted file mode 100644 index f703df2..0000000 --- a/src/main/java/org/nuiton/util/ListenerSet.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * - * ListenerSet.java - * - * Created: 10 mai 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * Copyright Code Lutin - * - * - * Mise a jour: $Date$ - * par : */ -package org.nuiton.util; - -import java.beans.Statement; -import java.lang.ref.Reference; -import java.util.HashSet; -import java.util.Iterator; - -/** - * <p>Cette classe permet de mettre en place facilement le support de listeners. - * Elle ne permet d'ajouter qu'une seul fois le meme listener. Si elle est - * la derniere à avoir une référence sur le listener, le listener est supprimé - * de la liste des listeners.</p> - * <p>Si on souhaite avoir une vérification sur le type de listener ajouté - * il faut utiliser le constructeur qui prend une classe en paramètre. Dans ce - * cas la méthode {@link #add(Object)} vérifie que l'object passé est bien - * du type ou un enfant du type donné en paramètre du constructeur - * <p>Il y a deux façon de prévenir les listeners d'un event soit par le - * mécanisme inclu dans cette classe en utilisant la méthode {@link #fire} soit - * en utilisant soit même l'Iterateur sur les listeners encore valide.</p> - * <pre> - * ListenerSet listeners = new ListenerSet(); - * ... - * listeners.fire("monEvent", MonObjetEvent); - * </pre> - * ou bien - * <pre> - * ListenerSet listeners = new ListenerSet(); - * ... - * for(Iterator i=listeners.iterator(); i.hasNext();){ - * MonListener l = (MonListener)i.next(); - * l.monEvent(MonObjetEvent); - * } - * </pre> - * Cette deuxième façon de faire est plus sûr car elle n'utilise pas - * l'introspection et donc une vérification est faite sur le nom de la méthode - * à appeler à la compilation, mais elle est plus verbeuse à écrire. - * - * @param <L> listeners type - * @see CategorisedListenerSet - */ -public class ListenerSet<L> implements Iterable<L> { // ListenerSet - - /** Listeners reference set. */ - protected HashSet<Reference<L>> listeners = new HashSet<Reference<L>>(); - - public int size() { - return listeners.size(); - } - - /** - * Ajoute un listener dans la liste des listeners. - * - * @param l le listener à ajouter. Si l'objet passé est null, rien n'est fait - * si l'objet n'est pas du type passé en argument du constructeur - * une IllegalArgumentException est levée. - */ - public void add(L l) { - if (l == null) { - return; - } - - TransparenteWeakReference<L> ref = new TransparenteWeakReference<L>(l); - listeners.add(ref); - } - - /** - * ajoute tous les listeners d'un ListenerSet - * - * @param ls The feature to be added to the All attribute - */ - public void addAll(ListenerSet<L> ls) { - listeners.addAll(ls.listeners); - } - - /** - * Appel la méthode du listener en passant l'objet event en paramètre - * Cette méthode echoue si la methode ou l'objet contenant la methode a - * appeler n'est pas public - * - * @param methodName le nom de la methode a appeler - * @param event l'event a passer en parametre de la methode a appeler - * @throws Exception si un des listeners leve une exception lors de l'appel - */ - public void fire(String methodName, Object event) throws Exception { - for (Iterator<L> i = iterator(); i.hasNext(); ) { - L o = i.next(); - Statement stm = new Statement(o, methodName, new Object[]{event}); - stm.execute(); - } - } - - /** - * Appele la méthode du listener sans argument. - * - * Cette méthode echoue si la methode ou l'objet contenant la methode a - * appeler n'est pas public. - * - * @param methodName le nom de la methode a appeler - * @throws Exception si un des listeners leve une exception lors de l'appel - */ - public void fire(String methodName) throws Exception { - for (Iterator<L> i = iterator(); i.hasNext(); ) { - L o = i.next(); - Statement stm = new Statement(o, methodName, null); - stm.execute(); - } - } - - /** - * Get iterator on listener list. - * - * @return iterator on listener list. - */ - public Iterator<L> iterator() { - return new ReferenceIterator<L>(listeners.iterator()); - } - - /** - * Remove listener. - * - * @param l listener to remove - */ - public void remove(L l) { - TransparenteWeakReference<L> ref = new TransparenteWeakReference<L>(l); - listeners.remove(ref); - } - - @Override - public String toString() { - return listeners.toString(); - } - - /** Iterator qui supprime les references vides lors du parcours */ - static class ReferenceIterator<T> implements Iterator<T> { - /** DOCUMENTME Description of the Field */ - protected Iterator<Reference<T>> iter = null; - - /** DOCUMENTME Description of the Field */ - protected T nextObject = null; - - /** - * Un iterator contenant des References - * - * @param iter DOCUMENTME Description of the Parameter - */ - public ReferenceIterator(Iterator<Reference<T>> iter) { - this.iter = iter; - findNext(); - } - - /** DOCUMENTME Method */ - protected void findNext() { - while (iter.hasNext() && nextObject == null) { - Reference<T> ref = iter.next(); - T o = ref.get(); - if (o != null) { - nextObject = o; - } else { - iter.remove(); - } - } - } - - /** - * DOCUMENTME Method - * - * @return DOCUMENTME Description of the Return Value - */ - public boolean hasNext() { - return nextObject != null; - } - - /** - * DOCUMENTME Method - * - * @return DOCUMENTME Description of the Return Value - */ - public T next() { - T result = nextObject; - nextObject = null; - findNext(); - return result; - } - - /** DOCUMENTME Method */ - public void remove() { - iter.remove(); - } - } - -} // ListenerSet diff --git a/src/main/java/org/nuiton/util/LoggingException.java b/src/main/java/org/nuiton/util/LoggingException.java deleted file mode 100644 index 41f4338..0000000 --- a/src/main/java/org/nuiton/util/LoggingException.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/** - * LogException.java - * - * Created: Sat Apr 20 2002 - * - * @author POUSSIN Benjamin <bpoussin@free.fr> - * Copyright Code Lutin - * - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -public class LoggingException extends RuntimeException { // LogException - - private static final long serialVersionUID = 3495450140612716283L; - - public LoggingException(String msg) { - super(msg); - } - - public LoggingException(String msg, Throwable e) { - super(msg, e); - } - -} // LogException diff --git a/src/main/java/org/nuiton/util/LoggingPatternFormatter.java b/src/main/java/org/nuiton/util/LoggingPatternFormatter.java deleted file mode 100644 index c0b350d..0000000 --- a/src/main/java/org/nuiton/util/LoggingPatternFormatter.java +++ /dev/null @@ -1,512 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/** - * PatternFormatter.java - * <p> - * Created: Sat Apr 20 2002 - * - * @author POUSSIN Benjamin <bpoussin@free.fr> - * Copyright Code Lutin - * <p> - * <p> - * Mise a jour: $Date$ - * par : $Author$ - */ - -package org.nuiton.util; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.logging.Formatter; -import java.util.logging.LogManager; -import java.util.logging.LogRecord; - -/** - * Classe org.nuiton.logging.PatternFormatter. - * <ul> - * <li>n: new line</li> - * <li>%: %</li> - * <li>{: {</li> - * </ul> - * <ul> - * <li>d: date</li> - * </ul> - * - * Date follow the same pattern as DateFormat. - * - * Sized - * <ul> - * <li>o: free memory</li> - * <li>O: total memory</li> - * <li>t: thread id</li> - * <li>p: priority level</li> - * <li>c: class name</li> - * <li>m: message</li> - * <li>a: argument</li> - * <li>e: exception</li> - * </ul> - * <p> - * Sized element support justify pattern. - * {[+|-]<size>[:<maxPo>]}. - * '+' is - * left justify, '-' rigth justify, size the prefered size for the element if it is not bigger. - * If maxPos option is present blanc is not add if it go up to maxPos. - * <p> - * SubString - * <ul> - * <li>M: method name</li> - * </ul> - * <p> - * L'element SubString a les memes possibilites que le pattern justify, - * et permet en plus de suprimer une sous chaine, - * cela permet de supprimer le debut du nom d'une classe. - * Syntaxe : - * {*<substring>|[+|-]<size>[:<maxPos>]} - * {<substring>*|[+|-]<size>[:<maxPos>]} - * L'etoile represente le texte qui restera. - */ -public class LoggingPatternFormatter extends Formatter { // PatternFormatter - - private static final String DEFAULT_PATTERN = "%d{yyyy-MM-dd HH:mm:ss} [free:%o{-7}|total:%O{-7}][%t][%p{7}] %c{org.nuiton.*|25} %M{15:105}: %m%n%e"; - - protected HashMap<String, Class<?>> arguments = null; - - protected ArrayList<Argument> compile = null; - - protected String pattern = null; - - public LoggingPatternFormatter() { - try { - arguments = new HashMap<String, Class<?>>(); - initArguments(); - LogManager manager = LogManager.getLogManager(); - String cname = this.getClass().getName(); - pattern = manager.getProperty(cname + ".pattern"); - if (pattern == null) - pattern = DEFAULT_PATTERN; - compilePattern(pattern); - } catch (Exception eee) { - System.err.println("Impossible d'utiliser le PatternFormatter"); - eee.printStackTrace(); - throw new LoggingException( - "Exception durant l'initialisation du PatternFormatter", - eee); - } - } - - /** - * Methode qui formate le record - * - * @param record FIXME - * @return FIXME - */ - public String format(LogRecord record) { - StringBuffer result = new StringBuffer(); - for (Iterator i = compile.iterator(); i.hasNext(); ) { - ((Argument) i.next()).toString(record, result); - } - return result.toString(); - } - - /** - * Si vous souhaitez ajouter des type d'argument - * Surcharger cette methode et a la fin fait un super.initArguments() - */ - protected void initArguments() { - arguments.put("d", DateArgument.class); - arguments.put("o", FreeMemoryArgument.class); - arguments.put("O", TotalMemoryArgument.class); - arguments.put("t", ThreadArgument.class); - arguments.put("p", PriorityLevelArgument.class); - arguments.put("c", ClassNameArgument.class); - arguments.put("M", MethodNameArgument.class); - arguments.put("m", MessageArgument.class); - arguments.put("e", ExceptionArgument.class); - } - - /** - * Genere a partir de la chaine la liste des objet Argument. - * - * @param pattern FIXME - */ - protected void compilePattern(String pattern) { - compile = new ArrayList<Argument>(); - String[] match = findNextPattern(pattern); - while (!match[1].equals("")) { - compile.add(new StringArgument(match[0])); - compile.add(patternToArgument(match[1])); - match = findNextPattern(match[2]); - } - compile.add(new StringArgument(match[0])); - } - - /** - * Recherche dans la chaine le prochaine pattern. - * - * @param s FIXME - * @return un tableau de 3 chaines, [0] ce qu'il y a avant le - * parttern, [1] le parttern, [2] ce qu'il y a apres le pattern. - */ - protected String[] findNextPattern(String s) { - String[] result = new String[]{"", "", ""}; - if (s == null) { - return result; - } - - int d = s.indexOf("%"); - - if (d != -1) { // il y a un % - if (d + 2 < s.length() && s.charAt(d + 2) == '{') { - int f = s.indexOf("}", d); - if (f != -1) { // il y a une pattern %c{pattern} - result[0] = s.substring(0, d); - result[1] = s.substring(d + 1, f); - result[2] = s.substring(f + 1); - } else { - throw new LoggingException("Error, { at position " - + (d + 2) + " not terminated in :" + s); - } - } else { //pas de pattern - result[0] = s.substring(0, d); - result[1] = s.substring(d + 1, d + 2); - result[2] = s.substring(d + 2); - } - } else { - result[0] = s; - } - - return result; - } - - /** - * Converti un pattern en un objet Argument - * - * @param s FIXME - * @return FIXME - */ - protected Argument patternToArgument(String s) { - if (s.charAt(0) == 'n') { // new ligne - return new StringArgument("\n"); - - } else if (s.charAt(0) == '%') { // le caractere % - return new StringArgument("%"); - - } else if (s.charAt(0) == '{') { // le caractere { - return new StringArgument("{"); - - } else { - String code = s.substring(0, 1); - Class argumentClass = (Class) arguments.get(code); - if (argumentClass == null) - throw new LoggingException("Erreur dans le pattern '" + code - + "' inconnu"); - Argument argument; - try { - argument = (Argument) argumentClass.newInstance(); - } catch (InstantiationException eee) { - throw new LoggingException( - "Erreur lors de l'instanciation de l'objet Argument: " - + argumentClass.getName(), eee); - } catch (IllegalAccessException eee) { - throw new LoggingException( - "Erreur lors de l'instanciation de l'objet Argument: " - + argumentClass.getName(), eee); - } - if (s.length() > 1) { // on a un pattern - argument.setPattern(s.substring(2)); - } - - return argument; - } - } - - /////////////////////////////////////////////////////////////////////////////// - //////////////////////////// Les Classes Argument ///////////////////////////// - /////////////////////////////////////////////////////////////////////////////// - - static protected abstract class Argument { - protected String pattern; - - public Argument() { - } - - public void setPattern(String pattern) { - this.pattern = pattern; - } - - abstract public StringBuffer toString(LogRecord record, - StringBuffer toAppendTo); - } - - static protected class StringArgument extends Argument { - protected String s = null; - - public StringArgument(String s) { - super(); - this.s = s; - } - - public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { - toAppendTo.append(s); - return toAppendTo; - } - } - - static protected class DateArgument extends Argument { - protected SimpleDateFormat dateFormat = null; - - public DateArgument() { - super(); - } - - public void setPattern(String pattern) { - super.setPattern(pattern); - dateFormat = new SimpleDateFormat(pattern); - } - - public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { - toAppendTo.append(dateFormat.format(new Date(record.getMillis()))); - return toAppendTo; - } - } - - static abstract protected class SizedArgument extends Argument { - protected boolean left = true; - - protected int width = 0; - - protected int maxPos = -1; - - public SizedArgument() { - super(); - } - - public void setPattern(String pattern) { - super.setPattern(pattern); - if (pattern.length() > 0) { - String[] subpattern = pattern.split(":"); - pattern = subpattern[0]; - char op = pattern.charAt(0); - if (pattern.charAt(0) == '+' || pattern.charAt(0) == '-') { - pattern = pattern.substring(1); - } - width = Integer.parseInt(pattern); - left = op != '-'; - if (subpattern.length > 1) { - maxPos = Integer.parseInt(subpattern[1]); - } - } - } - - protected StringBuffer justify(String s, StringBuffer toAppendTo) { - int blanc = width - s.length(); - if (left) { - toAppendTo.append(s); - while (0 < blanc-- - && (maxPos == -1 || toAppendTo.length() < maxPos)) { - toAppendTo.append(" "); - } - } else { - while (0 < blanc-- - && (maxPos == -1 || toAppendTo.length() < maxPos)) { - toAppendTo.append(" "); - } - toAppendTo.append(s); - } - return toAppendTo; - } - } - - static abstract protected class SubStringArgument extends SizedArgument { - /** - * la chaine qui doit etre supprimee - */ - protected String removeString = null; - - /** - * vrai si la chaine doit etre retiree du debut, faux pour la fin - */ - protected boolean atBeginning = true; - - public SubStringArgument() { - super(); - } - - public void setPattern(String pattern) { - String[] subpattern = pattern.split("\\|"); - for (int i = 0; i < subpattern.length; i++) { - try { //on essai de voir si le pattern convient au SizedArgument - super.setPattern(subpattern[i]); - } catch (NumberFormatException eee) { - // il ne convient pas au SizedArgument - // c pour le substring - atBeginning = subpattern[i].charAt(0) != '*'; - if (subpattern[i].charAt(0) == '*') { - removeString = subpattern[i].substring(1); - } else if (subpattern[i].endsWith("*")) { - removeString = subpattern[i].substring(0, subpattern[i] - .length() - 1); - } - } - } - } - - protected String substring(String s) { - if (atBeginning) { - if (s.startsWith(removeString)) - return s.substring(removeString.length()); - } else { - if (s.endsWith(removeString)) - return s.substring(0, s.length() - removeString.length()); - } - return s; - } - } - - static abstract protected class OctetArgument extends SizedArgument { - protected static final String[] UNITE = {"o", "Ko", "Mo", "Go", "To", - "Po"}; - - protected int diviseur = 1024; - - public OctetArgument() { - super(); - } - - /** - * Methode permettant l'affichage d'un taille avec une representation - * humainement lisible. - * - * @param size la taille rendre lisible - * @param unit les unites a utiliser (les petits en premier) - * @param diviseur le diviseur entre unite (ex: 1000 ou 1024) - * @return la representation - */ - protected String toReadableSize(long size, String[] unit, int diviseur) { - int unitIndex = 0; - while (size > 99999 && unitIndex < unit.length) { - size /= diviseur; - unitIndex++; - } - String result = size + unit[unitIndex]; - return result; - } - } - - static protected class FreeMemoryArgument extends OctetArgument { - public FreeMemoryArgument() { - super(); - } - - public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { - return justify(toReadableSize(Runtime.getRuntime().freeMemory(), - UNITE, diviseur), toAppendTo); - } - } - - static protected class TotalMemoryArgument extends OctetArgument { - public TotalMemoryArgument() { - super(); - } - - public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { - return justify(toReadableSize(Runtime.getRuntime().totalMemory(), - UNITE, diviseur), toAppendTo); - } - } - - static protected class ThreadArgument extends SizedArgument { - public ThreadArgument() { - super(); - } - - public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { - return justify(Thread.currentThread().getName(), toAppendTo); - } - } - - static protected class PriorityLevelArgument extends SizedArgument { - public PriorityLevelArgument() { - super(); - } - - public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { - return justify(record.getLevel().toString(), toAppendTo); - } - } - - static protected class ClassNameArgument extends SubStringArgument { - public ClassNameArgument() { - super(); - } - - public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { - return justify(substring(record.getSourceClassName()), toAppendTo); - } - } - - static protected class MethodNameArgument extends SizedArgument { - public MethodNameArgument() { - super(); - } - - public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { - return justify(record.getSourceMethodName(), toAppendTo); - } - } - - static protected class MessageArgument extends SizedArgument { - public MessageArgument() { - super(); - } - - public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { - return justify(record.getMessage(), toAppendTo); - } - } - - static protected class ExceptionArgument extends Argument { - public ExceptionArgument() { - super(); - } - - public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { - Throwable e = record.getThrown(); - if (e != null) { - toAppendTo.append(e.getMessage()); - toAppendTo.append("\n"); - StringWriter st = new StringWriter(); - e.printStackTrace(new PrintWriter(st)); - toAppendTo.append(st.toString()); - toAppendTo.append("\n"); - } - return toAppendTo; - } - } - -} // PatternFormatter diff --git a/src/main/java/org/nuiton/util/MD5InputStream.java b/src/main/java/org/nuiton/util/MD5InputStream.java deleted file mode 100644 index e3e0752..0000000 --- a/src/main/java/org/nuiton/util/MD5InputStream.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import static org.nuiton.i18n.I18n.t; - -/** - * MD5InputStream, a subclass of FilterInputStream implementing MD5 - * functionality on a stream. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class MD5InputStream extends DigestInputStream { - - /** Class logger. */ - private static Log log = LogFactory.getLog(MD5InputStream.class); - - protected static MessageDigest getMD5Digest() throws IllegalStateException { - try { - MessageDigest digest = MessageDigest.getInstance("MD5"); - return digest; - } catch (NoSuchAlgorithmException e) { - if (log.isErrorEnabled()) { - log.error(t("nuitonutil.error.could.not.find.MD5"), e); - } - throw new IllegalStateException(e); - } - } - - /** - * Compute the MD5 for the given {@code input}. - * - * <b>Note:</b> The the stream will be closed after calling the method - * even if something was wrong. - * - * @param input the stream to parse - * @return the MD5 hash for the given input stream - * @throws IOException if any pb while reading in stream or digest - */ - public static byte[] hash(InputStream input) throws IOException { - MD5InputStream in = new MD5InputStream(input); - try { - while (in.read() != -1) { - // read a caracter on stream - } - - byte[] result = in.hash(); - return result; - } finally { - in.close(); - } - } - - - /** - * Compute the MD5 for the given {@code input} file. - * - * @param input the File stream to parse - * @return the MD5 hash for the given input File - * @throws IOException if any pb while reading in stream or digest - */ - public static byte[] hash(File input) throws IOException { - InputStream inputStream = new BufferedInputStream(new FileInputStream(input)); - byte[] result; - try { - result = hash(inputStream); - } finally { - inputStream.close(); - } - return result; - } - - - /** - * Compute the MD5 for the given {@code input} sring. - * - * @param input the stream to parse - * @return the MD5 hash for the given input String - * @throws IOException if any pb while reading in stream or digest - */ - public static byte[] hash(String input) throws IOException { - byte[] result = hash(new ByteArrayInputStream(input.getBytes())); - return result; - } - - /** length of readed stream */ - protected long streamLength; - - /** - * Creates a MD5InputStream - * - * @param in The input stream - */ - public MD5InputStream(InputStream in) { - super(in, getMD5Digest()); - } - - @Override - public int read() throws IOException { - int c = super.read(); - - if (c == -1) { - return -1; - } - streamLength++; - return c; - } - - @Override - public int read(byte bytes[], int offset, int length) throws IOException { - int r; - - if ((r = super.read(bytes, offset, length)) == -1) { - return r; - } - streamLength += r; - return r; - } - - /** - * Returns array of bytes representing hash of the stream as finalized for - * the current state. - * - * @return hash - * @see MessageDigest#digest() - */ - public byte[] hash() { - return getMessageDigest().digest(); - } - - public long getStreamLength() { - return streamLength; - } -} - diff --git a/src/main/java/org/nuiton/util/MD5OutputStream.java b/src/main/java/org/nuiton/util/MD5OutputStream.java deleted file mode 100644 index 7245244..0000000 --- a/src/main/java/org/nuiton/util/MD5OutputStream.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.io.OutputStream; -import java.security.DigestOutputStream; -import java.security.MessageDigest; - -/** - * - * - */ - -public class MD5OutputStream extends DigestOutputStream { - - /** - * Creates MD5OutputStream - * - * @param out The output stream - */ - - public MD5OutputStream(OutputStream out) { - super(out, MD5InputStream.getMD5Digest()); - } - - /** - * @return array of bytes representing hash of the stream as finalized for - * the current state. - * @see MessageDigest#digest() - */ - - public byte[] hash() { - return getMessageDigest().digest(); - } - -} - diff --git a/src/main/java/org/nuiton/util/MatrixMap.java b/src/main/java/org/nuiton/util/MatrixMap.java deleted file mode 100644 index 2bf7668..0000000 --- a/src/main/java/org/nuiton/util/MatrixMap.java +++ /dev/null @@ -1,2357 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2012 CodeLutin, Chatellier Eric - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util; - -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.Serializable; -import java.util.AbstractList; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.RandomAccess; - -/** - * Permet de stocker des informations dans une matrix a N dimension - * Si lors de l'ajout on indique une dimension qui n'existe pas encore ou - * un element dans une dimension qui n'existe pas, la matrice ajoute - * automatiquement les elements manquant pour que l'ajout se passe bien. - * <p> - * MatrixMap permet de stocker les elements avec des cles de n'importe quel - * type. Les coordonnees utilisant ces objets sont converti en coordonnees - * numeriques qui est la seul chose que sait gere Matrix. Ces coordonnees - * numeriques sont alors convertis en coordonnees lineaire pour le stockage - * dans Vector. On decoupe ainsi les problemes et on minimise le stockage et - * certain traitement sur les données puisqu'au final toutes les données sont - * dans une simple liste. - * <p> - * Pour créer une nouvelle matrice, il faut utiliser une des méthodes de - * {@link MatrixMap.Factory} - * - * @author Benjamin Poussin - poussin@codelutin.com - * @since 2.2.1 - */ -public interface MatrixMap<E> extends Iterable<E> { - - /** - * Classe permettant la creation de matrice - */ - class Factory { - public static <T> MatrixMap<T> create(List... semantics) { - MatrixMap<T> result = new MatrixMapFixed<T>(semantics); - return result; - } - - public static <T> MatrixMap<T> create(String name, List... semantics) { - MatrixMap<T> result = new MatrixMapFixed<T>(name, semantics); - return result; - } - - public static <T> MatrixMap<T> create(String name, String[] dimNames, List... semantics) { - MatrixMap<T> result = new MatrixMapFixed<T>(name, dimNames, semantics); - return result; - } - - public static <T> MatrixMap<T> create(MatrixMap<T> matrix) { - MatrixMap<T> result = new MatrixMapFixed<T>(matrix); - return result; - } - - public static <T> MatrixMap<T> createElastic(List... semantics) { - MatrixMap<T> result = create(semantics); - result = createElastic(result); - return result; - } - - public static <T> MatrixMap<T> createElastic(String name, List... semantics) { - MatrixMap<T> result = create(name, semantics); - result = createElastic(result); - return result; - } - - public static <T> MatrixMap<T> createElastic(String name, String[] dimNames, List... semantics) { - MatrixMap<T> result = create(name, dimNames, semantics); - result = createElastic(result); - return result; - } - - public static <T> MatrixMap<T> createElastic(MatrixMap<T> matrix) { - MatrixMap<T> result = new MatrixMapElastic<T>(matrix); - return result; - } - } - - @Override - MatrixMapIterator<E> iterator(); - - /** - * Copy la matrice pour pouvoir la modifier sans perdre les donnees - * initiales. - * - * @return new matrix - */ - MatrixMap<E> copy(); - - SemanticList[] getSemantics(); - - SemanticList getSemantic(int dim); - - void setSemantic(int dim, List sem); - - void setName(String name); - - String getName(); - - String[] getDimensionNames(); - - void setDimensionNames(String[] names); - - void setDimensionName(int dim, String name); - - String getDimensionName(int dim); - - int getDimCount(); - - int[] getDim(); - - int getDim(int d); - - /** - * Applique sur chaque element de la matrice la fonction f - * - * @param f la fonction a appliquer - * @return Retourne la matrice elle meme. Les modifications sont faites directement - * dessus - */ - MatrixMap<E> map(MapFunction<E> f); - - /** - * Retourne l'element a une certaine position en utilisant des indices - * ex: 2,3,1 - * - * @param coordinates FIXME - * @return FIXME - */ - E getValueIndex(int... coordinates); - - /** - * Modifie l'element a une certaine position en utilisant des indices - * ex: 2,3,1 - * - * @param value la nouvelle valeur - * @param coordinates FIXME - */ - void setValueIndex(E value, int... coordinates); - - /** - * Retourne l'element a une certaine position en utilisant les semantiques - * - * @param coordinates FIXME - * @return FIXME - */ - E getValue(Object... coordinates); - - /** - * Modifie l'element a une certaine position en utilisant les semantiques - * - * @param value la nouvelle valeur - * @param coordinates FIXME - */ - void setValue(E value, Object... coordinates); - - /** - * Verifie que deux matrices sont completement equals - * (dimension, semantique, nom, valeur, ...) - * - * @param mat FIXME - * @return FIXME - */ - boolean equals(MatrixMap mat); - - /** - * Verifie si les matrices sont egales en ne regardant que les valeurs et - * pas les semantiques - * - * @param mat FIXME - * @return equality on values - */ - boolean equalsValues(MatrixMap<E> mat); - - /** - * Representation string de la matrice quelque soit le nombre de dimension - * - * @return FIXME - */ - String toStringGeneric(); - - /** - * Indique si les semantiques passées en argument sont valable pour la - * matrice courante - * - * @param semantics FIXME - * @return FIXME - */ - boolean isValidCoordinates(Object[] semantics); - - /** - * Copie une matrice dans la matrice actuelle. La matrice à copier à le même - * nombre de dimension. Si la matrice à copier est trop grande seul les - * éléments pouvant être copier le seront. - * - * @param mat la matrice à copier - * @return return la matrice courante. - */ - MatrixMap paste(MatrixMap<E> mat); - - /** - * Permet de prendre une sous matrice dans la matrice courante. La sous - * matrice a le même nombre de dimensions mais sur une des dimensions on ne - * prend que certain élément. - * - * @param dim la dimension dans lequel on veut une sous matrice - * @param start la position dans dim d'ou il faut partir pour prendre la - * sous matrice. 0 ≤ start < dim.size si start est négatif alors - * la position de départ est calculé par rapport à la fin de la - * dimension, pour avoir le dernier élément il faut passer -1 - * @param nb le nombre d'élément à prendre dans la dimension si nb est - * inférieur ou égal à 0 alors cela indique qu'il faut prendre - * tous les éléments jusqu'à la fin de la dimension. - * @return new matrix - */ - MatrixMap<E> getSubMatrix(int dim, Object start, int nb); - - /** - * Permet de prendre une sous matrice dans la matrice courante. La sous - * matrice a le même nombre de dimensions mais sur une des dimensions on ne - * prend que certain élément. - * - * @param dim la dimension dans lequel on veut une sous matrice - * @param elem les éléments dans la dimension à conserver - * @return new matrix - */ - MatrixMap<E> getSubMatrix(int dim, Object... elem); - - /** - * Permet de prendre une sous matrice dans la matrice courante. - * <p> - * Réalise plusieurs appels à {@link #getSubMatrix(int, Object...)} suivant - * l'implémentation. - * - * @param elems les éléments dans la dimension à conserver - * @return new matrix - */ - MatrixMap<E> getSubMatrix(Object[]... elems); - - /** - * Reduit la matrice de sorte que toutes les dimensions qui n'ont qu'un - * élement soit supprimée. Au pire cette méthode retourne une matrice à une - * seule dimension à un seul élément. - * - * @return une nouvelle matrice plus petite que la matrice actuelle ou egal - * s'il n'y a aucune dimension à supprimer - */ - MatrixMap<E> reduce(); - - /** - * Reduit le matrice seulement sur les dimensions passées en argument. Si - * une des dimensions passées en arguement n'a pas qu'un seul élément, cette - * dimension n'est pas prise en compte. - * - * @param dims les dimensions sur lequel il faut faire la reduction - * @return une nouvelle matrice - */ - MatrixMap<E> reduceDims(int... dims); - - /** - * Reduit la matrice de sorte que toutes les dimensions qui n'ont qu'un - * élement soit supprimée. Au pire cette méthode retourne une matrice à une - * seule dimension à un seul élément. - * - * @param minNbDim le nombre minimum de dimension que l'on souhaite pour la - * matrice résultat - * @return une nouvelle matrice plus petite que la matrice actuelle ou egal - * s'il n'y a aucune dimension à supprimer - */ - MatrixMap<E> reduce(int minNbDim); - - /** - * Permet de retourner une nouvelle matrice ayant les semantiques passées - * en parametre. La nouvelle matrice contient les données de l'ancienne - * matrice par copie en fonction des semantiques - * - * @param sems FIXME - * @return FIXME - */ - MatrixMap<E> extend(Object... sems); - - /////////////////////////////////////////////////////////////////////////// - // - // C L A S S E I N T E R N E - // - /////////////////////////////////////////////////////////////////////////// - - /** - * Classe contenant des méthodes statiques pour aider a la manipulation - * des matrices - */ - class MatrixHelper { - - /** - * Mais en forme un texte pour qu'il fasse exactement la longueur - * demandee (length). Si length est possitif alors s'il y besoin - * d'ajouter des espaces, ils seront mis devant le texte, sinon il - * seront mis apres le texte - * - * @param o l'objet a convertir en string - * @param length la longueur de representation souhaite - * @param valueIfNull la valeur a utilise si l'objet est null - * @return FIXME - */ - public static String format(Object o, int length, String valueIfNull) { - if (o == null) { - o = valueIfNull; - } - int absLength = Math.abs(length); - - String result = String.valueOf(o); - if (absLength > 3) { - result = StringUtils.abbreviate(result, absLength); - } - if (length < 0) { - result = StringUtils.leftPad(result, absLength); - } else if (length > 0) { - result = StringUtils.rightPad(result, absLength); - } - - return result; - } - - /** - * Permet de convertir des coordonnées définies par des entiers en coordonnées - * semantique par des objets - * - * @param semantics la semantique à utilisé pour la conversion - * @param coordinates les coordonnées à convertir - * @return un tableau donnant les coordonnées sous forme semantique s'il n'y - * a pas de semantique (liste pleine de null) alors un objet Integer - * est créer pour représenter la semantique de la dimension. - */ - public static Object[] dimensionToSemantics(List[] semantics, - int[] coordinates) { - Object[] result = new Object[coordinates.length]; - for (int i = 0; i < result.length; i++) { - result[i] = semantics[i].get(coordinates[i]); - } - return result; - } - - /** - * Permet de convertir des coordonnées sémantiques en coordonnées défini par - * des entiers. Cette fonction est l'inverse de - * {@link #dimensionToSemantics}. - * - * @param semantics la semantique à utiliser pour la conversion - * @param coordinates les coordonnées sémantique - * @return les coordonnées en entier. - */ - public static int[] semanticsToDimension(List[] semantics, - Object[] coordinates) { - int[] result = new int[coordinates.length]; - for (int i = 0; i < coordinates.length; i++) { - result[i] = indexOf(semantics, i, coordinates[i]); - } - return result; - } - - /** - * Permet de retrouver la position d'un objet dans une liste - * - * @param semantics la semantique à utilisé pour la recherche - * @param dim la dimension dans lequel il faut faire la recherche - * @param o l'objet à rechercher - * @return la position de l'objet dans la dimension demandée - * @throws NoSuchElementException If element doesn't exists - */ - public static int indexOf(List[] semantics, int dim, Object o) - throws NoSuchElementException { - int result = -1; - if ((0 <= dim) && (dim < semantics.length)) { - result = semantics[dim].indexOf(o); - } - if (result == -1) { - throw new NoSuchElementException( - "L'objet passé en argument n'a pas été retrouvé ou la dimension donnée ne convient pas:" - + o + " in " + semantics[dim]); - } - return result; - } - - /** - * Permet de savoir si deux dimension sont identiques. - * - * @param dim1 first dimensions - * @param dim2 second dimensions - * @return dimension equality - */ - public static boolean sameDimension(int[] dim1, int[] dim2) { - return Arrays.equals(dim1, dim2); - } - - } - - /** - * Iterateur de matrice - * - * @param <E> FIXME - */ - interface MatrixMapIterator<E> extends Iterator<E> { - int[] getCoordinates(); - - E getValue(); - - void setValue(E value); - - Object[] getSemanticsCoordinates(); - } - - class MatrixMapIteratorImpl<E> implements MatrixMapIterator<E> { // MatrixMapIteratorImpl - - protected MatrixIterator<E> iterator = null; - - protected List[] semantics = null; - - protected int pos = 0; - - /** - * @param iterator la matrice sur lequel l'iterator doit travailler - * @param semantics la semantique de matrix, si matrix n'a pas de semantique - * alors il faut passer null - */ - public MatrixMapIteratorImpl(MatrixIterator<E> iterator, List[] semantics) { - this.iterator = iterator; - this.semantics = semantics; - pos = 0; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public E next() { - return iterator.next(); - } - - @Override - public void remove() { - iterator.remove(); - } - - public int[] getCoordinates() { - return iterator.getCoordinates(); - } - - public E getValue() { - return iterator.getValue(); - } - - public void setValue(E value) { - iterator.setValue(value); - } - - public Object[] getSemanticsCoordinates() { - Object[] result = null; - if (semantics != null) { - int[] coordinates = getCoordinates(); - result = MatrixHelper.dimensionToSemantics(semantics, - coordinates); - } - return result; - } - - } // MatrixMapIteratorImpl - - /** - * Collection particuliere utilisee pour la stockage des semantiques. - * <p> - * Sert a optimiser la recherche de la position d'une donnee dans la liste. - * Permet aussi de verifier qu'on ajoute pas de doublon dans la liste - * - * @param <T> FIXME - */ - class SemanticList<T> extends AbstractList<T> implements RandomAccess { - - protected ArrayList<T> datas = null; - - protected Map<T, Integer> index = new HashMap<T, Integer>(); - - public SemanticList() { - this(new ArrayList<T>()); - } - - public SemanticList(Collection<T> c) { - datas = new ArrayList<T>(c); - } - - /* - * @see java.util.AbstractList#get(int) - */ - @Override - public T get(int index) { - T result = datas.get(index); - return result; - } - - @Override - public void add(int index, T element) { - datas.add(index, element); - this.index.clear(); - } - - @Override - public T set(int index, T element) { - T result = datas.set(index, element); - this.index.clear(); - return result; - } - - @Override - public T remove(int index) { - T result = super.remove(index); - this.index.clear(); - return result; - } - - - /* - * @see java.util.AbstractCollection#size() - */ - @Override - public int size() { - int result = datas.size(); - return result; - } - - /* - * @see java.util.AbstractList#indexOf(java.lang.Object) - */ - @Override - public int indexOf(Object o) { - Map<T, Integer> index = getIndex(); - Integer result = index.get(o); - int resultIndex = -1; - if (result != null) { - resultIndex = result.intValue(); - } - return resultIndex; - } - - protected Map<T, Integer> getIndex() { - if (index.isEmpty()) { - for (int i = 0; i < datas.size(); i++) { - index.put(datas.get(i), Integer.valueOf(i)); - } - } - return index; - } - } - - /** - * Implantation particuliere de matrice, qui lorsqu'on lui passe des - * dimension qui n'existe pas, elle les ajoutes dans les semantiques. Ceci - * n'est vrai que pour le set avec des semantiques, le set avec des indices - * ne rend pas la matrice elastique. - * <p> - * Cette classe fonctionne avec une matrice interne que l'on change lorsque - * l'on a besoin de modifier les dimensions. Le changement de dimension - * a donc un cout (creation d'une nouvelle matrice, copie des elements) - * <p> - * Si on cree une sous matrice, et que l'on modifie la matrice mere - * La sous matrice n'est pas impacter, puisqu'elle est base sur l'ancienne - * represention interne de la matrice elastique, les deux matrices n'ont donc - * plus de lien. - * <p> - * Les methodes reduce et extend retourne de nouvelle matrice qui ne sont - * pas elastique. Si on veut qu'elle le soit, il faut les reencapsuler - * - * @param <E> FIXME - */ - class MatrixMapElastic<E> implements MatrixMap<E> { - - protected MatrixMap<E> internalMatrixMap; - - public MatrixMapElastic() { - internalMatrixMap = Factory.create(); - } - - public MatrixMapElastic(MatrixMap<E> m) { - setInternalMatrixMap(m); - } - - public MatrixMap<E> getInternalMatrixMap() { - return internalMatrixMap; - } - - public void setInternalMatrixMap(MatrixMap<E> internalMatrixMap) { - this.internalMatrixMap = internalMatrixMap; - } - - public MatrixMapIterator<E> iterator() { - return getInternalMatrixMap().iterator(); - } - - public MatrixMap<E> copy() { - return getInternalMatrixMap().copy(); - } - - public SemanticList[] getSemantics() { - return getInternalMatrixMap().getSemantics(); - } - - public SemanticList getSemantic(int dim) { - return getInternalMatrixMap().getSemantic(dim); - } - - public void setSemantic(int dim, List sem) { - getInternalMatrixMap().setSemantic(dim, sem); - } - - public void setName(String name) { - getInternalMatrixMap().setName(name); - } - - public String getName() { - return getInternalMatrixMap().getName(); - } - - public String[] getDimensionNames() { - return getInternalMatrixMap().getDimensionNames(); - } - - public void setDimensionNames(String[] names) { - getInternalMatrixMap().setDimensionNames(names); - } - - public void setDimensionName(int dim, String name) { - getInternalMatrixMap().setDimensionName(dim, name); - } - - public String getDimensionName(int dim) { - return getInternalMatrixMap().getDimensionName(dim); - } - - public int getDimCount() { - return getInternalMatrixMap().getDimCount(); - } - - public int[] getDim() { - return getInternalMatrixMap().getDim(); - } - - public int getDim(int d) { - return getInternalMatrixMap().getDim(d); - } - - public MatrixMap<E> map(MapFunction<E> f) { - return getInternalMatrixMap().map(f); - } - - public E getValueIndex(int... coordinates) { - return getInternalMatrixMap().getValueIndex(coordinates); - } - - public void setValueIndex(E value, int... coordinates) { - // la matrice est elastique que pour le set avec des semantics - getInternalMatrixMap().setValueIndex(value, coordinates); - } - - public E getValue(Object... coordinates) { - return getInternalMatrixMap().getValue(coordinates); - } - - public void setValue(E value, Object... coordinates) { - // check si les coordonnees sont valide. - // si non valide alors on extend la matrice interne - // et on appelle sur la nouvelle matrice interne - if (!isValidCoordinates(coordinates)) { - MatrixMap<E> newMatrixMap = getInternalMatrixMap().extend(coordinates); - setInternalMatrixMap(newMatrixMap); - } - getInternalMatrixMap().setValue(value, coordinates); - } - - @Override - public boolean equals(Object obj) { - return getInternalMatrixMap().equals(obj); - } - - public boolean equals(MatrixMap mat) { - return getInternalMatrixMap().equals(mat); - } - - public boolean equalsValues(MatrixMap<E> mat) { - return getInternalMatrixMap().equalsValues(mat); - } - - @Override - public String toString() { - return getInternalMatrixMap().toString(); - } - - public String toStringGeneric() { - return getInternalMatrixMap().toStringGeneric(); - } - - public boolean isValidCoordinates(Object[] semantics) { - return getInternalMatrixMap().isValidCoordinates(semantics); - } - - public MatrixMap paste(MatrixMap<E> mat) { - return getInternalMatrixMap().paste(mat); - } - - public MatrixMap<E> getSubMatrix(int dim, Object start, int nb) { - return getInternalMatrixMap().getSubMatrix(dim, start, nb); - } - - public MatrixMap<E> getSubMatrix(int dim, Object... elem) { - return getInternalMatrixMap().getSubMatrix(dim, elem); - } - - public MatrixMap<E> getSubMatrix(Object[]... elems) { - return getInternalMatrixMap().getSubMatrix(elems); - } - - public MatrixMap<E> reduce() { - return getInternalMatrixMap().reduce(); - } - - public MatrixMap<E> reduceDims(int... dims) { - return getInternalMatrixMap().reduceDims(dims); - } - - public MatrixMap<E> reduce(int minNbDim) { - return getInternalMatrixMap().reduce(minNbDim); - } - - public MatrixMap<E> extend(Object... sems) { - return getInternalMatrixMap().extend(sems); - } - - } - - /** - * Implantation de MatrixMap dont les dimensions sont fixees a la creation - * Les dimensions ne change plus par la suite - * - * @param <E> FIXME - */ - class MatrixMapFixed<E> extends AbstractMatrixMap<E> { - /** - * Logger. - */ - static private Log log = LogFactory.getLog(MatrixMapFixed.class); - - protected Matrix<E> matrix = null; - - public MatrixMapFixed(List... semantics) { - super(semantics); - } - - public MatrixMapFixed(String name, List... semantics) { - this(semantics); - setName(name); - } - - public MatrixMapFixed(String name, String[] dimNames, List... semantics) { - this(name, semantics); - for (int i = 0; dimNames != null && i < dimNames.length; i++) { - setDimensionName(i, dimNames[i]); - } - } - - public MatrixMapFixed(MatrixMap<E> matrix) { - this(matrix.getName(), matrix.getDimensionNames(), matrix.getSemantics()); - this.pasteIndex(matrix); - } - - protected Matrix<E> getMatrix() { - if (matrix == null) { - matrix = new Matrix<E>(getDim()); - } - return matrix; - } - - @Override - public MatrixMapIterator<E> iterator() { - return new MatrixMapIteratorImpl<E>(getMatrix().iterator(), getSemantics()); - } - - @Override - public MatrixMap<E> map(MapFunction<E> f) { - getMatrix().data.map(f); - return this; - } - - @Override - public E getValueIndex(int... coordinates) { - if (coordinates.length == 0) { - throw new IllegalArgumentException("Coordinates must not be empty"); - } - return getMatrix().getValue(coordinates); - } - - /** - * Modifie un element de la matrice en fonction des dimensions passé en - * paramètre.<br> - * <p> - * Exemple: Si on a un matrice 3D.<br> - * m.set(v, [1,1,1]) modifie un element de la matrice.<br> - * - * @param value la value a inserer - * @param coordinates les coordonées où faire le remplacement - */ - @Override - public void setValueIndex(E value, int... coordinates) { - if (coordinates.length == 0) { - throw new IllegalArgumentException("Coordinates must not be empty"); - } - getMatrix().setValue(coordinates, value); - } - - /** - * Copie une matrice dans la matrice actuelle. La matrice à copier à le même - * nombre de dimension. Si la matrice à copier est trop grande seul les - * éléments pouvant être copier le seront. - * - * @param origin le point à partir duquel il faut faire la copie - * @param mat la matrice à copier - * @return return la matrice courante. - */ - public MatrixMap<E> paste(int[] origin, MatrixMap<E> mat) { - if (mat != null) { - // si les matrice mat et this on les memes dimensions - // et que origin est 0, on optimise en appeler une methode paste - // sur Matrix qui l'appel sur le vector - - // permet de savoir si l'origin est bien le point 0 de la matrice - boolean origin0 = true; - for (int i = 0; i < origin.length && origin0; i++) { - origin0 = origin0 && origin[i] == 0; - } - if (origin0 - && mat instanceof MatrixMapFixed - && Arrays.equals(mat.getDim(), this.getDim())) { - getMatrix().data.paste(((MatrixMapFixed<E>) mat).getMatrix().data); - } else { - super.paste(origin, mat); - } - } - return this; - } - - } - - /** - * Classe abstraite permettant de facilement implanter les matrice fixe, - * elastique et submatrix - * - * @param <E> FIXME - */ - abstract class AbstractMatrixMap<E> implements MatrixMap<E> { - - /** - * Logger. - */ - static private Log log = LogFactory.getLog(AbstractMatrixMap.class); - - protected String name = null; - - protected String[] dimNames = null; - - protected int[] dim = null; - - protected SemanticList[] semantics = null; - - protected void init(int[] dim) { - this.dim = new int[dim.length]; - System.arraycopy(dim, 0, this.dim, 0, dim.length); - semantics = new SemanticList[dim.length]; - dimNames = new String[dim.length]; - } - - protected AbstractMatrixMap(int[] dim) { - init(dim); - for (int i = 0; i < getDimCount(); i++) { - // par defaut les listes des semantiques contiennent des nulls - // FIXME no multiple null allowed - setSemantic(i, Collections.nCopies(dim[i], null)); - } - } - - public AbstractMatrixMap(List... semantics) { - int[] dim = new int[semantics.length]; - for (int i = 0; i < dim.length; i++) { - if (semantics[i] == null) { - dim[i] = 0; - } else { - dim[i] = semantics[i].size(); - } - } - init(dim); - for (int i = 0; i < getDimCount(); i++) { - setSemantic(i, semantics[i]); - } - } - - protected AbstractMatrixMap(String name, int[] dim) { - this(dim); - setName(name); - } - - protected AbstractMatrixMap(String name, int[] dim, String[] dimNames) { - this(dim); - setName(name); - for (int i = 0; dimNames != null && i < dimNames.length; i++) { - setDimensionName(i, dimNames[i]); - } - } - - public AbstractMatrixMap(String name, List... semantics) { - this(semantics); - setName(name); - } - - public AbstractMatrixMap(String name, String[] dimNames, List... semantics) { - this(name, semantics); - for (int i = 0; dimNames != null && i < dimNames.length; i++) { - setDimensionName(i, dimNames[i]); - } - } - - public AbstractMatrixMap(MatrixMap<E> matrix) { - this(matrix.getName(), matrix.getDimensionNames(), matrix.getSemantics()); - this.pasteIndex(matrix); - } - - /** - * Copy la matrice pour pouvoir la modifier sans perdre les donnees - * initiales. - * - * @return new matrix - */ - public MatrixMap<E> copy() { - MatrixMap<E> result = new MatrixMapFixed<E>(this); - return result; - } - - @Override - public MatrixMap clone() { - return copy(); - } - - public SemanticList[] getSemantics() { - return semantics; - } - - public SemanticList getSemantic(int dim) { - return semantics[dim]; - } - - public void setSemantic(int dim, List sem) { - // make copy because this matrix can change semantics - SemanticList l = new SemanticList(sem); - semantics[dim] = l; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public String[] getDimensionNames() { - return dimNames; - } - - public void setDimensionNames(String[] names) { - for (int i = 0; names != null && i < names.length; i++) { - setDimensionName(i, names[i]); - } - } - - public void setDimensionName(int dim, String name) { - dimNames[dim] = name; - } - - public String getDimensionName(int dim) { - return dimNames[dim]; - } - - public int getDimCount() { - return dim.length; - } - - public int[] getDim() { - return dim; - } - - public int getDim(int d) { - return dim[d]; - } - - /** - * Retourne la matrice elle meme. Les modifications sont faites directement - * dessus - */ - @Override - public MatrixMap<E> map(MapFunction<E> f) { - for (MatrixMapIterator<E> i = iterator(); i.hasNext(); ) { - i.setValue(f.apply(i.next())); - } - return this; - } - - public E getValue(Object... coordinates) { - if (coordinates.length == 0) { - throw new IllegalArgumentException("Coordinates must not be empty"); - } - int[] intCoordinates = - MatrixHelper.semanticsToDimension(getSemantics(), coordinates); - E result = getValueIndex(intCoordinates); - return result; - } - - public void setValue(E value, Object... coordinates) { - if (coordinates.length == 0) { - throw new IllegalArgumentException("Coordinates must not be empty"); - } - int[] intCoordinates = - MatrixHelper.semanticsToDimension(getSemantics(), coordinates); - setValueIndex(value, intCoordinates); - } - - // TODO peut-etre faire une variante de equals qui regarde par rapport au - // coordonnées sémantique - @Override - public boolean equals(Object o) { - return o instanceof MatrixMap && equals((MatrixMap) o); - } - - public boolean equals(MatrixMap mat) { - boolean result = true; - // le nom doit être le même - result = result && getName().equals(mat.getName()); - - result = result && equalsValues(mat); - - // les sémantiques doivent-être identique - for (int i = 0; result && i < getDimCount(); i++) { - String dimName1 = getDimensionName(i); - String dimName2 = mat.getDimensionName(i); - result = ObjectUtils.equals(dimName1, dimName2); - if (log.isTraceEnabled()) { - log.trace("dimName1(" + dimName1 + ")==dimName2(" + dimName2 - + ")=" + result); - } - // System.out.println("dimName1("+dimName1+")==dimName2("+dimName2+ - // ")="+result); - - List sem1 = getSemantic(i); - List sem2 = mat.getSemantic(i); - result = result && ObjectUtils.equals(sem1, sem2); - if (log.isTraceEnabled()) { - log.trace("sem1(" + sem1 + ")==sem2(" + sem2 + ")=" + result); - } - // System.out.println("sem1("+sem1+")==sem1("+sem2+ ")="+result); - } - - if (log.isTraceEnabled()) { - log.trace("result=" + result); - } - // System.out.println("result="+result); - return result; - } - - /** - * Verifie si les matrices sont egales en ne regardant que les valeurs et - * pas les semantiques - * - * @param mat FIXME - * @return equality on values - */ - public boolean equalsValues(MatrixMap mat) { - boolean result = true; - // les dimensions doivent-être identique - result = result && MatrixHelper.sameDimension(getDim(), mat.getDim()); - - // toutes les données doivent être identique - for (MatrixMapIterator<E> i = mat.iterator(); result && i.hasNext(); ) { - E v1 = i.next(); - E v2 = getValueIndex(i.getCoordinates()); - result = v1 == v2; - if (log.isTraceEnabled()) { - log.trace("v1(" + v1 + ")==v2(" + v2 + ")=" + result); - } - } - - return result; - } - - /** - * Si la matrice est 1D - * <pre> - * MaMatrice(matrix1D) [ - * MaDimName: Dim1, Dim2, Dim3, - * v1, v2, v3 - * ] - * </pre> - * <p> - * Si la matrice est 2D - * <pre> - * MaMatrice(matrix2D) [ - * MaDimX - * MaDimY Dim1, Dim2, Dim3, - * DimA v1, v2, v3 - * DimB v4, v5, v6 - * DimC v7, v8, v9 - * ] - * </pre> - * <p> - * Pour les autres types de matrice la methode {@link #toStringGeneric() } - * est utilise - * - * @return FIXME - */ - @Override - public String toString() { - int LENGTH = 10; - StringBuilder result = new StringBuilder(); - if (getDimCount() == 1) { - result.append(MatrixHelper.format(getName(), -LENGTH, "#NoNameMat")); - result.append("(matrix1D)[\n"); - String dimName = getDimensionName(0); - result.append(MatrixHelper.format(dimName, LENGTH, "#NoNameDim")); - for (Object sem : getSemantic(0)) { - result.append(","); - result.append(MatrixHelper.format(sem, -LENGTH, null)); - } - result.append(StringUtils.repeat(" ", LENGTH + 1)); - for (int i = 0; i < getDim(0); i++) { - Object v = getValueIndex(i); - result.append(MatrixHelper.format(v, -LENGTH, null) + ","); - } - result.append("\n]"); - } else if (getDimCount() == 2) { - int[] pos = new int[2]; - result.append(MatrixHelper.format(getName(), -LENGTH, "#NoNameMat")); - result.append("(matrix2D) [\n"); - - result.append(StringUtils.repeat(" ", LENGTH + 1)); - String dimNameX = getDimensionName(0); - result.append(MatrixHelper.format(dimNameX, LENGTH, "#DimX")); - result.append("\n"); - String dimNameY = getDimensionName(1); - result.append(MatrixHelper.format(dimNameY, LENGTH, "#DimY")); - result.append(" "); - for (Object sem : getSemantic(0)) { - result.append(MatrixHelper.format(sem, -LENGTH, null)); - result.append(","); - } - - for (int y = 0; y < getDim(1); y++) { - result.append("\n"); - Object sem = getSemantic(1).get(y); - result.append(MatrixHelper.format(sem, LENGTH, null)); - result.append(" "); - for (int x = 0; x < getDim(0); x++) { - pos[0] = x; - pos[1] = y; - Object v = getValueIndex(pos); - result.append(MatrixHelper.format(v, -LENGTH, null) + ","); - } - } - result.append("\n]"); - } else { - result.append(toStringGeneric()); - } - return result.toString(); - } - - /** - * Representation string de la matrice quelque soit le nombre de dimension - * - * @return FIXME - */ - public String toStringGeneric() { - StringBuilder result = new StringBuilder(); - result.append(MatrixHelper.format(getName(), 0, "#NoNameMat")); - result.append("(matrix" + getDimCount() + "D)[\n"); - result.append("dimensions = ["); - for (int i = 0; i < getDim().length; i++) { - result.append(getDim()[i] + ","); - } - result.append("]\ndata = ["); - for (MatrixMapIterator i = this.iterator(); i.hasNext(); ) { - result.append(i.next() + ","); - } - result.append("]\n"); - return result.toString(); - } - - public boolean isValidCoordinates(int[] dim) { - boolean result = getDimCount() == dim.length; - for (int i = 0; result && i < dim.length; i++) { - result = 0 <= dim[i] && dim[i] < getDim(i); - } - return result; - } - - public boolean isValidCoordinates(Object[] semantics) { - boolean result = getDimCount() == semantics.length; - for (int i = 0; result && i < semantics.length; i++) { - List semantic = getSemantic(i); - result = semantic.contains(semantics[i]); - } - return result; - } - - /** - * Copie une matrice dans la matrice actuelle. La matrice à copier à le même - * nombre de dimension. Si la matrice à copier est trop grande seul les - * éléments pouvant être copier le seront. - * - * @param mat la matrice à copier - * @return return la matrice courante. - */ - public MatrixMap pasteIndex(MatrixMap<E> mat) { - return paste(new int[getDimCount()], mat); - } - - protected MatrixMap<E> paste(int[] origin, MatrixMap<E> mat) { - if (mat != null) { - for (MatrixMapIterator<E> mi = mat.iterator(); mi.hasNext(); ) { - E value = mi.next(); - int[] coordinates = ArrayUtil.sum(origin, mi.getCoordinates()); - if (isValidCoordinates(coordinates)) { - setValueIndex(value, coordinates); - } - } - } - return this; - } - - /** - * Modifie la matrice actuel en metant les valeurs de mat passé en parametre - * La copie se fait en fonction de la semantique, si un element dans une - * dimension n'est pas trouvé, alors il est passé - */ - public MatrixMap<E> paste(MatrixMap<E> mat) { - if (mat != null) { - for (MatrixMapIterator<E> mi = mat.iterator(); mi.hasNext(); ) { - E value = mi.next(); - Object[] sems = mi.getSemanticsCoordinates(); - if (isValidCoordinates(sems)) { - setValue(value, sems); - } - } - } - return this; - } - - /** - * Permet de prendre une sous matrice dans la matrice courante. La sous - * matrice a le même nombre de dimensions mais sur une des dimensions on ne - * prend que certain élément. - * - * @param dim la dimension dans lequel on veut une sous matrice si dim est - * négatif alors la dimension est prise à partir de la fin par - * exemple si l'on veut la derniere dimension il faut passer -1 - * pour dim - * @param start la position dans dim d'ou il faut partir pour prendre la - * sous matrice. - * @param nb le nombre d'élément à prendre dans la dimension. si nb est - * inférieur ou égal à 0 alors cela indique qu'il faut prendre - * tous les éléments jusqu'à la fin de la dimension. - * @return new matrix - */ - public MatrixMap<E> getSubMatrix(int dim, int start, int nb) { - if (dim < 0) { - dim = getDimCount() + dim; - } - if (start < 0) { - start = getDim(dim) + start; - } - if (nb <= 0) { - nb = getDim(dim) - start; - } - return new SubMatrix<E>(this, dim, start, nb); - } - - /** - * Permet de prendre une sous matrice dans la matrice courante. La sous - * matrice a le même nombre de dimensions mais sur une des dimensions on ne - * prend que certain élément. - * - * @param dim la dimension dans lequel on veut une sous matrice - * @param start la position dans dim d'ou il faut partir pour prendre la - * sous matrice. 0 ≤ start < dim.size si start est négatif alors - * la position de départ est calculé par rapport à la fin de la - * dimension, pour avoir le dernier élément il faut passer -1 - * @param nb le nombre d'élément à prendre dans la dimension si nb est - * inférieur ou égal à 0 alors cela indique qu'il faut prendre - * tous les éléments jusqu'à la fin de la dimension. - * @return new matrix - */ - public MatrixMap<E> getSubMatrix(int dim, Object start, int nb) { - int begin = MatrixHelper.indexOf(getSemantics(), dim, start); - return getSubMatrix(dim, begin, nb); - } - - /** - * Add to desambiguas some call with xpath engine, but do the same thing - * {@link #getSubMatrix(int, Object[])} - * - * @param dim FIXME - * @param elem FIXME - * @return new matrix - */ - public MatrixMap<E> getSubMatrixOnSemantic(int dim, Object... elem) { - MatrixMap<E> result = getSubMatrix(dim, elem); - return result; - } - - /** - * Permet de prendre une sous matrice dans la matrice courante. La sous - * matrice a le même nombre de dimensions mais sur une des dimensions on ne - * prend que certain élément. - * - * @param dim la dimension dans lequel on veut une sous matrice - * @param elem les éléments dans la dimension à conserver - * @return new matrix - */ - public MatrixMap<E> getSubMatrix(int dim, Object... elem) { - int[] ielem = new int[elem.length]; - for (int i = 0; i < ielem.length; i++) { - ielem[i] = MatrixHelper.indexOf(getSemantics(), dim, elem[i]); - } - return getSubMatrix(dim, ielem); - } - - /** - * Permet de prendre une sous matrice dans la matrice courante. - * <p> - * Réalise plusieurs appels à {@link #getSubMatrix(int, Object...)} suivant - * l'implémentation. - * - * @param elems les éléments dans la dimension à conserver - * @return new matrix - */ - public MatrixMap<E> getSubMatrix(Object[]... elems) { - - // la reduction doit se faire sur le meme nombre de dimension - if (elems.length != dim.length) { - throw new IllegalArgumentException(String.format( - "Can't get sub matrix with different dimension count " - + "(expected: %d, got %d)", dim.length, elems.length)); - } - - MatrixMap<E> result = this; - for (int i = 0; i < elems.length; ++i) { - if (elems[i] != null) { - result = result.getSubMatrix(i, elems[i]); - } - } - return result; - } - - /** - * Permet de prendre une sous matrice dans la matrice courante. La sous - * matrice a le même nombre de dimensions mais sur une des dimensions on ne - * prend que certain élément. - * - * @param dim la dimension dans lequel on veut une sous matrice - * @param elem les indices des éléments dans la dimension à conserver - * @return new matrix - */ - public MatrixMap<E> getSubMatrix(int dim, int[] elem) { - return new SubMatrix<E>(this, dim, elem); - } - - /** - * Permet de prendre une sous matrice dans la matrice courante. - * <p> - * Réalise plusieurs appels a {@link #getSubMatrix(int, int[])} suivant - * l'implementation. - * - * @param elems les indices des éléments pour chaque dimension à conserver - * @return new matrix - */ - public MatrixMap<E> getSubMatrix(int[]... elems) { - - // la reduction doit se faire sur le meme nombre de dimension - if (elems.length != dim.length) { - throw new IllegalArgumentException(String.format( - "Can't get sub matrix with different dimension count " - + "(expected: %d, got %d)", dim.length, elems.length)); - } - - MatrixMap<E> result = this; - for (int i = 0; i < elems.length; ++i) { - if (elems[i] != null) { - result = new SubMatrix<E>(result, i, elems[i]); - } - } - return result; - } - - /** - * Reduit la matrice de sorte que toutes les dimensions qui n'ont qu'un - * élement soit supprimée. Au pire cette méthode retourne une matrice à une - * seule dimension à un seul élément. - * - * @return une nouvelle matrice plus petite que la matrice actuelle ou egal - * s'il n'y a aucune dimension à supprimer - */ - public MatrixMap<E> reduce() { - return reduce(1); - } - - /** - * Reduit le matrice seulement sur les dimensions passées en argument. Si - * une des dimensions passées en arguement n'a pas qu'un seul élément, cette - * dimension n'est pas prise en compte. - * - * @param dims les dimensions sur lequel il faut faire la reduction - * @return une nouvelle matrice - */ - public MatrixMap<E> reduceDims(int... dims) { - Arrays.sort(dims); - // tableau permettant de faire la correspondance entre les dimensions - // de la matrice actuelle et les dimentsions de la nouvelle matrice - // l'element i du tableau qui correcpond à la dimensions i de la - // nouvelle matrice contient la dimension equivalente dans - // la matrice actuelle - int[] correspondance = new int[getDimCount()]; - // les nouvelles semantiques - List<List> sem = new ArrayList<List>(); - // les nouveaux noms de dimensions - List<String> dimName = new ArrayList<String>(); - // il faut au moins une dimension pour la matrice - int minNbDim = 1; - for (int j = getDimCount() - 1; j >= 0; j--) { - // si la dimension à plus d'un élément ou qu'il n'est pas dans dims - // on garde la dimension - if (getDim(j) > 1 || Arrays.binarySearch(dims, j) < 0 - || j < minNbDim) { - // on ne conserve que les dimensions supérieure à 1 - correspondance[sem.size()] = j; - sem.add(getSemantic(j)); - dimName.add(getDimensionName(j)); - minNbDim--; - } - } - MatrixMap<E> result = reduce(dimName, sem, correspondance); - return result; - } - - /** - * Reduit la matrice de sorte que toutes les dimensions qui n'ont qu'un - * élement soit supprimée. Au pire cette méthode retourne une matrice à une - * seule dimension à un seul élément. - * - * @param minNbDim le nombre minimum de dimension que l'on souhaite pour la - * matrice résultat - * @return une nouvelle matrice plus petite que la matrice actuelle ou egal - * s'il n'y a aucune dimension à supprimer - */ - public MatrixMap<E> reduce(int minNbDim) { - // tableau permettant de faire la correspondance entre les dimensions - // de la matrice actuelle et les dimentsions de la nouvelle matrice - // l'element i du tableau qui correcpond à la dimensions i de la - // nouvelle matrice contient la dimension equivalente dans - // la matrice actuelle - int[] correspondance = new int[getDimCount()]; - // les nouvelles semantiques - List<List> sem = new ArrayList<List>(); - // les nouveaux noms de dimensions - List<String> dimName = new ArrayList<String>(); - for (int j = getDimCount() - 1; j >= 0; j--) { - // si la dimension à plus d'un élément ou si on a pas assez de - // dimension pour avoir le minimum demandé on prend la dimension - if (getDim(j) > 1 || j < minNbDim) { - // on ne conserve que les dimensions supérieure à 1 - correspondance[sem.size()] = j; - sem.add(getSemantic(j)); - dimName.add(getDimensionName(j)); - // on vient de prendre une dimension il nous en faut une de - // moins - minNbDim--; - } - } - - MatrixMap<E> result = reduce(dimName, sem, correspondance); - return result; - } - - /** - * Create new matrice from the current matrix. - * - * @param dimName dimension name for new matrix - * @param sem semantic for new matrix - * @param correspondance array to do the link between current matrix and - * returned matrix - * @return new matrix - */ - protected MatrixMap<E> reduce(List<String> dimName, List<List> sem, int[] correspondance) { - // on converti les listes en tableau en inversant l'ordre car on - // a fait un parcours en sens inverse - int nbDim = sem.size(); - List[] newSemantics = new List[nbDim]; - String[] newDimNames = new String[nbDim]; - int[] tmpcorrespondance = new int[nbDim]; - for (int i = 0; i < nbDim; i++) { - newSemantics[i] = sem.get(nbDim - 1 - i); - newDimNames[i] = dimName.get(nbDim - 1 - i); - tmpcorrespondance[i] = correspondance[nbDim - 1 - i]; - } - correspondance = tmpcorrespondance; - - MatrixMap<E> result = new MatrixMapFixed<E>(getName(), newDimNames, newSemantics); - - // on reprend les valeurs - int[] newCoordinates = new int[result.getDimCount()]; - for (MatrixMapIterator<E> mi = iterator(); mi.hasNext(); ) { - E value = mi.next(); - int[] oldCoordinates = mi.getCoordinates(); - for (int i = 0; i < newCoordinates.length; i++) { - newCoordinates[i] = oldCoordinates[correspondance[i]]; - } - result.setValueIndex(value, newCoordinates); - } - return result; - } - - public MatrixMap<E> extend(Object... sems) { - String name = getName(); - String[] dimNames = getDimensionNames(); - SemanticList[] semantics = getSemantics(); - - // si pas assez de dimension on en rajoute - if (sems.length > semantics.length) { - String[] newDimNames = new String[sems.length]; - System.arraycopy(dimNames, 0, newDimNames, 0, dimNames.length); - dimNames = newDimNames; - - SemanticList[] newSems = new SemanticList[sems.length]; - System.arraycopy(semantics, 0, newSems, 0, semantics.length); - semantics = newSems; - - for (int i = semantics.length; i < newSems.length; i++) { - newSems[i] = new SemanticList(); - } - } - - // si les objets demande n'existe pas dans la semantics on l'ajoute - for (int i = 0; i < sems.length; i++) { - if (semantics[i].indexOf(sems[i]) == -1) { - semantics[i].add(sems[i]); - } - } - - MatrixMap<E> result = MatrixMap.Factory.create(name, dimNames, semantics); - result.paste(this); - return result; - } - - } - - /** - * Pour l'instant une sous matrice a obligatoirement le meme nombre de dimension - * que la matrice qu'elle contient. Elle permet juste de reduire le nombre - * d'element d'une dimension. - * <p> - * C'est comme une "vue" réduite sur la vraie matrices. - */ - class SubMatrix<E> extends AbstractMatrixMap<E> { // SubMatrix - - protected MatrixMap<E> matrix = null; - - protected DimensionConverter converter = null; - - public SubMatrix(MatrixMap<E> matrix, int dim, int start, int nb) { - super(matrix.getName(), matrix.getDimensionNames(), matrix.getSemantics()); - this.matrix = matrix; - - converter = new ShiftConverter(dim, start, nb); - setSemantic(dim, getSemantic(dim).subList(start, start + nb)); - getDim()[dim] = nb; - } - - public SubMatrix(MatrixMap<E> matrix, int dim, int[] elem) { - super(matrix.getName(), matrix.getDimensionNames(), matrix.getSemantics()); - this.matrix = matrix; - - converter = new MappingConverter(dim, elem); - - List oldSemantic = getSemantic(dim); - List newSemantic = new LinkedList(); - for (int i = 0; i < elem.length; i++) { - newSemantic.add(oldSemantic.get(elem[i])); - } - setSemantic(dim, newSemantic); - getDim()[dim] = elem.length; - } - - @Override - public MatrixMapIterator<E> iterator() { - return new SubMatrixIterator<E>(this); - } - - @Override - public E getValueIndex(int... coordinates) { - return matrix.getValueIndex(converter.convertCoordinates(coordinates)); - } - - @Override - public void setValueIndex(E value, int... coordinates) { - matrix.setValueIndex(value, converter.convertCoordinates(coordinates)); - } - - protected class SubMatrixIterator<E> implements MatrixMapIterator<E> { - - protected SubMatrix<E> subMatrix = null; - - protected int[] cpt = null; - - protected int[] last = null; - - public SubMatrixIterator(SubMatrix<E> subMatrix) { - this.subMatrix = subMatrix; - cpt = new int[subMatrix.getDimCount()]; - cpt[cpt.length - 1] = -1; - - last = new int[subMatrix.getDimCount()]; - for (int i = 0; i < last.length; i++) { - last[i] = subMatrix.getDim(i) - 1; - } - - } - - @Override - public boolean hasNext() { - return !Arrays.equals(cpt, last); - } - - @Override - public E next() { - int ret = 1; - int[] dim = getDim(); - for (int i = cpt.length - 1; i >= 0; i--) { - cpt[i] = cpt[i] + ret; - ret = cpt[i] / dim[i]; - cpt[i] = cpt[i] % dim[i]; - } - E result = getValue(); - return result; - } - - @Override - public void remove() { - setValue(null); - } - - public int[] getCoordinates() { - return cpt; - } - - public Object[] getSemanticsCoordinates() { - int[] coordinates = getCoordinates(); - Object[] result = MatrixHelper.dimensionToSemantics(subMatrix.getSemantics(), coordinates); - return result; - } - - public E getValue() { - return subMatrix.getValueIndex(getCoordinates()); - } - - public void setValue(E value) { - subMatrix.setValue(value, getCoordinates()); - } - } - - /** - * Permet de faire une conversion de la dimension demandé dans la sous - * matrice avec la position reel de la matrice sous jacente. - */ - protected interface DimensionConverter extends Serializable { - int[] convertCoordinates(int[] coordinates); - } - - /** - * La conversion est juste un decalage d'indice - */ - protected static class ShiftConverter implements DimensionConverter { - - /** - * serialVersionUID. - */ - private static final long serialVersionUID = 1L; - - protected int dim; - - protected int start; - - protected int nb; - - public ShiftConverter(int dim, int start, int nb) { - this.dim = dim; - this.start = start; - this.nb = nb; - } - - @Override - public int[] convertCoordinates(int[] coordinates) { - int[] result = null; - if (coordinates[dim] < nb) { - result = new int[coordinates.length]; - System.arraycopy(coordinates, 0, result, 0, result.length); - result[dim] = result[dim] + start; - } else { - throw new NoSuchElementException( - "L'indice est supérieur au nombre d'élement de la sous matrice pour cette dimension."); - } - return result; - } - } - - /** - * La conversion est le mapping d'un element vers un autre element. - */ - protected static class MappingConverter implements DimensionConverter { - - /** - * serialVersionUID. - */ - private static final long serialVersionUID = -6367416559713556559L; - - protected int dim; - - protected int[] elem = null; - - public MappingConverter(int dim, int[] elem) { - this.dim = dim; - this.elem = new int[elem.length]; - System.arraycopy(elem, 0, this.elem, 0, elem.length); - } - - @Override - public int[] convertCoordinates(int[] coordinates) { - int[] result = null; - if (coordinates[dim] < elem.length) { - result = new int[coordinates.length]; - System.arraycopy(coordinates, 0, result, 0, result.length); - result[dim] = elem[coordinates[dim]]; - - } else { - throw new NoSuchElementException( - "L'indice est supérieur au nombre d'élements de la sous matrice pour cette dimension."); - } - return result; - } - } - } // SubMatrix - - /** - * Objet matrice qui ne permet que le stockage avec des positions int - * dans une matrice a autant de dimension que l'on souhaite. - * - * @param <E> FIXME - */ - class Matrix<E> implements Iterable<E> { // BasicMatrix - - /** - * Les dimensions de la matrice - */ - protected int[] dimensions = null; - - /** - * La matrice en représentation linéaire - */ - protected Vector<E> data = null; - - /** - * tableau de facteur permettant de convertir les coordonnées dans la - * matrice en un indice dans la représentation linéaire de la matrice - */ - protected int[] linearFactor = null; - - /** - * Crée une nouvelle matrice ayant les dimensions demandées. - * - * @param dimensions dimensions - */ - public Matrix(int[] dimensions) { - checkDim(dimensions); - - // copie des dimensions pour que personne à l'extérieur de l'objet - // ne puisse les modifiers par la suite - this.dimensions = new int[dimensions.length]; - System.arraycopy(dimensions, 0, this.dimensions, 0, dimensions.length); - - // calcul du linearFactor - linearFactor = new int[dimensions.length]; - linearFactor[linearFactor.length - 1] = 1; - for (int i = linearFactor.length - 2; i >= 0; i--) { - linearFactor[i] = linearFactor[i + 1] * dimensions[i + 1]; - } - - // creation de la matrice lineaire - data = new Vector<E>(linearFactor[0] * dimensions[0]); - } - - /** - * Retourne le nombre de dimension de la matrice - * - * @return le nombre de dimension de la matrice; - */ - public int getNbDim() { - return dimensions.length; - } - - /** - * Retourne la taille d'une dimension - * - * @param dim la dimension dont on souhaite la taille - * @return la taille d'une dimension - */ - public int getDim(int dim) { - checkDim(dim); - return dimensions[dim]; - } - - /** - * Retourne un tableau representant les dimensions de la matrice. Le tableau - * retourné n'est pas une copie, il ne faut donc pas le modifier - * - * @return le tableau des dimensions. - */ - public int[] getDim() { - return dimensions; - } - - /** - * Retourne un element de la matrice - * - * @param pos la position de l'element à retourner - * @return un element de la matrice - */ - public E getValue(int[] pos) { - int indice = coordonatesToLinear(pos); - return data.getValue(indice); - } - - /** - * Modifie un élement de la matrice - * - * @param pos la position de l'element à modifier - * @param value la nouvelle valeur à mettre dans la matrice - */ - public void setValue(int[] pos, E value) { - int indice = coordonatesToLinear(pos); - data.setValue(indice, value); - } - - /** - * Retourne un objet Inc pret a etre utilisé pour boucler sur tous les - * element de la matrice. - * - * @return un objet Inc pret à être utilisé - */ - @Override - public MatrixIterator<E> iterator() { - return new MatrixIterator<E>(this); - } - - /** - * Permet de faire un traitement sur chaque valeur de la matrice - * - * @param f la fonction a appliquer à chaque élement de la matrice - */ - public void map(MapFunction f) { - data.map(f); - } - - /** - * Permet de convertir les coordonnées d'un élément en un indice dans la - * représentation linéraire de la matrice. - * - * @param coordonates les coordonnées à lineariser - * @return un indice réprésentant les coordonnées de façon linéaire - */ - protected int coordonatesToLinear(int[] coordonates) { - checkPos(coordonates); - - int result = 0; - for (int i = 0; i < linearFactor.length; i++) { - result += coordonates[i] * linearFactor[i]; - } - return result; - } - - /** - * Convertie une coordonnée lineaire en coordonnées spaciales - * - * @param pos la coordonnée linéaire - * @return les coordonnées spaciales de l'élément - */ - protected int[] linearToCoordinates(int pos) { - int[] result = new int[linearFactor.length]; - - for (int i = 0; i < result.length; i++) { - result[i] = pos / linearFactor[i]; - pos -= result[i] * linearFactor[i]; - } - return result; - } - - /** - * Permet de vérifier que les dimensions de la nouvelle matrice sont - * corrects - * - * @param dim les dimensions de la nouvelle matrice - * @throws IllegalArgumentException si une dimension n'est pas valide - */ - protected void checkDim(int[] dim) { - for (int i = 0; i < dim.length; i++) { - if (dim[i] <= 0) { - throw new IllegalArgumentException(String.format( - "Dimension %s is invalid %s", i, dim[i])); - } - } - } - - /** - * Permet de vérifier qu'une dimension demandé existe bien dans la matrice - * - * @param dim la position de la dimension que l'on souhaite - * @throws IndexOutOfBoundsException si la dimension demandée n'existe pas - */ - protected void checkDim(int dim) { - if (dim < 0 || dim >= getNbDim()) { - throw new IndexOutOfBoundsException(String.format( - "Invalid dimension %s max dimension is %s", - dim, getNbDim())); - } - } - - /** - * Verifie que les coordonnées demandé appartiennent bien à la matrice - * - * @param pos les coordonnées souhaitées dans la matrice - * @throws NoSuchElementException si les coordonnées ne correspondent pas à - * un élement de la matrice - */ - protected void checkPos(int[] pos) { - int[] dim = getDim(); - boolean result = dim.length == pos.length; - for (int i = 0; result && i < dim.length; i++) { - result = (0 <= pos[i]) && (pos[i] < dim[i]); - } - if (!result) { - throw new NoSuchElementException(String.format( - "Invalid element asked %s for real dimension %s", Arrays.toString(pos), Arrays - .toString(dim))); - } - } - - @Override - public String toString() { - StringBuffer result = new StringBuffer(); - if (getNbDim() == 1) { - result.append("matrix1D ["); - for (int i = 0; i < data.size(); i++) { - result.append(data.getValue(i) + ","); - } - result.append("]"); - } else if (getNbDim() == 2) { - int[] pos = new int[2]; - result.append("matrix2D ["); - for (int y = 0; y < getDim(1); y++) { - result.append("\n"); - for (int x = 0; x < getDim(0); x++) { - pos[0] = x; - pos[1] = y; - result.append(getValue(pos) + ","); - } - } - result.append("]"); - } else { - result.append("dimensions = [\n"); - for (int i = 0; i < dimensions.length; i++) { - result.append(dimensions[i] + ","); - } - result.append("\n]\nmatrice = [\n"); - for (int i = 0; i < data.size(); i++) { - result.append(data.getValue(i) + ","); - } - result.append("\n]\nlinearFactor = [\n"); - for (int i = 0; i < linearFactor.length; i++) { - result.append(linearFactor[i] + ","); - } - result.append("\n]\n"); - } - return result.toString(); - } - - @Override - public boolean equals(Object o) { - if (o instanceof Matrix) { - Matrix other = (Matrix) o; - return this == o - || (Arrays.equals(this.dimensions, other.dimensions) && this.data - .equals(other.data)); - } - return false; - } - - } // BasicMatrix - - class MatrixIterator<E> implements Iterator<E> { // MatrixIteratorImpl - - protected Matrix<E> matrix = null; - - protected int pos = -1; - - /** - * @param matrix la matrice sur lequel l'iterator doit travailler - */ - public MatrixIterator(Matrix<E> matrix) { - this.matrix = matrix; - pos = -1; - } - - @Override - public boolean hasNext() { - return pos + 1 < matrix.data.size(); - } - - @Override - public E next() { - if (hasNext()) { - pos++; - } else { - throw new NoSuchElementException(); - } - E result = getValue(); - return result; - } - - @Override - public void remove() { - setValue(null); - } - - public E getValue() { - return matrix.data.getValue(pos); - } - - public void setValue(E value) { - matrix.data.setValue(pos, value); - } - - public int[] getCoordinates() { - return matrix.linearToCoordinates(pos); - } - - } // MatrixIteratorImpl - - /** - * Permet de stocker des données à une position lineaire et de la redemander. - * Cette classe ne gére que les données lineaire. L'avantage de cette classe est - * de ne conserver que les elements differents de la valeur par defaut, ce qui - * minimize la taille du tableau necessaire a conserver les données. - * - * @param <E> FIXME - */ - class Vector<E> { // Vector - - /** - * maximum number of element, maximum pos value - */ - protected int capacity = 0; - - /** - * la valeur par defaut - */ - protected E defaultValue = null; - - /** - * contient la position de l'element, le tableau est trie - */ - protected int[] position; - - protected int positionSize = 0; - - /** - * contient la valeur de l'element - */ - protected ArrayList<E> data = new ArrayList<E>(); - - public Vector(int capacity) { - this.capacity = capacity; - position = new int[8]; - Arrays.fill(position, Integer.MAX_VALUE); - } - - public Vector(int capacity, E defaultValue) { - this(capacity); - this.defaultValue = defaultValue; - } - - public int size() { - return capacity; - } - - // poussin 20060827 TODO: verifier l'implantation, il semble quelle soit - // fausse et ne puisse pas recherche le nombre max correctement - public E getMaxOccurrence() { - E result = defaultValue; - - E[] tmp = (E[]) data.toArray(); - - // si potentiellement il y a plus d'element identique dans data - // que de valeur par defaut, on recherche la valeur possible - if (this.capacity < 2 * tmp.length) { - Arrays.sort(tmp); - - // le nombre de fois que l'on a rencontrer la valeur la plus - // nombreuse - int max = 1; - // le nombre de fois que l'on a rencontrer la valeur courante - int count = 1; - // la valeur la plus rencontrer - result = tmp[0]; - // la valeur que l'on vient de traiter précédement - E old = tmp[0]; - // la valeur courante lu dans le tableaux - E current = tmp[0]; - // tant que l'on peut encore trouve un element plus nombreux dans le - // tableau on le parcours - for (int i = 1; max < tmp.length - i + count && i < tmp.length; i++) { - current = tmp[i]; - - if (current == old) { - count++; - } else { - if (count > max) { - max = count; - result = old; - } - count = 1; - old = current; - } - } - if (count > max) { - max = count; - result = current; - } - - if (max <= capacity - tmp.length) { - // en fin de compte, il n'y a pas plus d'element identique - // dans data que de defaultValue - result = defaultValue; - } - } - - return result; - } - - protected void checkPos(int pos) { - if (pos < 0 || pos >= capacity) { - throw new IllegalArgumentException("pos " + pos + " is not in [0, " - + capacity + "]"); - } - } - - public E getValue(int pos) { - checkPos(pos); - - E result = defaultValue; - int index = findIndex(pos); - if (index >= 0) { - result = data.get(index); - } - return result; - } - - public void setValue(int pos, E value) { - checkPos(pos); - - int index = findIndex(pos); - if (index >= 0) { - if (value == defaultValue) { - // il etait present, on supprime l'element - removeElementAt(index); - data.remove(index); - } else { - // il etait deja present, on modifie la valeur - data.set(index, value); - } - } else { - // il n'etait pas present - if (value != defaultValue) { - // il faut ajouter dans position et dans data - index = -index - 1; - - addElementAt(index, pos); - data.add(index, value); - } - } - } - - public boolean equals(Object o) { - boolean result = false; - if (o instanceof Vector) { - Vector other = (Vector) o; - result = Arrays.equals(this.position, other.position) - && data.equals(other.data); - } - return result; - } - - /** - * retourne la position dans le tableau position de la position lineaire - * - * @param pos FIXME - * @return la position ou < 0 donnant la position de l'element s'il etait - * present - */ - protected int findIndex(int pos) { - return Arrays.binarySearch(position, pos); - } - - protected void ensureCapacity(int mincap) { - if (mincap > position.length) { - int newcap = (position.length * 3) / 2 + 1; - int olddata[] = position; - position = new int[newcap >= mincap ? newcap : mincap]; - System.arraycopy(olddata, 0, position, 0, positionSize); - for (int i = positionSize; i < position.length; i++) { - position[i] = Integer.MAX_VALUE; - } - } - } - - protected void addElementAt(int index, int element) { - ensureCapacity(positionSize + 1); - int numtomove = positionSize - index; - System.arraycopy(position, index, position, index + 1, numtomove); - position[index] = element; - positionSize++; - } - - protected int removeElementAt(int index) { - int oldval = position[index]; - int numtomove = positionSize - index - 1; - if (numtomove > 0) { - System.arraycopy(position, index + 1, position, index, numtomove); - } - positionSize--; - position[positionSize] = Integer.MAX_VALUE; - return oldval; - } - - /** - * On recopie tous les attributs pour que le vector ressemble exactement a - * celui passé en argument - * @param v FIXME - */ - public void paste(Vector<E> v) { - this.capacity = v.capacity; - this.defaultValue = v.defaultValue; - this.positionSize = v.positionSize; - this.position = new int[v.position.length]; - System.arraycopy(v.position, 0, this.position, 0, - this.position.length); - this.data.clear(); - this.data.addAll(v.data); - } - - /** - * on applique sur chaque donnée existante et sur default - * @param f FIXME - */ - public void map(MapFunction<E> f) { - // on commence toujours par modifier la valeur par defaut - // car les valeurs suivante pourrait prendre cette valeur - // et donc disparaitre des tableaux si besoin - defaultValue = f.apply(defaultValue); - // on fait la boucle a l'envers au cas ou on supprime des valeurs - for (int i = data.size() - 1; i >= 0; i--) { - E value = f.apply(data.get(i)); - if (value == defaultValue) { - // il etait present, on supprime l'element - removeElementAt(i); - data.remove(i); - } else { - // il etait deja present, on modifie la valeur - data.set(i, value); - } - } - } - } // Vector - - /** - * Permet de faire un traitement sur des valeurs et d'en retourner - * des nouvelles. - * - * @param <E> FIXME - */ - interface MapFunction<E> { // MapFunction - - /** - * Permet de faire un traitement sur value et de retourne une nouvelle - * valeur. - * - * @param value la valeur courante sur lequel il faut faire le traitement - * @return la nouvelle valeur à mettre dans la matrice à la place de - * l'ancienne. - */ - E apply(E value); - - } // MapFunction - -} diff --git a/src/main/java/org/nuiton/util/MonthEnum.java b/src/main/java/org/nuiton/util/MonthEnum.java deleted file mode 100644 index 13005d2..0000000 --- a/src/main/java/org/nuiton/util/MonthEnum.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import static org.nuiton.i18n.I18n.t; - -/** - * Une énumération pour représenter les mois d'une année. - * - * @author Tony Chemit - chemit@codelutin.com - */ - -public enum MonthEnum { - - JANUARY(t("nuitonutil.month.january")), - FEBRUARY(t("nuitonutil.month.february")), - MARCH(t("nuitonutil.month.march")), - APRIL(t("nuitonutil.month.april")), - MAY(t("nuitonutil.month.may")), - JUNE(t("nuitonutil.month.june")), - JULY(t("nuitonutil.month.july")), - AUGUST(t("nuitonutil.month.august")), - SEPTEMBER(t("nuitonutil.month.september")), - OCTOBER(t("nuitonutil.month.october")), - NOVEMBER(t("nuitonutil.month.november")), - DECEMBER(t("nuitonutil.month.december")); - - /** Logger */ - private static final Log log = LogFactory.getLog(MonthEnum.class); - - private final String libelle; - - MonthEnum(String libelle) { - this.libelle = libelle; - } - - public String getLibelle() { - return libelle; - } - - public static MonthEnum valueOf(String month, MonthEnum defaultValue) { - MonthEnum monthEnum = null; - try { - monthEnum = valueOf(month.toUpperCase()); - } catch (Exception e) { - log.error( - t("nuitonutil.error.unfound.month", month, defaultValue), - e); - } - return monthEnum == null ? defaultValue : monthEnum; - } - - @Override - public String toString() { - // on force la traduction (au cas où i18n n'était pas ini au moment - // du chargement de l'enum...) - return t(libelle); - } -} diff --git a/src/main/java/org/nuiton/util/NumberUtil.java b/src/main/java/org/nuiton/util/NumberUtil.java deleted file mode 100644 index 5ea7e6c..0000000 --- a/src/main/java/org/nuiton/util/NumberUtil.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.nuiton.util; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2014 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import com.google.common.base.Predicate; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.util.Arrays; - -/** - * @author Kevin Morin - morin@codelutin.com - * @since 3.0 - */ -public class NumberUtil { - - /** - * Logger. - */ - private static final Log log = LogFactory.getLog(NumberUtil.class); - - /** - * Divide the divisor by the dividend. - * Returns an array containing the quotients rounded up or down - * to ensure the sum of the quotients equals the divisor. - * <p> - * e.g. divideAndEnsureSum(100, 3) returns {34, 33, 33} - * - * @param divisor the divisor - * @param dividend the dividend - * @return an array whose length equals dividend - */ - public static int[] divideAndEnsureSum(int divisor, int dividend) { - // dividing by 0 is not permitted - if (dividend == 0) { - return null; - } - - int quotient = (int) ((double) divisor) / dividend; - int[] result = new int[dividend]; - Arrays.fill(result, quotient); - - int sum = quotient * dividend; - int i = 0; - while (sum != divisor && i < dividend) { - result[i]++; - sum++; - i++; - } - - return result; - } - - public static final Predicate<Integer> NULL_OR_ZERO_INTEGER = new Predicate<Integer>() { - - @Override - public boolean apply(Integer input) { - return input == null || input == 0; - } - }; - - public static final Predicate<Float> NULL_OR_ZERO_FLOAT_ONE_DIGIT = new Predicate<Float>() { - - @Override - public boolean apply(Float input) { - return input == null || Math.abs(roundOneDigit(input)) < 0.1; - } - }; - public static final Predicate<Float> NULL_OR_ZERO_FLOAT_TWO_DIGITS = new Predicate<Float>() { - - @Override - public boolean apply(Float input) { - return input == null || Math.abs(roundTwoDigits(input)) < 0.01; - } - }; - public static final Predicate<Float> NULL_OR_ZERO_FLOAT_THREE_DIGITS = new Predicate<Float>() { - - @Override - public boolean apply(Float input) { - return input == null || Math.abs(roundThreeDigits(input)) < 0.001; - } - }; - public static final Predicate<Float> NULL_OR_ZERO_FLOAT_FOUR_DIGITS = new Predicate<Float>() { - - @Override - public boolean apply(Float input) { - return input == null || Math.abs(roundFourDigits(input)) < 0.0001; - } - }; - - public static final Predicate<Float> NULL_OR_ZERO_FLOAT_FIVE_DIGITS = new Predicate<Float>() { - - @Override - public boolean apply(Float input) { - return input == null || Math.abs(roundFiveDigits(input)) < 0.00001; - } - }; - - protected static final MathContext mc1Digit = new MathContext(1); - protected static final MathContext mc2Digits = new MathContext(2); - protected static final MathContext mc3Digits = new MathContext(3); - protected static final MathContext mc4Digits = new MathContext(4); - protected static final MathContext mc5Digits = new MathContext(5); - - public static Float roundOneDigit(Float number) { - return round(number, mc1Digit); - } - - public static Float roundTwoDigits(Float number) { - return round(number, mc2Digits); - } - - public static Float roundThreeDigits(Float number) { - return round(number, mc3Digits); - } - - public static Float roundFourDigits(Float number) { - return round(number, mc4Digits); - } - - public static Float roundFiveDigits(Float number) { - return round(number, mc5Digits); - } - - public static Float roundNDigits(Float number, int digits) { - return round(number, new MathContext(digits)); - } - - public static Float round(Float number, MathContext mc) { - float old = number; - float partieEntier = (int) old; - float digit = old - (int) old; - number = partieEntier + new BigDecimal(digit).round(mc).floatValue(); - if (log.isDebugEnabled()) { - log.debug("round " + old + " to " + number + " with mc = " + mc); - } - return number; - } - -} diff --git a/src/main/java/org/nuiton/util/ObjectUtil.java b/src/main/java/org/nuiton/util/ObjectUtil.java deleted file mode 100644 index f7fc15b..0000000 --- a/src/main/java/org/nuiton/util/ObjectUtil.java +++ /dev/null @@ -1,806 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * - * ObjectUtil.java - * - * Created: 2 nov. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -import org.apache.commons.beanutils.BeanUtils; -import org.apache.commons.beanutils.ConvertUtils; -import org.apache.commons.beanutils.MethodUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.Array; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -import static org.nuiton.i18n.I18n.t; - -/** - * Outils pour manipuler des objets. Création d'un objet à partir d'une chaîne - * le décrivant, conversion d'un objet en Object, récupération de méthodes - * à partir de leur nom, de constructeurs à partir de leurs paramètres... - * - * Created: 4 novembre 2004 - * - * @author Benjamin Poussin - poussin@codelutin.com - * - */ -public class ObjectUtil { // ObjectUtil - - /** Logger. */ - static private Log log = LogFactory.getLog(ObjectUtil.class); - - /** Used to know what is separator between class and method*/ - public static final String CLASS_METHOD_SEPARATOR = "#"; - - protected static final Integer ZERO = 0; - - protected static final Character ZEROC = (char) 0; - - protected static final Float ZEROF = 0f; - - protected static final Long ZEROL = 0l; - - protected static final Double ZEROD = 0.; - - protected static final Byte ZEROB = 0; - - /** - * ObjectUtil constructor - * private because of this class is a static class : nobody - * can make an instance of this class - */ - private ObjectUtil() { - } - - /** - * Invoke constructor on clazz to create new instance. Try to find argument - * for constructor in args parameter. - * - * @param <E> FIXME - * @param clazz class of object to instanciate - * @param args all possible parameter that constructor can used - * @param nullIfMissing if no suitable class or object found in args, - * use null value (no exception) - * @return new instance - * @throws IllegalArgumentException if something is wrong during instanciation - */ - public static <E> E newInstance(Class<E> clazz, - Collection<?> args, - boolean nullIfMissing) { - Constructor<E>[] constructors = - (Constructor<E>[]) clazz.getConstructors(); - if (constructors.length != 1) { - throw new IllegalArgumentException( - t("nuitonutil.error.class.with.more.than.one.constructor", - clazz)); - } - - // copy collection into modifiable list to add new object - List<?> container = new LinkedList(args); - - Constructor<E> constructor = constructors[0]; - Class<?>[] paramTypes = constructor.getParameterTypes(); - Object[] params = new Object[paramTypes.length]; - - for (int i = 0; i < paramTypes.length; i++) { - Object o = choiceArgument(paramTypes[i], container, nullIfMissing); - params[i] = o; - } - - try { - E result = constructor.newInstance(params); - return result; - } catch (Exception eee) { - throw new IllegalArgumentException(t( - t("nuitonutil.error.cant.instanciate.class", - clazz, Arrays.toString(params))), eee); - } - } - - /** - * Permet de matcher un type d'argument attendu clazz parmi un ensemble - * possible de candidat. Les candidats peuvent etre des classes qu'il faudra - * instancier pour satisfaire le type demande. - * - * @param clazz le type recherché - * @param args la liste des arguments ou des types - * @param nullIfMissing pour retourner nulle si l'argument n'est pas trouvé - * @return le type d'argument trouvé - */ - static protected Object choiceArgument(Class<?> clazz, - List args, - boolean nullIfMissing) { - Object result = null; - boolean addResult = false; - for (Object o : args) { - if (o != null) { - if (o instanceof Class<?> && - clazz.isAssignableFrom((Class<?>) o)) { - - // cas on l'on trouve une class dans arg qui une fois - // instancier convient - result = newInstance((Class<?>) o, args, nullIfMissing); - addResult = true; - break; - } else if (clazz.isInstance(o)) { - - // cas on l'on retrouve un objet assignable pour ce type - result = o; - break; - } - } - } - - if (addResult) { - // on ajoute en tete pour qu'il soit retrouve dans les premiers - // et non pas reinstancier une nouvelle fois si on en a besoin - // a nouveau - args.add(0, result); - } - - // si on ne retrouve rien, result est reste a null - if (result == null && !nullIfMissing) { - throw new IllegalArgumentException(t( - t("nuitonutil.error.unfound.assignable.argument", - clazz, args))); - } - return result; - } - - /** - * Create new object from string like org.nuiton.Toto(name=machine, int=10) - * where machine and int is properties on org.nuiton.Toto object. - * Conversion between 10 in string and 10 as integer as automaticaly done - * - * For String property you can use ex: - * <ul> - * <li> name="my string with , in string"</li> - * <li> name='my string with , in string'</li> - * </ul> - * @param classnameAndProperties FIXME - * @return the instanciated object FIXME - * @throws ClassNotFoundException FIXME - * @throws IllegalAccessException FIXME - * @throws InstantiationException FIXME - * @throws NoSuchMethodException FIXME - * @throws InvocationTargetException FIXME - */ - public static Object create(String classnameAndProperties) throws - ClassNotFoundException, - InstantiationException, - IllegalAccessException, - InvocationTargetException, - NoSuchMethodException { - int p = classnameAndProperties.indexOf('('); - int l = classnameAndProperties.lastIndexOf(')'); - String[] properties = null; - String classname; - if (p != -1) { - String tmp = classnameAndProperties.substring(p + 1, l); - properties = StringUtil.split(tmp, ","); - classname = classnameAndProperties.substring(0, p); - } else { - classname = classnameAndProperties; - } - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - Class<?> clazz = loader.loadClass(classname); - Object o = clazz.getConstructor().newInstance(); - if (properties != null) { - for (String prop : properties) { - int e = prop.indexOf('='); - String propName = prop.substring(0, e).trim(); - String propValue = prop.substring(e + 1).trim(); - if (propValue.charAt(0) == '"' && - propValue.charAt(propValue.length() - 1) == '"') { - propValue = propValue.substring(1, propValue.length() - 1); - } else if (propValue.charAt(0) == '\'' && - propValue.charAt(propValue.length() - 1) == '\'') { - propValue = propValue.substring(1, propValue.length() - 1); - } - BeanUtils.setProperty(o, propName, propValue); - } - } - return o; - } - - static protected Object convert(String v, Class<?> clazz) { - Object t = ConvertUtils.convert(v, clazz); - - if (t != null && - !String.class.getName().equals(clazz.getName()) && - String.class.getName().equals(t.getClass().getName())) { - throw new IllegalArgumentException(String.format( - "Can convert argument to correct type. %s can't be" + - " converted from String to %s conversion is done to %s", - v, clazz.getName(), t.getClass().getName())); - } - return t; - } - - /** - * Clone object by introspection because Cloneable interface don't permit - * to call clone :(. This methode replace next code that don't work :( - * - * <pre> - * if (o instanceof Cloneable) { - * Object n = ((Cloneable)o).clone(); - * } - * </pre> - * - * @param <E> FIXME - * @param e object to clone - * @return new instance of E - * @throws CloneNotSupportedException if some error occur during clone - */ - public static <E extends Cloneable> E clone(E e) throws CloneNotSupportedException { - try { - E result = (E) MethodUtils.invokeExactMethod(e, "clone", null); - return result; - } catch (Exception eee) { - // on est oblige de faire un log, car CloneNotSupportedException - // ne prend pas d'exception en arguement :( - log.error("Can't clone object", eee); - throw new CloneNotSupportedException(); - } - } - - /** - * Use serialization/deserialization to do deep clone of object - * - * @param <E> FIXME - * @param e object to clone - * @return new instance of E - * @throws CloneNotSupportedException if some error occur during clone - */ - public static <E> E deepClone(E e) throws CloneNotSupportedException { - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(bos); - try { - oos.writeObject(e); - } finally { - oos.close(); - } - - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - E result; - ObjectInputStream ois = new ObjectInputStream(bis); - try { - result = (E) ois.readObject(); - } finally { - ois.close(); - } - - return result; - } catch (Exception eee) { - // on est oblige de faire un log, car CloneNotSupportedException - // ne prend pas d'exception en arguement :( - log.error("Can't clone object", eee); - throw new CloneNotSupportedException(); - } - } - - /** - * Call method m with params as String. Each param is converted to required type for - * method with beanutils converter - * - * @param o object where method must be call - * @param m method to call - * @param params parameters for method call - * @return returned method's value - * @throws IllegalAccessException FIXME - * @throws IllegalArgumentException FIXME - * @throws InvocationTargetException FIXME - * @throws InstantiationException FIXME - */ - public static Object call(Object o, Method m, String... params) - throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { - Class<?>[] types = m.getParameterTypes(); - if (!m.isVarArgs() && params.length != types.length) { - throw new IllegalArgumentException(String.format( - "Bad number params we have %1$s parameters and waiting %2$s.", - params.length, types.length)); - } - - int last = types.length; - if (m.isVarArgs()) { - // on traite le dernier differement - last--; - } - - Object[] parameters = new Object[types.length]; - for (int i = 0; i < last; i++) { - String v = params[i]; - Class<?> clazz = types[i]; - Object t = convert(v, clazz); - parameters[i] = t; - } - - if (m.isVarArgs()) { - Class<?> clazz = types[last]; // get var args type - clazz = clazz.getComponentType(); // get array component type - List<Object> tmp = new ArrayList<Object>(); - for (int i = last; i < params.length; i++) { - String v = params[i]; - Object t = convert(v, clazz); - tmp.add(t); - } - parameters[last] = tmp.toArray((Object[]) Array.newInstance(clazz, tmp.size())); - } - - if (log.isDebugEnabled()) { - log.debug(t("nuitonutil.debug.objectutil.invoke", m, Arrays.toString(parameters))); - } - Object result = m.invoke(o, parameters); - return result; - } - - /** - * Get all methods with name given in argument without check parameters. - * - * @param clazz where to search method - * @param methodName method name to search - * @param ignoreCase if true, ignore difference in method name case - * @return list of detected methods - */ - public static List<Method> getMethod(Class<?> clazz, - String methodName, - boolean ignoreCase) { - List<Method> result = new ArrayList<Method>(); - - Method[] methods = clazz.getMethods(); - for (Method m : methods) { - if (ignoreCase && methodName.equalsIgnoreCase(m.getName()) || - methodName.equals(m.getName())) { - result.add(m); - } - } - - return result; - } - - /** - * List method that match name, name must be [package.][class][#][method] - * if package, class or method missing, exception throw - * - * @param name name of the method - * @param ignoreCase check exact method name if false - * @return list of method that match name - * @since 2.6.9 - */ - static public List<Method> getMethod(String name, boolean ignoreCase) { - Class<?> clazz; - String className; - String methodName; - - // looking for method name - int sep = name.lastIndexOf(CLASS_METHOD_SEPARATOR); - if (sep == -1) { - throw new IllegalArgumentException(String.format( - "Can't find method in %s", name)); - } else { - className = name.substring(0, sep); - methodName = name.substring(sep + 1); - } - - // looking for class name - try { - clazz = Class.forName(className); - } catch (ClassNotFoundException eee) { - throw new IllegalArgumentException(String.format( - "Can't find class %s", className)); - } - - List<Method> result = ObjectUtil.getMethod(clazz, methodName, ignoreCase); - return result; - } - - public static Object newInstance(String constructorWithParams) throws ClassNotFoundException { - int p = constructorWithParams.indexOf('('); - int l = constructorWithParams.lastIndexOf(')'); - String[] params = null; - String classname; - if (p != -1) { - String tmp = constructorWithParams.substring(p + 1, l); - params = StringUtil.split(tmp, ","); - classname = constructorWithParams.substring(0, p); - } else { - classname = constructorWithParams; - } - Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(classname); - Object result = newInstance(clazz, params); - return result; - } - - /** - * Create new instance of clazz, call constructor with params as String. - * Each param is converted to required type for - * constructor with beanutils converter, first constructor that permit - * instanciation is used - * - * @param <T> type to instanciate - * @param clazz class to instanciate - * @param params parameters for constructor call - * @return new instance of clazz - * @throws IllegalArgumentException FIXME - */ - public static <T> T newInstance(Class<T> clazz, String... params) - throws IllegalArgumentException { - if (params == null) { - params = StringUtil.EMPTY_STRING_ARRAY; - } - List<Constructor<T>> constructors = getConstructor(clazz, params.length); - - for (Constructor<T> c : constructors) { - try { - Class<?>[] types = c.getParameterTypes(); - - int last = types.length; - if (c.isVarArgs()) { - // on traite le dernier differement - last--; - } - - Object[] parameters = new Object[types.length]; - for (int i = 0; i < last; i++) { - String v = params[i]; - Class<?> argClazz = types[i]; - Object t = convert(v, argClazz); - parameters[i] = t; - } - - if (c.isVarArgs()) { - - // get var args type - Class<?> argClazz = types[last]; - - // get array component type - argClazz = argClazz.getComponentType(); - List<Object> tmp = new ArrayList<Object>(); - for (int i = last; i < params.length; i++) { - String v = params[i]; - Object t = convert(v, argClazz); - tmp.add(t); - } - parameters[last] = - tmp.toArray((Object[]) Array.newInstance( - argClazz, tmp.size())); - } - - if (log.isDebugEnabled()) { - log.debug(t("nuitonutil.debug.objectutil.create", - clazz, Arrays.toString(parameters))); - } - T result = c.newInstance(parameters); - - return result; - } catch (Exception eee) { - // this constructors don't work, try next - if (log.isDebugEnabled()) { - log.debug("Creation failed try with next constructor"); - } - } - } - throw new IllegalArgumentException( - t("nuitonutil.debug.objectutil.instantiate", - clazz, Arrays.toString(params))); - } - - /** - * Get all constructors that support paramNumber as parameters numbers. - * Varargs is supported - * - * @param <T> le type de la classe a inspecter - * @param clazz la classe sur lequel rechercher le constructeur - * @param paramNumber le nombre de parametre souhaite pour le constructeur, - * -1 indique que tous les constructeur sont souhaite. - * @return list of constructors - */ - @SuppressWarnings("unchecked") - public static <T> List<Constructor<T>> getConstructor(Class<T> clazz, - int paramNumber) { - List<Constructor<T>> result = new ArrayList<Constructor<T>>(); - Constructor<T>[] constructors = - (Constructor<T>[]) clazz.getConstructors(); - for (Constructor<T> c : constructors) { - if (paramNumber < 0 || - c.isVarArgs() && - c.getParameterTypes().length <= paramNumber - 1 || - c.getParameterTypes().length == paramNumber) { - result.add(c); - } - } - - return result; - } - - /** - * Method toObject - * - * @param o Object to transform - * @return the same object - * @deprecated since 2.6 (since java 5 boxing-unboxing does it for you) - */ - @Deprecated - public static Object toObject(Object o) { - return o; - } - - /** - * Method toObject - * - * transform a char to a Character Object - * - * @param c the char to transform - * @return the Charactere object corresponding - * @deprecated since 2.6 (since java 5 boxing-unboxing does it for you) - */ - @Deprecated - public static Object toObject(char c) { - return new Character(c); - } - - /** - * Method toObject - * - * transform a byte to a Byte Object - * - * @param b the byte to transform - * @return the byte object corresponding - * @deprecated since 2.6 (since java 5 boxing-unboxing does it for you) - */ - @Deprecated - public static Object toObject(byte b) { - return new Byte(b); - } - - /** - * Method toObject - * - * transform a short to a Short object - * - * @param s the short to transform - * @return the Short object corresponding - * @deprecated since 2.6 (since java 5 boxing-unboxing does it for you) - */ - @Deprecated - public static Object toObject(short s) { - return new Short(s); - } - - /** - * Method toObject - * - * transform an int to an Integer object - * - * @param i the int to transform - * @return the Integer Object corresponding - * @deprecated since 2.6 (since java 5 boxing-unboxing does it for you) - */ - @Deprecated - public static Object toObject(int i) { - return new Integer(i); - } - - /** - * Method toObject - * - * transform a long to a Long object - * - * @param l the long to transform - * @return the Long Object corresponding - * @deprecated since 2.6 (since java 5 boxing-unboxing does it for you) - */ - @Deprecated - public static Object toObject(long l) { - return new Long(l); - } - - /** - * Method toObject - * - * transform a float to a Float Object - * - * @param f the float to transform - * @return the Float Object corresponding - * @deprecated since 2.6 (since java 5 boxing-unboxing does it for you) - */ - @Deprecated - public static Object toObject(float f) { - return new Float(f); - } - - /** - * Method toObject - * - * transform a double to a Double object - * - * @param d the double to transform - * @return the Double object corresponding - * @deprecated since 2.6 (since java 5 boxing-unboxing does it for you) - */ - @Deprecated - public static Object toObject(double d) { - return new Double(d); - } - - /** - * Method toObject - * - * transform a boolean to a Boolean object - * - * @param b the boolean to transform - * @return the Boolean object corresponding - * @deprecated since 2.6 (since java 5 boxing-unboxing does it for you) - */ - @Deprecated - public static Object toObject(boolean b) { - return b ? Boolean.TRUE : Boolean.FALSE; - } - - /** - * Obtains the null value for the given type (works too with primitive - * types). - * - * @param type the type to test - * @return the {@code null} value or default value for primitive types - * @see com.google.common.base.Defaults - * @since 1.1.5 - * @deprecated since 2.6 (there is some other library which does it - */ - @Deprecated - public static Object getNullValue(Class<?> type) { - if (type == null) { - throw new NullPointerException("parameter 'type' can not be null"); - } - if (type.isPrimitive()) { - type = MethodUtils.getPrimitiveWrapper(type); - if (Boolean.class.isAssignableFrom(type)) { - return Boolean.FALSE; - } - if (Integer.class.isAssignableFrom(type)) { - return ZERO; - } - if (Character.class.isAssignableFrom(type)) { - return ZEROC; - } - if (Float.class.isAssignableFrom(type)) { - return ZEROF; - } - if (Long.class.isAssignableFrom(type)) { - return ZEROL; - } - if (Double.class.isAssignableFrom(type)) { - return ZEROD; - } - if (Byte.class.isAssignableFrom(type)) { - return ZEROB; - } - } - return null; - } - - /** - * Tests if the given value is null according to default value for - * primitive types if nedded. - * - * @param value the value to test - * @return {@code true} if value is null or default value on a primitive - * @since 1.1.5 - */ - public static boolean isNullValue(Object value) { - if (value == null) { - return true; - } - Class<?> type = value.getClass(); - - //FIXME-TC20100212 : this case can not be, due to auto-boxing mecanism - if (type.isPrimitive()) { - type = MethodUtils.getPrimitiveWrapper(type); - - if (Boolean.class.isAssignableFrom(type)) { - return Boolean.FALSE.equals(value); - } - if (Integer.class.isAssignableFrom(type)) { - return ZERO.equals(value); - } - if (Character.class.isAssignableFrom(type)) { - return ZEROC.equals(value); - } - if (Float.class.isAssignableFrom(type)) { - return ZEROF.equals(value); - } - if (Long.class.isAssignableFrom(type)) { - return ZEROL.equals(value); - } - if (Double.class.isAssignableFrom(type)) { - return ZEROD.equals(value); - } - if (Byte.class.isAssignableFrom(type)) { - return ZEROB.equals(value); - } - } - return false; - } - - public static boolean isNullValue(boolean value) { - return Boolean.FALSE.equals(value); - } - - public static boolean isNullValue(byte value) { - return value == ZEROB; - } - - public static boolean isNullValue(int value) { - return value == ZEROB; - } - - public static boolean isNullValue(char value) { - return value == ZEROC; - } - - public static boolean isNullValue(float value) { - return value == ZEROF; - } - - public static boolean isNullValue(double value) { - return value == ZEROD; - } - - /** - * Verifie si la classe est de type primitif. - * - * @param clazz nom de la classe a tester - * @return vrai si le classe est de type primitif faux sinon - */ - public static boolean isPrimitive(Class<?> clazz) { - return clazz.isPrimitive() || clazz == Boolean.class - || clazz == Byte.class || clazz == Character.class - || clazz == Short.class || clazz == Integer.class - || clazz == Long.class || clazz == Float.class - || clazz == Double.class; - } - -} // ObjectUtil - diff --git a/src/main/java/org/nuiton/util/PagerBean.java b/src/main/java/org/nuiton/util/PagerBean.java deleted file mode 100644 index 5d9374f..0000000 --- a/src/main/java/org/nuiton/util/PagerBean.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.nuiton.util; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.io.Serializable; - -/** - * A pager bean. - * - * Was previously {@code org.nuiton.util.PagerUtil.PagerBean}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.6.2 - * @deprecated since 3.0, prefer using {@link org.nuiton.util.pagination.PaginationParameter}. - */ -@Deprecated -public class PagerBean implements Serializable { - - private static final long serialVersionUID = 1L; - - /** Number of records (says numbers of rows displayable. */ - protected long records; - - /** Index of the first record in this page. */ - protected long recordStartIndex; - - /** Index of the last record in this page. */ - protected long recordEndIndex; - - /** Index of the page. */ - protected int pageIndex; - - /** Page size, says number of records in a page. */ - protected int pageSize; - - /** Number of pages. */ - protected long pagesNumber; - - public long getRecords() { - return records; - } - - public long getRecordStartIndex() { - return recordStartIndex; - } - - public long getRecordEndIndex() { - return recordEndIndex; - } - - public int getPageIndex() { - return pageIndex; - } - - public int getPageSize() { - return pageSize; - } - - public long getPagesNumber() { - return pagesNumber; - } - - public void setRecords(long records) { - this.records = records; - } - - public void setRecordStartIndex(long recordStartIndex) { - this.recordStartIndex = recordStartIndex; - } - - public void setRecordEndIndex(long recordEndIndex) { - this.recordEndIndex = recordEndIndex; - } - - public void setPageIndex(int pageIndex) { - this.pageIndex = pageIndex; - } - - public void setPageSize(int pageSize) { - this.pageSize = pageSize; - } - - public void setPagesNumber(long pagesNumber) { - this.pagesNumber = pagesNumber; - } - - @Override - public String toString() { - String result = new ToStringBuilder(this) - .append("records", records) - .append("recordStartIndex", recordStartIndex) - .append("recordEndIndex", recordEndIndex) - .append("pageIndex", pageIndex) - .append("pageSize", pageSize) - .append("pagesNumber", pagesNumber) - .toString(); - return result; - } - -} diff --git a/src/main/java/org/nuiton/util/PagerBeanUtil.java b/src/main/java/org/nuiton/util/PagerBeanUtil.java deleted file mode 100644 index 8838717..0000000 --- a/src/main/java/org/nuiton/util/PagerBeanUtil.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.nuiton.util; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import org.apache.commons.lang3.tuple.Pair; - -import java.util.ArrayList; -import java.util.List; - -/** - * Useful method around {@link PagerBean}. - * - * Was previously {@code org.nuiton.util.PagerUtil}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.6.2 - */ -public class PagerBeanUtil { - - /** - * Given a total count of elements and a page size, compute the number of - * pages available. - * - * @param totalCount total count of elements in the pager - * @param pageSize size of a page - * @return the number of available pages - */ - public static long getTotalPage(long totalCount, int pageSize) { - long result = (long) Math.ceil((double) totalCount / (double) pageSize); - return result; - } - - /** - * Compute the pager bound given his datas: - * <ul> - * <li>{@code totalCount}: count of all elements of the pager</li> - * <li>{@code pageSize}: number of elements in a page</li> - * <li>{@code page}: the requested page number starting at {@code 1}</li> - * </ul> - * - * @param totalCount total count of elements in the pager - * @param page pager page number (starting at {@code 1}) - * @param pageSize number of elements in a page - * @return the bound of start and end index of the requested elements of the pager - */ - public static Pair<Long, Long> getPageBound(long totalCount, - int page, - int pageSize) { - - page = Math.max(page, 1); - long pageSize2 = pageSize == -1 ? totalCount : Math.max(pageSize, 1); - - long start = (page - 1l) * pageSize2; - long end = page * pageSize2; // End in subList is exclusive - - end = Math.min(end, totalCount); //To be sure that end will not be out of bound in subList - - Pair<Long, Long> result = Pair.of(start, end); - return result; - } - - /** - * Get the elements of the lists using the pager datas: - * - * <ul> - * <li>{@code elements}:all elements of the pager</li> - * <li>{@code pageSize}: number of elements in a page</li> - * <li>{@code page}: the requested page number starting at {@code 1}</li> - * </ul> - * - * @param elements all pager elements - * @param page pager page number (starting at {@code 1}) - * @param pageSize number of elements in a page - * @param <E> n'importe quel type - * @return la liste une fois filtrée - */ - public static <E> List<E> getPage(List<E> elements, int page, int pageSize) { - - Pair<Long, Long> bound = getPageBound(elements.size(), page, pageSize); - - long start = bound.getLeft(); - long end = bound.getRight(); - - List<E> subList = elements.subList((int) start, (int) end); - List<E> result = new ArrayList<E>(subList); - - return result; - } - - /** - * Given a pagerBean, compute his {@link PagerBean#recordStartIndex}, - * {@link PagerBean#recordEndIndex} and {@link PagerBean#pagesNumber}. - * - * @param bean the pagerBean to fill - * @since 2.4.3 - */ - public static void computeRecordIndexesAndPagesNumber(PagerBean bean) { - long records = bean.getRecords(); - int pageSize = bean.getPageSize(); - - Pair<Long, Long> pageBound = - getPageBound(records, bean.getPageIndex(), pageSize); - bean.setRecordStartIndex(pageBound.getLeft()); - bean.setRecordEndIndex(pageBound.getRight()); - bean.setPagesNumber(getTotalPage(records, pageSize)); - } - - public static PagerBean newPagerBean() { - return new PagerBean(); - } -} diff --git a/src/main/java/org/nuiton/util/PeriodDates.java b/src/main/java/org/nuiton/util/PeriodDates.java deleted file mode 100644 index 90bb7ad..0000000 --- a/src/main/java/org/nuiton/util/PeriodDates.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -/** - * TODO tchemit 2010-08-25 JAVADOC + I18N - * PeriodDates.java - * - * Created on 2009-08-13 - * - * @author fdesbois - */ -public class PeriodDates implements Serializable { - - private static final long serialVersionUID = 1L; - - private String pattern; - - private Calendar fromCalendar; - - private Calendar thruCalendar; - - public PeriodDates() { - } - - public PeriodDates(Date fromDate, Date thruDate) throws IllegalArgumentException { - if (thruDate != null && fromDate != null && fromDate.after(thruDate)) { - throw new IllegalArgumentException("The fromDate can't be after the thruDate !"); - } - - setFromDate(fromDate); - setThruDate(thruDate); - - pattern = DateUtil.DEFAULT_PATTERN; - } - - public PeriodDates(Calendar fromCalendar, Calendar thruCalendar) throws IllegalArgumentException { - if (thruCalendar != null && fromCalendar != null && fromCalendar.after(thruCalendar)) { - throw new IllegalArgumentException("The fromDate can't be after the thruDate !"); - } - this.fromCalendar = fromCalendar; - this.thruCalendar = thruCalendar; - - pattern = DateUtil.DEFAULT_PATTERN; - } - - /** - * Create a period from the date of today. If monthAfter is negative, the current day will be - * the thruDate of the period. The period extremities will be initialized (first day of month for - * fromDate and last day of month for thruDate). Time is set to 0 for both - * dates. - * <pre> - * Ex 1 : - * Today = 12/05/2009 - * monthAfter = 5 - * Period = 01/05/2009 to 31/10/2009 - * Ex 2 : - * Today = 12/05/2009 - * monthAfter = -4 - * Period = 01/01/2009 to 31/05/2009 - * </pre> - * - * @param monthAfter the number of month from the current one - * @return a new PeriodDates - */ - public static PeriodDates createMonthsPeriodFromToday(int monthAfter) { - Calendar calendarFrom = Calendar.getInstance(); - Calendar calendarThru = Calendar.getInstance(); - - // Reset time - Date minTime = DateUtil.setMinTimeOfDay(new Date()); - calendarFrom.setTime(minTime); - calendarThru.setTime(minTime); - - if (monthAfter < 0) { - calendarFrom.add(Calendar.MONTH, monthAfter); - } else { - calendarThru.add(Calendar.MONTH, monthAfter); - } - - PeriodDates period = new PeriodDates(calendarFrom, calendarThru); - period.initDayOfMonthExtremities(); - period.setPattern(DateUtil.MONTH_PATTERN); - return period; - } - - public String getPattern() { - return pattern; - } - - public void setPattern(String pattern) { - this.pattern = pattern; - } - - /** Set first day of month for dateFrom and last day of month for dateThru */ - public void initDayOfMonthExtremities() { - if (fromCalendar == null || thruCalendar == null) { - throw new NullPointerException("fromDate or thruDate can't be null to" + - " change dayOfMonth extremities"); - } - Date fromDate = fromCalendar.getTime(); - fromDate = DateUtil.setFirstDayOfMonth(fromDate); - fromDate = DateUtil.setMinTimeOfDay(fromDate); - fromCalendar.setTime(fromDate); - - Date thruDate = thruCalendar.getTime(); - thruDate = DateUtil.setLastDayOfMonth(thruDate); - thruDate = DateUtil.setMaxTimeOfDay(thruDate); - thruCalendar.setTime(thruDate); - } - - public void setFromDate(Date fromDate) { - //this.fromDate = fromDate; - if (fromDate != null) { - if (thruCalendar != null && fromDate.after(thruCalendar.getTime())) { - throw new IllegalArgumentException("The fromDate can't be after the thruDate !"); - } - if (fromCalendar == null) { - fromCalendar = Calendar.getInstance(); - } - fromCalendar.setTime(fromDate); - } else { - fromCalendar = null; - } - } - - public Date getFromDate() { - return fromCalendar != null ? fromCalendar.getTime() : null; - } - - public int getFromMonth() { - return fromCalendar.get(Calendar.MONTH); - } - - public void setThruDate(Date thruDate) { - //this.thruDate = thruDate; - if (thruDate != null) { - if (fromCalendar != null && thruDate.before(fromCalendar.getTime())) { - throw new IllegalArgumentException("The thruDate can't be before the fromDate !"); - } - if (thruCalendar == null) { - thruCalendar = Calendar.getInstance(); - } - thruCalendar.setTime(thruDate); - } else { - thruCalendar = null; - } - } - - public Date getThruDate() { - return thruCalendar != null ? thruCalendar.getTime() : null; - } - - public List<Date> getMonths() { - List<Date> months = new ArrayList<Date>(); - if (fromCalendar == null || thruCalendar == null) { - return months; - } - -// Calendar current = (Calendar) fromCalendar.clone(); -// current.set(Calendar.DAY_OF_MONTH, 1); -// Calendar end = (Calendar) thruCalendar.clone(); -// end.set(Calendar.DAY_OF_MONTH, 1); - - // Prepare calendars for while condition : - // set first day of month + reset time to 00:00:00.000 - Date tmp = DateUtil.setFirstDayOfMonth(fromCalendar.getTime()); - tmp = DateUtil.setMinTimeOfDay(tmp); - Calendar current = DateUtil.getDefaultCalendar(tmp); - - tmp = DateUtil.setFirstDayOfMonth(thruCalendar.getTime()); - tmp = DateUtil.setMinTimeOfDay(tmp); - Calendar end = DateUtil.getDefaultCalendar(tmp); - - while (!current.equals(end)) { - months.add(current.getTime()); - current.add(Calendar.MONTH, 1); - } - months.add(current.getTime()); - - return months; - } - - public List<String> getFormatedMonths() { - List<String> results = new ArrayList<String>(); - for (Date date : getMonths()) { - String str = DateUtil.formatDate(date, pattern); - results.add(str); - } - return results; - } - - public boolean beforeEnd(Calendar calendar) { - return calendar.before(thruCalendar) || calendar.equals(thruCalendar); - } - - public boolean afterEnd(Calendar calendar) { - return calendar.after(thruCalendar); - } - - public boolean afterBegin(Calendar calendar) { - return calendar.after(fromCalendar) || calendar.equals(fromCalendar); - } - - public boolean between(Calendar calendar) { - return beforeEnd(calendar) && afterBegin(calendar); - } - - public boolean beforeEnd(Date date) { - Calendar calendar = DateUtil.getDefaultCalendar(date); - return beforeEnd(calendar); - } - - public boolean afterEnd(Date date) { - Calendar calendar = DateUtil.getDefaultCalendar(date); - return afterEnd(calendar); - } - - public boolean afterBegin(Date date) { - Calendar calendar = DateUtil.getDefaultCalendar(date); - return afterBegin(calendar); - } - - public boolean between(Date date) { - Calendar calendar = DateUtil.getDefaultCalendar(date); - return between(calendar); - } - - - @Override - public String toString() { - String fromStr = DateUtil.formatDate(getFromDate(), pattern); - String thruStr = DateUtil.formatDate(getThruDate(), pattern); - return "[ " + getFromDate() + " (pattern: " + fromStr + ") → " + - getThruDate() + " (pattern: " + thruStr + ") ]"; - } - -} diff --git a/src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java b/src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java deleted file mode 100644 index 0d772d2..0000000 --- a/src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin, Chatellier Eric - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Properties; - -/** - * Class used to not print first line into delegated {@link OutputStream}. - * - * Used to remove first comment line writed by {@link Properties#store(OutputStream, String)}. - * - * @author chatellier - */ -public class PropertiesDateRemoveFilterStream extends FilterOutputStream { - - protected boolean firstLineOver; - - protected char endChar; - - public PropertiesDateRemoveFilterStream(OutputStream out) { - super(out); - firstLineOver = false; - String lineSeparator = System.getProperty("line.separator"); - endChar = lineSeparator.charAt(lineSeparator.length() - 1); - } - - @Override - public void write(int b) throws IOException { - if (!firstLineOver) { - char c = (char) b; - if (c == endChar) { - firstLineOver = true; - } - } else { - out.write(b); - } - } - -} diff --git a/src/main/java/org/nuiton/util/RecursiveProperties.java b/src/main/java/org/nuiton/util/RecursiveProperties.java deleted file mode 100644 index 18d18d8..0000000 --- a/src/main/java/org/nuiton/util/RecursiveProperties.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin, Chatellier Eric - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.util.Properties; - -/** - * Overrides {@link Properties} in order to check if the expected value - * contains another property key like "${...}". It that case, the key - * will be replaced by its value if possible. - * - * Example : - * <pre> - * myFirstName=Arnaud - * myName=Thimel - * org.nuiton.topia.userInfo.fullName=${fullName} - * fullName=${myFirstName} ${myName} - * namePhrase=My name is ${myName}. - * instruction=Put your text like this : ${myText} - * </pre> - * - * Dans ce cas, - * <ul> - * <li>getProperty("org.nuiton.topia.userInfo.fullName") renverra "Arnaud Thimel" - * <li>getProperty("namePhrase") renverra "My name is Thimel." - * <li>getProperty("instruction") renverra "Put your text like this : ${myText}" - * </ul> - * - * @author Arnaud Thimel - thimel@codelutin.com - */ -public class RecursiveProperties extends Properties { - - private static final long serialVersionUID = -5012939272780929116L; - - public RecursiveProperties() { - } - - public RecursiveProperties(Properties defaults) { - super(defaults); - } - - @Override - public String getProperty(String key) { - String result = super.getProperty(key); - if (result == null) { - return null; - } - //Ex : result="My name is ${myName}." - int pos = result.indexOf("${", 0); - //Ex : pos=11 - while (pos != -1) { - int posEnd = result.indexOf("}", pos + 1); - //Ex : posEnd=19 - if (posEnd != -1) { - String value = getProperty(result.substring(pos + 2, posEnd)); - // Ex : getProperty("myName"); - if (value != null) { - // Ex : value="Thimel" - result = result.substring(0, pos) + value + result.substring(posEnd + 1); - // Ex : result="My name is " + "Thimel" + "." - pos = result.indexOf("${", pos + value.length()); - // Ex : pos=-1 - } else { - // Ex : value=null - pos = result.indexOf("${", posEnd + 1); - // Ex : pos=-1 - } - // Ex : pos=-1 - } - } - return result; - } - -} //RecursiveProperties diff --git a/src/main/java/org/nuiton/util/ReflectUtil.java b/src/main/java/org/nuiton/util/ReflectUtil.java deleted file mode 100644 index 78b3501..0000000 --- a/src/main/java/org/nuiton/util/ReflectUtil.java +++ /dev/null @@ -1,722 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * Introspection sur une classe. Détermine si un attribut est constant, - * recherche de constantes d'un type donné, conversion d'une classe en - * Enum... - * - * Created: 30 décembre 2007 - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class ReflectUtil { - - - /** Logger */ - static private Log log = LogFactory.getLog(ReflectUtil.class); - - /** - * Pour déterminer si un champ d'une classe est une constante - * (modifiers sont static, final et public) - * - * @param field le champs à tester - * @return {@code true} si les modifiers sont final, static et public - */ - public static boolean isConstantField(Field field) { - int modifiers = field.getModifiers(); - return Modifier.isPublic(modifiers) && - Modifier.isStatic(modifiers) && - Modifier.isFinal(modifiers); - } - - /** - * Recherche dans une classe donnée {@code klazz}, les constantes d'un - * certain type {@code searchingClass} et les retourne. - * - * L'algorithme parcourt aussi les superclasses. - * - * @param <T> enumeration's type - * @param klass la classe contenant les constantes - * @param searchingClass le type des champs constants à récupérer - * @return la liste des champs du type requis dans - * @throws RuntimeException si problème lors de la récupération - */ - @SuppressWarnings({"unchecked"}) - public static <T> List<T> getConstants(Class<?> klass, - Class<T> searchingClass) { - List<T> result = new ArrayList<T>(); - for (Field field : klass.getDeclaredFields()) { - if (!field.isAccessible()) { - field.setAccessible(true); - } - if (searchingClass.isAssignableFrom(field.getType()) && - isConstantField(field)) { - try { - result.add((T) field.get(null)); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - } - Class<?> superClass = klass.getSuperclass(); - if (superClass != null) { - result.addAll(getConstants(superClass, searchingClass)); - } - return result; - } - - /** - * @param <T> enumeration's type - * @param klass the required class - * @param fieldName the required constant name - * @return the constant value - */ - @SuppressWarnings({"unchecked"}) - public static <T> T getConstant(Class<?> klass, String fieldName) { - try { - T result = null; - Field f = klass.getDeclaredField(fieldName); - if (isConstantField(f)) { - f.setAccessible(true); - result = (T) f.get(null); - } - return result; - } catch (NoSuchFieldException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - /** - * Convertit une classe non typée, en une classe d'enum - * - * @param <T> enumeration's type - * @param type la classe a typer - * @return la classe typee - * @throws IllegalArgumentException si le type est null ou non une extension - * de la classe Enum. - */ - @SuppressWarnings({"unchecked"}) - public static <T extends Enum<T>> Class<T> getEnumClass(Class<?> type) throws IllegalArgumentException { - if (type == null) { - throw new IllegalArgumentException(t("nuitonutil.error.null.parameter", "type")); - } - if (!type.isEnum()) { - throw new IllegalArgumentException(t("nuitonutil.error.not.an.enum", type)); - } - return (Class<T>) type; - } - - /** - * Cherche une methode selon son nom et ses paramètres d'invocation. - * - * @param klass la classe dans laquelle rechercher la méthode - * @param methodName le nom de la méthode recherchée - * @param strict un drapeau pour déclancher une exception si la méthode - * n'est pas trouvée - * @param arguments les arguments d'invocation de la méthode - * @return la méthode trouvée - * @throws IllegalArgumentException si la méthode n'est pas trouvée et que - * le drapeau {@code strict} est à {@code true} - * @since 1.3.1 - */ - public static Method getDeclaredMethod(Class<?> klass, - String methodName, - boolean strict, - Object... arguments) throws IllegalArgumentException { - HashSet<Class<?>> classes = new HashSet<Class<?>>(); - Method method; - try { - method = getDeclaredMethod(klass, methodName, classes, arguments); - } finally { - if (log.isDebugEnabled()) { - log.debug("Inspected classes : " + classes); - } - classes.clear(); - } - if (method == null && strict) { - throw new IllegalArgumentException( - "could not find method " + methodName + " on type " + - klass.getName()); - } - - return method; - } - - /** - * Obtain the boxed type of any incoming type. - * - * If incoming type is not a primitive type, then just returns himself. - * - * @param type the type to box - * @return the boxed type - * @see Class#isPrimitive() - * @since 1.3.1 - */ - public static Class<?> boxType(Class<?> type) { - if (!type.isPrimitive()) { - return type; - } - if (boolean.class.equals(type)) { - return Boolean.class; - } - if (char.class.equals(type)) { - return Character.class; - } - if (byte.class.equals(type)) { - return Byte.class; - } - if (short.class.equals(type)) { - return Short.class; - } - if (int.class.equals(type)) { - return Integer.class; - } - if (long.class.equals(type)) { - return Long.class; - } - if (float.class.equals(type)) { - return Float.class; - } - if (double.class.equals(type)) { - return Double.class; - } - if (void.class.equals(type)) { - return Void.class; - } - // should never come here... - return type; - - } - - /** - * Obtain the unboxed type of any incoming type. - * - * If incoming type is a primitive type, then just returns himself. - * - * @param type the type to unbox - * @return the unboxed type - * @see Class#isPrimitive() - * @since 1.3.1 - */ - public static Class<?> unboxType(Class<?> type) { - if (type.isPrimitive()) { - return type; - } - if (Boolean.class.equals(type)) { - return boolean.class; - } - if (Character.class.equals(type)) { - return char.class; - } - if (Byte.class.equals(type)) { - return byte.class; - } - if (Short.class.equals(type)) { - return short.class; - } - if (Integer.class.equals(type)) { - return int.class; - } - if (Long.class.equals(type)) { - return long.class; - } - if (Float.class.equals(type)) { - return float.class; - } - if (Double.class.equals(type)) { - return double.class; - } - if (Void.class.equals(type)) { - return void.class; - } - - // not a primitive type - return type; - } - - /** - * Obtain all the declared fields of the given {@code objectClass} with a - * deep scan inside super classes and interfaces. - * - * <strong>Note:</strong> The type {@link Object} will not be scanned. - * - * @param objectClass the object class to scan - * @return the set of all declared fields found - * @since 2.0 - */ - public static Set<Field> getAllDeclaredFields(Class<?> objectClass) { - Set<Field> result = new HashSet<Field>(); - Set<Class<?>> visitedClasses = new HashSet<Class<?>>(); - - try { - getAllDeclaredFields(objectClass, visitedClasses, result); - } finally { - visitedClasses.clear(); - } - return result; - } - - /** - * Obtain all the declared methods of the given {@code objectClass} with a - * deep scan inside super classes and interfaces. - * - * <strong>Note:</strong> The type {@link Object} will not be scanned. - * - * @param objectClass the object class to scan - * @return the set of all declared methods found - * @since 2.0 - */ - public static Set<Method> getAllDeclaredMethods(Class<?> objectClass) { - Set<Method> result = new HashSet<Method>(); - Set<Class<?>> visitedClasses = new HashSet<Class<?>>(); - - try { - getAllDeclaredMethods(objectClass, visitedClasses, result); - } finally { - visitedClasses.clear(); - } - return result; - } - - /** - * Obtain all the fields with the given annotation type. - * - * <strong>Note:</strong> This method will not scan deeply the given type - * (no scan of super-classes nor interfaces). - * - * @param objectClass the type to scan - * @param annotationClass the type of annotation to scan - * @param <A> type of annotation to scan - * @return the dictionnary of fields with the given annotation - * @since 2.0 - */ - public static <A extends Annotation> Map<Field, A> getFieldAnnotation(Class<?> objectClass, - Class<A> annotationClass) { - Map<Field, A> result = getFieldAnnotation(objectClass, - annotationClass, - false - ); - return result; - } - - /** - * Obtain all the fields with the given annotation type. - * - * <strong>Note:</strong> This method will scan deeply the given type - * if parameter {@code deepVisit} is setted to {@code true}. - * - * <strong>Note:</strong> The type {@link Object} will not be scanned. - * - * @param objectClass the type to scan - * @param annotationClass the type of annotation to scan - * @param deepVisit flag to visit deeply the class (if set to - * {@code true}, will also scan super classes - * and interfaces) - * @param <A> type of annotation to scan - * @return the dictionnary of fields with the given annotation - * @since 2.0 - */ - public static <A extends Annotation> Map<Field, A> getFieldAnnotation(Class<?> objectClass, - Class<A> annotationClass, - boolean deepVisit) { - - Map<Field, A> result = new HashMap<Field, A>(); - Set<Class<?>> visitedClasses = new HashSet<Class<?>>(); - - try { - getFieldAnnotation(objectClass, - annotationClass, - deepVisit, - visitedClasses, - result - ); - } finally { - visitedClasses.clear(); - } - - return result; - } - - /** - * Obtain all the methods with the given annotation type. - * - * <strong>Note:</strong> This method will not scan deeply the given type - * (no scan of super-classes nor interfaces). - * - * @param objectClass the type to scan - * @param annotationClass the type of annotation to scan - * @param <A> type of annotation to scan - * @return the dictionnary of methods with the given annotation - * @since 2.0 - */ - public static <A extends Annotation> Map<Method, A> getMethodAnnotation(Class<?> objectClass, - Class<A> annotationClass) { - Map<Method, A> result = getMethodAnnotation(objectClass, - annotationClass, - false - ); - return result; - } - - /** - * Obtain all the methods with the given annotation type. - * - * <strong>Note:</strong> This method will scan deeply the given type - * if parameter {@code deepVisit} is setted to {@code true}. - * - * <strong>Note:</strong> The type {@link Object} will not be scanned. - * - * @param objectClass the type to scan - * @param annotationClass the type of annotation to scan - * @param <A> type of annotation to scan - * @param deepVisit flag to visit deeply the class (if set to - * {@code true}, will also scan super classes - * and interfaces) - * @return the dictionnary of methods with the given annotation - * @since 2.0 - */ - public static <A extends Annotation> Map<Method, A> getMethodAnnotation(Class<?> objectClass, - Class<A> annotationClass, - boolean deepVisit) { - Map<Method, A> result = new HashMap<Method, A>(); - Set<Class<?>> visitedClasses = new HashSet<Class<?>>(); - - try { - getMethodAnnotation(objectClass, - annotationClass, - deepVisit, - visitedClasses, - result - ); - } finally { - visitedClasses.clear(); - } - return result; - } - - protected static Method getDeclaredMethod(Class<?> klass, - String methodName, - Set<Class<?>> visitedClasses, - Object... arguments) { - if (visitedClasses.contains(klass)) { - - // this means class was already unsucessfull visited - return null; - } - visitedClasses.add(klass); - Method method = null; - for (Method m : klass.getDeclaredMethods()) { - if (!methodName.equals(m.getName())) { - continue; - } - - // same method name - - Class<?>[] types = m.getParameterTypes(); - if (arguments.length != types.length) { - continue; - } - - // same number arguments - - Class<?>[] prototype = m.getParameterTypes(); - if (log.isDebugEnabled()) { - log.debug("Found a method with same parameters size : " + - m.getName() + " : " + Arrays.toString(prototype)); - } - int index = 0; - boolean parametersMatches = true; - for (Object argument : arguments) { - Class<?> type = prototype[index++]; - if (argument == null) { - - // can not say anything, let says it is ok... - continue; - } - Class<?> runtimeType = argument.getClass(); - if (log.isDebugEnabled()) { - log.debug("Test parameter [" + (index - 1) + "] : " + - type + " vs " + runtimeType); - } - - type = boxType(type); - runtimeType = boxType(runtimeType); - - if (!type.equals(runtimeType) && - !type.isAssignableFrom(runtimeType)) { - - // not same type - parametersMatches = false; - if (log.isDebugEnabled()) { - log.debug("Types are not matching."); - } - break; - } - } - if (parametersMatches) { - - // same parameters types, this is a match - method = m; - } - break; - } - if (method == null) { - - // try on super class - if (klass.getSuperclass() != null) { - method = getDeclaredMethod(klass.getSuperclass(), - methodName, - visitedClasses, - arguments - ); - } - } - - if (method == null) { - - // try on interfaces - Class<?>[] interfaces = klass.getInterfaces(); - for (Class<?> anInterface : interfaces) { - method = getDeclaredMethod(anInterface, - methodName, - visitedClasses, - arguments - ); - if (method != null) { - break; - } - } - } - return method; - - } - - protected static void getAllDeclaredFields(Class<?> objectClass, - Set<Class<?>> visitedClasses, - Set<Field> result) { - - if (visitedClasses.contains(objectClass) || - Object.class.equals(objectClass)) { - - // already scanned - // or arrives to Object.class - return; - } - - // mark as scanned - visitedClasses.add(objectClass); - - Field[] declaredFields = objectClass.getDeclaredFields(); - result.addAll(Arrays.asList(declaredFields)); - - Class<?> superclass = objectClass.getSuperclass(); - if (superclass != null) { - - // scan also the superclass - getAllDeclaredFields(superclass, - visitedClasses, - result - ); - } - - Class<?>[] interfaces = objectClass.getInterfaces(); - - for (Class<?> anInterface : interfaces) { - - // scan also the interface - getAllDeclaredFields(anInterface, - visitedClasses, - result - ); - } - - } - - protected static void getAllDeclaredMethods(Class<?> objectClass, - Set<Class<?>> visitedClasses, - Set<Method> result) { - - if (visitedClasses.contains(objectClass) || - Object.class.equals(objectClass)) { - - // already scanned - // or arrives to Object.class - return; - } - - // mark as scanned - visitedClasses.add(objectClass); - - Method[] declaredFields = objectClass.getDeclaredMethods(); - result.addAll(Arrays.asList(declaredFields)); - - Class<?> superclass = objectClass.getSuperclass(); - if (superclass != null) { - - // scan also the superclass - getAllDeclaredMethods(superclass, - visitedClasses, - result - ); - } - - Class<?>[] interfaces = objectClass.getInterfaces(); - - for (Class<?> anInterface : interfaces) { - - // scan also the interface - getAllDeclaredMethods(anInterface, - visitedClasses, - result - ); - } - - } - - protected static <A extends Annotation> void getFieldAnnotation(Class<?> objectClass, - Class<A> annotationClass, - boolean deepVisit, - Set<Class<?>> visitedClasses, - Map<Field, A> result) { - - if (visitedClasses.contains(objectClass) || - Object.class.equals(objectClass)) { - - // already scanned - // or arrives to Object.class - return; - } - - // mark as scanned - visitedClasses.add(objectClass); - - for (Field field : objectClass.getDeclaredFields()) { - A annotation = field.getAnnotation(annotationClass); - if (annotation != null) { - result.put(field, annotation); - } - } - - if (deepVisit) { - - Class<?> superclass = objectClass.getSuperclass(); - if (superclass != null) { - - // scan also the superclass - getFieldAnnotation(superclass, - annotationClass, - deepVisit, - visitedClasses, - result - ); - } - - Class<?>[] interfaces = objectClass.getInterfaces(); - - for (Class<?> anInterface : interfaces) { - - // scan also the interface - getFieldAnnotation(anInterface, - annotationClass, - deepVisit, - visitedClasses, - result - ); - } - } - } - - protected static <A extends Annotation> void getMethodAnnotation(Class<?> objectClass, - Class<A> annotationClass, - boolean deepVisit, - Set<Class<?>> visitedClasses, - Map<Method, A> result) { - - if (visitedClasses.contains(objectClass) || - Object.class.equals(objectClass)) { - - // already scanned - // or arrives to Object.class - return; - } - - // mark as scanned - visitedClasses.add(objectClass); - - for (Method method : objectClass.getDeclaredMethods()) { - A annotation = method.getAnnotation(annotationClass); - if (annotation != null) { - result.put(method, annotation); - } - } - - if (deepVisit) { - - Class<?> superclass = objectClass.getSuperclass(); - if (superclass != null) { - - // scan also the superclass - getMethodAnnotation(superclass, - annotationClass, - deepVisit, - visitedClasses, - result - ); - } - - Class<?>[] interfaces = objectClass.getInterfaces(); - - for (Class<?> anInterface : interfaces) { - - // scan also the interface - getMethodAnnotation(anInterface, - annotationClass, - deepVisit, - visitedClasses, - result - ); - } - } - } -} diff --git a/src/main/java/org/nuiton/util/Resource.java b/src/main/java/org/nuiton/util/Resource.java deleted file mode 100644 index ed5fd40..0000000 --- a/src/main/java/org/nuiton/util/Resource.java +++ /dev/null @@ -1,917 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin, Chatellier Eric - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.ImageIcon; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.JarURLConnection; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLClassLoader; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.jar.Attributes; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.Manifest; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipInputStream; - -import static org.nuiton.i18n.I18n.t; - -/** - * Cette class permet de rechercher un fichier en indiquant son nom avec son - * chemin. Cette librairie ira ensuite chercher ce fichier sur le système de - * fichier, et s'il n'est pas trouvé dans le classpath. Le fichier peut donc - * être dans un fichier .jar ou .zip. Exemple : - * <pre> - * URL image = Resource.getURL("/images/bidulle.png"); - * </pre> - * - * Created: 5 août 2003 - * - * @author Benjamin Poussin - poussin@codelutin.com - * - */ -public class Resource { // Resource - - /** Logger. */ - private static final Log log = LogFactory.getLog(Resource.class); - - protected Resource() { - - } - - /** - * Permet d'ajouter dans le classloader par defaut une nouvelle URL dans - * lequel il faut rechercher les fichiers. - * - * @param url l'url a ajouter - */ - public static void addDefaultClassLoader(URL url) { - ClassLoader classLoader = ClassLoader.getSystemClassLoader(); - addClassLoader(classLoader, url); - } - - /** - * Permet d'ajouter dans un classloader une nouvelle URL dans - * lequel il faut rechercher les fichiers. - * - * @param classLoader le classloader a modifier - * @param url l'url a ajouter - */ - public static void addClassLoader(ClassLoader classLoader, URL url) { - try { - Method method = URLClassLoader.class.getDeclaredMethod("addURL", - new Class[]{URL.class}); - method.setAccessible(true); - method.invoke(classLoader, url); - } catch (Exception eee) { - throw new RuntimeException(t("nuitonutil.error.add.url.in.classloader", classLoader, eee)); - } - } - - /** - * Recherche la ressource nom. - * - * @param name nom de la ressource - * @return l'url de la ressource - * @throws ResourceNotFoundException si la resource n'a pas ete trouvee - */ - public static URL getURL(String name) { - URL url = getURLOrNull(name); - if (url != null) { - return url; - } - - throw new ResourceNotFoundException(t("nuitonutil.error.resource.not.found", name)); - } - - /** - * Recherche la ressource nom. - * - * @param name le nom de la ressource - * @return l'url de la ressource ou null - */ - public static URL getURLOrNull(String name) { - // on recherche d'abord sur le filesystem - File file = new File(name); - if (file.exists()) { - try { - return file.toURI().toURL(); - } catch (MalformedURLException eee) { - log.warn(t("nuitonutil.error.convert.file.to.url", file, eee.getMessage())); - } - } - - // on ne l'a pas trouve on recherche dans le classpath - - // on supprime le / devant le nom de la ressource, sinon elle - // n'est pas trouve (pas de recherche dans les differents - // element du classpath. - if (name.length() > 1 && name.startsWith("/")) { - name = name.substring(1); - } - URL url = ClassLoader.getSystemClassLoader().getResource(name); - if (url != null) { - return url; - } - - ClassLoader cl = Resource.class.getClassLoader(); - url = cl.getResource(name); - return url; - } - - /** - * Retourne l'icone demandee. - * - * @param name le nom de l'icone - * @return Retourne l'icon demande ou null s'il n'est pas trouvé - */ - public static ImageIcon getIcon(String name) { - try { - return new ImageIcon(getURL(name)); - } catch (Exception eee) { - log.warn("Can't find icon: " + name, eee); - return null; - } - } - - /** - * Retourner la liste des fichiers du classLoader. Ces fichiers doivent - * correspondre au pattern donne. - * - * Utile par defaut {@link ClassLoader#getSystemClassLoader()}. - * - * @param pattern le nom du fichier a extraire du fichier compressé ou - * du repertoire doit correspondre au pattern (repertoire + nom - * compris). - * @return la liste des urls correspondant au pattern - */ - public static List<URL> getURLs(String pattern) { - return getURLs(pattern, (URLClassLoader) null); - } - - /** - * Retourner la liste des fichiers du classLoader. Ces fichiers doivent - * correspondre au pattern donne. - * - * @param classLoader classloader to use (if null, use {@link ClassLoader#getSystemClassLoader()} - * @param pattern le nom du fichier a extraire du fichier compressé ou - * du repertoire doit correspondre au pattern (repertoire + nom - * compris). - * @return la liste des urls correspondant au pattern - */ - public static List<URL> getURLs(String pattern, URLClassLoader classLoader) { - if (classLoader == null) { - classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); - } - URL[] arrayURL = ClassLoaderUtil.getURLs(classLoader); - return getURLs(pattern, arrayURL); - } - - /** - * Retourner la liste des fichiers du classLoader. Ces fichiers doivent - * correspondre au pattern donne. - * - * @param arrayURL les urls ou chercher - * @param pattern le nom du fichier a extraire du fichier compressé ou - * dur epertoire doit correspondre au pattern (repertoire + nom - * compris). - * @return la liste des urls correspondant au pattern - */ - public static List<URL> getURLs(String pattern, URL... arrayURL) { - long t0 = System.nanoTime(); - - List<URL> urlList = new HashList<URL>(); - - if (arrayURL.length == 1) { - URL jarURL = arrayURL[0]; - if (isJar(jarURL.toString())) { - // jar invocation - try { - arrayURL = getClassPathURLsFromJarManifest(jarURL); - } catch (Exception e) { - log.warn(e); - arrayURL = new URL[]{jarURL}; - } - } - } - if (log.isDebugEnabled()) { - for (URL url : arrayURL) { - log.debug("found url " + url); - } - } - - for (URL urlFile : arrayURL) { - // EC-20100510 this cause wrong accent encoding - //String fileName = urlFile.getFile(); -// String fileName; -// try { -// fileName = urlFile.toURI().getPath(); -// } catch (Exception e) { -// if (log.isWarnEnabled()) { -// log.warn(e); -// } -// // warning, this can cause wrong encoding !!! -// fileName = urlFile.getFile(); -// } - -// // TODO deal with encoding in windows, this is very durty, but it -// // works... - File file = FileUtils.toFile(urlFile); - String fileName = file.getAbsolutePath(); -// File file = new File(fileName.replaceAll("%20", " ")); - if (!file.exists()) { - // this case should not appear - if (log.isDebugEnabled()) { - log.debug("Can't find file " + file + " (" + fileName + ")"); - } - continue; - } - if (isJar(fileName)) { - // cas ou le ichier du classLoader est un fichier jar - if (log.isDebugEnabled()) { - log.debug("jar to search " + file); - } - urlList.addAll(getURLsFromJar(file, pattern)); - continue; - } - if (file.isDirectory()) { - // cas ou le ichier du classLoader est un repertoire - if (log.isDebugEnabled()) { - log.debug("directory to search " + file); - } - // on traite le cas ou il peut y avoir des repertoire dans ce - // repertoire - urlList.addAll(getURLsFromDirectory(file, pattern)); - continue; - } - - if (isZip(fileName)) { - // cas ou le ichier du classLoader est un fichier zip - if (log.isDebugEnabled()) { - log.debug("zip to search " + file); - } - urlList.addAll(getURLsFromZip(file, pattern)); - } - - } - if (log.isInfoEnabled()) { - log.info("search URLs pattern: " + pattern + " in " - + arrayURL.length + " urls in " - + StringUtil.convertTime(System.nanoTime() - t0)); - } - return urlList; - } - - public static URL[] getClassPathURLsFromJarManifest(URL jarURL) - throws IOException { - URL[] result; - File jarFile = FileUtils.toFile(jarURL); - if (log.isDebugEnabled()) { - log.debug("class-path jar to scan " + jarFile); - } - JarFile jar = new JarFile(jarFile); - try { -// String jarPath = jarURL.toURI().getPath(); -// File jarFile = new File(jarPath); - File container = jarFile.getParentFile(); - Manifest mf = jar.getManifest(); - String classPath = null; - if (mf != null && mf.getMainAttributes() != null) { - classPath = mf.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); - } - String[] paths; - if (classPath != null) { - paths = classPath.split(" "); - } else { - paths = StringUtil.EMPTY_STRING_ARRAY; - } - result = new URL[paths.length + 1]; - result[0] = jarURL; - File path; - for (int i = 0; i < paths.length; i++) { - String s = paths[i]; - // test de l'existence d'un protocole dans le path (genre file:...) - if (s.indexOf(':') != -1) { - result[i + 1] = new URL(s); - continue; - } - - if (s.startsWith(".") || !s.startsWith("/")) { - // relative url - path = new File(container, s); - } else { - path = new File(s); - } - if (log.isDebugEnabled()) { - log.debug(path); - } - result[i + 1] = path.toURI().toURL(); - } -// jar.close(); - } finally { - if (jar != null) { - jar.close(); - } - } - return result; - } - - public static List<URL> getURLsFromZip(File zipFile, String pattern) { - try { - if (log.isTraceEnabled()) { - log.trace("search '" + pattern + "' in " + zipFile); - } - - List<URL> result = new ArrayList<URL>(); -// InputStream in = new FileInputStream(zipFile); - ZipInputStream zis = - new ZipInputStream(new FileInputStream(zipFile)); - try { - while (zis.available() != 0) { - ZipEntry entry = zis.getNextEntry(); - - if (entry == null) { - break; - } - - String name = entry.getName(); - if (log.isTraceEnabled()) { - log.trace("zipFile: " + zipFile + " name: " + name); - } - if (pattern == null || name.matches(pattern)) { - // on recupere le fichier correspondant au pattern dans - // le classloader - URL url = getURL(name); - // on ajoute le fichier correspondant au pattern dans - // la liste - if (log.isTraceEnabled()) { - log.trace("zipFile: " + zipFile + " url: " + url); - } - result.add(url); - } - } - } finally { - zis.close(); - } - if (log.isTraceEnabled()) { - log.trace("found with pattern '" + pattern + "' : " + result); - } - return result; - } catch (IOException eee) { - throw new ResourceException(t("nuitonutil.error.get.url.from.zip", - zipFile.getAbsolutePath(), - eee.getMessage()) - ); - } - } - - public static List<URL> getURLsFromJar(File jarfile, String pattern) { - try { - if (log.isTraceEnabled()) { - log.trace("search '" + pattern + "' in " + jarfile); - } - - List<URL> result = new ArrayList<URL>(); -// InputStream in = new FileInputStream(jarfile); - ZipInputStream zis = - new ZipInputStream(new FileInputStream(jarfile)); - try { - while (zis.available() != 0) { - ZipEntry entry = zis.getNextEntry(); - - if (entry == null) { - break; - } - - String name = entry.getName(); - if (log.isTraceEnabled()) { - log.trace("jarfile: " + jarfile + " name: " + name); - } - if (pattern == null || name.matches(pattern)) { - // on recupere le fichier correspondant au pattern - // dans le classloader - URL url = getURL(name); - // on ajoute le fichier correspondant au pattern dans - // la liste - if (log.isTraceEnabled()) { - log.trace("jarfile: " + jarfile + " url: " + url); - } - result.add(url); - } - } - } finally { - zis.close(); - } - if (log.isTraceEnabled()) { - log.trace("found with pattern '" + pattern + "' : " + result); - } - return result; - } catch (IOException eee) { - throw new ResourceException(t("nuitonutil.error.get.url.from.zip", - jarfile.getAbsolutePath(), - eee.getMessage()) - ); - } - } - - /** - * Retourne la liste des fichiers correspondant au pattern donne, aucun - * ordre ne doit être supposé sur les fichiers. - * - * @param repository repertoire dans lequel on recherche les fichiers - * @param pattern le nom du fichier a extraire du fichier du repertoire doit - * correspondre au pattern (repertoire + nom compris). si le - * pattern est null, tous les fichiers trouvé sont retourné. - * @return la liste des urls correspondant au pattern - */ - public static List<URL> getURLsFromDirectory(File repository, String pattern) { - try { - if (log.isTraceEnabled()) { - log.trace("search '" + pattern + "' in " + repository); - } - - List<URL> urlList = new HashList<URL>(); - File[] filesList = repository.listFiles(); - - if (filesList != null) { - - for (File file : filesList) { - - String name = file.getAbsolutePath(); - - if (log.isTraceEnabled()) { - log.trace("directory: " + repository + " name: " - + name); - } - - // cas de recursivite : repertoire dans un repertoire - if (file.exists() && file.isDirectory()) { - urlList.addAll(getURLsFromDirectory(file, - pattern)); - // si le fichier du repertoire n'est pas un repertoire - // on verifie s'il correspond au pattern - } else if (pattern == null || name.matches(pattern)) { - URL url = file.toURI().toURL(); - if (log.isTraceEnabled()) { - log.trace("directory: " + repository + " url: " - + url); - } - urlList.add(url); - } - } - } - if (log.isTraceEnabled()) { - log.trace("found with pattern '" + pattern + "' : " + urlList); - } - return urlList; - } catch (MalformedURLException eee) { - throw new ResourceException( - t("nuitonutil.error.convert.file.to.url", - repository + " (pattern " + pattern + ") ", - eee.getMessage()) - ); - //throw new ResourceException("Le fichier n'a pu être converti en URL", eee); - } - } - - /** - * Verifie si le fichier est un fichier jar. - * - * @param name nom du fichier a tester - * @return vrai si le fichier se termine par .jar faux sinon - */ - public static boolean isJar(String name) { - if (name != null && name.length() > 4) { - String ext = name.substring(name.length() - 4, name.length()); - return ".jar".equalsIgnoreCase(ext); - } - return false; - } - - /** - * Verifie si le fichier est un fichier zip - * - * @param name nom du fichier a tester - * @return vrai si le fichier se termine par .zip faux sinon - */ - public static boolean isZip(String name) { - if (name != null && name.length() > 4) { - String ext = name.substring(name.length() - 4, name.length()); - return ".zip".equalsIgnoreCase(ext); - } - return false; - } - - /** - * Test if an url contains the given directory with no recurse seeking. - * - * @param url the url to seek - * @param directory the directory to find - * @return {@code true} if directory was found, {@code false} otherwise. - * @throws IOException if any io pb - */ - public static boolean containsDirectDirectory(URL url, String directory) throws IOException { -// String fileName = url.getFile(); -// // TODO deal with encoding in windows, this is very durty, but it works... -// File file = new File(fileName.replaceAll("%20", " ")); - File file = FileUtils.toFile(url); - String fileName = file.getAbsolutePath(); - if (!file.exists()) { - return false; - } - if (isJar(fileName) || isZip(fileName)) { - // cas ou le fichier du classLoader est un fichier jar ou zip - if (log.isTraceEnabled()) { - log.trace("zip to search " + file); - } - ZipFile zipFile = new ZipFile(file); - try { - return zipFile.getEntry(directory + '/') != null; - } finally { - zipFile.close(); - } - } - if (file.isDirectory()) { - // cas ou le ichier du classLoader est un repertoire - if (log.isTraceEnabled()) { - log.trace("directory to search " + file); - } - return new File(file, directory).exists(); - } - - if (log.isWarnEnabled()) { - log.warn(t("nuitonutil.error.unknown.url.type", url)); - } - return false; - } - - /** - * Return true if {@code str} is a pattern (contains * or ?). - * - * @param str str to test - * @return {@code true} if {@code str} is a pattern, {@code false} otherwise - * @since 2.2 - */ - protected static boolean isPattern(String str) { - return str.indexOf('*') != -1 || str.indexOf('?') != -1; - } - - /** - * Find pattern resouces in {@link ClassLoader#getSystemClassLoader()}. - * - * Usage : - * <pre> - * List<URL> urls = Resources.getResources("META-INF/.*\\.MF"); - * List<URL> urls = Resources.getResources("org/nuiton/util/.?esource\\.class"); - * </pre> - * - * @param pattern java regex style pattern to find - * @return url list found - * @throws IOException if any IO problem while seeking resources - * @since 2.2 - */ - public static List<URL> getResources(String pattern) throws IOException { - return getResources(pattern, null); - } - - /** - * Find pattern resouces in classloader. - * - * Usage : - * <pre> - * List<URL> urls = Resources.getResources("META-INF/.*\\.MF"); - * List<URL> urls = Resources.getResources("org/nuiton/util/.?esource\\.class"); - * </pre> - * - * @param pattern java regex style pattern to find - * @param classLoader classLoader - * @return url list found - * @throws IOException if any IO problem while seeking resources - * @since 2.2 - */ - public static List<URL> getResources(String pattern, - ClassLoader classLoader) throws IOException { - if (classLoader == null) { - classLoader = ClassLoader.getSystemClassLoader(); - } - - List<URL> urlList; - - if (isPattern(pattern)) { - urlList = getPatternRessources(pattern, classLoader); - } else { - urlList = new HashList<URL>(); - Enumeration<URL> resourceUrls = classLoader.getResources(pattern); - while (resourceUrls.hasMoreElements()) { - URL url = resourceUrls.nextElement(); - urlList.add(url); - } - } - - return urlList; - } - - /** - * Obtain some resources from a pattern using a specific class loader to - * seel resources. - * - * @param pattern pattern of searched resources - * @param classLoader class loader which responsible to seek resources - * @return list of resources found - * @throws IOException if any IO problem while scanning resources - * @since 2.2 - */ - protected static List<URL> getPatternRessources(String pattern, - ClassLoader classLoader) throws IOException { - - List<URL> urlList = new HashList<URL>(); - - // get root directory to get URL in classpath - // for example : - // /WEB-INF/*.xml → /WEB-INF/ - // /META-INF/persistence/*.xml → /META-INF/persistence/ - int prefixEnd = pattern.indexOf(":") + 1; - int rootDirEnd = pattern.length(); - while (rootDirEnd > prefixEnd && - isPattern(pattern.substring(prefixEnd, rootDirEnd))) { - rootDirEnd = pattern.lastIndexOf('/', rootDirEnd - 2) + 1; - } - if (rootDirEnd == 0) { - rootDirEnd = prefixEnd; - } - String rootDirPath = pattern.substring(0, rootDirEnd); - String subPattern = pattern.substring(rootDirPath.length()); - - Enumeration<URL> rootDirResources = - classLoader.getResources(rootDirPath); - - while (rootDirResources.hasMoreElements()) { - URL rootDirResource = rootDirResources.nextElement(); - - if (isJarUrl(rootDirResource)) { - // cas ou le ichier du classLoader est un fichier jar - if (log.isDebugEnabled()) { - log.debug("jar to search " + rootDirResource); - } - urlList.addAll(doFindPathMatchingJarResources(rootDirResource, subPattern)); - } else { - urlList.addAll(doFindMatchingFileSystemResources(rootDirResource, subPattern)); - } - } - - return urlList; - } - - /** - * Test if an url detnoe a jar file. - * - * Code taken from spring source code : - * org.springframework.core.io.support.PathMatchingResourcePatternResolver - * - * @param url url to test - * @return true if url denote a jar file - * @since 2.2 - */ - public static boolean isJarUrl(URL url) { - String protocol = url.getProtocol(); - return "jar".equals(protocol) || - "zip".equals(protocol) || - "wsjar".equals(protocol); - } - - /** - * Find all resources in jar files that match the given location pattern - * via the Java Regex style Matcher. - * - * Code taken from spring source code : - * org.springframework.core.io.support.PathMatchingResourcePatternResolver - * - * @param rootDirResource the root directory as Resource - * @param subPattern the sub pattern to match (below the root directory) - * @return the Set of matching Resource instances - * @throws IOException in case of I/O errors - * @see JarURLConnection - * @since 2.2 - */ - protected static List<URL> doFindPathMatchingJarResources(URL rootDirResource, - String subPattern) throws IOException { - - URLConnection con = rootDirResource.openConnection(); - JarFile jarFile; - String jarFileUrl; - String rootEntryPath; - boolean newJarFile = false; - - if (con instanceof JarURLConnection) { - // Should usually be the case for traditional JAR files. - JarURLConnection jarCon = (JarURLConnection) con; - jarCon.setUseCaches(false); - jarFile = jarCon.getJarFile(); - jarFileUrl = jarCon.getJarFileURL().toExternalForm(); - JarEntry jarEntry = jarCon.getJarEntry(); - rootEntryPath = jarEntry != null ? jarEntry.getName() : ""; - } else { - // No JarURLConnection → need to resort to URL file parsing. - // We'll assume URLs of the format "jar:path!/entry", with the protocol - // being arbitrary as long as following the entry format. - // We'll also handle paths with and without leading "file:" prefix. - String urlFile = rootDirResource.getFile(); - int separatorIndex = urlFile.indexOf("!/"); - if (separatorIndex != -1) { - jarFileUrl = urlFile.substring(0, separatorIndex); - rootEntryPath = urlFile.substring(separatorIndex + "!/".length()); - //jarFile = getJarFile(jarFileUrl); - if (jarFileUrl.startsWith("file:")) { - jarFile = new JarFile(jarFileUrl.substring("file:".length())); - } else { - jarFile = new JarFile(jarFileUrl); - } - } else { - jarFile = new JarFile(urlFile); - jarFileUrl = urlFile; - rootEntryPath = ""; - } - newJarFile = true; - } - - try { - if (log.isDebugEnabled()) { - log.debug("Looking for matching resources in jar file [" + jarFileUrl + "]"); - } - if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) { - // Root entry path must end with slash to allow for proper matching. - // The Sun JRE does not return a slash here, but BEA JRockit does. - rootEntryPath = rootEntryPath + "/"; - } - List<URL> result = new HashList<URL>(8); - for (Enumeration<?> entries = jarFile.entries(); entries.hasMoreElements(); ) { - JarEntry entry = (JarEntry) entries.nextElement(); - String entryPath = entry.getName(); - if (entryPath.startsWith(rootEntryPath)) { - String relativePath = entryPath.substring(rootEntryPath.length()); - if (relativePath.matches(subPattern)) { - URL entryURL = new URL(rootDirResource, relativePath); - result.add(entryURL); - } - } - } - return result; - } finally { - // Close jar file, but only if freshly obtained - - // not from JarURLConnection, which might cache the file reference. - if (newJarFile) { - jarFile.close(); - } - } - } - - /** - * Find all resources in the file system that match the given location pattern - * via the Java style matcher. - * - * Code taken from spring source code : - * org.springframework.core.io.support.PathMatchingResourcePatternResolver - * - * @param rootDirResource the root directory as Resource - * @param subPattern the sub pattern to match (below the root directory) - * @return the Set of matching Resource instances - * @throws IOException in case of I/O errors - * @see #retrieveMatchingFiles(File, String) - * @since 2.2 - */ - protected static List<URL> doFindMatchingFileSystemResources(URL rootDirResource, - String subPattern) - throws IOException { - - File rootDir; - try { - rootDir = new File(rootDirResource.toURI().getSchemeSpecificPart()); - rootDir = rootDir.getAbsoluteFile(); - } catch (URISyntaxException ex) { - return Collections.emptyList(); - } - return retrieveMatchingFiles(rootDir, subPattern); - } - - /** - * Retrieve files that match the given path pattern, - * checking the given directory and its subdirectories. - * - * Code taken from spring source code : - * org.springframework.core.io.support.PathMatchingResourcePatternResolver - * - * @param rootDir the directory to start from - * @param pattern the pattern to match against, - * relative to the root directory - * @return the Set of matching File instances - * @throws IOException if directory contents could not be retrieved - * @since 2.2 - */ - protected static List<URL> retrieveMatchingFiles(File rootDir, - String pattern) throws IOException { - if (!rootDir.exists()) { - return Collections.emptyList(); - } - if (!rootDir.isDirectory()) { - return Collections.emptyList(); - } - if (!rootDir.canRead()) { - return Collections.emptyList(); - } - //String fullPattern = StringUtils.replace(rootDir.getAbsolutePath(), File.separator, "/"); - String fullPattern = rootDir.getAbsolutePath().replace(File.separator, "/"); - if (!pattern.startsWith("/")) { - fullPattern += "/"; - } - //fullPattern = fullPattern + StringUtils.replace(pattern, File.separator, "/"); - fullPattern = fullPattern + pattern.replace(File.separator, "/"); - List<URL> result = new HashList<URL>(8); - doRetrieveMatchingFiles(fullPattern, rootDir, result); - return result; - } - - /** - * Recursively retrieve files that match the given pattern, - * adding them to the given result list. - * - * Code taken from spring source code : - * org.springframework.core.io.support.PathMatchingResourcePatternResolver - * - * @param fullPattern the pattern to match against, - * with preprended root directory path - * @param dir the current directory - * @param result the Set of matching File instances to add to - * @throws IOException if directory contents could not be retrieved - * @since 2.2 - */ - protected static void doRetrieveMatchingFiles(String fullPattern, - File dir, - List<URL> result) throws IOException { - if (log.isDebugEnabled()) { - log.debug("Searching directory [" + dir.getAbsolutePath() + - "] for files matching pattern [" + fullPattern + "]"); - } - File[] dirContents = dir.listFiles(); - if (dirContents == null) { - if (log.isWarnEnabled()) { - log.warn("Could not retrieve contents of directory [" + dir.getAbsolutePath() + "]"); - } - return; - } - for (File content : dirContents) { - //String currPath = StringUtils.replace(content.getAbsolutePath(), File.separator, "/"); - String currPath = content.getAbsolutePath().replace(File.separator, "/"); - //if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) { - if (content.isDirectory() && (currPath + "/").matches(fullPattern + ".*")) { - if (!content.canRead()) { - if (log.isDebugEnabled()) { - log.debug("Skipping subdirectory [" + dir.getAbsolutePath() + - "] because the application is not allowed to read the directory"); - } - } else { - doRetrieveMatchingFiles(fullPattern, content, result); - } - } - //if (getPathMatcher().match(fullPattern, currPath)) { - if (currPath.matches(fullPattern)) { - result.add(content.toURI().toURL()); - } - } - } - -} // Resource diff --git a/src/main/java/org/nuiton/util/ResourceException.java b/src/main/java/org/nuiton/util/ResourceException.java deleted file mode 100644 index de00c00..0000000 --- a/src/main/java/org/nuiton/util/ResourceException.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * - * ResourceException.java - * - * Created: 6 nov. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -public class ResourceException extends RuntimeException { // ResourceException - - private static final long serialVersionUID = -5490688835958083084L; - - public ResourceException(String msg) { - super(msg); - } - - public ResourceException(String msg, Throwable e) { - super(msg, e); - } - -} // ResourceException - diff --git a/src/main/java/org/nuiton/util/ResourceNotFoundException.java b/src/main/java/org/nuiton/util/ResourceNotFoundException.java deleted file mode 100644 index fc6487e..0000000 --- a/src/main/java/org/nuiton/util/ResourceNotFoundException.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/** - * ResourceNotFoundException.java - * - * Created: Sun Apr 14 2002 - * - * @author POUSSIN Benjamin <bpoussin@free.fr> - * Copyright Code Lutin - * - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -public class ResourceNotFoundException extends ResourceException { // ResourceNotFoundException - - private static final long serialVersionUID = 623160949107461992L; - - public ResourceNotFoundException(String msg) { - super(msg); - } - - public ResourceNotFoundException(String msg, Throwable e) { - super(msg, e); - } - -} // ResourceNotFoundException diff --git a/src/main/java/org/nuiton/util/ResourceResolver.java b/src/main/java/org/nuiton/util/ResourceResolver.java deleted file mode 100644 index 44a1936..0000000 --- a/src/main/java/org/nuiton/util/ResourceResolver.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.URIResolver; -import javax.xml.transform.stream.StreamSource; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * <p> - * ResourceResolver is a URIResolver for XSL transformation. - * </p> - * <p> - * Its purpose is to catch the XSL document(...) function call and return a - * valid data source only if the wanted resource is present in the project - * resources. - * </p> - * <p>The main goal of ResourceResolver is to retrieve datasources locally, if the - * wanted resource is not present in project resource then null will be - * returned. - * </p> - * The resolve function search for the file part of href parameter: - * <ul> - * <li>href: http://argouml.org/profiles/uml14/default-uml14.xmi</li> - * <li>file part: default-uml14.xmi.</li> - * </ul> - * The resource is searched this way: - * <ul> - * <li>eg: {@code [file part extension]/[file part]}</li> - * <li>eg: {@code xmi/default-uml14.xmi}</li> - * </ul> - * - * You should assign this ResourceResolver on - * {@link Transformer} but not on {@link TransformerFactory}. - * - * @author chorlet - */ -public class ResourceResolver implements URIResolver { - - /** log. */ - private static final Log log = LogFactory.getLog(ResourceResolver.class); - - /** Shared Cache to not search in full classpath at each request. */ - protected static final SortedMap<String, Source> sourceCache = - new TreeMap<String, Source>(); - - /** Shared Cache of not local resources */ - protected static final Set<String> unresolvedCache = new HashSet<String>(); - - /** le pattern de detection d'une uri */ - public static final Pattern HREF_PATTERN = - Pattern.compile("([a-zA-Z]+)\\:\\/\\/(.+)"); - - /** Pour vider le cache partage. */ - public static synchronized void clearCache() { - sourceCache.clear(); - unresolvedCache.clear(); - } - - protected String base; - - /** le niveau de verbosite */ - protected boolean verbose = log.isDebugEnabled(); - - /** le classe loader utilise pour recuperer les resources */ - protected ClassLoader cl = getClass().getClassLoader(); - - public ResourceResolver() { - this(null); - } - - public ResourceResolver(String base) { - if (base != null && base.endsWith("/") && base.length() > 1) { - base = base.substring(0, base.length() - 1); - } - this.base = base; - if (log.isTraceEnabled()) { - log.trace(this + ", base : " + this.base); - } - } - - /** - * Resolve href on local resource. - * - * @return null if local resource not found - */ - @Override - public synchronized Source resolve(String href, String base) { - - if (unresolvedCache.contains(href)) { - // href was already unfound in class-path, - // do not search twice (class-path search can be expensive) - if (verbose) { - log.info("Skip unresolved " + href); - } - return null; - } - - if (sourceCache.containsKey(href)) { - // directly use the cached source, skip all other stuff - if (verbose) { - log.info("use cached source " + href); - } - return sourceCache.get(href); - } - - // at this point, the href is undiscovered, try to find in in class-path - - - if (verbose) { - log.info("Resolving " + href); - } - - // URI : - // example 1 : pathmap://UML_METAMODELS/UML.metamodel.uml - // example 2 : http://argouml.org/profiles/uml14/default-java.xmi - - // relative path : - // example 3 : xxx/zzz/ttt.uml - - Source source; - - // if URI - Matcher matcher = HREF_PATTERN.matcher(href); - if (matcher.matches()) { -// String protocol = matcher.group(1); - String path = matcher.group(2); - // try look only with the filename - // this is the last chance to find something :) - source = findHrefSource(path); - } else { - - // no protocol, so should be a relative path location - source = findRelativeSource(href); - } - - if (source == null) { - // means this resolver was not able to find the source - if (verbose) { - log.info("detect unresolved source " + href); - } - unresolvedCache.add(href); - } else { - // find a new cacheable source, add it in cache - if (verbose) { - log.info("detect cacheable source " + href); - } - sourceCache.put(href, source); - } - -// if (href.matches("[a-zA-Z]+://.+")) { -// String filename = null; -// int beginIndex = href.lastIndexOf('/'); -// if (beginIndex > -1) { -// filename = href.substring(beginIndex + 1); -// } -// if (filename != null && !filename.isEmpty()) { -// source = findSource(filename, true); -// } -// } else { -// source = findSource(href, false); -// } - return source; - } - - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - public void setCl(ClassLoader cl) { - this.cl = cl; - } - - protected Source findHrefSource(String path) { - long t0 = System.nanoTime(); - String filename; - int beginIndex = path.lastIndexOf('/'); - if (beginIndex > -1) { - filename = path.substring(beginIndex + 1); - } else { - filename = path; - } - if (filename == null || filename.isEmpty()) { - return null; - } - String resource; - - resource = ".*/" + filename; - - if (verbose) { - log.info("will discover " + resource); - } - - URL url = null; - - // use given classloader to work in maven - List<URL> urls = null; - URLClassLoader ucl = null; - if (cl == null) { - ClassLoader cl2 = getClass().getClassLoader(); - if (cl2 instanceof URLClassLoader) { - ucl = (URLClassLoader) cl2; - } - } - if (cl instanceof URLClassLoader) { - ucl = (URLClassLoader) cl; - } - try { - urls = Resource.getURLs(resource, ucl); - } catch (ResourceNotFoundException rnfe) { - // Nothing to do - } - - if (urls != null && !urls.isEmpty()) { - url = urls.get(0); - } - - - Source source = null; - - if (url != null) { - if (verbose) { - log.info(url.toString()); - } - source = new StreamSource(url.toString()); - } - if (verbose) { - String time = StringUtil.convertTime(System.nanoTime() - t0); - log.info("resolved in " + time); - } - return source; - } - - protected Source findRelativeSource(String path) { - long t0 = System.nanoTime(); - String filename = path; -// int beginIndex = path.lastIndexOf('/'); -// if (beginIndex > -1) { -// filename = path.substring(beginIndex + 1); -// } else { -// filename = path; -// } -// if (filename == null || filename.isEmpty()) { -// return null; -// } - String resource; - if (base != null) { - resource = base + "/" + filename; - } else { - resource = filename; - } - - if (verbose) { - log.info("will discover " + resource); - } - - URL url = Resource.getURLOrNull(resource); - - Source source = null; - - if (url != null) { - if (verbose) { - log.info(url.toString()); - } - source = new StreamSource(url.toString()); - } - if (verbose) { - String time = StringUtil.convertTime(System.nanoTime() - t0); - log.info("resolved in " + time); - } - return source; - } -} diff --git a/src/main/java/org/nuiton/util/ReverseFileReader.java b/src/main/java/org/nuiton/util/ReverseFileReader.java deleted file mode 100644 index 6660598..0000000 --- a/src/main/java/org/nuiton/util/ReverseFileReader.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin, Chatellier Eric - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; - -/** - * Reverse file reader. - * - * Read file line by line for end of file to begin of file. - * - * @author chatellier - */ -public class ReverseFileReader implements Closeable { - protected String filename; - - protected RandomAccessFile randomfile; - - protected long position; - - public ReverseFileReader(File file) throws IOException { - // Open up a random access file - randomfile = new RandomAccessFile(file, "r"); - // Set our seek position to the end of the file - position = randomfile.length(); - - // Seek to the end of the file - randomfile.seek(position); - //Move our pointer to the first valid position at the end of the file. - String thisLine = randomfile.readLine(); - while (thisLine == null) { - position--; - randomfile.seek(position); - thisLine = randomfile.readLine(); - randomfile.seek(position); - } - } - - public ReverseFileReader(String filename) throws IOException { - this(filename != null ? new File(filename) : null); - } - - /** - * Read one line from the current position towards the beginning. - * - * @return the next line of text from this file, or null if end of file is - * encountered before even one byte is read. - * @throws IOException if any pb while reading line - */ - public String readLine() throws IOException { - int thisCode; - char thisChar; - String finalLine = ""; - - // If our position is less than zero already, we are at the beginning - // with nothing to return. - if (position < 0) { - return null; - } - - for (; ; ) { - // we've reached the beginning of the file - if (position < 0) { - break; - } - // Seek to the current position - randomfile.seek(position); - - // Read the data at this position - thisCode = randomfile.readByte(); - thisChar = (char) thisCode; - - // If this is a line break or carrige return, stop looking - if (thisCode == 13 || thisCode == 10) { - // See if the previous character is also a line break character. - // this accounts for crlf combinations - randomfile.seek(position - 1); - int nextCode = randomfile.readByte(); - if (thisCode == 10 && nextCode == 13 - || thisCode == 13 && nextCode == 10) { - // If we found another linebreak character, ignore it - position = position - 1; - } - // Move the pointer for the next readline - position--; - break; - } else { - // This is a valid character append to the string - finalLine = thisChar + finalLine; - } - // Move to the next char - position--; - } - // return the line - return finalLine; - } - - @Override - public void close() throws IOException { - if (randomfile != null) { - randomfile.close(); - } - } - - @Override - protected void finalize() throws Throwable { - close(); - super.finalize(); - } -} diff --git a/src/main/java/org/nuiton/util/SemVer.java b/src/main/java/org/nuiton/util/SemVer.java deleted file mode 100644 index 6cf5ea2..0000000 --- a/src/main/java/org/nuiton/util/SemVer.java +++ /dev/null @@ -1,676 +0,0 @@ -package org.nuiton.util; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.Validate; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Implantation de http://semver.org/. - * <p> - * Cette objet est immutable, Il faut utiliser {@link #getCreator()} - * pour modifier un de ses elements - * <p> - * Quelques changement par rapport au site: - * <ul> - * <li> le numero de version peut avoir entre 1 et N element, et non pas 3 obligatoirement - * <li> on peut avoir un -SNAPSHOT ajoute en toute fin de la version - * </ul> - * <p> - * Un SemVer est en plusieurs elements dont chaque element peut avoir plusieurs - * composant. Les composants sont utilise le meme separateur '.'. - * <ul> - * <li> version: 1 à N composant numerique, les 3 premiers sont nomme - * <ul> - * <li> major - * <li> minor - * <li> patch - * </ul> - * <li> prerelease: 0 à N composant alphanumerique, le prefix est '-' - * <li> build: 0 à N composant alphanumerique, le prefix est '+' - * <li> SNAPSHOT: 0 ou 1 composant dont le nom est fixe le prefix est '-' - * </ul> - * Le mieux pour construire ou modifier un SemVer est d'utilise une methode creator: - * <ul> - * <li> SemVer.creator(1,2,3).done() → "1.2.3" - * <li> SemVer.creator("1.2.3","rc2").done() → "1.2.3-rc2" - * <li> SemVer.creator().setVersion(2.3.4).setBuild("r223").done() → "2.3.4+r223" - * <li> SemVer.creator().setVersion(2.3.4).setSnapshot(true).done() → "2.3.4-SNAPSHOT" - * <li> SemVer.creator(new SemVer("1.2.3")).incMajor().done() → "2.2.2" - * <li> new SemVer("1.2.3").getCreator().incMinor().setPrerelease(beta).done() → "1.3.3-beta" - * </ul> - * - * @author Benjamin Poussin - poussin@codelutin.com - * @since 2.6.7 - * @deprecated since 3.0 (use now {@link org.nuiton.util.version.SemVer}). - */ -@Deprecated -public class SemVer implements Comparable<SemVer> { - - /** - * Logger. - */ - static private Log log = LogFactory.getLog(SemVer.class); - - /** - * Separateur utiliser entre chaque element d'une partie - */ - final static public String SERIES_SEPARATOR = "."; // le separateur - /** - * Seperateur entre la version et l'element prerelease - */ - final static public String PRERELEASE_SEPARATOR = "-"; // le separateur de Prerelease - /** - * Separateur utiliser devant l'element build - */ - final static public String BUILD_SEPARATOR = "+"; // le separateur de build - - /** - * pattern pour une partie de l'element version - */ - final static public String PATTERN_VERSION = "[0-9]+"; // le version ne sont que des nombres - /** - * pattern pour une partie de l'element prerelease - */ - final static public String PATTERN_PRERELEASE = "[0-9A-Za-z-]+"; // les Prerelease sont des chiffre, lettre ou '-' - /** - * pattern pour une partir de l'element build - */ - final static public String PATTERN_BUILD = "[0-9A-Za-z-]+";// les Build sont des chiffre, lettre ou '-' - - /** - * Separateur de SNAPSHOT - */ - final static public String SNAPSHOT_SEPARATOR = "-"; - /** - * la chaine de caractere representant le SNAPSHOT - */ - final static public String SNAPSHOT = "SNAPSHOT"; - - // "(1.20.300)(-alpha-1.20)?(+r123.20130126)?" - // version prerelease build - /** - * pattern qui permet de separer les 3 constituante d'une version, ne - * supporte pas le SNAPSHOT, il faut donc que le SNAPSHOT ait ete retirer - * avant d'appliquer le pattern - */ - final static Pattern PATTERN_ALL = Pattern.compile( - "(" + PATTERN_VERSION + "(?:" + Pattern.quote(SERIES_SEPARATOR) + PATTERN_VERSION + ")*)" + - "(" + Pattern.quote(PRERELEASE_SEPARATOR) + PATTERN_PRERELEASE + "(?:" + Pattern.quote(SERIES_SEPARATOR) + PATTERN_PRERELEASE + ")*)?" + - "(" + Pattern.quote(BUILD_SEPARATOR) + PATTERN_BUILD + "(?:" + Pattern.quote(SERIES_SEPARATOR) + PATTERN_BUILD + ")*)?"); - - protected String version; - protected String prerelease; - protected String build; - protected String snapshot; - - /** - * Create new Version object, strip is done on argument to remove extra space - * - * @param versionString FIXME - * @throws IllegalArgumentException if argument isn't valid version string - */ - public SemVer(String versionString) { - String v = StringUtils.strip(versionString); // on conserve versionString intact pour le message d'erreur - if (StringUtils.endsWithIgnoreCase(v, SNAPSHOT_SEPARATOR + SNAPSHOT)) { - snapshot = SNAPSHOT; - v = StringUtils.substringBeforeLast(v, SNAPSHOT_SEPARATOR); - } - Matcher matcher = PATTERN_ALL.matcher(v); - boolean match = matcher.matches(); - if (match) { - version = matcher.group(1); - prerelease = StringUtils.removeStart(matcher.group(2), PRERELEASE_SEPARATOR); - build = StringUtils.removeStart(matcher.group(3), BUILD_SEPARATOR); - } else { - throw new IllegalArgumentException(String.format("Bad version string: '%s'", versionString)); - } - } - - /** - * @param o the other version to test - * @return {@code true} if current version is before the given one - */ - public boolean before(SemVer o) { - int result = compareTo(o); - return result < 0; - } - - /** - * @param o the other version to test - * @return {@code true} if current version is after the given one - */ - public boolean after(SemVer o) { - int result = compareTo(o); - return result > 0; - } - - public int compareTo(SemVer other) { - int result = compare(this.getVersion(), other.getVersion(), false); - if (result == 0) { - result = compare(this.getPrerelease(), other.getPrerelease(), true); - if (result == 0) { - result = compare(this.getBuild(), other.getBuild(), false); - if (result == 0) { - result = compare(this.getSnapshot(), other.getSnapshot(), true); - } - } - } - return result; - } - - /** - * Compare deux elements de meme semantique (version, prerelease, build, snapshot) - * sinon le comportement est non predictible - * - * @param a FIXME - * @param b FIXME - * @param nullIsHigh indique si un des elements est null, s'il est plus - * grand ou plus petit que l'autre - * @return negatif si a inferieur b, 0 si a == b, positif si a superieur a b - */ - protected int compare(String a, String b, boolean nullIsHigh) { - int result; - if (nullIsHigh) { - result = nullIsHigh(a, b); - } else { - result = nullIsLow(a, b); - } - - if (result == 0 && a != null && b != null) { - // on decoupe suivant le '.' - String[] aSeries = StringUtils.split(a, SERIES_SEPARATOR); - String[] bSeries = StringUtils.split(b, SERIES_SEPARATOR); - - int length = Math.max(aSeries.length, bSeries.length); - for (int i = 0; result == 0 & i < length; i++) { - // s'il y en a un qui est plus court, on prend par defaut "" - String va = i < aSeries.length ? aSeries[i] : ""; - String vb = i < bSeries.length ? bSeries[i] : ""; - - // s'il n'y a que des nombres pour une valeur on ajoute des espaces - // devant pour qu'il est la meme longueur que l'autre et ainsi - // pouvoir les comparer lexicographiquement - int pad = Math.max(va.length(), vb.length()); - if (StringUtils.isNumeric(va)) { - va = StringUtils.leftPad(va, pad); - } - if (StringUtils.isNumeric(vb)) { - vb = StringUtils.leftPad(vb, pad); - } - - // on compare les deux valeurs - result = va.compareTo(vb); - } - } - return result; - } - - /** - * Ne compare par le chaine, seulement la nullite, si un des arguments - * est null, alors il est plus grand que l'autre. - * <p> - * 1.0 est plus grand que 1.0-Beta - * - * @param a FIXME - * @param b FIXME - * @return FIXME - */ - protected int nullIsHigh(String a, String b) { - int result = 0; - if (a == null ^ b == null) { - if (a == null) { - result = 1; - } else { - result = -1; - } - } - return result; - } - - /** - * Ne compare par le chaine, seulement la nullite, si un des arguments - * est null, alors il est plus petit que l'autre. - * <p> - * 1.0+r123 est plus grand que 1.0 - * - * @param a FIXME - * @param b FIXME - * @return FIXME - */ - protected int nullIsLow(String a, String b) { - int result = 0; - if (a == null ^ b == null) { - if (a == null) { - result = -1; - } else { - result = 1; - } - } - return result; - } - - /** - * Donne le nombre de composante de l'element - * <ul> - * <li>1.2.3 retourne 3 - * <li>99.100 retourne 2 - * </ul> - * - * @param element FIXME - * @return FIXME - */ - protected int getComposantCount(String element) { - int result = 0; - if (StringUtils.isNotBlank(element)) { - result = 1 + StringUtils.countMatches(element, SERIES_SEPARATOR); - } - return result; - } - - /** - * Retourne un des composants de l'element version - * - * @param element FIXME - * @param i FIXME - * @return FIXME - */ - protected String getComposant(String element, int i) { - String[] v = StringUtils.split(element, SERIES_SEPARATOR); - Validate.validIndex(v, i, - "Ask '%s', element '%s' don't have enought composant", i, element); - - String s = v[i]; - return s; - } - - - public String getVersion() { - return version; - } - - /** - * Donne le nombre de composante de la version - * <ul> - * <li>1.2.3 retourne 3 - * <li>99.100 retourne 2 - * </ul> - * - * @return FIXME - */ - public int getVersionCount() { - int result = getComposantCount(getVersion()); - return result; - } - - /** - * Retourne un des composants de l'element version - * - * @param i FIXME - * @return FIXME - */ - public String getVersion(int i) { - String s = getComposant(getVersion(), i); - return s; - } - - public String getMajor() { - String result = getVersion(0); - return result; - } - - public String getMinor() { - String result = getVersion(1); - return result; - } - - public String getPatch() { - String result = getVersion(2); - return result; - } - - public String getPrerelease() { - return prerelease; - } - - /** - * Donne le nombre de composante de la Prerelease - * <ul> - * <li>1.2.3 retourne 3 - * <li>99.100 retourne 2 - * </ul> - * - * @return FIXME - */ - public int getPrereleaseCount() { - int result = getComposantCount(getPrerelease()); - return result; - } - - /** - * Retourne un des composants de l'element version - * - * @param i FIXME - * @return FIXME - */ - public String getPrerelease(int i) { - String s = getComposant(getPrerelease(), i); - return s; - } - - public String getBuild() { - return build; - } - - /** - * Donne le nombre de composante de la Prerelease - * <ul> - * <li>1.2.3 retourne 3 - * <li>99.100 retourne 2 - * </ul> - * - * @return FIXME - */ - public int getBuildCount() { - int result = getComposantCount(getBuild()); - return result; - } - - /** - * Retourne un des composants de l'element version - * - * @param i FIXME - * @return FIXME - */ - public String getBuild(int i) { - String s = getComposant(getBuild(), i); - return s; - } - - public String getSnapshot() { - return snapshot; - } - - public boolean isSnapshot() { - return StringUtils.isNotBlank(snapshot); - } - - static protected String ifNotNull(String prefix, String s) { - String result = ""; - if (StringUtils.isNotBlank(s)) { - result = prefix + s; - } - return result; - } - - @Override - public boolean equals(Object o) { - boolean result = o instanceof SemVer && this.compareTo((SemVer) o) == 0; - return result; - } - - @Override - public int hashCode() { - return toString().hashCode(); - } - - /** - * Convertit la representation textuelle de la version en identifiant java valide : - * - en java : "-" "." "+" interdit - * - * @return la valeur ou les carateres interdits sont remplaces par '_' - */ - public String toJavaIdentifier() { - String result = toString(); - - // attention dans les crochets le '-' a une signification, il faut donc le mettre en 1er - result = result.replaceAll("[-+.]", "_"); - - return result; - } - - @Override - public String toString() { - return getVersion() - + ifNotNull(PRERELEASE_SEPARATOR, getPrerelease()) - + ifNotNull(BUILD_SEPARATOR, getBuild()) - + ifNotNull(SNAPSHOT_SEPARATOR, getSnapshot()); - } - - /** - * Retourne un objet creator initialise avec les donnees de ce SemVer - * ce qui permet de creer un nouveau SemVer en modifiant un des elements - * - * @return FIXME - */ - public SemVerCreator getCreator() { - return creator(this); - } - - /** - * Indique si la chaine represente bien une version au format SemVer - * - * @param version FIXME - * @return FIXME - */ - static public boolean isSemVer(String version) { - if (StringUtils.endsWithIgnoreCase(version, SNAPSHOT)) { - version = StringUtils.substringBeforeLast(version, SNAPSHOT); - } - Matcher matcher = PATTERN_ALL.matcher(version); - boolean result = matcher.matches(); - return result; - } - - /** - * Permet de creer un objet version. Si des arguments sont passer en parametre - * ils sont pris dans l'ordre pour: la version, la prerelease, le build, le snapshot - * <pre> - * SemVer v = SemVer.creator().setVersion("1.2").setPrerelease("beta.1").setBuild("r123").done(); - * SemVer v = SemVer.creator("1.2", "beta.1","r123", SemVer.SNAPSHOT).done(); - * </pre> - * - * @param v FIXME - * @return FIXME - */ - static public SemVerCreator creator(String... v) { - SemVerCreator result = new SemVerCreator(); - if (v != null) { - if (v.length > 0) { - result.setVersion(v[0]); - if (v.length > 1) { - result.setPrerelease(v[1]); - if (v.length > 2) { - result.setBuild(v[2]); - if (v.length > 3) { - if (v[3] == null) { - result.setSnapshot(false); - } else if (StringUtils.equalsIgnoreCase(SNAPSHOT, v[3])) { - result.setSnapshot(true); - } else { - throw new IllegalArgumentException(String.format( - "Illegal SNAPSHOT string '%s'", - v[3])); - } - if (v.length > 4) { - throw new IllegalArgumentException(String.format( - "too many string arguments '%s' maximum 4", - v.length)); - } - } - } - } - } - } - return result; - } - - /** - * Createur qui permet de passer en parametre les different composante de - * l'element version - * - * @param v FIXME - * @return FIXME - */ - static public SemVerCreator creator(int... v) { - SemVerCreator result = creator(StringUtils.join(v, SERIES_SEPARATOR)); - return result; - } - - /** - * Create creator initialized with SemVer value, you can change some Element - * by puting null value. - * <p> - * SemVer n = SemVer.creator(v).setBuild("r123").setSnapshot(false).done(); - * - * @param v FIXME - * @return FIXME - */ - static public SemVerCreator creator(SemVer v) { - SemVerCreator result = creator( - v.getVersion(), v.getPrerelease(), v.getBuild(), v.getSnapshot()); - return result; - } - - /** - * Retourne un Createur sans aucune information. Cette methode permet - * aussi de desambiguise les deux autres methode creator qui si elle - * n'ont pas de parametre sont semblable - * - * @return FIXME - */ - static public SemVerCreator creator() { - SemVerCreator result = new SemVerCreator(); - return result; - } - - /** - * Construit un objet version, la verification de la coherence est faite lors - * de l'appel du create. - */ - static public class SemVerCreator { - protected String version; - protected String prerelease; - protected String build; - protected String snapshot; - - public SemVerCreator setVersion(Integer... v) { - // l'argument est bien Integer, car join ne travail qu'avec des objets :( - version = StringUtils.join(v, SERIES_SEPARATOR); - return this; - } - - public SemVerCreator setVersion(String v) { - version = v; - return this; - } - - public SemVerCreator setPrerelease(String v) { - prerelease = v; - return this; - } - - public SemVerCreator setBuild(String v) { - build = v; - return this; - } - - public SemVerCreator setSnapshot(boolean b) { - if (b) { - snapshot = SNAPSHOT; - } else { - snapshot = null; - } - return this; - } - - /** - * Incremente la composante 'indice' de l'element version de 'inc', la composante - * doit representer un entier sinon une exception est leve - * - * @param indice la composante de la version a incrementer - * @param inc le nombre a lui ajouter - * @return new instance, this SemVer is not modified - */ - public SemVerCreator incVersion(int indice, int inc) { - String[] v = StringUtils.split(version, SERIES_SEPARATOR); - Validate.validIndex(v, indice, "Version don't have enought composant"); - - String s = v[indice]; - - Validate.isTrue(StringUtils.isNumeric(s), "String '%s' must be numeric", s); - int i = Integer.parseInt(s); - i += inc; - s = String.valueOf(i); - - v[indice] = s; - version = StringUtils.join(v, SERIES_SEPARATOR); - - return this; - } - - /** - * Return new instance, this SemVer is not modified - * - * @return new instance where major version number is incremented by 1 - */ - public SemVerCreator incMajor() { - return incVersion(0, 1); - } - - /** - * Return new instance, this SemVer is not modified - * - * @return new instance where major version number is incremented by 1 - */ - public SemVerCreator incMinor() { - return incVersion(1, 1); - } - - /** - * Return new instance, this SemVer is not modified - * - * @return new instance where major version number is incremented by 1 - */ - public SemVerCreator incPatch() { - return incVersion(2, 1); - } - - public SemVer done() { - SemVer result = new SemVer( - StringUtils.defaultString(version) + - ifNotNull(PRERELEASE_SEPARATOR, prerelease) + - ifNotNull(BUILD_SEPARATOR, build) + - ifNotNull(SNAPSHOT_SEPARATOR, snapshot) - ); - return result; - } - } - -} diff --git a/src/main/java/org/nuiton/util/SortedProperties.java b/src/main/java/org/nuiton/util/SortedProperties.java deleted file mode 100644 index 08c235e..0000000 --- a/src/main/java/org/nuiton/util/SortedProperties.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.Properties; -import java.util.Vector; - -/** - * Permet d'avoir les propriétés triées. - * - * @author Julien Ruchaud - ruchaud@codelutin.com - * - */ -public class SortedProperties extends Properties { - - private static final long serialVersionUID = -1147150444452577558L; - - - public SortedProperties() { - } - - public SortedProperties(Properties defaults) { - super(defaults); - } - - @Override - public synchronized Enumeration<Object> keys() { - List<Object> objects = Collections.list(super.keys()); - Vector<Object> result; - try { - // Attention, si les clef ne sont pas des string, ca ne marchera pas - List<String> list = CollectionUtil.toGenericList(objects, - String.class); - Collections.sort(list); - result = new Vector<Object>(list); - } catch (IllegalArgumentException e) { - // keys are not string !!! - // can not sort keys - result = new Vector<Object>(objects); - } - return result.elements(); - } -} diff --git a/src/main/java/org/nuiton/util/StringUtil.java b/src/main/java/org/nuiton/util/StringUtil.java deleted file mode 100644 index 336db40..0000000 --- a/src/main/java/org/nuiton/util/StringUtil.java +++ /dev/null @@ -1,771 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin, Chatellier Eric - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.lang3.SystemUtils; - -import java.awt.Color; -import java.lang.reflect.Field; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.DateFormat; -import java.text.MessageFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Locale; - -/** - * Classe contenant un ensemle de methode static utiles pour la manipulation des - * chaine de caractere mais qui ne sont pas defini dans la classe String de - * Java. - * - * Created: 21 octobre 2003 - * - * @author Benjamin Poussin - poussin@codelutin.com - * @author Tony Chemit - chemit@codelutin.com - * - */ -public class StringUtil { // StringUtil - - public static final String[] EMPTY_STRING_ARRAY = new String[0]; - - /** Constructor for the StringUtil object */ - protected StringUtil() { - } - - /** - * Know if a string is a valid e-mail. - * - * @param str a string - * @return true if {@code str} is syntactically a valid e-mail address - * @since 2.1 - */ - public static boolean isEmail(String str) { - return str.matches("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+((\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)?)+@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?$"); - } - - /** - * Add quotes if needed to escape special csv chars (',', '\n', '\t', ',', ';', '"') - * - * @param value to escape - * @param csvSeparator separator used for csv - * @return escaped if needed value - */ - public static String escapeCsvValue(String value, String csvSeparator) { - - boolean valueNeedQuotes = - value.contains("\n") - || value.contains("\t") - || value.contains(",") - || value.contains(";") - || value.contains("\"") - || value.contains(csvSeparator); - - if (valueNeedQuotes) { - // escape '"' char to prevent - value = value.replaceAll("\"", "\"\""); - value = "\"" + value + "\""; - } - return value; - } - - /** - * Contract to use in {@link StringUtil#join(Iterable, ToString, String, boolean) } - * method. This will provide a toString method to convert an object in a - * string. - * - * @param <O> type of object manipulated - */ - public interface ToString<O> { - - /** - * Convert an object o in a string. - * - * @param o to convert - * @return the string for this object o - */ - String toString(O o); - } - - /** - * Used to build csv file using {@link StringUtil#join(Iterable, ToString, String, boolean) } - * method. This will provide a toString method to convert an object in a - * string and escape csv values if needed. - * - * @param <O> type of object manipulated - */ - public static class ToCSV<O> implements StringUtil.ToString<O> { - - protected String csvSeparator; - - public ToCSV(String csvSeparator) { - this.csvSeparator = csvSeparator; - } - - @Override - public String toString(O o) { - String value = getStringValue(o); - return escapeCsvValue(value, csvSeparator); - } - - /** - * Use {@link Object#toString()} method by default - * Must be override to use other methods to get string value. - * - * @param o to convert - * @return String value - */ - public String getStringValue(O o) { - return o.toString(); - } - } - - /** - * Used to concat an {@code iterable} of Object separated - * by {@code separator} using the toString() method of each object. - * You can specify if the string must be trimmed or not. - * - * @param iterable Iterable with objects to treate - * @param separator to used - * @param trim if each string must be trim - * @return the String chain of all elements separated by separator, never - * return null, will return an empty String for an empty list. - */ - public static String join(Iterable<?> iterable, String separator, - boolean trim) { - String result = join(iterable, null, separator, trim); - return result; - } - - /** - * Used to concat an {@code iterable} of object {@code <O>} separated by - * {@code separator}. This method need a {@code ts} contract to - * call on each object. The ToString can be null to use directly the - * toString() method on the object. The {@code trim} boolean is used - * to specify if each string object has to be trimmed. The null elements - * in the {@code list} will be ignored. - * - * @param <O> type of object in the list - * @param iterable Iterable with objects to treate - * @param ts used to specify how the object is converted in String - * @param separator to used between each object string - * @param trim if trim() method need to by apply on each object string - * @return the String chain of all elements separated by separator, never - * return null, will return an empty String for an empty list. - * @throws NullPointerException if iterable is {@code null}. - */ - public static <O> String join(Iterable<O> iterable, ToString<O> ts, - String separator, boolean trim) throws NullPointerException { - if (iterable == null) { - throw new NullPointerException("null iterable can't be used" + - " to join the elements with " + separator); - } - // Do nothing for an empty list - if (!iterable.iterator().hasNext()) { - return ""; - } - StringBuilder builder = new StringBuilder(); - for (O o : iterable) { - // Ignore the null object in the list - if (o == null) { - continue; - } - String str; - // Use ToString contract from argument - if (ts != null) { - str = ts.toString(o); - // Or call toString() method directly on object - } else { - str = o.toString(); - } - // Apply trim if needed - if (trim) { - str = str.trim(); - } - builder.append(separator).append(str); - } - // Suppress the first separator at beginning of the chain - String result = builder.substring(separator.length()); - return result; - } - - /** - * substring from begin to end of s - * - * example: - * substring("tatetitotu", -4) → totu - * - * @param s the string to substring - * @param begin if begin < 0 then begin start at end of string - begin - * @return the result of substring - */ - public static String substring(String s, int begin) { - String result = substring(s, begin, s.length()); - return result; - } - - /** - * substring from begin to end of s - * - * example: - * substring("tatetitotu", -4, -2) → to - * - * @param s the string to substring - * @param begin if begin < 0 then begin start at end of string - begin - * @param end if end < 0 then end start at end of string - end - * @return the result of substring - */ - public static String substring(String s, int begin, int end) { - if (begin < 0) { - begin = s.length() + begin; - } - if (end < 0) { - end = s.length() + end; - } - if (end < begin) { - end = begin; - } - - String result; - result = s.substring(begin, end); - return result; - } - - private static final Character[] openingChars = {'(', '{', '['}; - - private static final Character[] closingChars = {')', '}', ']'}; - - /** - * Split string use 'separator' as separator. If String contains "'()[]{} - * this method count the number of open char end close char to split - * correctly argument - * - * WARNING: cette method ne fonctionne pas si le contenu contient - * des carateres utilisé pour le parsing et présent une seule fois. - * Par exemple: "l'idenfiant" contient ' qui empeche totalement le - * parsing de fonctionner. - * - * @param args string to split - * @param separator separator use to split string - * @return array of string - */ - public static String[] split(String args, String separator) { - return split(openingChars, closingChars, args, separator); - } - - - /** - * Use to split string array representation in array according with ',' as - * default separator. - * - * WARNING: cette method ne fonctionne pas si le contenu contient - * des carateres utilisé pour le parsing et présent une seule fois. - * Par exemple: "l'idenfiant" contient ' qui empeche totalement le - * parsing de fonctionner. - * - * @param stringList string that represent array - * @return array with length > 0 if listAsString ≠ null or null - */ - public static String[] split(String stringList) { - String[] result; - result = split(stringList, ","); - return result; - } - - /** - * Split string use 'separator' as separator. If String contains "' - * and {@code openingChar} {@code closingChars} - * - * this method count the number of open char end close char to split - * correctly argument - * - * WARNING: cette method ne fonctionne pas si le contenu contient - * des carateres utilisé pour le parsing et présent une seule fois. - * Par exemple: "l'idenfiant" contient ' qui empeche totalement le - * parsing de fonctionner. - * - * @param openingChars list of opening caracteres - * @param closingChars list of closing caracteres - * @param args string to split - * @param separator separator use to split string - * @return array of string - */ - public static String[] split(Character[] openingChars, - Character[] closingChars, - String args, String separator) { - if (args == null) { - return EMPTY_STRING_ARRAY; - } - - List<String> result = new ArrayList<String>(); - - int start = 0; - int end; - StringBuilder op = new StringBuilder(); // stack of {([< currently open - char last = '\0'; // contains " or ' if string is openned - - List<Character> opening = Arrays.asList(openingChars); - - List<Character> closing = Arrays.asList(closingChars); - - for (int i = 0; i < args.length(); i++) { - char c = args.charAt(i); - if (c == '\\') { - // pass next char - i++; - } else if (last != '"' && last != '\'') { - if (opening.contains(c)) { - op.append(c); - } else if (closing.contains(c)) { - op.deleteCharAt(op.length() - 1); - } else if (c == '"' || c == '\'') { - // open string " or ' - last = c; - } else if (op.length() == 0 && - args.regionMatches(i, separator, 0, - separator.length())) { - // end of one arguement - end = i; - // pass separator - i += separator.length() - 1; - - String a = args.substring(start, end); - result.add(a); - // start of next argument - start = end + separator.length(); - } - } else if (c == last) { - // close string " or ' - last = '\0'; - } - } - - if (start < args.length()) { - String a = args.substring(start, args.length()); - result.add(a); - } - - return result.toArray(new String[result.size()]); - } - - public static boolean toBoolean(String s) { - return "true".equalsIgnoreCase(s); - } - - public static byte toByte(String s) { - return Byte.parseByte(s); - } - - public static double toDouble(String s) { - return Double.parseDouble(s); - } - - public static float toFloat(String s) { - return Float.parseFloat(s); - } - - public static long toLong(String s) { - return Long.parseLong(s); - } - - public static short toShort(String s) { - return Short.parseShort(s); - } - - public static int toInt(String s) { - return Integer.parseInt(s); - } - - public static char toChar(String s) { - // fixme a revoir - return s.charAt(0); - } - - public static boolean[] toArrayBoolean(String... s) { - boolean[] result = new boolean[s.length]; - for (int i = 0; i < result.length; i++) { - result[i] = toBoolean(s[i]); - } - return result; - } - - public static byte[] toArrayByte(String... s) { - byte[] result = new byte[s.length]; - for (int i = 0; i < result.length; i++) { - result[i] = toByte(s[i]); - } - return result; - } - - public static double[] toArrayDouble(String... s) { - double[] result = new double[s.length]; - for (int i = 0; i < result.length; i++) { - result[i] = toDouble(s[i]); - } - return result; - } - - public static float[] toArrayFloat(String... s) { - float[] result = new float[s.length]; - for (int i = 0; i < result.length; i++) { - result[i] = toFloat(s[i]); - } - return result; - } - - public static long[] toArrayLong(String... s) { - long[] result = new long[s.length]; - for (int i = 0; i < result.length; i++) { - result[i] = toLong(s[i]); - } - return result; - } - - public static short[] toArrayShort(String... s) { - short[] result = new short[s.length]; - for (int i = 0; i < result.length; i++) { - result[i] = toShort(s[i]); - } - return result; - } - - public static int[] toArrayInt(String... s) { - int[] result = new int[s.length]; - for (int i = 0; i < result.length; i++) { - result[i] = toInt(s[i]); - } - return result; - } - - public static char[] toArrayChar(String... s) { - char[] result = new char[s.length]; - for (int i = 0; i < result.length; i++) { - result[i] = toChar(s[i]); - } - // fixme a revoir - return result; - } - - private static final char[] HEX_CHARS = {'0', '1', '2', '3', - '4', '5', '6', '7', - '8', '9', 'a', 'b', - 'c', 'd', 'e', 'f',}; - - /** - * Turns array of bytes into string representing each byte as - * unsigned hex number. - * - * @param hash Array of bytes to convert to hex-string - * @return Generated hex string - */ - public static String asHex(byte hash[]) { - char buf[] = new char[hash.length * 2]; - for (int i = 0, x = 0; i < hash.length; i++) { - buf[x++] = HEX_CHARS[hash[i] >>> 4 & 0xf]; - buf[x++] = HEX_CHARS[hash[i] & 0xf]; - } - return new String(buf); - } - - /** - * Essai de convertir une chaine de caractere en une couleur si possible si - * ce n'est pas possible retourne null. - * - * @param s la couleur sous la forme de string, par exemple "red", - * "yellow" ou bien en RGB "#FFAA99", et avec un canal alpha - * "#FFAA3366" - * @return la couleur demandé si possible sinon null - * @throws IllegalArgumentException FIXME - * @throws StringUtilException if any problem while conversion - */ - public static Color toColor(String s) throws StringUtilException { - try { - if (s.startsWith("#")) { - // récuperation des valeurs hexa - String hr = s.substring(1, 3); - String hg = s.substring(3, 5); - String hb = s.substring(5, 7); - - // conversion en entier - int r = Integer.parseInt(hr, 16); - int g = Integer.parseInt(hg, 16); - int b = Integer.parseInt(hb, 16); - - if (s.length() == 9) { - // s'il y a un canal alpha on l'utilise - String ha = s.substring(7, 9); - int a = Integer.parseInt(ha, 16); - return new Color(r, g, b, a); - } else { - return new Color(r, g, b); - } - } else { - Field f; - f = Color.class.getField(s); - return (Color) f.get(Color.class); - } - } catch (NumberFormatException e) { - throw new StringUtilException( - "Error during conversion from string to color", e); - } catch (SecurityException e) { - throw new StringUtilException( - "Error during conversion from string to color", e); - } catch (NoSuchFieldException e) { - throw new StringUtilException( - "Error during conversion from string to color", e); - } catch (IllegalArgumentException e) { - throw new StringUtilException( - "Error during conversion from string to color", e); - } catch (IllegalAccessException e) { - throw new StringUtilException( - "Error during conversion from string to color", e); - } - } - - public static Date toDate(String s) throws ParseException { - return DateFormat.getDateInstance().parse(s); - } - - static final protected double[] timeFactors = {1000000, 1000, 60, 60, 24}; - - static final protected String[] timeUnites = {"ns", "ms", "s", "m", "h", - "d"}; - - /** - * Converts an time delay into a human readable format. - * - * @param value the delay to convert - * @return the memory representation of the given value - * @see #convert(long, double[], String[]) - */ - public static String convertTime(long value) { - return convert(value, timeFactors, timeUnites); - } - - /** - * Converts an time period into a human readable format. - * - * @param value the begin time - * @param value2 the end time - * @return the time representation of the given value - * @see #convert(long, double[], String[]) - */ - public static String convertTime(long value, long value2) { - return convertTime(value2 - value); - } - - static final protected double[] memoryFactors = {1024, 1024, 1024, 1024}; - - static final protected String[] memoryUnites = {"o", "Ko", "Mo", "Go", - "To"}; - - /** - * Converts an memory measure into a human readable format. - * - * @param value the memory measure to convert - * @return the memory representation of the given value - * @see #convert(long, double[], String[]) - */ - public static String convertMemory(long value) { - return convert(value, memoryFactors, memoryUnites); - } - - /** - * Note: this method use the current locale - * (the {@link Locale#getDefault()}) in the method - * {@link MessageFormat#MessageFormat(String)}. - * - * @param value value to convert - * @param factors facotrs used form conversion - * @param unites libelle of unites to use - * @return the converted representation of the given value - */ - public static String convert(long value, double[] factors, String[] unites) { - long sign = value == 0 ? 1 : value / Math.abs(value); - int i = 0; - double tmp = Math.abs(value); - while (i < factors.length && i < unites.length && tmp > factors[i]) { - tmp = tmp / factors[i++]; - } - - tmp *= sign; - String result; - result = MessageFormat.format("{0,number,0.###}{1}", tmp, - unites[i]); - return result; - } - - /** - * Vérifie q'une chaine de caractère est valid pour les bloc openner closer, ie. - * - * que les blocs définit par les deux caractères s'entrechevauchent pas. - * - * Exemple avec '(' ')' : - * - * (a(b)) est valide, par contre ((aaa))) n'est pas valide - * - * @param txt txte a verifier - * @param opener le caractère ouvrant - * @param closer le caractère fermant - * @return {@code true} is la chaine est valide - */ - public static boolean checkEnclosure(String txt, char opener, char closer) { - if (txt.indexOf(opener) == -1 && txt.indexOf(closer) == -1) { - // ok pas de block détectés - return true; - } - List<Integer> opens = new ArrayList<Integer>(); - for (int i = 0; i < txt.length(); i++) { - char c = txt.charAt(i); - if (c == opener) { - // add a open block - opens.add(i); - continue; - } - if (c == closer) { - if (opens.isEmpty()) { - // problem no block left - return false; - } - // on supprime le dernier bloc - opens.remove(opens.size() - 1); - } - } - return opens.isEmpty(); - } - - /** - * Convertir un nom en une constante Java - * - * Les seuls caractères autorisés sont les alpha numériques, ains - * que l'underscore. tous les autres caractères seront ignorés. - * - * @param name le nom à convertir - * @return la constante générée - */ - public static String convertToConstantName(String name) { - StringBuilder sb = new StringBuilder(); - char lastChar = 0; - for (int i = 0, j = name.length(); i < j; i++) { - char c = name.charAt(i); - if (Character.isDigit(c)) { - sb.append(c); - lastChar = c; - continue; - } - if (!Character.isLetter(c)) { - if (lastChar != '_') { - sb.append('_'); - } - lastChar = '_'; - continue; - } - if (Character.isUpperCase(c)) { - if (!Character.isUpperCase(lastChar) && lastChar != '_') { - sb.append('_'); - } - sb.append(c); - } else { - sb.append(Character.toUpperCase(c)); - } - lastChar = c; - } - String result = sb.toString(); - // clean tail - while (!result.isEmpty() && result.endsWith("_")) { - result = result.substring(0, result.length() - 1); - } - // clean head - while (!result.isEmpty() && result.startsWith("_")) { - result = result.substring(1); - } - return result; - } - - /** - * Convert a String to MD5. - * - * @param toEncode string concerned - * @return md5 corresponding - * @throws IllegalStateException if could not found algorithm MD5 - */ - public static String encodeMD5(String toEncode) { - - byte[] uniqueKey = toEncode.getBytes(); - byte[] hash; - // on récupère un objet qui permettra de crypter la chaine - hash = MD5InputStream.getMD5Digest().digest(uniqueKey); -// hash = MessageDigest.getInstance("MD5").digest(uniqueKey); - - StringBuilder hashString = new StringBuilder(); - for (byte aHash : hash) { - String hex = Integer.toHexString(aHash); - if (hex.length() == 1) { - hashString.append("0"); - hashString.append(hex.charAt(hex.length() - 1)); - } else { - hashString.append(hex.substring(hex.length() - 2)); - } - } - return hashString.toString(); - } - - /** - * Convert a String to SHA1. - * - * @param toEncode string to encode - * @return sha1 corresponding - * @throws IllegalStateException if could not found algorithm SHA1 - */ - public static String encodeSHA1(String toEncode) { - String result; - - try { - MessageDigest sha1Md = MessageDigest.getInstance("SHA-1"); - - byte[] digest = sha1Md.digest(toEncode.getBytes()); - result = asHex(digest); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("Can't find SHA-1 message digest algorithm", ex); - } - - return result; - } - - /** - * - * @return the file separator escaped for a regex regarding the os used. - */ - public static String getFileSeparatorRegex() { - String result; - if(SystemUtils.IS_OS_WINDOWS) { - result = "\\\\"; - } else { - result = "/"; - } - return result; - } -} diff --git a/src/main/java/org/nuiton/util/StringUtilException.java b/src/main/java/org/nuiton/util/StringUtilException.java deleted file mode 100644 index c9e30cd..0000000 --- a/src/main/java/org/nuiton/util/StringUtilException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -/** @author pineau */ -public class StringUtilException extends RuntimeException { - - private static final long serialVersionUID = 6148795384335489591L; - - public StringUtilException(String message, Exception e) { - super(message, e); - } - -} diff --git a/src/main/java/org/nuiton/util/TimeLog.java b/src/main/java/org/nuiton/util/TimeLog.java deleted file mode 100644 index 758bf6d..0000000 --- a/src/main/java/org/nuiton/util/TimeLog.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin, Benjamin POUSSIN - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.HashMap; -import java.util.Map; - -/** - * Cette classe permet de facilement trace le temps d'execution entre deux points - * - * usage - * <pre> - * final static private Log log = LogFactory.getLog(MyClass.class); - * final static private TimeLog timeLog = new TimeLog(MyClass.class, 5000, 1000); - * - * - * long start = timeLog.getTime(); - * ... - * // do some work - * ... - * start = timeLog.log(start, "MyMethod step 1", "do some work"); - * ... - * // do some work - * ... - * timeLog.log(start, "MyMethod step 2", "do other work"); - * - * - * System.out.println ("time: " + timeLog.getCallCount()); - * </pre> - * - * You can configure log level in configuration file with: - * log4j.logger.org.codelutin.MyClass=DEBUG - * log4j.logger.org.codelutin.MyClass.TimeLog=INFO - * - * @author Benjamin Poussin - poussin@codelutin.com - * - * @see CallAnalyse - * @since 2.1 - */ -public class TimeLog { - - public static class CallStat { - - protected long callNumber; - - protected long maxCallTime = 0; - - protected long minCallTime = Integer.MAX_VALUE; - - protected long callTime; - - @Override - public String toString() { - - String callTimeString = StringUtil.convertTime(callTime); - String avgTimeString = StringUtil.convertTime(callTime / callNumber); - String minCallTimeString = StringUtil.convertTime(minCallTime); - String maxCallTimeString = StringUtil.convertTime(maxCallTime); - - return String.format("total call %s, total time %s, min time %s, max time %s, avg time %s", - callNumber, callTimeString, minCallTimeString, maxCallTimeString, avgTimeString); - } - - } - - /** loggueur used to log time */ - protected Log timeLog; - - /** time to trigger log time in info level (ns) (default: 1s) */ - protected long timeToLogInfo = 1000l * 1000000l; - - /** time to trigger log time in warn level (ns) (default: 3s) */ - protected long timeToLogWarn = 3000l * 1000000l; - - /** for each method of all proxies, keep number of call */ - protected Map<String, CallStat> callCount = new HashMap<String, CallStat>(); - - /** @param logTime log used to log time message. */ - protected TimeLog(Log logTime) { - timeLog = logTime; - } - - /** - * @param logName log category used to log time message. This category must - * be category used to log message in classe that use this TimeLog - * (normaly class name). TimeLog is added at the end. - */ - public TimeLog(String logName) { - this(LogFactory.getLog(logName + ".TimeLog")); - } - - /** - * @param logName log category used to log time message. This category must - * be category used to log message in classe that use this TimeLog - * (normaly class name) - * @since 2.1 - */ - public TimeLog(Class<?> logName) { - this(logName.getName()); - } - - /** - * @param logName log category used to log time message. This category must - * be category used to log message in classe that use this TimeLog - * (normaly class name) - * @param timeToLogInfo time in milliseconde after that we log info - * @param timeToLogWarn time in milliseconde after that we log warn - */ - public TimeLog(String logName, long timeToLogInfo, long timeToLogWarn) { - this(logName); - setTimeToLogInfo(timeToLogInfo); - setTimeToLogWarn(timeToLogWarn); - } - - /** - * @param logName log category used to log time message. This category must - * be category used to log message in classe that use this TimeLog - * (normaly class name) - * @param timeToLogInfo time in milliseconde after that we log info - * @param timeToLogWarn time in milliseconde after that we log warn - */ - public TimeLog(Class<?> logName, long timeToLogInfo, long timeToLogWarn) { - this(logName.getName(), timeToLogInfo, timeToLogWarn); - } - - /** @param timeToLogInfoMs time in milliseconde after that we log info */ - public void setTimeToLogInfo(long timeToLogInfoMs) { - timeToLogInfo = timeToLogInfoMs * 1000000l; // convert ms → ns - } - - /** @param timeToLogWarnMs time in milliseconde after that we log warn */ - public void setTimeToLogWarn(long timeToLogWarnMs) { - timeToLogWarn = timeToLogWarnMs * 1000000l; // convert ms → ns - } - - public Map<String, CallStat> getCallCount() { - return callCount; - } - - /** - * return time in format acceptable for - * {@link #log(long, long, String, String)} method. - * - * @return the current time in nanoseconds - */ - public static long getTime() { - return System.nanoTime(); - } - - /** - * add new trace, stop time is automaticaly computed. - * - * @param startNs time returned by {@link #getTime()} method - * @param methodName key name to store this time - * @return time used as stop time, this permit to chain many add in same - * method to trace time. - */ - public long log(long startNs, String methodName) { - long result = log(startNs, getTime(), methodName, ""); - return result; - } - - /** - * add new trace, stop time is automaticaly computed - * - * @param startNs time returned by {@link #getTime()} method - * @param methodName key name to store this time - * @param msg message to add to log - * @return time used as stop time, this permit to chain many add in same - * method to trace time. - */ - public long log(long startNs, String methodName, String msg) { - long result = log(startNs, getTime(), methodName, msg); - return result; - } - - /** - * add new trace - * - * @param startNs time returned by {@link #getTime()} method - * @param stopNs time returned by {@link #getTime()} method - * @param methodName key name to store this time - * @param msg message to add to log - * @return time used as stop time (stopNs) - */ - public long log(long startNs, long stopNs, String methodName, String msg) { - long time = stopNs - startNs; - - // incremente le nombre d'appel pour cette methode - CallStat calls = callCount.get(methodName); - if (calls == null) { - // is not thread safe, but if we lose one or two call, is not importante - calls = new CallStat(); - callCount.put(methodName, calls); - } - calls.callNumber++; - calls.callTime += time; - - // keep max time - if (calls.maxCallTime < time) { - calls.maxCallTime = time; - } - - // keep min time - if (calls.minCallTime > time) { - calls.minCallTime = time; - } - - // affiche le temps de l'appel si necessaire - String timeString = StringUtil.convertTime(time); - String message = String.format("[%s] for method '%s', %s (%s)", - timeString, methodName, msg, calls); - - if (time > timeToLogWarn && timeLog.isWarnEnabled()) { - timeLog.warn(message); - } else if (time > timeToLogInfo && timeLog.isInfoEnabled()) { - timeLog.info(message); - } else if (timeLog.isDebugEnabled()) { - timeLog.debug(message); - } - return stopNs; - } - -} diff --git a/src/main/java/org/nuiton/util/TransparenteSoftReference.java b/src/main/java/org/nuiton/util/TransparenteSoftReference.java deleted file mode 100644 index bd50c2d..0000000 --- a/src/main/java/org/nuiton/util/TransparenteSoftReference.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * -* TransparenteSoftReference.java -* -* Created: 10 mai 2004 -* -* @author Benjamin Poussin <poussin@codelutin.com> -* Copyright Code Lutin -* -* -* Mise a jour: $Date$ -* par : $Author$ -*/ -package org.nuiton.util; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; - -/** - * Cette classe etant SoftReference et surcharge les méthodes equals et - * hashCode pour que ces méthodes retournes les mêmes résultat que les objets - * contenu. - */ -public class TransparenteSoftReference<T> extends SoftReference<T> { - - protected int hash; - - protected String toString; - - /** - * DOCUMENTME Constructor for the TransparenteSoftReference object - * - * @param o DOCUMENTME Description of the Parameter - */ - public TransparenteSoftReference(T o) { - this(o, true); - } - - public TransparenteSoftReference(T o, ReferenceQueue<? super T> queue) { - this(o, queue, true); - } - - public TransparenteSoftReference(T o, boolean objectToStringUsed) { - super(o); - init(o, objectToStringUsed); - } - - public TransparenteSoftReference(T o, - ReferenceQueue<? super T> queue, - boolean objectToStringUsed) { - super(o, queue); - init(o, objectToStringUsed); - } - - /** - * On conserve le hash pour que la Reference puisse encore se faire - * passer pour l'objet alors que celui-ci a disparu de la memoire - * - * @param o TODO - * @param objectToStringUsed TODO - */ - protected void init(T o, boolean objectToStringUsed) { - if (o == null) { - hash = 0; - } else { - hash = o.hashCode(); - if (objectToStringUsed) { - toString = o.toString(); - } - if (toString == null) { - toString = o.getClass().getName() + '@' + - Integer.toHexString(hash); - } - if (toString.length() > 100) { - toString = toString.substring(0, 100) + "..."; - } - } - } - - /** - * DOCUMENTME Method - * - * @param o DOCUMENTME Description of the Parameter - * @return DOCUMENTME Description of the Return Value - */ - public boolean equals(Object o) { - if (o == this) { - return true; - } - // on travail avec un variable local pour ne pas etre obligé de - // synchroniser la méthode - Object local = get(); - if (o instanceof Reference) { - o = ((Reference<?>) o).get(); - } - - boolean result = - o == null && local == null - || o != null && o.equals(local); - - return result; - } - - /** - * DOCUMENTME Method - * - * @return DOCUMENTME Description of the Return Value - */ - public int hashCode() { - return hash; - } - - public String toString() { - return toString; - } - -} diff --git a/src/main/java/org/nuiton/util/TransparenteWeakReference.java b/src/main/java/org/nuiton/util/TransparenteWeakReference.java deleted file mode 100644 index 7902fd1..0000000 --- a/src/main/java/org/nuiton/util/TransparenteWeakReference.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * - * TransparenteWeakReference.java - * - * Created: 10 mai 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * Copyright Code Lutin - * - * - * Mise a jour: $Date$ - * par : */ -package org.nuiton.util; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.WeakReference; - -/** - * Cette classe etant WeakReference et surcharge les méthodes equals et - * hashCode pour que ces méthodes retournes les mêmes résultat que les objets - * contenu. - * - * @param <T> type of object - */ -public class TransparenteWeakReference<T> extends WeakReference<T> { - - protected int hash; - - protected String toString; - - protected boolean objectToStringUsed = true; - - public TransparenteWeakReference(T o) { - this(o, true); - } - - public TransparenteWeakReference(T o, ReferenceQueue<? super T> queue) { - this(o, queue, true); - } - - /** - * @param o TODO ? - * @param objectToStringUsed if true, this ref used toString method of - * encapsulated object otherwize used default Object toString - */ - public TransparenteWeakReference(T o, boolean objectToStringUsed) { - super(o); - init(o, objectToStringUsed); - } - - public TransparenteWeakReference(T o, - ReferenceQueue<? super T> queue, - boolean objectToStringUsed) { - super(o, queue); - init(o, objectToStringUsed); - } - - /** - * On conserve le hash pour que la Reference puisse encore se faire - * passer pour l'objet alors que celui-ci a disparu de la memoire - * - * @param o TODO ? - * @param objectToStringUsed TODO ? - */ - protected void init(T o, boolean objectToStringUsed) { - if (o == null) { - hash = 0; - } else { - hash = o.hashCode(); - if (objectToStringUsed) { - toString = o.toString(); - } - if (toString == null) { - toString = o.getClass().getName() + '@' + - Integer.toHexString(hash); - } - if (toString.length() > 100) { - toString = toString.substring(0, 100) + "..."; - } - } - } - - /** - * @param o l'objet a comparer - * @return {@code true} si meme reference memoire on les objets - * references sont egaux - */ - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - // on travail avec un variable local pour ne pas etre obligé de - // synchroniser la méthode - Object local = get(); - Object other = o; - if (o instanceof Reference<?>) { - other = ((Reference<?>) o).get(); - - if (other == null) { - // on fait l'egalite sur les hash car on a perdu les objets - return o.hashCode() == hashCode(); - } - } - - return other == null && local == null || - other != null && other.equals(local); - } - - @Override - public int hashCode() { - return hash; - } - - @Override - public String toString() { - return toString; - } -} diff --git a/src/main/java/org/nuiton/util/Version.java b/src/main/java/org/nuiton/util/Version.java deleted file mode 100644 index a3aa90b..0000000 --- a/src/main/java/org/nuiton/util/Version.java +++ /dev/null @@ -1,350 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.lang3.ObjectUtils; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.regex.Matcher; - -import static org.nuiton.i18n.I18n.t; - -/** - * A class to represent an application version with possible classifier. - * - * Replace previously org.nuiton.util.VersionNumber class. - * - * Simple version number is defined like this : - * <pre> - * 1.0.0 or 1 - * </pre> - * - * A version can be more complex, with a classifier like this : - * <pre> - * 1.0.0-alpha-1, 1.0.0-beta-2, 1.0.0-rc-1 - * </pre> - * - * A classifier (alpha, beta, rc, ...) must be follwed by a classifier number. - * - * Note : - * - * - initial value is 0 - * - * - the equals order is defined on {@link #getVersion()} property. - * - * - the class is comparable, using the natural version order : - * - * <pre>0 <0.1 <1 <1.0 <1.1-alpha-0 <1.1-alpha-1 <1.1-beta-0 < 1.1-rc-1 <1.1 </pre> - * - * - the class is immutable, you should not instanciate directly a Version, - * but prefer use the factory static methods - * {@code VersionUtil.valueOf(...)} instead. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.1.0 - * @deprecated since 3.0 (use now {@link org.nuiton.util.version.Version}). - */ -@Deprecated -public class Version implements Comparable<Version>, Serializable { - - private static final long serialVersionUID = 1L; - - /** Version V0 */ - public static final Version VZERO = new Version(); - - /** optional classifier */ - protected final String classifier; - - /** optional classifier number (if no classifier should be null) */ - protected final Integer classifierNumber; - - /** main numbers of the version */ - protected final int[] numbers; - - /** - * boolean to define if version is a snapshot (if so a -SNAPSHOT is - * added at the end of the textual representation of the version). - * - * @since 2.4.3 - */ - protected final boolean snapshot; - - /** - * A flag to attach or not the classifier with his number. - * - * If set to false (the default cas then a - will be used to separe them). - * - * Even if the {@link Version} class is immutable, this state can be change - * since it is only used to build the string representation of a version. - * - * Notes that this state is NOT used to test equality of two version, - * neither for the comparaison. - * - * @since 2.4.3 - */ - protected boolean classifierNumberAttached; - - /** - * representation textuelle de la version (celle utilisee dans le - * {@link #toString()}. - */ - protected transient String version; - - /** Constructeur par defaut, definit la version par defaut, i.e 0 */ - public Version() { - this(0); - } - - /** - * Constructeur d'une version simple (sans classifier). - * - * @param numbers les nombres de la version - */ - public Version(int... numbers) { - this(null, null, false, numbers); - } - - /** - * Constructeur d'une version (simple ou avec classifier) - * - * @param classifier le classifier (peut-être null) - * @param classiferNumber la version du classifier (doit etre null si le - * classifier est null) - * @param numbers les nombres de la version - */ - public Version(String classifier, Integer classiferNumber, int... numbers) { - this(classifier, classiferNumber, false, numbers); - } - - /** - * Constructeur d'une version (simple ou avec classifier) - * - * @param classifier le classifier (peut-être null) - * @param classiferNumber la version du classifier (doit etre null si le - * classifier est null) - * @param snapshot boolean pour renseigner le champ {@link #snapshot}. - * @param numbers les nombres de la version - * @since 2.4.3 - */ - public Version(String classifier, Integer classiferNumber, - boolean snapshot, int... numbers) { - this.numbers = numbers.length == 0 ? new int[]{0} : numbers; - // always keep a lower case classifier - this.classifier = classifier == null ? null : - classifier.trim().toLowerCase(); - classifierNumber = classiferNumber; - this.snapshot = snapshot; - } - - /** - * Constructeur de version a partir de sa representation textuelle - * - * @param version la represention de la version a instancier - * @throws IllegalArgumentException si la version n'est pas valide - */ - public Version(String version) throws IllegalArgumentException { - if (version == null || version.trim().isEmpty()) { - // version par defaut - version = "0"; - } - - Matcher matcher = VersionUtil.VERSION_PATTERN.matcher(version); - - if (!matcher.matches()) { - - // try with classifier number attached to classifier - matcher = VersionUtil.VERSION_PATTERN2.matcher(version); - classifierNumberAttached = true; - } - - if (!matcher.matches()) { - // not a known pattern - throw new IllegalArgumentException( - t("nuitonutil.error.version.pattern", version)); - } - - // get numbers as string - String[] strNumbers = matcher.group(1).split("\\."); - String strClassifier = matcher.group(2); - String strClassifierNumber = matcher.group(3); - String strSnapshot = matcher.group(4); - Integer intClassifierNumber = null; - - if (strClassifier != null) { - - // possede un classifier - - // classifier number - intClassifierNumber = Integer.valueOf(strClassifierNumber); - } - - snapshot = strSnapshot != null; - - // numbers - numbers = new int[strNumbers.length]; - - for (int i = 0, j = strNumbers.length; i < j; i++) { - String number = strNumbers[i].trim(); - numbers[i] = Integer.valueOf(number); - } - - // classifier - classifier = strClassifier; - - // classifier number - classifierNumber = intClassifierNumber; - } - - public int[] getNumbers() { - return numbers; - } - - public String getClassifier() { - return classifier; - } - - public boolean hasClassifier() { - return classifier != null && !classifier.isEmpty(); - } - - public Integer getClassifierNumber() { - return classifierNumber; - } - - public boolean isSnapshot() { - return snapshot; - } - - public int getNbComponents() { - return numbers.length; - } - - public boolean isClassifierNumberAttached() { - return classifierNumberAttached; - } - - public int getNumber(int level) { - if (level < 0 || level >= numbers.length) { - throw new IllegalArgumentException( - "not a valid level " + level + " for the VersionNumber " + - this); - } - return numbers[level]; - } - - public String getVersion() { - if (version == null) { - StringBuilder sb = new StringBuilder(); - for (int number : numbers) { - sb.append('.').append(number); - } - if (hasClassifier()) { - sb.append('-'); - sb.append(classifier); - if (!classifierNumberAttached) { - sb.append('-'); - } - sb.append(classifierNumber); - } - if (isSnapshot()) { - sb.append(VersionUtil.SNAPSHOT_SUFFIX); - } - version = sb.substring(1); - } - return version; - } - - /** - * Convertit la representation textuelle de la version en identifiant java valide : - * - en java : "." interdit - * - en mysql, h2 ... : "." interdit - * - * @return la valeur ou les carateres interdits sont remplaces par '_' - */ - public String getValidName() { - String validName = getVersion(); - - // replace ". et -" - validName = validName.replaceAll("\\.|-", "_"); - - return validName; - } - - /** - * Change the internal state {@link #classifierNumberAttached}. - * - * @param classifierNumberAttached the new value of the classifierNumberAttached state - */ - public void setClassifierNumberAttached(boolean classifierNumberAttached) { - if (version != null) { - // will force - version = null; - } - this.classifierNumberAttached = classifierNumberAttached; - } - - @Override - public String toString() { - String t = getVersion(); - return t; - } - - @Override - public int compareTo(Version o) { - int result = VersionUtil.DEFAULT_VERSION_COMPARATOR.compare(this, o); - return result; - } - - /** - * @param o the other version to test - * @return {@code true} if current version is before the given one - */ - public boolean before(Version o) { - int result = compareTo(o); - return result < 0; - } - - /** - * @param o the other version to test - * @return {@code true} if current version is after the given one - */ - public boolean after(Version o) { - int result = compareTo(o); - return result > 0; - } - - @Override - public boolean equals(Object obj) { - return obj != null && obj instanceof Version && - Arrays.equals(numbers, ((Version) obj).numbers) && - ObjectUtils.equals(classifier, ((Version) obj).classifier) && - ObjectUtils.equals(classifierNumber, ((Version) obj).classifierNumber) && - ObjectUtils.equals(snapshot, ((Version) obj).snapshot); - } - - @Override - public int hashCode() { - return getVersion().hashCode(); - } -} diff --git a/src/main/java/org/nuiton/util/VersionUtil.java b/src/main/java/org/nuiton/util/VersionUtil.java deleted file mode 100644 index e829643..0000000 --- a/src/main/java/org/nuiton/util/VersionUtil.java +++ /dev/null @@ -1,568 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; - -/** - * Class of usefull methods on {@link Version} objects. - * - * There is some factory methods : {@code valueOf(XXX)} to obtain a new - * version. - * - * Some methods to transform a version (since version are immutable, we can not - * modify Version's property) : - * <pre> - * - inc(Version) : to increment a version - * - dec(Version) : to decrement a version - * - addClassifier(Version, String, Integer) : to add a classifier to a version - * - removeClassifier(Version) : to remove a classifier from a version - * </pre> - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.1.0 - * @deprecated since 3.0 (use now {@link org.nuiton.util.version.Version}). - */ -@Deprecated -public class VersionUtil { - - /** - * Pattern pour detecter une version (avec si classifier et numéro de - * classifier séparé par un -, par exemple : 1.0-beta-1). - * - * Le pattern possède toujours 4 groupes de captures. - * - * - Le groupe 1 est le nombre de la version - * - Le groupe 2 est le classifier (peut-etre null) - * - Le groupe 3 est le numéro de classifier (peut-etre null) - * - Le groupe 4 est le suffix -SNAPSHOT (peut-etre null) - * - * Dans le cas d'une version simple (sans classifier), le groupe 2, 3 et - * 4 sont null. - * - * Dans le cas d'une version non snapshot, le groupe 4 est null. - */ - public static final Pattern VERSION_PATTERN = - Pattern.compile("^(\\d+(?:\\.(?:\\d+))*)(?:-(\\w+?)-(\\d+?)){0,1}(-SNAPSHOT){0,1}$"); - - /** - * Pattern pour detecter une version (avec si classifier et numéro de - * classifier collé, par exemple : 1.0-rc1). - * - * Le pattern possède toujours 4 groupes de captures. - * - * - Le groupe 1 est le nombre de la version - * - Le groupe 2 est le classifier (peut-etre null) - * - Le groupe 3 est le numéro de classifier (peut-etre null) - * - Le groupe 4 est le suffix -SNAPSHOT (peut-etre null) - * - * Dans le cas d'une version simple (sans classifier), le groupe 2, 3 et - * 4 sont null. - * - * Dans le cas d'une version non snapshot, le groupe 4 est null. - */ - public static final Pattern VERSION_PATTERN2 = - Pattern.compile("^(\\d+(?:\\.(?:\\d+))*)(?:-(\\w+?)(\\d+?)){0,1}(-SNAPSHOT){0,1}$"); - - /** - * Shared instance of default version comparator. - * - * @see VersionComparator - */ - public static final VersionComparator DEFAULT_VERSION_COMPARATOR = - new VersionComparator(); - - /** The snapshot suffix. */ - public static final String SNAPSHOT_SUFFIX = "-SNAPSHOT"; - - /** - * Recuperation d'une instance de version simple (sans classifier). - * - * @param numbers les nombres de la version - * @param snapshot boolean pour indiquer que la version es une snapshot ou pas - * @return l'instance de la version requise - */ - public static Version valueOf(boolean snapshot, int... numbers) { - Version version = valueOf(null, null, snapshot, numbers); - return version; - } - - /** - * Recuperation d'une instance de version simple (sans classifier). - * - * @param numbers les nombres de la version - * @return l'instance de la version requise - */ - public static Version valueOf(int... numbers) { - Version version = valueOf(null, null, false, numbers); - return version; - } - - /** - * Recuperation d'une instance de version. - * - * @param classifier le classifier (peut-etre null) - * @param classifierNumber la version du classifier (doit etre null si le - * classifier est null) - * @param numbers les nombres de la version - * @return l'instance de la version requise - */ - public static Version valueOf(String classifier, - Integer classifierNumber, int... numbers) { - Version v = valueOf(classifier, classifierNumber, false, numbers); - return v; - } - - /** - * Recuperation d'une instance de version. - * - * @param classifier le classifier (peut-etre null) - * @param classifierNumber la version du classifier (doit etre null si le - * classifier est null) - * @param snapshot boolean pour indiquer que la version es une snapshot ou pas - * @param numbers les nombres de la version - * @return l'instance de la version requise - */ - public static Version valueOf(String classifier, - Integer classifierNumber, - boolean snapshot, - int... numbers) { - Version v = new Version(classifier, classifierNumber, snapshot, numbers); - return v; - } - - /** - * Recuperation d'une instance de version a partir de sa version textuelle. - * - * @param version la representation textuelle de la version - * @return l'instance de la version requise - */ - public static Version valueOf(String version) { - Version v = new Version(version); - return v; - } - - /** - * Construction d'une nouvelle version avec un classifier a partir d'une - * version donnee. - * - * @param version la version de base (sans classifier) - * @param classifier le classifier a ajouter - * @param classifierNumber la version du classifier a ajouter - * @return l'instance de la version requise - * @throws NullPointerException si le classifier ou le - * classifierNumber est null. - * @throws IllegalArgumentException si la version donnee contient deja un - * classifier. - */ - public static Version addClassifier(Version version, - String classifier, - Integer classifierNumber) - throws NullPointerException, IllegalArgumentException { - Version result; - if (classifier == null) { - throw new NullPointerException("classifier can not be null"); - } - if (classifierNumber == null) { - throw new NullPointerException("classifierNumber can not be null"); - } - if (version.hasClassifier()) { - throw new IllegalArgumentException( - "version " + version + "contains already a classifier "); - } - result = valueOf(classifier, - classifierNumber, - version.isSnapshot(), - version.getNumbers()); - return result; - } - - /** - * Construction d'une nouvelle version sans classifier a partir d'une - * version donnee (sans classifier). - * - * @param version la version de base (avec classifier) - * @return l'instance de la version requise - * @throws IllegalArgumentException si la version donnee contient deja - * un classifier. - */ - public static Version removeClassifier(Version version) - throws IllegalArgumentException { - Version result; - if (!version.hasClassifier()) { - throw new IllegalArgumentException( - "version " + version + "does no contain a classifier "); - } - result = valueOf(version.isSnapshot(), version.getNumbers()); - return result; - } - - public static Version addSnapshot(Version version) { - if (version.isSnapshot()) { - throw new IllegalArgumentException( - "version " + version + "is already a snapshot"); - } - Version result = valueOf(version.getClassifier(), version.getClassifierNumber(), true, version.getNumbers()); - return result; - } - - public static Version removeSnapshot(Version version) { - if (!version.isSnapshot()) { - throw new IllegalArgumentException( - "version " + version + "is already a snapshot"); - } - Version result = valueOf(version.getClassifier(), version.getClassifierNumber(), false, version.getNumbers()); - return result; - } - - /** - * Incremente le numero de version donnee, seul le dernier constituant est - * incremente: 1.2.3.4 → 1.2.3.5; null → 1; 0 → 1. - * - * Si la version a un classifier, alors c'est la version du classifier qui - * change : 1.1-alpha-12 → 1.1-alpha-13 - * - * @param v la version a incrementer - * @return la nouvelle version - */ - public static Version inc(Version v) { - int nbComponents = v.getNbComponents(); - int[] newNumbers = Arrays.copyOf(v.numbers, nbComponents); - String newClassifier = v.classifier; - Integer newClassifierNumber = v.classifierNumber; - - if (v.hasClassifier()) { - newClassifierNumber++; - } else { - newNumbers[nbComponents - 1] = newNumbers[nbComponents - 1] + 1; - } - - Version result = valueOf(newClassifier, newClassifierNumber, - v.isSnapshot(), - newNumbers); - return result; - } - - /** - * Remove the suffix {@code -SNAPSHOT} stamp from a version (if any). - * - * @param version the string representation of the version - * @return the string representation of the given version - * without the {@code -SNAPSHOT} suffix (if any). - * @throws NullPointerException if version is null - */ - public static String removeSnapshot(String version) - throws NullPointerException { - if (version == null) { - throw new NullPointerException("version parameter can not be null"); - } - int index = version.indexOf(SNAPSHOT_SUFFIX); - if (index > -1) { - version = version.substring(0, index); - } - return version; - } - - /** - * Filter versions. - * - * @param versions versions to filter - * @param min min version to accept - * @param max max version to accept - * @param includeMin flag to include min version - * @param includeMax flag to include max version - * @return versions between min and max - */ - public static List<Version> filterVersions(Set<Version> versions, - Version min, - Version max, - boolean includeMin, - boolean includeMax) { - List<Version> toApply = new ArrayList<Version>(); - for (Version v : versions) { - int t; - if (min != null) { - t = v.compareTo(min); - if (t < 0 || t == 0 && !includeMin) { - // version trop ancienne - continue; - } - } - if (max != null) { - t = v.compareTo(max); - if (t > 0 || t == 0 && !includeMax) { - // version trop recente - continue; - } - } - toApply.add(v); - } - return toApply; - } - - /** - * L'implantation d'un comparateur de versions permettant de controler - * l'ordre du numero de version, classifier et numero de classifer. - * - * Toute implementation de ce contrat devrait suivre cet algorithme : - * - * 1) Si versions égales, on quitte. - * - * 2) On teste l'ordre des nombres {@link #compareNumbers(Version, Version)} - * - * Si différent, alors versions différentes, on quitte - * - * 3) On teste l'ordre des classifiers - * {@link #compareClassifier(Version, Version)} - * - * Si différent, alors versions différentes, on quitte - * - * 4) On teste l'ordre des versions de classifiers - * {@link #compareClassifierNumber(Version, Version)}. - */ - public static class VersionComparator implements Comparator<Version> { - - @Override - public int compare(Version o1, Version o2) { - - if (o1.equals(o2)) { - - // versions are equals - return 0; - } - - // compare on numbers - - int result = compareNumbers(o1, o2); - - if (result != 0) { - - // compare snapshot - return result; - } - - // numbers are equals - - // compare on classifier - - result = compareClassifier(o1, o2); - - if (result != 0) { - return result; - } - - // classifier are equals - - // compare on classifierNumber - - result = compareClassifierNumber(o1, o2); - - if (result != 0) { - return result; - } - - // classifierNumber are equals - - // compare on snapshot - result = compareSnapshot(o1, o2); - - return result; - } - - public int compareNumbers(Version o1, Version o2) { - int nbComponents1 = o1.numbers.length; - int nbComponents2 = o2.numbers.length; - int minlen = Math.min(nbComponents1, nbComponents2); - for (int i = 0; i < minlen; i++) { - int t1 = o1.numbers[i]; - int t2 = o2.numbers[i]; - if (t1 == t2) { - continue; - } - return t1 - t2; - } - - // common version are equals - - // the longer number wins - // example : 1.0.0 > 1.0 > 1 - - return nbComponents1 - nbComponents2; - } - - public int compareClassifier(Version o1, Version o2) { - if (o1.hasClassifier() && o2.hasClassifier()) { - // o1 et o2 ont un classifier - return o1.classifier.compareTo(o2.classifier); - } - - if (!o1.hasClassifier() && !o2.hasClassifier()) { - // o1 et o2 n'ont un classifier - return 0; - } - - if (!o1.hasClassifier()) { - // o1 n'a pas de classifier, o1 est donc plus recent - return 1; - } - - if (!o2.hasClassifier()) { - // o2 n'a pas de classifier, o2 est donc plus recent - return -1; - } - - // o1 et o2 n'ont pas de classifier, il sont donc egaux - return 0; - - } - - public int compareClassifierNumber(Version o1, Version o2) { - - if (!o1.hasClassifier() && !o2.hasClassifier()) { - // o1 et o2 n'ont un classifier - return 0; - } - return o1.classifierNumber - o2.classifierNumber; - } - - public int compareSnapshot(Version o1, Version o2) { - - boolean snapshot1 = o1.isSnapshot(); - boolean snapshot2 = o2.isSnapshot(); - if ((snapshot1 && snapshot2) || (!snapshot1 && !snapshot2)) { - // equals - return 0; - } - if (snapshot1) { - // !snapshot2, so v1 est before v2 - return -1; - } - return 1; - } - } - - /** - * Tests if two versions are equals. - * - * @param version0 the first version - * @param version1 the second version - * @return {@code true} if versions are equals, {@code false} otherwise. - */ - public static boolean equals(String version0, String version1) { - Version v0 = valueOf(version0); - Version v1 = valueOf(version1); - boolean result = v0.equals(v1); - return result; - } - - /** - * Tests if the first version is smaller than the second version. - * - * @param version0 the first version - * @param version1 the second version - * @return {@code true} if {@code version0} is before {@code version1}, - * {@code false} otherwise. - */ - public static boolean smallerThan(String version0, String version1) { - Version v0 = valueOf(version0); - Version v1 = valueOf(version1); - boolean result = v0.before(v1); - return result; - } - - /** - * Tests if the first version is greater than the second version. - * - * @param version0 the first version - * @param version1 the second version - * @return {@code true} if {@code version0} is after {@code version1}, - * {@code false} otherwise. - */ - public static boolean greaterThan(String version0, String version1) { - Version v0 = valueOf(version0); - Version v1 = valueOf(version1); - boolean result = v0.after(v1); - return result; - } - - /** - * Trier un ensemble de versions données en entrees - * - * On affiche le resultat dans la console - * - * @param args les versions - */ - public static void main(String... args) { - - List<Version> list = new ArrayList<Version>(); - List<Version> snapshots = new ArrayList<Version>(); - - for (String a : args) { - if (a.endsWith(SNAPSHOT_SUFFIX)) { - snapshots.add(valueOf( - a.substring(0, a.length() - VersionUtil.SNAPSHOT_SUFFIX.length()))); - continue; - } - Version v = valueOf(a); - list.add(v); - } - Collections.sort(list); - List<String> asString = new ArrayList<String>(); - for (Version v : list) { - asString.add(v.toString()); - } - // repositionnement des snapshots - for (Version snap : snapshots) { - String v = snap.toString(); - if (list.contains(snap)) { - // on ajoute juste avant - int index = asString.indexOf(v); - asString.add(index, v + SNAPSHOT_SUFFIX); - } else { - // ajout dans la liste initiale - list.add(snap); - Collections.sort(list); - int index = list.indexOf(snap); - if (index == 0) { - asString.add(0, v + SNAPSHOT_SUFFIX); - } else { - Version v2 = list.get(index - 1); - index = asString.indexOf(v2.toString()); - asString.add(index + 1, v + SNAPSHOT_SUFFIX); - } - list.remove(snap); - } - } - StringBuilder buffer = new StringBuilder(); - for (String s : asString) { - buffer.append(s).append("\n"); - } - System.out.println(buffer.toString()); - } -} diff --git a/src/main/java/org/nuiton/util/ZipStreamEncoder.java b/src/main/java/org/nuiton/util/ZipStreamEncoder.java deleted file mode 100644 index 86df696..0000000 --- a/src/main/java/org/nuiton/util/ZipStreamEncoder.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Map; -import java.util.zip.Deflater; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -/** The Class ZipStreamEncoder. */ -public class ZipStreamEncoder extends Thread { - - /** Logger. */ - static private Log log = LogFactory.getLog(ZipStreamEncoder.class); - - /** The Constant BUFFER. */ - static final int BUFFER = 2048; - - /** The files. */ - private Map<String, InputStream> files; - - /** The zos. */ - private ZipOutputStream zos; - - /** - * Instantiates a new zip stream encoder. - * - * @param files the files - * @param os the os - */ - public ZipStreamEncoder(Map<String, InputStream> files, OutputStream os) { - this.files = files; - - zos = new ZipOutputStream(os); - zos.setMethod(ZipOutputStream.DEFLATED); - zos.setLevel(Deflater.BEST_COMPRESSION); - } - - /* (non-Javadoc) - * @see java.lang.Thread#run() - */ - @Override - public void run() { - byte data[] = new byte[BUFFER]; - try { - for (Map.Entry<String, InputStream> kv : files.entrySet()) { - ZipEntry entry = new ZipEntry(kv.getKey()); - InputStream origin = kv.getValue(); - zos.putNextEntry(entry); - int count; - while ((count = origin.read(data, 0, BUFFER)) != -1) { - zos.write(data, 0, count); - } - origin.close(); - } - - zos.close(); - } catch (IOException e) { - for (Map.Entry<String, InputStream> kv : files.entrySet()) { - InputStream origin = kv.getValue(); - try { - origin.close(); - } catch (IOException ioe) { - log.error("Impossible to close " + kv.getKey()); - } - } - log.error("Impossible to compress in stream"); - throw new RuntimeException("Impossible to compress in stream"); - } - } - -} diff --git a/src/main/java/org/nuiton/util/ZipUtil.java b/src/main/java/org/nuiton/util/ZipUtil.java deleted file mode 100644 index 727d0f8..0000000 --- a/src/main/java/org/nuiton/util/ZipUtil.java +++ /dev/null @@ -1,603 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Enumeration; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - -/** - * Opérations sur des fichiers Zip. Compression et décompression avec ou - * sans filtres, scan des fichiers créés ou écrasés lors de la décompression... - * - * Created: 24 août 2006 10:13:35 - * - * @author Benjamin Poussin - poussin@codelutin.com - * - */ -public class ZipUtil { - - /** Class logger. */ - private static Log log = LogFactory.getLog(ZipUtil.class); - - /** Taille du buffer pour les lectures/écritures. */ - private static final int BUFFER_SIZE = 8 * 1024; - - /** Le séparateur de fichier en local. */ - private static final String LOCAL_SEP = File.separator; - - private static final String LOCAL_SEP_PATTERN = "\\".equals(LOCAL_SEP) ? - LOCAL_SEP + LOCAL_SEP : LOCAL_SEP; - - /** Le séparateur zip. */ - private static final String ZIP_SEP = "/"; - - private static final String ZIP_SEP_PATTERN = "/"; - - /** Accept all file pattern. */ - protected static FileFilter ALL_FILE_FILTER = new FileFilter() { - public boolean accept(File pathname) { - return true; - } - }; - - /** - * Uncompress zipped file in targetDir. - * - * @param file the zip source file - * @param targetDir the destination directory - * @return return last entry name - * @throws IOException if any problem while uncompressing - */ - public static String uncompress(File file, File targetDir) throws IOException { - String result; - result = uncompressAndRename(file, targetDir, null, null); - return result; - } - - /** - * Uncompress zipped stream in targetDir. - * - * - * @param stream the zip source stream, stream is closed before return - * @param targetDir the destination directory - * @return return last entry name - * @throws IOException if any problem while uncompressing - * @since 2.6.6 - */ - public static String uncompress(InputStream stream, File targetDir) throws IOException { - String result = uncompressAndRename(stream, targetDir, null, null); - return result; - } - - /** - * Uncompress zipped file in targetDir, and rename uncompressed file if - * necessary. If renameFrom or renameTo is null no renaming is done - * - * file in zip use / to separate directory and not begin with / - * each directory ended with / - * - * @param file the zip source file - * @param targetDir the destination directory - * @param renameFrom pattern to permit rename file before uncompress it - * @param renameTo new name for file if renameFrom is applicable to it - * you can use $1, $2, ... if you have '(' ')' in renameFrom - * @return return last entry name - * @throws IOException if any problem while uncompressing - */ - public static String uncompressAndRename(File file, - File targetDir, - String renameFrom, - String renameTo) throws IOException { - return uncompressAndRename(new FileInputStream(file), targetDir, renameFrom, renameTo); - } - - - /** - * Uncompress zipped stream in targetDir, and rename uncompressed file if - * necessary. If renameFrom or renameTo is null no renaming is done - * - * file in zip use / to separate directory and not begin with / - * each directory ended with / - * - * @param stream the zip source stream, stream is closed before return - * @param targetDir the destination directory - * @param renameFrom pattern to permit rename file before uncompress it - * @param renameTo new name for file if renameFrom is applicable to it - * you can use $1, $2, ... if you have '(' ')' in renameFrom - * @return return last entry name - * @throws IOException if any problem while uncompressing - * @since 2.6.6 - */ - public static String uncompressAndRename(InputStream stream, - File targetDir, - String renameFrom, - String renameTo) throws IOException { - String result = ""; - ZipInputStream in = new ZipInputStream(new BufferedInputStream(stream)); - try { - ZipEntry entry; - while ((entry = in.getNextEntry()) != null) { - String name = entry.getName(); - if (renameFrom != null && renameTo != null) { - name = name.replaceAll(renameFrom, renameTo); - if (log.isDebugEnabled()) { - log.debug("rename " + entry.getName() + " → " + name); - } - } - result = name; - File target = new File(targetDir, name); - if (entry.isDirectory()) { - FileUtil.createDirectoryIfNecessary(target); - } else { - FileUtil.createDirectoryIfNecessary(target.getParentFile()); - OutputStream out = new BufferedOutputStream(new FileOutputStream(target)); - try { - byte[] buffer = new byte[BUFFER_SIZE]; - int len; - while ((len = in.read(buffer, 0, BUFFER_SIZE)) != -1) { - out.write(buffer, 0, len); - } - } finally { - out.close(); - } - } - } - } finally { - in.close(); - } - return result; - } - - /** - * Compress 'includes' files in zipFile. If file in includes is directory - * only the directory is put in zipFile, not the file contained in directory - * - * @param zipFile the destination zip file - * @param root for all file in includes that is in this directory, then we - * remove this directory in zip entry name (aka -C for tar), can be null; - * @param includes the files to include in zip - * @throws IOException if any problem while compressing - */ - public static void compressFiles(File zipFile, - File root, - Collection<File> includes) throws - IOException { - compressFiles(zipFile, root, includes, false); - } - - /** - * Compress 'includes' files in zipFile. If file in includes is directory - * only the directory is put in zipFile, not the file contained in directory - * - * @param zipFile the destination zip file - * @param root for all file in includes that is in this directory, then we - * remove this directory in zip entry name (aka -C for tar), can be null; - * @param includes the files to include in zip - * @param createMD5 also create a MD5 file (zip name + .md5). MD5 file is created after zip. - * @throws IOException if any problem while compressing - */ - public static void compressFiles(File zipFile, - File root, - Collection<File> includes, - boolean createMD5) throws IOException { - OutputStream oStream = new FileOutputStream(zipFile); - - // if md5 creation flag - if (createMD5) { - oStream = new MD5OutputStream(oStream); - } - try { - ZipOutputStream zipOStream = new ZipOutputStream(oStream); - - for (File file : includes) { - String entryName = toZipEntryName(root, file); - - // Création d'une nouvelle entrée dans le zip - ZipEntry entry = new ZipEntry(entryName); - entry.setTime(file.lastModified()); - zipOStream.putNextEntry(entry); - - if (file.isFile() && file.canRead()) { - byte[] readBuffer = new byte[BUFFER_SIZE]; - int bytesIn; - BufferedInputStream bis = new BufferedInputStream( - new FileInputStream(file), BUFFER_SIZE); - try { - while ((bytesIn = - bis.read(readBuffer, 0, BUFFER_SIZE)) != -1) { - zipOStream.write(readBuffer, 0, bytesIn); - } - } finally { - bis.close(); - } - } - zipOStream.closeEntry(); - } - zipOStream.close(); - - // if md5 creation flag - if (createMD5) { - String md5hash = StringUtil.asHex(((MD5OutputStream) oStream).hash()); - File md5File = new File(zipFile.getAbsoluteFile() + ".md5"); - FileUtils.write(md5File, md5hash); - } - } finally { - oStream.close(); - } - } - - /** - * If fileOrDirectory is directory Compress recursively all file in this - * directory, else if is just file compress one file. - * - * Entry result name in zip start at fileOrDirectory. - * example: if we compress /etc/apache, entry will be apache/http.conf, ... - * - * @param zipFile the target zip file - * @param fileOrDirectory the file or directory to compress - * @throws IOException if any problem while compressing - */ - public static void compress(File zipFile, - File fileOrDirectory) throws IOException { - compress(zipFile, fileOrDirectory, null, false); - } - - /** - * If fileOrDirectory is directory Compress recursively all file in this - * directory, else if is just file compress one file. - * - * Entry result name in zip start at fileOrDirectory. - * example: if we compress /etc/apache, entry will be apache/http.conf, ... - * - * @param zipFile the target zip file - * @param fileOrDirectory the file or directory to compress - * @param filter used to accept file, if null, all file is accepted - * @throws IOException if any problem while compressing - */ - public static void compress(File zipFile, - File fileOrDirectory, - FileFilter filter) throws IOException { - compress(zipFile, fileOrDirectory, filter, false); - } - - /** - * If fileOrDirectory is directory Compress recursively all file in this - * directory, else if is just file compress one file. - * - * Entry result name in zip start at fileOrDirectory. - * example: if we compress /etc/apache, entry will be apache/http.conf, ... - * - * @param zipFile the target zip file - * @param fileOrDirectory the file or directory to compress - * @param filter used to accept file, if null, all file is accepted - * @param createMD5 also create a MD5 file (zip name + .md5). MD5 file is created after zip. - * @throws IOException if any problem while compressing - */ - public static void compress(File zipFile, - File fileOrDirectory, - FileFilter filter, - boolean createMD5) throws IOException { - if (filter == null) { - filter = ALL_FILE_FILTER; - } - List<File> files = new ArrayList<File>(); - if (fileOrDirectory.isDirectory()) { - files = FileUtil.getFilteredElements(fileOrDirectory, filter, true); - } else if (filter.accept(fileOrDirectory)) { - files.add(fileOrDirectory); - } - - compressFiles(zipFile, fileOrDirectory.getParentFile(), files, - createMD5); - } - - /** - * <li> supprime le root du fichier - * <li> Converti les '\' en '/' car les zip entry utilise des '/' - * <li> ajoute un '/' a la fin pour les repertoires - * <li> supprime le premier '/' si la chaine commence par un '/' - * - * @param root the root directory - * @param file the file to treate - * @return the zip entry name corresponding to the given {@code file} - * from {@code root} dir. - */ - private static String toZipEntryName(File root, File file) { - String result = file.getPath(); - - if (root != null) { - String rootPath = root.getPath(); - if (result.startsWith(rootPath)) { - result = result.substring(rootPath.length()); - } - } - - result = result.replace('\\', '/'); - if (file.isDirectory()) { - result += '/'; - } - while (result.startsWith("/")) { - result = result.substring(1); - } - return result; - } - - /** - * Scan a zipFile, and fill two lists of relative paths corresponding of - * zip entries. - * First list contains all entries to be added while a uncompress operation - * on the destination directory {@code targetDir}. - * Second list contains all entries to be overwritten while a uncompress - * operation on the destination directory {@code targetDir}. - * - * If {@code targetDir} is {@code null} we don't fill {@code existingFiles} list. - * - * @param zipFile location of the zip to scanZip - * @param targetDir location of destination for a uncompress operation. - * If {@code null} we don't test to - * find overwritten files. - * @param newFiles list of files to be added while a uncompress - * @param existingFiles list of files to be overwritten while a uncompress - * if the {@code targetDir}, - * (only use if {@code targetDir} is not - * {@code null}) - * @param excludeFilter used to exclude some files - * @param renameFrom {@link #uncompressAndRename(File, File, String, String)} - * @param renameTo {@link #uncompressAndRename(File, File, String, String)} - * @throws IOException if any exception while dealing with zipfile - */ - public static void scan(File zipFile, - File targetDir, - List<String> newFiles, - List<String> existingFiles, - FileFilter excludeFilter, - String renameFrom, - String renameTo) throws IOException { - ZipFile zip = null; - try { - zip = new ZipFile(zipFile); - boolean findExisting = targetDir != null && targetDir.exists(); - boolean filter = findExisting && excludeFilter != null; - boolean rename = renameFrom != null && renameTo != null; - Enumeration<? extends ZipEntry> entries = zip.entries(); - while (entries.hasMoreElements()) { - String entryName = entries.nextElement().getName(); - if (rename) { - entryName = entryName.replaceAll(renameFrom, renameTo); - } - String name = convertToLocalEntryName(entryName); - if (findExisting || filter) { - File file = new File(targetDir, name); - if (filter && excludeFilter.accept(file)) continue; - if (file.exists()) { - existingFiles.add(name); - continue; - } - } - newFiles.add(name); - } - } finally { - if (zip != null) { - zip.close(); - } - } - } - - @SuppressWarnings({"unchecked"}) - public static List<String>[] scanAndExplodeZip(File source, - File root, - FileFilter excludeFilter) - throws IOException { - - List<String> overwrittenFiles = new ArrayList<String>(); - List<String> newFiles = new ArrayList<String>(); - - // obtain list of relative paths (to add or overwrite) - scan(source, root, newFiles, overwrittenFiles, excludeFilter, null, - null); - - return new List[]{newFiles, overwrittenFiles}; - } - - /** - * uncompress zipped file in targetDir. - * - * If {@code toTreate} if not null nor empty, we use it to filter - * entries to uncompress : it contains a list of relative local path of - * files to uncompress. - * Otherwise just delegate to {@link ZipUtil#uncompress(File, File)}. - * - * @param file location of zip file - * @param targetDir destination directory - * @param toTreate list of relative local path of entries to treate - * @param renameFrom {@link #uncompressAndRename(File, File, String, String)} - * @param renameTo {@link #uncompressAndRename(File, File, String, String)} - * @return return last entry name - * @throws IOException if nay exception while operation - */ - public static String uncompress(File file, - File targetDir, - List<String> toTreate, - String renameFrom, - String renameTo) throws IOException { - if (toTreate == null || toTreate.isEmpty()) { - return uncompressAndRename(file, targetDir, renameFrom, renameTo); - } - - boolean rename = renameFrom != null && renameTo != null; - - String result = ""; - ZipEntry entry; - ZipInputStream in = new ZipInputStream(new FileInputStream(file)); - try { - while ((entry = in.getNextEntry()) != null) { - String name = entry.getName(); - if (rename) { - result = convertToLocalEntryName(name.replaceAll(renameFrom, - renameTo)); - } else { - result = convertToLocalEntryName(name); - } - - if (log.isDebugEnabled()) { - log.debug("open [" + name + "] : " + result); - } - if (!toTreate.contains(result)) { - continue; - } - - if (log.isDebugEnabled()) { - log.debug("copy [" + name + "] : " + result); - } - File target = new File(targetDir, result); - if (entry.isDirectory()) { - FileUtil.createDirectoryIfNecessary(target); - } else { - FileUtil.createDirectoryIfNecessary(target.getParentFile()); - OutputStream out = new BufferedOutputStream( - new FileOutputStream(target)); - try { - byte[] buffer = new byte[BUFFER_SIZE]; - int len; - while ((len = in.read(buffer, 0, BUFFER_SIZE)) != -1) { - out.write(buffer, 0, len); - } - } finally { - out.close(); - } - } - } - } finally { - in.close(); - } - return result; - } - - /** - * Unzip compressed archive and keep non excluded patterns. - * - * @param file archive file - * @param targetDir destination file - * @param excludes excludes pattern (pattern must match complete entry name including root folder) - * @throws IOException FIXME - */ - public static void uncompressFiltred(File file, - File targetDir, - String... excludes) throws IOException { - - ZipFile zipFile = new ZipFile(file); - - Enumeration<? extends ZipEntry> entries = zipFile.entries(); - - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - - String name = entry.getName(); - // add continue to break loop - boolean excludeEntry = false; - if (excludes != null) { - for (String exclude : excludes) { - if (name.matches(exclude)) { - excludeEntry = true; - } - } - } - - if (!excludeEntry) { - File target = new File(targetDir, name); - if (entry.isDirectory()) { - FileUtil.createDirectoryIfNecessary(target); - } else { - // get inputstream only here - FileUtil.createDirectoryIfNecessary(target.getParentFile()); - InputStream in = zipFile.getInputStream(entry); - try { - OutputStream out = new BufferedOutputStream( - new FileOutputStream(target)); - try { - byte[] buffer = new byte[8 * 1024]; - int len; - - while ((len = in.read(buffer, 0, 8 * 1024)) != -1) { - out.write(buffer, 0, len); - } - } finally { - out.close(); - } - } finally { - in.close(); - } - } - } - } - } - - /** - * Tests if the given file is a zip file. - * - * @param file the file to test - * @return {@code true} if the file is a valid zip file, - * {@code false} otherwise. - * @throws IOException if could not open zip file - * @since 2.4.9 - */ - public static boolean isZipFile(File file) throws IOException { - - boolean result = false; - try { - ZipFile zipFile = new ZipFile(file); - zipFile.close(); - result = true; - } catch (IOException e) { - // silent test - } - return result; - } - - protected static String convertToLocalEntryName(String txt) { - String s = txt.replaceAll(ZIP_SEP_PATTERN, LOCAL_SEP_PATTERN); - if (s.endsWith(ZIP_SEP)) { - s = s.substring(0, s.length() - 1); - } - return s; - } -} diff --git a/src/main/java/org/nuiton/util/beans/BeanMonitor.java b/src/main/java/org/nuiton/util/beans/BeanMonitor.java deleted file mode 100644 index 9a895e2..0000000 --- a/src/main/java/org/nuiton/util/beans/BeanMonitor.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.beans; - -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * A monitor of beans. - * - * You indicates which properties to monitor (via the constructor). - * - * Then attach a bean to monitor via the method {@link #setBean(Object)}. - * - * The method {@link #clearModified()} reset the states about modified - * properties. - * - * The method {@link #wasModified()} tells if there was any modification on - * monitored properties for the attached bean since the last call to - * {@link #clearModified()} (or {@link #setBean(Object)}. - * - * the method {@link #getModifiedProperties()} gives you the names of monitored - * properties for the attached bean since the last call to - * {@link #clearModified()} (or {@link #setBean(Object)}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4.1 - */ -public class BeanMonitor { - - /** Logger */ - private static final Log log = LogFactory.getLog(BeanMonitor.class); - - /** Names of properties to watch or not on attached bean. */ - protected final List<String> propertyNames; - - /** If true, then listen to the properties which are not in the propertyNames */ - protected boolean excludeMode; - - /** Names of monitored and modified properties for the attached bean. */ - protected final Map<String, PropertyDiff> propertyDiffs; - - /** - * The {@link PropertyChangeListener} which listen modification on bean - * only on monitored properties. - */ - protected final PropertyChangeListener listener; - - /** The bean to monitor. */ - protected Object bean; - - /** - * Constructor of monitor with property names to monitor. - * - * @param propertyNames the names of properties to monitor - */ - public BeanMonitor(String... propertyNames) { - this(false, propertyNames); - } - - public BeanMonitor(boolean exclude, String... propertyNames) { - this.excludeMode = exclude; - this.propertyNames = new ArrayList<String>(Arrays.asList(propertyNames)); - propertyDiffs = new LinkedHashMap<String, PropertyDiff>(); - - listener = new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - String propertyName = evt.getPropertyName(); - if (excludeMode && BeanMonitor.this.propertyNames.contains(propertyName) - || !excludeMode && !BeanMonitor.this.propertyNames.contains(propertyName)) { - return; - } - - // the property is monitored - - Object newValue = evt.getNewValue(); - Object oldValue = evt.getOldValue(); - - PropertyDiff propertyDiff; - - if (propertyDiffs.containsKey(propertyName)) { - - // property was already modified - propertyDiff = propertyDiffs.get(propertyName); - - // change the target value - propertyDiff.setTargetValue(newValue); - - // check if value did not come back to original - Object originalValue = propertyDiff.getSourceValue(); - - if (ObjectUtils.equals(originalValue, newValue)) { - - // coming back to original value - // the property is no more modified - propertyDiffs.remove(propertyName); - } - } else { - - // check old value and newvalue are real not equals - if (ObjectUtils.notEqual(newValue, oldValue)) { - propertyDiff = new PropertyDiff( - propertyName, - oldValue, - propertyName, - newValue, - null - ); - - // add it to modified properties - propertyDiffs.put(propertyName, propertyDiff); - } - - } - } - }; - } - - /** - * Obtains the monitored {@link #bean}. - * - * @return the attached bean, or {@code null} if none attached. - */ - public Object getBean() { - return bean; - } - - /** - * Tells if any of the monitored properties were modified on the attached - * bean since last call to {@link #clearModified()} or - * {@link #setBean(Object)}. - * - * @return {@code true} if there were a modified monitored property on - * the attached bean, {@code false} otherwise. - */ - public boolean wasModified() { - return !propertyDiffs.isEmpty(); - } - - /** - * Obtains the names of monitored properties which has been touched for the - * attached bean since last call to {@link #clearModified()} or - * {@link #setBean(Object)}. - * - * @return the array of property names to monitor. - */ - public String[] getModifiedProperties() { - Set<String> propertyNames = propertyDiffs.keySet(); - return propertyNames.toArray(new String[propertyNames.size()]); - } - - /** - * Obtains the original values for all modified properties. - * - * @return the dictionnary of original values for modified properties - */ - public Map<String, Object> getOriginalValues() { - - // always expose a copy of map - Map<String, Object> map = new TreeMap<String, Object>(); - for (PropertyDiff propertyDiff : propertyDiffs.values()) { - map.put(propertyDiff.getSourceProperty(), - propertyDiff.getSourceValue()); - } - return map; - } - - /** - * Obtains the property diffs since the bean is monitoried. - * - * @return the property diffs since the bean is monitoried. - * @since 2.4 - */ - public PropertyDiff[] getPropertyDiffs() { - Collection<PropertyDiff> values = propertyDiffs.values(); - return values.toArray(new PropertyDiff[values.size()]); - } - - /** - * Sets the {@code bean} to monitor. - * - * As a side effect, it will attach the {@link #listener} to new bean - * (if not null) and remove it from the previous bean attached (if not null). - * - * As a second side effect, it will always clean the modified states, - * using the method {@link #clearModified()}. - * - * @param bean the new bean to monitor - */ - public void setBean(Object bean) { - Object oldBean = this.bean; - this.bean = bean; - - // while removing a bean must clean modified states - clearModified(); - - if (oldBean != null) { - - // dettach listener from old bean - try { - BeanUtil.removePropertyChangeListener(listener, oldBean); - } catch (Exception eee) { - log.error(String.format("Could remove the PropertychangeListener %1$s from object %2$s for following reason \\: %3$s", - listener, oldBean, eee.getMessage())); - } - } - if (bean != null) { - - // attach listener to new bean - try { - BeanUtil.addPropertyChangeListener(listener, bean); - } catch (Exception eee) { - log.error(String.format("Could not add the PropertychangeListener %1$s on object %2$s for following reason \\: %3$s", - listener, bean, eee.getMessage())); - } - } - } - - /** To clear the modified states. */ - public void clearModified() { - propertyDiffs.clear(); - } - - /** - * To change the list of properties to watch. - * - * <strong>Note:</strong> As a side-effect, we call a - * {@link #clearModified()} method after having changed the list of - * properties to watch. - * - * @param properties the list of properties to watch on the bean. - * @since 3.0 - */ - public void setProperties(String... properties) { - propertyNames.clear(); - propertyNames.addAll(Arrays.asList(properties)); - clearModified(); - } - - public boolean isExcludeMode() { - return excludeMode; - } - - public void setExcludeMode(boolean excludeMode) { - this.excludeMode = excludeMode; - clearModified(); - } -} diff --git a/src/main/java/org/nuiton/util/beans/BeanUtil.java b/src/main/java/org/nuiton/util/beans/BeanUtil.java deleted file mode 100644 index 01c9949..0000000 --- a/src/main/java/org/nuiton/util/beans/BeanUtil.java +++ /dev/null @@ -1,451 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.beans; - -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import org.apache.commons.beanutils.MethodUtils; -import org.apache.commons.beanutils.PropertyUtils; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyDescriptor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * Usefull methods around the {@link PropertyChangeListener}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4.1 - */ -public class BeanUtil { - - public static final String ADD_PROPERTY_CHANGE_LISTENER = - "addPropertyChangeListener"; - - public static final String REMOVE_PROPERTY_CHANGE_LISTENER = - "removePropertyChangeListener"; - - protected BeanUtil() { - // no instance - } - - /** - * Is a property is readable ? - * - * @since 2.5.11 - */ - public static final Predicate<PropertyDescriptor> IS_READ_DESCRIPTOR = new Predicate<PropertyDescriptor>() { - @Override - public boolean apply(PropertyDescriptor input) { - return input.getReadMethod() != null; - } - }; - - /** - * Is a property is writable ? - * - * @since 2.5.11 - */ - public static final Predicate<PropertyDescriptor> IS_WRITE_DESCRIPTOR = new Predicate<PropertyDescriptor>() { - @Override - public boolean apply(PropertyDescriptor input) { - return input.getWriteMethod() != null; - } - }; - - /** - * Is a property is readable and writable ? - * - * @since 2.5.11 - */ - public static final Predicate<PropertyDescriptor> IS_READ_AND_WRITE_DESCRIPTOR = Predicates.and( - IS_READ_DESCRIPTOR, - IS_WRITE_DESCRIPTOR - ); - - /** - * Test if the given type is JavaBean compiliant, says that it has two - * public methods : - * <ul> - * <li>{@code addPropertyChangeListener}</li> - * <li>{@code removePropertyChangeListener}</li> - * </ul> - * - * @param type type to test - * @return {@code true} if type is Javabean compiliant, {@code false} - * otherwise - * @since 2.0 - */ - public static boolean isJavaBeanCompiliant(Class<?> type) { - - try { - type.getMethod(ADD_PROPERTY_CHANGE_LISTENER, - PropertyChangeListener.class); - } catch (NoSuchMethodException e) { - // no add method - return false; - } - - try { - type.getMethod(REMOVE_PROPERTY_CHANGE_LISTENER, - PropertyChangeListener.class); - } catch (NoSuchMethodException e) { - // no add method - return false; - } - - return true; - } - - /** - * Add the given {@code listener} to the given {@code bean} using the - * normalized method named {@code addPropertyChangeListener}. - * - * @param listener the listener to add - * @param bean the bean on which the listener is added - * @throws InvocationTargetException if could not invoke the method - * {@code addPropertyChangeListener} - * @throws NoSuchMethodException if method - * {@code addPropertyChangeListener} - * does not exist on given bean - * @throws IllegalAccessException if an illegal access occurs when - * invoking the method - * {@code addPropertyChangeListener} - */ - public static void addPropertyChangeListener(PropertyChangeListener listener, - Object bean) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { - MethodUtils.invokeExactMethod(bean, - ADD_PROPERTY_CHANGE_LISTENER, - new Object[]{listener}, - new Class[]{PropertyChangeListener.class} - ); - } - - /** - * Remove the given {@code listener} from the given {@code bean} using the - * normalized method named {@code removePropertyChangeListener}. - * - * @param listener the listener to remove - * @param bean the bean on which the listener is removed - * @throws InvocationTargetException if could not invoke the method - * {@code removePropertyChangeListener} - * @throws NoSuchMethodException if method - * {@code removePropertyChangeListener} - * does not exist on given bean - * @throws IllegalAccessException if an illegal access occurs when - * invoking the method - * {@code removePropertyChangeListener} - */ - public static void removePropertyChangeListener(PropertyChangeListener listener, - Object bean) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { - MethodUtils.invokeExactMethod(bean, - REMOVE_PROPERTY_CHANGE_LISTENER, - new Object[]{listener}, - new Class[]{PropertyChangeListener.class} - ); - } - - /** - * Obtains all readable properties from a given type. - * - * @param beanType the type to seek - * @return the set of all readable properties for the given type - * @since 2.0 - */ - public static Set<String> getReadableProperties(Class<?> beanType) { - Set<Class<?>> exploredTypes = new HashSet<Class<?>>(); - Set<String> result = new HashSet<String>(); - - // get properties for the class - getReadableProperties(beanType, result, exploredTypes); - - // the special getClass will never be a JavaBean property... - result.remove("class"); - - return result; - } - - /** - * Obtains all writeable properties from a given type. - * - * @param beanType the type to seek - * @return the set of all writeable properties for the given type - * @since 2.0 - */ - public static Set<String> getWriteableProperties(Class<?> beanType) { - Set<Class<?>> exploredTypes = new HashSet<Class<?>>(); - Set<String> result = new HashSet<String>(); - - // get properties for the class - getWriteableProperties(beanType, result, exploredTypes); - - return result; - } - - /** - * Obtains all readable properties from a given type. - * - * @param beanType the type to seek - * @param propertyName FIXME - * @return the set of all readable properties for the given type - * @since 2.0 - */ - public static boolean isNestedReadableProperty(Class<?> beanType, String propertyName) { - boolean result = propertyName.contains("."); - if (result) { - int dotIndex = propertyName.indexOf("."); - String firstLevelProperty = propertyName.substring(0, dotIndex); - - Class<?> nestedType = getReadableType(beanType, firstLevelProperty); - if (nestedType == null) { - - result = false; - } else { - - String rest = propertyName.substring(dotIndex + 1); - result = isNestedReadableProperty(nestedType, rest); - } - - } else { - - // not a nested property check it directly - Class<?> nestedType = getReadableType(beanType, propertyName); - result = nestedType != null; - } - - return result; - } - - public static Class<?> getReadableType(Class<?> beanType, String propertyName) { - PropertyDescriptor[] descriptors = - PropertyUtils.getPropertyDescriptors(beanType); - - Class<?> result = null; - for (PropertyDescriptor descriptor : descriptors) { - String name = descriptor.getName(); - if (descriptor.getReadMethod() != null && - propertyName.equals(name)) { - result = descriptor.getReadMethod().getReturnType(); - break; - } - } - - if (result == null) { - - // try with super-class - if (beanType.getSuperclass() != null) { - - // get properties fro super-class - result = getReadableType(beanType.getSuperclass(), propertyName); - } - } - - if (result == null) { - - // try it with interfaces - Class<?>[] interfaces = beanType.getInterfaces(); - for (Class<?> anInterface : interfaces) { - - result = getReadableType(anInterface, propertyName); - - if (result != null) { - - // found it - break; - } - } - } - return result; - } - - /** - * Scan the given type and obtain {@link PropertyDescriptor} - * given the (optional) predicate (except the {@code class} property of - * any java object). - * - * <strong>Note:</strong> If no predicate is given, then all descriptors - * are returned. - * - * @param beanType the bean type to scan - * @param predicate the optional predicate to keep descriptor - * @return set of all matching descriptors - * @since 2.6.11 - */ - public static Set<PropertyDescriptor> getDescriptors(Class<?> beanType, - Predicate<PropertyDescriptor> predicate) { - - if (predicate == null) { - predicate = Predicates.alwaysTrue(); - } - - Set<Class<?>> exploredTypes = new HashSet<Class<?>>(); - Map<String, PropertyDescriptor> result = new TreeMap<String, PropertyDescriptor>(); - - getDescriptors(beanType, predicate, result, exploredTypes); - - // the special getClass will never be a JavaBean property... - result.remove("class"); - - return new HashSet<PropertyDescriptor>(result.values()); - } - - public static Method getMutator(Object bean, String property) { - Method mutator = null; - if (bean == null) { - throw new NullPointerException("could not find bean"); - } - if (property == null) { - throw new NullPointerException("could not find property"); - } - - try { - PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(bean, property); - if (descriptor != null) { - mutator = descriptor.getWriteMethod(); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - - return mutator; - } - - protected static void getDescriptors(Class<?> beanType, - Predicate<PropertyDescriptor> predicate, - Map<String, PropertyDescriptor> result, - Set<Class<?>> exploredTypes) { - - if (exploredTypes.contains(beanType)) { - - // already explored - return; - } - exploredTypes.add(beanType); - - PropertyDescriptor[] descriptors = - PropertyUtils.getPropertyDescriptors(beanType); - - for (PropertyDescriptor descriptor : descriptors) { - String name = descriptor.getName(); - if (!result.containsKey(name) && predicate.apply(descriptor)) { - result.put(name, descriptor); - } - } - - if (beanType.getSuperclass() != null) { - - // get properties fro super-class - getDescriptors(beanType.getSuperclass(), predicate, result, exploredTypes); - } - Class<?>[] interfaces = beanType.getInterfaces(); - for (Class<?> anInterface : interfaces) { - - // get properties fro super-class - getDescriptors(anInterface, predicate, result, exploredTypes); - } - } - - protected static void getReadableProperties(Class<?> beanType, - Set<String> result, - Set<Class<?>> exploredTypes) { - - if (exploredTypes.contains(beanType)) { - - // already explored - return; - } - exploredTypes.add(beanType); - - // get properties for the class - getReadableProperties(beanType, result); - - if (beanType.getSuperclass() != null) { - - // get properties fro super-class - getReadableProperties(beanType.getSuperclass(), result, exploredTypes); - } - Class<?>[] interfaces = beanType.getInterfaces(); - for (Class<?> anInterface : interfaces) { - - // get properties fro super-class - getReadableProperties(anInterface, result, exploredTypes); - } - } - - protected static void getReadableProperties(Class<?> beanType, - Set<String> result) { - - PropertyDescriptor[] descriptors = - PropertyUtils.getPropertyDescriptors(beanType); - for (PropertyDescriptor descriptor : descriptors) { - String name = descriptor.getName(); - if (descriptor.getReadMethod() != null) { - result.add(name); - } - } - } - - protected static void getWriteableProperties(Class<?> beanType, - Set<String> result, - Set<Class<?>> exploredTypes) { - - if (exploredTypes.contains(beanType)) { - - // already explored - return; - } - exploredTypes.add(beanType); - - // get properties for the class - getWriteableProperties(beanType, result); - - if (beanType.getSuperclass() != null) { - - // get properties fro super-class - getWriteableProperties(beanType.getSuperclass(), result, exploredTypes); - } - Class<?>[] interfaces = beanType.getInterfaces(); - for (Class<?> anInterface : interfaces) { - - // get properties fro super-class - getWriteableProperties(anInterface, result, exploredTypes); - } - } - - protected static void getWriteableProperties(Class<?> beanType, - Set<String> result) { - - PropertyDescriptor[] descriptors = - PropertyUtils.getPropertyDescriptors(beanType); - for (PropertyDescriptor descriptor : descriptors) { - String name = descriptor.getName(); - if (descriptor.getReadMethod() != null) { - result.add(name); - } - } - } -} diff --git a/src/main/java/org/nuiton/util/beans/Binder.java b/src/main/java/org/nuiton/util/beans/Binder.java deleted file mode 100644 index b94131a..0000000 --- a/src/main/java/org/nuiton/util/beans/Binder.java +++ /dev/null @@ -1,1086 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.beans; - -import com.google.common.base.Defaults; -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.util.ObjectUtil; - -import java.beans.PropertyDescriptor; -import java.io.Serializable; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * A {@code binder} permits to copy some properties from an object to another - * one. - * - * It is based on a {@link BinderModel} which contains the mapping of properties - * to transfert from the source object to the destination object. - * - * Use the method {@link #copy(Object, Object, String...)} to transfert properties. - * - * Use the method {@link #obtainProperties(Object, String...)} to obtain some - * properties from a given object. - * - * For more informations about how to obtain a binder, see the - * {@link BinderFactory} or the package info javadoc or unit tests... - * - * @param <I> the source bean type - * @param <O> the destination bean type - * @author Tony Chemit - chemit@codelutin.com - * @see BinderFactory - * @see BinderModelBuilder - * @since 1.1.5 - */ -public class Binder<I, O> implements Serializable { - - /** Logger. */ - private static final Log log = LogFactory.getLog(Binder.class); - - private static final long serialVersionUID = 1L; - - /** - * Types of loading of collections. - * - * @since 1.3 - */ - public enum CollectionStrategy { - - /** To just copy the reference of the collection. */ - copy { - public Object copy(Object readValue) { - - // by default, just return same reference - return readValue; - } - }, - - /** To duplicate the collection */ - duplicate { - @SuppressWarnings({"unchecked"}) - @Override - public Object copy(Object readValue) { - if (readValue instanceof LinkedHashSet<?>) { - return new LinkedHashSet((Set<?>) readValue); - } - if (readValue instanceof Set<?>) { - return new HashSet((Set<?>) readValue); - } - // in any other cases, let says this is a ArrayList - if (readValue instanceof Collection<?>) { - return new ArrayList((Collection<?>) readValue); - } - return readValue; - } - }, - /** - * To bind the collection. - * - * <strong>Warning:</strong> Do not use it in the method {@link BinderModelBuilder#addCollectionStrategy(CollectionStrategy, String...)} - * since it is only use in internaly by the method {@link BinderModelBuilder#addCollectionBinder(Binder, String...)} - * - * Note: at this level, we will just create the collection. - */ - bind { - @Override - public Object copy(Object readValue) { - if (readValue instanceof LinkedHashSet<?>) { - return new LinkedHashSet(); - } - if (readValue instanceof Set<?>) { - return new HashSet(); - } - // in any other cases, let says this is a ArrayList - if (readValue instanceof Collection<?>) { - return new ArrayList(); - } - return readValue; - } - }; - - /** - * Copy a given collection. - * - * @param readValue the collection value to copy - * @return the copied collection - */ - public abstract Object copy(Object readValue); - } - - /** the model of the binder */ - protected BinderModel<I, O> model; - - /** - * Obtains the type of the source bean. - * - * @return the type of the source bean - */ - public Class<I> getSourceType() { - return getModel().getSourceType(); - } - - /** - * Obtains the type of the target bean. - * - * @return the type of the target bean - */ - public Class<O> getTargetType() { - return getModel().getTargetType(); - } - - /** - * Obtain from the given object all properties registered in the binder - * model. - * - * @param source the bean to read - * @param propertyNames subset of properties to load - * @param includeNullValues get <strong>all</strong> the properties and - * values for the given bean. If false, you'll get only the values - * @return the map of properties obtained indexed by their property name, - * or an empty map is the given {@code from} is {@code null}. - * @since 2.3 - */ - public Map<String, Object> obtainProperties(I source, - boolean includeNullValues, String... propertyNames) { - if (source == null) { - // special limit case - return Collections.emptyMap(); - } - - propertyNames = getProperties(propertyNames); - - Map<String, Object> result = new TreeMap<String, Object>(); - for (String sourceProperty : propertyNames) { - - try { - Object read; - Method readMethod = model.getSourceReadMethod(sourceProperty); - read = readMethod.invoke(source); - if (log.isDebugEnabled()) { - log.debug("property " + sourceProperty + ", type : " + - readMethod.getReturnType() + ", value = " + read); - } - if (readMethod.getReturnType().isPrimitive() && - ObjectUtil.getNullValue( - readMethod.getReturnType()).equals(read)) { - // for primitive type case, force nullity - read = null; - } - if (read != null) { - if (model.containsBinderProperty(sourceProperty)) { - if (model.containsCollectionProperty(sourceProperty)) { - read = bindCollection(sourceProperty, read); - } else { - read = bindProperty(sourceProperty, read); - } - } else if (model.containsCollectionProperty(sourceProperty)) { - - // specific collection strategy is set, must use it - read = getCollectionValue(sourceProperty, read); - } - } - - boolean include = read != null || includeNullValues; - if (include) { - result.put(sourceProperty, read); - } - } catch (Exception e) { - throw new RuntimeException("Could not obtain property: " + sourceProperty, e); - } - } - return result; - } - - /** - * Obtain from the given object all properties registered in the binder - * model. - * - * <b>Note:</b> If a property's value is null, it will not be injected in - * the result. - * - * @param source the bean to read - * @param propertyNames subset of properties to load - * @return the map of properties obtained indexed by their property name, - * or an empty map is the given {@code from} is {@code null}. - */ - public Map<String, Object> obtainProperties(I source, - String... propertyNames) { - return obtainProperties(source, false, propertyNames); - } - - /** - * Obtain a property from a source object (A source object type reflect - * the source type of the binder). - * - * <b>Note:</b> The property value has no special treatment, the result - * is the exact value from the source object (no binder collection transformation, ...). - * - * @param source the source object to inspect - * @param propertyName name of the property to get - * @param <OO> type of property to get - * @return the property value in the source object. - * @since 3.0 - */ - public <OO> OO obtainSourceProperty(I source, String propertyName) { - - Preconditions.checkNotNull(source, "source can not be null"); - Preconditions.checkNotNull(propertyName, "propertyName can not be null"); - - Method readMethod = model.getSourceReadMethod(propertyName); - - Preconditions.checkNotNull(readMethod, "Could not find source getter for property: " + propertyName); - - try { - OO result = (OO) readMethod.invoke(source); - if (log.isDebugEnabled()) { - log.debug("property " + propertyName + ", type : " + - readMethod.getReturnType() + ", value = " + result); - } - return result; - - } catch (Exception e) { - throw new RuntimeException("Could not obtain property: " + propertyName, e); - } - } - - /** - * Obtain a property from a target object (A target object type reflect - * the target type of the binder). - * - * <b>Note:</b> The property value has no special treatment, the result - * is the exact value from the target object (no binder collection transformation, ...). - * - * @param target the target object to inspect - * @param propertyName name of the property to get - * @param <OO> type of property to get - * @return the property value in the target object. - * @since 3.0 - */ - public <OO> OO obtainTargetProperty(O target, String propertyName) { - - Preconditions.checkNotNull(target, "target can not be null"); - Preconditions.checkNotNull(propertyName, "propertyName can not be null"); - - Method readMethod = model.getTargetReadMethod(propertyName); - - Preconditions.checkNotNull(readMethod, "Could not find target getter for property: " + propertyName); - - try { - OO result = (OO) readMethod.invoke(target); - if (log.isDebugEnabled()) { - log.debug("property " + propertyName + ", type : " + - readMethod.getReturnType() + ", value = " + result); - } - return result; - - } catch (Exception e) { - throw new RuntimeException("Could not obtain property: " + propertyName, e); - } - - } - - /** - * Inject all not null properties to the target bean. - * - * @param properties properties to set into bean - * @param target the bean to set - * @since 3.0 - */ - public void injectProperties(Map<String, Object> properties, O target) { - injectProperties(properties, target, false); - } - - /** - * Inject all properties to the target bean. - * - * @param properties properties to set into bean - * @param target the bean to set - * @param includeNullValues {@code true} to set also null properties values - * @since 3.0 - */ - public void injectProperties(Map<String, Object> properties, O target, boolean includeNullValues) { - - boolean useFunctions = model.isUseFunctions(); - - for (Map.Entry<String, Object> entry : properties.entrySet()) { - String propertyName = entry.getKey(); - if (!getModel().containsTargetProperty(propertyName)) { - - throw new IllegalStateException("Could not find property '" + propertyName + "' in binder " + this + "."); - } - - Object propertyValue = entry.getValue(); - if (propertyValue == null && !includeNullValues) { - - // Skip null value - continue; - } - - if (log.isDebugEnabled()) { - log.debug("Inject property: " + propertyName + " to " + target); - } - if (useFunctions && propertyValue != null) { - propertyValue = transform(propertyName, propertyValue); - } - if (propertyValue == null) { - Class<?> targetPropertyType = getTargetPropertyType(propertyName); - if (targetPropertyType.isPrimitive()) { - propertyValue = Defaults.defaultValue(targetPropertyType); - } - } - Method writeMethod = getModel().getTargetWriteMethod(propertyName); - try { - writeMethod.invoke(target, propertyValue); - } catch (Exception e) { - throw new RuntimeException( - "Could not set property [" + - target.getClass().getName() + ":" + - propertyName + "]", e); - } - - } - - } - - protected Object transform(String propertyName, Object propertyValue) { - Function function = model.getFunction(propertyValue.getClass()); - if (function != null) { - if (log.isDebugEnabled()) { - log.debug("Transform property: " + propertyName); - } - propertyValue = function.apply(propertyValue); - } - return propertyValue; - } - - /** - * Copy properties from a source bean to a destination one according to - * the model of the binder. If {@code propertyNames} is defined, only - * those properties will be copied. - * - * <b>Note:</b> If {@code from} object is null, then {@code null} values - * will be set to mapped properties into {@code dst} - * - * @param source the bean to read - * @param target the bean to write - * @param propertyNames optional subset of properties to copy (if none is - * specifed, will use all the properties defined in - * binder) - * @throws NullPointerException if target parameter is {@code null} - */ - public void copy(I source, O target, String... propertyNames) { - copy(source, target, false, propertyNames); - } - - /** - * Copy properties from a source bean to a destination one according to - * the model of the binder excluding {@code propertyNames}. - * - * <b>Note:</b> If {@code from} object is null, then {@code null} values - * will be set to mapped properties into {@code dst}. - * - * @param source the bean to read - * @param target the bean to write - * @param propertyNames optional subset of properties to copy (if none is - * specifed, will use all the properties defined in - * binder) - * @throws NullPointerException if target parameter is {@code null} - */ - public void copyExcluding(I source, O target, String... propertyNames) { - copy(source, target, true, propertyNames); - } - - /** - * Get the type of a source property. - * - * @param propertyName name of the source property - * @return the type of the source property - * @throws IllegalArgumentException if binder does not define this source property - */ - public Class<?> getSourcePropertyType(String propertyName) { - if (!model.containsSourceProperty(propertyName)) { - throw new IllegalArgumentException("Binder " + this + " does not contains source property: " + propertyName); - } - return model.getSourceReadMethod(propertyName).getReturnType(); - } - - /** - * Get the generic type of a source property. - * - * @param propertyName name of the source property - * @return the generic type of the source property - * @throws IllegalArgumentException if binder does not define this source property - */ - public Type getSourcePropertyGenericType(String propertyName) { - if (!model.containsSourceProperty(propertyName)) { - throw new IllegalArgumentException("Binder " + this + " does not contains source property: " + propertyName); - } - return model.getSourceReadMethod(propertyName).getGenericReturnType(); - } - - /** - * Get the type of a target property. - * - * @param propertyName name of the target property - * @return the type of the target property - * @throws IllegalArgumentException if binder does not define this target property - */ - public Class<?> getTargetPropertyType(String propertyName) { - if (!model.containsTargetProperty(propertyName)) { - throw new IllegalArgumentException("Binder " + this + " does not contains target property: " + propertyName); - } - return model.getTargetWriteMethod(propertyName).getParameterTypes()[0]; - } - - /** - * Get the generic type of a target property. - * - * @param propertyName name of the target property - * @return the generic type of the target property - * @throws IllegalArgumentException if binder does not define this target property - */ - public Type getTargetPropertyGenericType(String propertyName) { - if (!model.containsTargetProperty(propertyName)) { - throw new IllegalArgumentException("Binder " + this + " does not contains target property: " + propertyName); - } - return model.getTargetWriteMethod(propertyName).getGenericParameterTypes()[0]; - } - - /** - * Copy properties from a source bean to a destination one according to - * the model of the binder. - * - * <b>Note:</b> If {@code from} object is null, then {@code null} values - * will be set to mapped properties into {@code dst}. - * - * @param source the bean to read - * @param target the bean to write - * @param excludeProperties true to exclude following {@code propertyNames} - * @param propertyNames optional subset of properties to copy (if none is - * specifed, will use all the properties defined in - * binder) - * @throws NullPointerException if target parameter is {@code null} - * @throws RuntimeException if a property can not be copied to the target object - */ - protected void copy(I source, O target, boolean excludeProperties, - String... propertyNames) - throws RuntimeException { - if (target == null) { - throw new NullPointerException("parameter 'target' can no be null"); - } - - propertyNames = excludeProperties ? - getAllPropertiesExclude(propertyNames) : - getProperties(propertyNames); - - boolean useFunctions = model.isUseFunctions(); - - for (String sourceProperty : propertyNames) { - - String targetProperty = model.getTargetProperty(sourceProperty); - - try { - Object read = null; - Method readMethod = model.getSourceReadMethod(sourceProperty); - if (source != null) { - // obtain value from source - read = readMethod.invoke(source); - } - // obtain acceptable null value (for primitive types, use - // default values). - if (read == null) { - read = ObjectUtil.getNullValue(readMethod.getReturnType()); - } - if (log.isDebugEnabled()) { - log.debug("property " + sourceProperty + ", type : " + - readMethod.getReturnType() + ", value = " + read); - } - - if (model.containsBinderProperty(sourceProperty)) { - if (model.containsCollectionProperty(sourceProperty)) { - read = bindCollection(sourceProperty, read); - } else { - read = bindProperty(sourceProperty, read); - } - } else if (model.containsCollectionProperty(sourceProperty)) { - - // specific collection strategy is set, must use it - read = getCollectionValue(sourceProperty, read); - } - if (useFunctions && read != null) { - read = transform(sourceProperty, read); - } - model.getTargetWriteMethod(targetProperty).invoke(target, read); - } catch (Exception e) { - throw new RuntimeException( - "Could not bind property [" + - source.getClass().getName() + ":" + - sourceProperty + "] to [" + - target.getClass().getName() + ":" + - targetProperty + "]", e); - } - } - } - - protected Object readProperty(String sourceProperty, Object source, - Method readMethod) { - try { - Object read = null; - if (source != null) { - // obtain value from source - read = readMethod.invoke(source); - } - // obtain acceptable null value (for primitive types, use - // default values). - if (read == null) { - read = ObjectUtil.getNullValue(readMethod.getReturnType()); - } - if (log.isDebugEnabled()) { - log.debug("property " + sourceProperty + ", type : " + - readMethod.getReturnType() + ", value = " + read); - } - - if (model.containsBinderProperty(sourceProperty)) { - if (model.containsCollectionProperty(sourceProperty)) { - read = bindCollection(sourceProperty, read); - } else { - read = bindProperty(sourceProperty, read); - } - } else if (model.containsCollectionProperty(sourceProperty)) { - - // specific collection strategy is set, must use it - read = getCollectionValue(sourceProperty, read); - } - - return read; - } catch (Exception e) { - throw new RuntimeException( - "could not read property " + sourceProperty + - " on source " + source); - } - } - - protected List<PropertyDiff> diff(I source, - O target, - boolean excludeProperties, - String... propertyNames) { - if (source == null) { - throw new NullPointerException("parameter 'source' can no be null"); - } - if (target == null) { - throw new NullPointerException("parameter 'target' can no be null"); - } - - propertyNames = excludeProperties ? - getAllPropertiesExclude(propertyNames) : - getProperties(propertyNames); - - List<PropertyDiff> result = new LinkedList<PropertyDiff>(); - - for (String sourceProperty : propertyNames) { - - Method sourceReadMethod = model.getSourceReadMethod(sourceProperty); - - Object sourceRead = readProperty(sourceProperty, source, - sourceReadMethod); - - String targetProperty = model.getTargetProperty(sourceProperty); - - Method targetReadMethod = model.getTargetReadMethod(targetProperty); - - Object targetRead = readProperty(targetProperty, target, - targetReadMethod); - - if (ObjectUtils.notEqual(sourceRead, targetRead)) { - PropertyDiff propertyDiff = new PropertyDiff( - sourceProperty, - sourceRead, - targetProperty, - targetRead, - sourceReadMethod.getReturnType() - ); - result.add(propertyDiff); - } - } - - return result; - } - - /** - * Compare two beans property by property according to the model. - * - * List contains one element per property with different values (according - * to the result of an equals() call) - * - * @param source a bean of type I - * @param target a bean of type O - * @return a list with all the properties which values differ in source - * and target. Properties with equal values are not included. - * @since 2.3 - */ - public List<PropertyDiff> diff(I source, O target) { - return diff(source, target, false); - } - - /** - * Compare two beans property by property according to the model. - * - * List contains one element per property with different values (according - * to the result of an equals() call) - * - * @param source a bean of type I - * @param target a bean of type O - * @param propertyNames property names to exclude from the diff - * @return a list with all the properties which values differ in source - * and target. Properties with equal values and excluded properties - * will not be contained in the result - * @since 2.3 - */ - public List<PropertyDiff> diffExcluding(I source, - O target, - String... propertyNames) { - return diff(source, target, true, propertyNames); - } - - /** - * Get the model of the binder. - * - * @return the model of the binder - */ - protected BinderModel<I, O> getModel() { - return model; - } - - /** - * Set the model of the binder. - * - * @param model the model of the binder - */ - protected void setModel(BinderModel<I, O> model) { - this.model = model; - } - - /** - * Obtain the properties, if none is given in {@code propertyNames} - * parameter, will use all property names defined in binder's model, - * otherwise, check that all given property names are safe (registred in - * binder's model). - * - * @param propertyNames optional subset of properties to get - * @return the array of property names - */ - protected String[] getProperties(String... propertyNames) { - - if (propertyNames.length == 0) { - // use all properties in the binder - propertyNames = model.getSourceDescriptors(); - } else { - - // use a subset of properties, must check them - for (String propertyName : propertyNames) { - if (!model.containsSourceProperty(propertyName)) { - throw new IllegalArgumentException( - "property '" + propertyName + - "' is not known by binder"); - } - } - } - return propertyNames; - } - - /** - * Obtains all properties from binder's model except those {@code - * propertyNameExcludes}. Unknown properties will be ignored. - * - * @param propertyNameExcludes name of properties to exclude - * @return the array of property names without those in argument - */ - protected String[] getAllPropertiesExclude(String... propertyNameExcludes) { - List<String> excludes = Arrays.asList(propertyNameExcludes); - List<String> results = new ArrayList<String>(); - for (String propertyName : model.getSourceDescriptors()) { - if (!excludes.contains(propertyName)) { - results.add(propertyName); - } - } - return results.toArray(new String[results.size()]); - } - - protected Object getCollectionValue(String sourceProperty, Object readValue) { - CollectionStrategy strategy = - model.getCollectionStrategy(sourceProperty); - Object result = strategy.copy(readValue); - return result; - } - - protected Object bindProperty(String sourceProperty, Object read) throws IllegalAccessException, InstantiationException { - Binder<?, ?> binder = model.getBinder(sourceProperty); - Object result = bind(binder, read); - return result; - } - - @SuppressWarnings({"unchecked"}) - protected Object bindCollection(String sourceProperty, Object read) throws IllegalAccessException, InstantiationException { - - if (read == null) { - return null; - } - - Binder<?, ?> binder = model.getBinder(sourceProperty); - - Collection result = (Collection) model.getCollectionStrategy(sourceProperty).copy(read); - -// if (read instanceof LinkedHashSet<?>) { -// result = new LinkedHashSet(); -// } else if (read instanceof Set<?>) { -// result = new HashSet(); -// } else { -// -// // in any other cases, let says this is a ArrayList -// result = new ArrayList(); -// } - Collection<?> collection = (Collection<?>) read; - for (Object o : collection) { - Object r = bind(binder, o); - result.add(r); - } - return result; - } - - @SuppressWarnings({"unchecked"}) - protected Object bind(Binder binder, Object read) throws IllegalAccessException, InstantiationException { - Object result = null; - if (read != null) { - InstanceFactory<O> instanceFactory = binder.model.getInstanceFactory(); - if (instanceFactory == null) { - result = read.getClass().newInstance(); - } else { - result = instanceFactory.newInstance(); - } - binder.copy(read, result); - } - return result; - } - - /** - * Model of a {@link Binder}. - * - * TODO tchemit 20100225 should have special cases for collections treatment. - * - * @param <S> the source type - * @param <T> the target type - * @author Tony Chemit - chemit@codelutin.com - * @since 1.1.5 - */ - public static class BinderModel<S, T> implements Serializable { - - /** source type */ - protected final Class<S> sourceType; - - /** destination type */ - protected final Class<T> targetType; - - /** source type descriptors (key are property names) */ - protected final Map<String, PropertyDescriptor> sourceDescriptors; - - /** destination descriptors (key are property names) */ - protected final Map<String, PropertyDescriptor> targetDescriptors; - - /** - * properties mapping (key are source properties, value are destination - * properties) - */ - protected final Map<String, String> propertiesMapping; - - /** mapping of collection properties strategies */ - protected Map<String, CollectionStrategy> collectionStrategies; - - /** mapping of extra binders to use to copy properties */ - protected Map<String, Binder<?, ?>> binders; - - /** factory of target Instance */ - protected InstanceFactory<T> instanceFactory; - - /** - * Dictonnary of function to apply by source class type. - */ - protected final Map<Class<?>, Function<?, ?>> functions; - - private static final long serialVersionUID = 2L; - - public BinderModel(Class<S> sourceType, Class<T> targetType) { - this.sourceType = sourceType; - this.targetType = targetType; - sourceDescriptors = new TreeMap<String, PropertyDescriptor>(); - targetDescriptors = new TreeMap<String, PropertyDescriptor>(); - propertiesMapping = new TreeMap<String, String>(); - collectionStrategies = new TreeMap<String, CollectionStrategy>(); - binders = new TreeMap<String, Binder<?, ?>>(); - functions = new LinkedHashMap<>(); - } - - /** - * Gets the type of the binder's source. - * - * @return the type of the source object in the binder - */ - public Class<S> getSourceType() { - return sourceType; - } - - /** - * Gets the type of the binder's destination - * - * @return the type of the destination object in the binder - */ - public Class<T> getTargetType() { - return targetType; - } - - /** - * Gets all registred property names of the binder's source type. - * - * @return the array of all source object properties names to bind - */ - public String[] getSourceDescriptors() { - Set<String> universe = sourceDescriptors.keySet(); - return universe.toArray(new String[sourceDescriptors.size()]); - } - - public CollectionStrategy getCollectionStrategy(String property) { - return collectionStrategies.get(property); - } - - /** - * Gets all registred property names of the binder's destination type. - * - * @return the array of all source object properties names to bind - */ - public String[] getTargetDescriptors() { - Set<String> universe = targetDescriptors.keySet(); - return universe.toArray(new String[targetDescriptors.size()]); - } - - /** - * Gets the destination property name given the - * - * @param sourceProperty the name of the source property to bind - * @return the name of the destination object property to bind, or - * {@code null} if {@code propertySrc} is unknown in the model - */ - public String getTargetProperty(String sourceProperty) { - if (!containsSourceProperty(sourceProperty)) { - return null; - } - String dstProperty = propertiesMapping.get(sourceProperty); - return dstProperty; - } - - /** - * Gets the bean descriptor of the source type for the given - * destination property. - * - * @param sourceProperty name of the source type property name - * @return the descriptor or {@code null} if not found. - */ - public PropertyDescriptor getSourceDescriptor(String sourceProperty) { - // check src property is registred - if (!containsSourceProperty(sourceProperty)) { - return null; - } - PropertyDescriptor descriptor = sourceDescriptors.get(sourceProperty); - return descriptor; - } - - /** - * @param srcProperty the name of a property of the source object. - * @return the method to read in a source object for the given property. - */ - public Method getSourceReadMethod(String srcProperty) { - PropertyDescriptor descriptor = getSourceDescriptor(srcProperty); - Method readMethod = null; - if (descriptor != null) { - readMethod = descriptor.getReadMethod(); - } - return readMethod; - } - - /** - * @param sourceProperty the name of a property of the source object. - * @return the method to write in a source object for the given property. - */ - public Method getSourceWriteMethod(String sourceProperty) { - PropertyDescriptor descriptor = getSourceDescriptor(sourceProperty); - Method writeMethod = null; - if (descriptor != null) { - writeMethod = descriptor.getWriteMethod(); - } - return writeMethod; - } - - /** - * Gets the bean descriptor of the destination type for the given - * destination property. - * - * @param targetProperty name of the destination type property name - * @return the descriptor or {@code null} if not found. - */ - public PropertyDescriptor getTargetDescriptor(String targetProperty) { - // check dst property is registred - if (!containsTargetProperty(targetProperty)) { - return null; - } - PropertyDescriptor descriptor = targetDescriptors.get(targetProperty); - return descriptor; - } - - /** - * @param targetProperty the name of a property of the destination object. - * @return the method to read in a destination object for the given - * property. - */ - public Method getTargetReadMethod(String targetProperty) { - PropertyDescriptor descriptor = getTargetDescriptor(targetProperty); - Method readMethod = null; - if (descriptor != null) { - readMethod = descriptor.getReadMethod(); - } - return readMethod; - } - - /** - * @param targetProperty the name of a property of the destination object. - * @return the method to write in a destination object for the given - * property. - */ - public Method getTargetWriteMethod(String targetProperty) { - PropertyDescriptor descriptor = getTargetDescriptor(targetProperty); - Method writeMethod = null; - if (descriptor != null) { - writeMethod = descriptor.getWriteMethod(); - } - return writeMethod; - } - - public Class<?> getCollectionType(String sourceProperty) { - Method method = getSourceReadMethod(sourceProperty); - Class<?> type = method.getReturnType(); - if (Collection.class.isAssignableFrom(type)) { - return type; - } - return null; - } - - public void addCollectionStrategy(String propertyName, - CollectionStrategy strategy) { - collectionStrategies.put(propertyName, strategy); - } - - public void addBinder(String propertyName, Binder<?, ?> binder) { - binders.put(propertyName, binder); - } - - public boolean containsSourceProperty(String sourceProperty) { - return propertiesMapping.containsKey(sourceProperty); - } - - public boolean containsTargetProperty(String targetProperty) { - return propertiesMapping.containsValue(targetProperty); - } - - public boolean containsCollectionProperty(String propertyName) { - return collectionStrategies.containsKey(propertyName); - } - - public boolean containsBinderProperty(String propertyName) { - return binders.containsKey(propertyName); - } - - protected void addBinding(PropertyDescriptor sourceDescriptor, - PropertyDescriptor targetDescriptor) { - - String sourceProperty = sourceDescriptor.getName(); - String targetProperty = targetDescriptor.getName(); - sourceDescriptors.put(sourceProperty, sourceDescriptor); - targetDescriptors.put(targetProperty, targetDescriptor); - propertiesMapping.put(sourceProperty, targetProperty); - } - - protected void removeBinding(String source) { - String target = propertiesMapping.get(source); - - sourceDescriptors.remove(source); - targetDescriptors.remove(target); - propertiesMapping.remove(source); - - if (containsBinderProperty(source)) { - binders.remove(source); - } - if (containsCollectionProperty(source)) { - collectionStrategies.remove(source); - } - } - - protected Map<String, String> getPropertiesMapping() { - return propertiesMapping; - } - - public Binder<?, ?> getBinder(String sourceProperty) { - return binders.get(sourceProperty); - } - - public void setInstanceFactory(InstanceFactory<T> instanceFactory) { - this.instanceFactory = instanceFactory; - } - - public InstanceFactory<T> getInstanceFactory() { - return instanceFactory; - } - - public Function getFunction(Class<?> aClass) { - return functions.get(aClass); - } - - public boolean isUseFunctions() { - return !functions.isEmpty(); - } - - } -} diff --git a/src/main/java/org/nuiton/util/beans/BinderFactory.java b/src/main/java/org/nuiton/util/beans/BinderFactory.java deleted file mode 100644 index 42f6144..0000000 --- a/src/main/java/org/nuiton/util/beans/BinderFactory.java +++ /dev/null @@ -1,522 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.beans; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * Factory of {@link Binder}. - * - * <h1>Obtain a new binder</h1> - * To obtain a new binder you can use the {@code newBinder(XXX)} methods. - * - * For example to obtain a mirrored binder (same source and target type) which - * will be able to copy all accepting properties, use this code : - * <pre> - * Binder<BeanA, BeanA> binder = BinderFactory.newBinder(BeanA.class); - * </pre> - * <h1>Usage of contextale binder</h1> - * It is possible to use different binder for same source and target type, using a - * extra context name parameter, like this : - * <pre> - * Binder<BeanA, BeanA> binder = BinderFactory.newBinder(BeanA.class, "mycontext"); - * </pre> - * - * This is usefull when you register your own binder model in the factory (see - * next section) to bind different things from the same type of objects... - * - * <h1>Register a new binder model</h1> - * To register a new binder's model use one of the method {@code registerBinderModel(XXX)}. - * - * - * More documentation will come soon, yu can see the package info javadoc or - * unit tests... - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.5.3 - */ -public class BinderFactory { - - /** Logger. */ - private static final Log log = LogFactory.getLog(BinderFactory.class); - - /** Cache of registred binders indexed by their unique entry */ - protected static BindelModelEntryMap binderModels; - - /** - * Gets the registred mirror binder (source type = target type) with no - * context name specified. - * - * @param sourceType the type of source and target - * @param <S> the type of source and target - * @return the registred binder or {@code null} if not found. - */ - public static <S> Binder<S, S> newBinder(Class<S> sourceType) { - return newBinder0(sourceType, sourceType, null, Binder.class); - } - - /** - * Gets the registred mirror binder (source type = target type) with the - * given context name. - * - * @param sourceType the type of source and target - * @param contextName the context's name of the searched binder - * @param <S> the type of source and target - * @return the registred binder or {@code null} if not found. - */ - public static <S> Binder<S, S> newBinder(Class<S> sourceType, - String contextName) { - return newBinder0(sourceType, sourceType, contextName, Binder.class); - } - - /** - * Gets the registred binder given his types with no context name. - * - * @param sourceType the type of source - * @param targetType the type of target - * @param <S> the type of source - * @param <T> the type of target - * @return the registred binder or {@code null} if not found. - */ - public static <S, T> Binder<S, T> newBinder(Class<S> sourceType, - Class<T> targetType) { - return newBinder0(sourceType, targetType, null, Binder.class); - } - - - /** - * Gets the registred binder given his types with no context name. - * - * @param sourceType the type of source - * @param targetType the type of target - * @param contextName the context's name of the searched binder - * @param <S> the type of source - * @param <T> the type of target - * @return the registred binder or {@code null} if not found. - */ - public static <S, T> Binder<S, T> newBinder(Class<S> sourceType, - Class<T> targetType, - String contextName) { - return newBinder0(sourceType, targetType, contextName, Binder.class); - } - - /** - * Gets the registred binder given his types and his context's name. - * - * @param sourceType the type of source - * @param targetType the type of target - * @param contextName the context's name of the searched binder - * @param binderType type of binder required - * @param <S> the type of source - * @param <T> the type of target - * @param <B> the type of binder - * @return the new instanciated binder. - */ - public static <S, T, B extends Binder<S, T>> B newBinder(Class<S> sourceType, - Class<T> targetType, - String contextName, - Class<B> binderType) { - B binder = (B) newBinder0(sourceType, targetType, contextName, binderType); - return binder; - } - - public static <S, T> Binder.BinderModel<S, T> registerBinderModel(BinderModelBuilder<S, T> binderModelBuilder) throws IllegalArgumentException { - Binder.BinderModel<S, T> model = registerBinderModel(binderModelBuilder, null); - return model; - } - - public static <S, T> Binder.BinderModel<S, T> registerBinderModel(Binder<S, T> binder) throws IllegalArgumentException { - Binder.BinderModel<S, T> model = registerBinderModel(binder, null); - return model; - } - - public static <S, T> Binder.BinderModel<S, T> registerBinderModel(Binder.BinderModel<S, T> model) throws IllegalArgumentException { - - registerBinderModel(model, null); - return model; - } - - public static <S, T> Binder.BinderModel<S, T> registerBinderModel(BinderModelBuilder<S, T> binderModelBuilder, - String contextName) throws IllegalArgumentException { - Binder.BinderModel<S, T> model = binderModelBuilder.getModel(); - registerBinderModel(model, contextName); - return model; - } - - public static <S, T> Binder.BinderModel<S, T> registerBinderModel(Binder<S, T> binder, - String contextName) throws IllegalArgumentException { - Binder.BinderModel<S, T> model = binder.getModel(); - registerBinderModel(model, contextName); - return model; - } - - public static <S, T> Binder.BinderModel<S, T> registerBinderModel(Binder.BinderModel<S, T> model, - String contextName) throws IllegalArgumentException { - - // check if the given model is not already registred for the given context - Binder.BinderModel<S, T> registredModel = - getBinderModels().get(model, contextName); - - // let's add this model into cache of models - BinderModelEntry key = new BinderModelEntry(model, contextName); - - if (registredModel != null) { - - // this model is already registred, remove it from cache - if (log.isWarnEnabled()) { - log.warn("Remove existing binder model from cache : " + - toString(registredModel, contextName)); - } - } - - // add new model into cache - getBinderModels().put(key, model); - return model; - } - - /** - * Given a {@code model} and a {@code binderType}, instanciate a new binder - * and returns it. - * - * <strong>Note: </strong> This method will <strong>NOT</strong> register - * the model in the factory. If you want to reuse your model, please use - * one of the {@code registerBinderModel(XXX)} method. - * - * @param model the model used by the binder - * @param binderType the type of the binder - * @param <S> the source type - * @param <T> the target type - * @param <B> the type of the binder - * @return the new instanciated binder - * @since 2.1 - */ - public static <S, T, B extends Binder<S, T>> B newBinder(Binder.BinderModel<S, T> model, - Class<B> binderType) { - - B binder; - try { - binder = binderType.getConstructor().newInstance(); - } catch (Exception e) { - throw new IllegalStateException( - "Could not instanciate binder of type " + binderType, e); - } - - binder.setModel(model); - return binder; - } - - /** - * Clear the cache of registred binder models. - * - * <b>Note :</b> This is a convienient method for test purposes and should - * be used in a normal usage of this provider. - */ - public static void clear() { - if (binderModels != null) { - binderModels.clear(); - binderModels = null; - } - } - - /** - * Tells if there is a cached binder model for the given parameters. - * - * @param sourceType the type of source - * @param targetType the type of target - * @param contextName the context's name of the searched binder - * @param <S> the type of source - * @param <T> the type of target - * @return {@code true} if there is a cached binder model for the given - * parameters, {@code false} otherwise. - */ - public static <S, T> boolean isBinderModelExists(Class<S> sourceType, - Class<T> targetType, - String contextName) { - Binder.BinderModel<S, T> model = - getBinderModels().get(sourceType, targetType, contextName); - return model != null; - } - - /** - * Obtain a cached binder model. - * - * @param sourceType the type of source - * @param targetType the type of target - * @param contextName the context's name of the searched binder - * @param <S> the type of source - * @param <T> the type of target - * @return the cached binder model or {@code null} if not found. - */ - public static <S, T> Binder.BinderModel<S, T> getCachedBinderModel(Class<S> sourceType, - Class<T> targetType, - String contextName) { - Binder.BinderModel<S, T> model = - getBinderModels().get(sourceType, targetType, contextName); - return model; - } - - protected static BindelModelEntryMap getBinderModels() { - if (binderModels == null) { - binderModels = new BindelModelEntryMap(); - } - return binderModels; - } - - protected static String toString(Binder.BinderModel<?, ?> model, String contextName) { - return toString(model.getSourceType(), model.getTargetType(), contextName); - } - - protected static String toString(Class<?> sourceType, Class<?> targetType, String contextName) { - return "<" + sourceType.getName() + " - " + targetType.getName() + " > [" + contextName + "] "; - } - - /** - * Instanciate a new binder given his types and his context's name. - * - * If the corresponding binder model does not exist, then it will be created - * and cached (using the {@link BinderModelBuilder#newDefaultBuilder(Class, Class)} method). - * - * @param sourceType the type of source - * @param targetType the type of target - * @param contextName the context's name of the searched binder - * @param binderType type of binder required - * @param <S> the type of source - * @param <T> the type of target - * @param <B> the type of binder - * @return the new instanciated binder. - */ - protected static <S, T, B extends Binder<S, T>> Binder<S, T> newBinder0(Class<S> sourceType, - Class<T> targetType, - String contextName, - Class<B> binderType) { - - // obtain the cached model - Binder.BinderModel<S, T> model = - getBinderModels().get(sourceType, targetType, contextName); - - if (model == null) { - - // model not yet registred, let's create it - - if (log.isInfoEnabled()) { - log.info("No binder model found for " + - toString(sourceType, targetType, contextName) + - ", will create a new default one."); - } - - BinderModelBuilder<S, T> builder = - BinderModelBuilder.newDefaultBuilder(sourceType, targetType); - - // register the new binder model - model = registerBinderModel(builder, contextName); - } - - B binder = newBinder(model, binderType); - return binder; - } - - public static class BindelModelEntryMap implements Map<BinderModelEntry, Binder.BinderModel<?, ?>> { - - protected Map<BinderModelEntry, Binder.BinderModel<?, ?>> delegate; - - public BindelModelEntryMap() { - delegate = new HashMap<BinderModelEntry, Binder.BinderModel<?, ?>>(); - } - - public <S, T> Binder.BinderModel<S, T> get(Class<S> source, - Class<T> target, - String contextName) { - Binder.BinderModel<S, T> result = null; - - for (BinderModelEntry key : binderModels.keySet()) { - if (!key.getSourceType().equals(source)) { - continue; - } - if (!key.getTargetType().equals(target)) { - continue; - } - - if (key.getName() == null) { - if (contextName != null) { - continue; - } - } else { - if (!key.getName().equals(contextName)) { - continue; - } - } - - result = (Binder.BinderModel<S, T>) binderModels.get(key); - break; - } - return result; - } - - public <S, T> Binder.BinderModel<S, T> get(Binder.BinderModel<S, T> model, - String contextName) { - - Class<S> source = model.getSourceType(); - Class<T> target = model.getTargetType(); - Binder.BinderModel<S, T> result = get(source, target, contextName); - return result; - } - - @Override - public int size() { - return delegate.size(); - } - - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - @Override - public boolean containsKey(Object key) { - return delegate.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - return delegate.containsValue(value); - } - - @Override - public Binder.BinderModel<?, ?> get(Object key) { - return delegate.get(key); - } - - public Binder.BinderModel<?, ?> put(BinderModelEntry key, Binder.BinderModel<?, ?> value) { - return delegate.put(key, value); - } - - @Override - public Binder.BinderModel<?, ?> remove(Object key) { - return delegate.remove(key); - } - - public void putAll(Map<? extends BinderModelEntry, ? extends Binder.BinderModel<?, ?>> m) { - delegate.putAll(m); - } - - @Override - public void clear() { - delegate.clear(); - } - - @Override - public Set<BinderModelEntry> keySet() { - return delegate.keySet(); - } - - @Override - public Collection<Binder.BinderModel<?, ?>> values() { - return delegate.values(); - } - - @Override - public Set<Entry<BinderModelEntry, Binder.BinderModel<?, ?>>> entrySet() { - return delegate.entrySet(); - } - - } - - /** - * Definition of an binder model entry (source and target types + context name). - * - * <b>Note :</b>When no context is specified, we always use a - * {@code null} context name. - */ - public static class BinderModelEntry { - - protected final Class<?> sourceType; - - protected final Class<?> targetType; - - protected final String name; - - public BinderModelEntry(Class<?> sourceType, - Class<?> targetType, - String name) { - this.sourceType = sourceType; - this.targetType = targetType; - this.name = name; - } - - public BinderModelEntry(Binder.BinderModel<?, ?> model, String contextName) { - this(model.getSourceType(), model.getTargetType(), contextName); - } - - public Class<?> getSourceType() { - return sourceType; - } - - public Class<?> getTargetType() { - return targetType; - } - - public String getName() { - return name; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - BinderModelEntry that = (BinderModelEntry) o; - - return (name == null ? that.name == null : name.equals(that.name)) && - sourceType.equals(that.sourceType) && - targetType.equals(that.targetType); - } - - @Override - public int hashCode() { - int result = sourceType.hashCode(); - result = 31 * result + targetType.hashCode(); - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder("<"); - buffer.append(super.toString()); - buffer.append(", sourceType: ").append(getSourceType()).append(','); - buffer.append(" targetType: ").append(getTargetType()).append(','); - buffer.append(" name: ").append(getName()).append('>'); - - return buffer.toString(); - } - } -} diff --git a/src/main/java/org/nuiton/util/beans/BinderModelBuilder.java b/src/main/java/org/nuiton/util/beans/BinderModelBuilder.java deleted file mode 100644 index e0b068a..0000000 --- a/src/main/java/org/nuiton/util/beans/BinderModelBuilder.java +++ /dev/null @@ -1,651 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.beans; - -import com.google.common.base.Function; - -import java.beans.BeanInfo; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * Class to create a new {@link Binder.BinderModel}. - * <p> - * A such object is designed to build only one model of binder and can not be - * used directly to create a new binder, it prepares only the model of a new - * binder, which after must be registred in the {@link BinderFactory} to obtain - * a real {@link Binder}. - * <p> - * If you want to create more than one binder model, use each time a new - * binder builder. - * <p> - * To obtain a new instance of a build please use one of the factories method : - * <ul> - * <li>{@link #newEmptyBuilder(Class)}} to create a binder model with same - * source and target type</li> - * <li>{@link #newEmptyBuilder(Class, Class)} to create a binder model with a - * possible different source and target type</li> - * <li>{@link #newDefaultBuilder(Class)} to create a binder model with same - * source and target type and then fill the model with all matching properties.</li> - * <li>{@link #newDefaultBuilder(Class, Class)} to create a binder model - * with a possible different source and target type and then fill the model - * with all matching properties.</li> - * </ul> - * Then you can use folowing methods to specify what to put in the copy model : - * <ul> - * <li>{@link #addSimpleProperties(String...)} to add in the binder model simple - * properties (a simple property is a property present in both source and target type)</li> - * <li>{@link #addProperty(String, String)} to add in the binder model a single - * property (from source type) to be copied to another property (in target type)</li> - * <li>{@link #addProperties(String...)} to add in the binder model properties - * (says here you specify some couple of properties (sourcePropertyName, - * targetPropertyName) to be added in the binder model)</li> - * <li>{@link #addBinder(String, Binder)} to add in the binder model - * another binder to be used to copy the given simple property (same name in - * source and target type)</li> - * <li>{@link #addCollectionStrategy(Binder.CollectionStrategy, String...)} to - * specify the strategy to be used to bind some collection some source type to - * target type</li> - * <li>{@link #addCollectionBinder(Binder, String...)} to - * bind a collection: a new collection will be created and all elements of sources will be - * copy using the given binder.</li> - * </ul> - * <b>Note :</b> You can chain thoses methods since all of them always return - * the current instance of the builder : - * <pre> - * builder.addSimpleProperties(...).addProperty(...).addBinder(...) - * </pre> - * Here is an example of how to use the {@link BinderModelBuilder} : - * <pre> - * BinderModelBuilder<Bean, Bean> builder = new BinderModelBuilder(Bean.class); - * builder.addSimpleProperties("name", "surname"); - * BinderFactory.registerBinderModel(builder); - * Binder<Bean, Bean> binder = BinderFactory.getBinder(BeanA.class); - * </pre> - * Once the binder is registred into the {@link BinderFactory}, you can get it - * each time you need it : - * <pre> - * Binder<Bean, Bean> binder = BinderFactory.getBinder(Bean.class); - * </pre> - * - * @param <S> FIXME - * @param <T> FIXME - * @author Tony Chemit - chemit@codelutin.com - * @see Binder.BinderModel - * @see Binder - * @since 1.5.3 - */ -public class BinderModelBuilder<S, T> { - - /** - * Can the source and target type mismatch for a property ? - */ - protected boolean canTypeMismatch; - - /** - * current model used to build the binder - */ - protected Binder.BinderModel<S, T> model; - - /** - * source properties descriptors - */ - protected Map<String, PropertyDescriptor> sourceDescriptors; - - /** - * target properties descriptors - */ - protected Map<String, PropertyDescriptor> targetDescriptors; - - /** - * Creates a new mirrored and empty model binder for the given {@code type}. - * - * @param <S> FIXME - * @param type the type of mirrored binder - * @return the new instanciated builder - */ - public static <S> BinderModelBuilder<S, S> newEmptyBuilder(Class<S> type) { - return new BinderModelBuilder<S, S>(type, type); - } - - /** - * Creates a new empty model binder for the given types. - * - * @param <S> FIXME - * @param <T> FIXME - * @param sourceType type of the source of the binder - * @param targetType type of the target of the binder - * @return the new instanciated builder - */ - public static <S, T> BinderModelBuilder<S, T> newEmptyBuilder(Class<S> sourceType, - Class<T> targetType) { - return new BinderModelBuilder<S, T>(sourceType, targetType); - } - - /** - * Creates a new mirrored model builder and fill the model with all matching - * and available property from the given type. - * - * @param <S> FIXME - * @param sourceType the mirrored type of the binder model to create - * @param <S> the mirrored type of the binder model to create - * @return the new instanciated model builder fully filled - */ - public static <S> BinderModelBuilder<S, S> newDefaultBuilder(Class<S> sourceType) { - return newDefaultBuilder(sourceType, sourceType); - - } - - /** - * Creates a new model builder and fill the model with all matching - * and available properties from the source type to the target type. - * - * @param sourceType the source type of the model to create - * @param targetType the target type of the model to create - * @param <S> the source type of the binder model to create - * @param <T> the target type of the binder model to create - * @return the new instanciated model builder fully filled - */ - public static <S, T> BinderModelBuilder<S, T> newDefaultBuilder(Class<S> sourceType, - Class<T> targetType) { - return newDefaultBuilder(sourceType, targetType, true); - } - - /** - * Creates a new model builder and fill the model with all matching - * and available properties from the source type to the target type. - * - * @param sourceType the source type of the model to create - * @param targetType the target type of the model to create - * @param <S> the source type of the binder model to create - * @param <T> the target type of the binder model to create - * @param checkType flag to check if properties has same types, otherwise skip them - * @return the new instanciated model builder fully filled - * @since 2.4.5 - */ - public static <S, T> BinderModelBuilder<S, T> newDefaultBuilder(Class<S> sourceType, - Class<T> targetType, - boolean checkType) { - BinderModelBuilder<S, T> builder = - newEmptyBuilder(sourceType, targetType); - Map<String, PropertyDescriptor> source = builder.sourceDescriptors; - Map<String, PropertyDescriptor> target = builder.targetDescriptors; - List<String> properties = new ArrayList<String>(); - for (String propertyName : source.keySet()) { - if (!target.containsKey(propertyName)) { - - // not exactly match for this property, do not use this property - continue; - } - PropertyDescriptor sourceDescriptor = source.get(propertyName); - Method readMethod = sourceDescriptor.getReadMethod(); - if (readMethod == null) { - - // no getter on source, do not use this property - continue; - } - PropertyDescriptor targetDescriptor = target.get(propertyName); - Method writeMethod = targetDescriptor.getWriteMethod(); - if (writeMethod == null) { - - // no setter on target, do not use this property - continue; - } - - if (checkType) { - - // check types are compatible - - Class<?> writerType = writeMethod.getParameterTypes()[0]; - Class<?> readerType = readMethod.getReturnType(); - if (!writerType.equals(readerType)) { - - // types are not compatible - continue; - } - } - // can safely use this property - properties.add(propertyName); - } - - // add all detected properties - builder.addSimpleProperties( - properties.toArray(new String[properties.size()])); - return builder; - } - - /** - * Change the value of property {@code canTypeMismatch}. - * - * @param canTypeMismatch new {@code canTypeMismatch} value - * @return the builder - */ - public BinderModelBuilder<S, T> canTypeMismatch(boolean canTypeMismatch) { - this.canTypeMismatch = canTypeMismatch; - return this; - } - - public <K, V> BinderModelBuilder<S, T> addFunction(Class<K> type, Function<K, V> function) { - model.functions.put(type, function); - return this; - } - - /** - * Convinient method to create directly a {@link Binder} using the - * underlying {@link #model} the builder contains. - * <p> - * <strong>Note:</strong> Using this method will not make reusable the model - * via the {@link BinderFactory}. - * - * @return a new binder using the model of the builder. - * @see BinderFactory#newBinder(Binder.BinderModel, Class) - * @since 2.1 - */ - public Binder<S, T> toBinder() { - Binder<S, T> binder = toBinder(Binder.class); - return binder; - } - - /** - * Convinient method to create directly a {@link Binder} using the - * underlying {@link #model} the builder contains. - * <p> - * <strong>Note:</strong> Using this method will not make reusable the model - * via the {@link BinderFactory}. - * - * @param binderType type of binder to create - * @param <B> type of binder to create - * @return a new binder using the model of the builder. - * @see BinderFactory#newBinder(Binder.BinderModel, Class) - * @since 2.1 - */ - public <B extends Binder<S, T>> B toBinder(Class<B> binderType) { - B binder = BinderFactory.newBinder(model, binderType); - return binder; - } - - /** - * set factory of target instance - * @param instanceFactory FIXME - */ - public void setInstanceFactory(InstanceFactory<T> instanceFactory) { - model.setInstanceFactory(instanceFactory); - } - - /** - * Add to the binder model some simple properties (says source property name = target property name). - * <p> - * <b>Note:</b> If no model is present, the method will fail. - * - * @param properties the name of mirrored property - * @return the instance of the builder - * @throws IllegalStateException if no model was previously created - * @throws NullPointerException if a property is {@code null} - */ - public BinderModelBuilder<S, T> addSimpleProperties(String... properties) - throws IllegalStateException, NullPointerException { - for (String property : properties) { - if (property == null) { - throw new NullPointerException( - "parameter 'properties' can not contains a null value"); - } - addProperty0(property, property); - } - return this; - } - - /** - * Add to the binder model some simple properties (says source property name = target property name). - * <p> - * <b>Note:</b> If no model is present, the method will fail. - * - * @param sourceProperty the name of the source property to bind - * @param targetProperty the name of the target property to bind - * @return the instance of the builder - * @throws IllegalStateException if no model was previously created - * @throws NullPointerException if a parameter is {@code null} - */ - - public BinderModelBuilder<S, T> addProperty(String sourceProperty, - String targetProperty) - throws IllegalStateException, NullPointerException { - if (sourceProperty == null) { - throw new NullPointerException( - "parameter 'sourceProperty' can not be null"); - } - if (targetProperty == null) { - throw new NullPointerException( - "parameter 'targetProperty' can not be null"); - } - addProperty0(sourceProperty, targetProperty); - return this; - } - - /** - * Add to the binder model some properties. - * <p> - * Parameter {@code sourceAndTargetProperties} must be a array of couple - * of {@code sourceProperty}, {@code targetProperty}. - * <p> - * Example : - * <pre> - * builder.addProperties("name","name2","text","text"); - * </pre> - * <p> - * <b>Note:</b> If no model is present, the method will fail. - * - * @param sourceAndTargetProperties the couple of (sourceProperty - - * targetProperty) to bind - * @return the instance of the builder - * @throws IllegalStateException if no model was previously created - * @throws IllegalArgumentException if there is not the same number of - * source and target properties - * @throws NullPointerException if a parameter is {@code null} - */ - public BinderModelBuilder<S, T> addProperties(String... sourceAndTargetProperties) - throws IllegalStateException, IllegalArgumentException, - NullPointerException { - if (sourceAndTargetProperties.length % 2 != 0) { - throw new IllegalArgumentException( - "must have couple(s) of sourceProperty,targetProperty) " + - "but had " + Arrays.toString(sourceAndTargetProperties)); - } - for (int i = 0, max = sourceAndTargetProperties.length / 2; - i < max; i++) { - String sourceProperty = sourceAndTargetProperties[2 * i]; - String targetProperty = sourceAndTargetProperties[2 * i + 1]; - if (sourceProperty == null) { - throw new NullPointerException( - "parameter 'sourceAndTargetProperties' can not " + - "contains a null value"); - } - if (targetProperty == null) { - throw new NullPointerException( - "parameter 'sourceAndTargetProperties' can not " + - "contains a null value"); - } - addProperty0(sourceProperty, targetProperty); - } - return this; - } - - public BinderModelBuilder<S, T> addBinder(String propertyName, Binder<?, ?> binder) { - - if (model.containsCollectionProperty(propertyName)) { - - throw new IllegalStateException("Can't add a property binder, there is already a collection strategy defined!"); - } - - // check property is registred - if (!model.containsSourceProperty(propertyName)) { - throw new IllegalArgumentException( - "source property '" + propertyName + "' " + - " is NOT registred."); - } - - // check property is the same type of given binder - PropertyDescriptor descriptor = sourceDescriptors.get(propertyName); - Class<?> type = descriptor.getPropertyType(); - - if (!Collection.class.isAssignableFrom(type) && - !binder.model.getSourceType().isAssignableFrom(type)) { - throw new IllegalStateException( - "source property '" + propertyName + - "' has not the same type [" + type + - "] of the binder [" + binder.model.getSourceType() + "]."); - } - - // can safely add the strategy - model.addBinder(propertyName, binder); - - return this; - } - - public BinderModelBuilder<S, T> addCollectionStrategy(Binder.CollectionStrategy strategy, - String... propertyNames) { - - if (strategy.equals(Binder.CollectionStrategy.bind)) { - throw new IllegalStateException("Can't add bind stragegy here, must use the method addCollectionBinder"); - } - - for (String propertyName : propertyNames) { - - if (model.containsBinderProperty(propertyName)) { - - throw new IllegalStateException("Can't add a simple collection strategy, there is already a binder defined, please use now the addCollectionBinder method to do this!"); - } - - addCollectionStrategy0(propertyName, strategy, null); - - } - return this; - } - - public BinderModelBuilder<S, T> addCollectionBinder(Binder binder, - String... propertyNames) { - - for (String propertyName : propertyNames) { - - addCollectionStrategy0(propertyName, Binder.CollectionStrategy.bind, binder); - - } - - return this; - } - - /** - * Creates a new model builder inversing the the source and target of this builder. - * <p> - * the result build will contains the inversed properties mapping of the original builder. - * <p> - * Other builder attributes are not used used - * - * @return the new model builder - */ - public BinderModelBuilder<T, S> buildInverseModelBuilder() { - - BinderModelBuilder<T, S> builder = new BinderModelBuilder<>(model.getTargetType(), model.getSourceType()) - .canTypeMismatch(canTypeMismatch); - - for (Map.Entry<String, String> entry : model.getPropertiesMapping().entrySet()) { - String sourcePropertyName = entry.getKey(); - String targetPropertyName = entry.getValue(); - builder.addProperty(targetPropertyName, sourcePropertyName); - } - return builder; - - } - - protected BinderModelBuilder<S, T> addCollectionStrategy0(String propertyName, - Binder.CollectionStrategy strategy, - Binder binder) { - - // check property is registred - if (!model.containsSourceProperty(propertyName)) { - throw new IllegalArgumentException( - "source property '" + propertyName + "' " + - " is NOT registred."); - } - - // check property is collection type - PropertyDescriptor descriptor = sourceDescriptors.get(propertyName); - Class<?> type = descriptor.getPropertyType(); - if (!Collection.class.isAssignableFrom(type)) { - throw new IllegalStateException( - "source property '" + propertyName + - "' is not a collection type [" + type + "]"); - } - - // can safely add the strategy - model.addCollectionStrategy(propertyName, strategy); - - if (binder != null) { - - // add also the binder - model.addBinder(propertyName, binder); - - } - return this; - } - - /** - * Creates a binder for the given types. - * - * @param sourceType type of the source of the binder - * @param targetType type of the target of the binder - */ - protected BinderModelBuilder(Class<S> sourceType, Class<T> targetType) { - if (sourceType == null) { - throw new NullPointerException("sourceType can not be null"); - } - if (targetType == null) { - throw new NullPointerException("targetType can not be null"); - } - - if (model != null) { - throw new IllegalStateException( - "there is already a binderModel in construction, release " + - "it with the method createBinder before using this method." - ); - } - - // init model - model = new Binder.BinderModel<S, T>(sourceType, targetType); - - // obtain source descriptors - sourceDescriptors = new TreeMap<String, PropertyDescriptor>(); - loadDescriptors(model.getSourceType(), sourceDescriptors); - - // obtain target descriptors - targetDescriptors = new TreeMap<String, PropertyDescriptor>(); - loadDescriptors(model.getTargetType(), targetDescriptors); - - } - - protected void addProperty0(String sourceProperty, - String targetProperty) { - - // obtain source descriptor - PropertyDescriptor sourceDescriptor = - sourceDescriptors.get(sourceProperty); - if (sourceDescriptor == null) { - throw new IllegalArgumentException("no property '" + - sourceProperty + "' " + "found on type " + - model.getSourceType()); - } - // check srcProperty is readable - Method readMethod = sourceDescriptor.getReadMethod(); - if (readMethod == null) { - throw new IllegalArgumentException("property '" + sourceProperty + - "' " + "is not readable on type " + model.getSourceType()); - } - - // obtain dst descriptor - PropertyDescriptor targetDescriptor = - targetDescriptors.get(targetProperty); - if (targetDescriptor == null) { - throw new IllegalArgumentException("no property '" + - targetProperty + "' " + "found on type " + - model.getTargetType()); - } - // check dstProperty is writable - Method writeMethod = targetDescriptor.getWriteMethod(); - if (writeMethod == null) { - throw new IllegalArgumentException("property '" + targetProperty + - "' " + "is not writable on type " + model.getTargetType()); - } - - // check types are ok - Class<?> sourceType = sourceDescriptor.getPropertyType(); - Class<?> targetType = targetDescriptor.getPropertyType(); - //TODO-TC20100221 : should check if primitive and boxed it in such case - if (!sourceType.equals(targetType) && !canTypeMismatch) { - throw new IllegalArgumentException("source property '" + - sourceProperty + "' and target property '" + - targetProperty + "' are not compatible ( sourceType : " + - sourceType + " vs targetType :" + targetType + ')'); - } - - // check srcProperty does not exist - if (model.containsSourceProperty(sourceProperty)) { - - // just remove the old property mapping - model.removeBinding(sourceProperty); - - } - - // check dstProperty does not exist - // here we can not deal with it since we should remove the source - // property for the entry and this is a bit unatural - if (model.containsTargetProperty(targetProperty)) { - throw new IllegalArgumentException("destination property '" + - targetProperty + "' " + " was already registred."); - } - // safe to add the binding - model.addBinding(sourceDescriptor, targetDescriptor); - } - - protected Binder.BinderModel<S, T> getModel() { - return model; - } - - protected void clear() { - sourceDescriptors = null; - targetDescriptors = null; - model = null; - } - - protected static void loadDescriptors( - Class<?> type, - Map<String, PropertyDescriptor> descriptors) { - try { - - BeanInfo beanInfo = Introspector.getBeanInfo(type); - for (PropertyDescriptor descriptor : - beanInfo.getPropertyDescriptors()) { - if (!descriptors.containsKey(descriptor.getName())) { - descriptors.put(descriptor.getName(), descriptor); - } - } - } catch (IntrospectionException e) { - throw new RuntimeException("Could not obtain bean properties " + - "descriptors for source type " + type, e); - } - Class<?>[] interfaces = type.getInterfaces(); - for (Class<?> i : interfaces) { - loadDescriptors(i, descriptors); - } - Class<?> superClass = type.getSuperclass(); - if (superClass != null && !Object.class.equals(superClass)) { - loadDescriptors(superClass, descriptors); - } - } -} diff --git a/src/main/java/org/nuiton/util/beans/InstanceFactory.java b/src/main/java/org/nuiton/util/beans/InstanceFactory.java deleted file mode 100644 index 6bd17a8..0000000 --- a/src/main/java/org/nuiton/util/beans/InstanceFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2013 - 2014 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.beans; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public interface InstanceFactory<O> { - - O newInstance(); - -} diff --git a/src/main/java/org/nuiton/util/beans/PropertyDiff.java b/src/main/java/org/nuiton/util/beans/PropertyDiff.java deleted file mode 100644 index fed8e37..0000000 --- a/src/main/java/org/nuiton/util/beans/PropertyDiff.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.beans; - -/** - * TODO - * - * @author Brendan Le Ny - bleny@codelutin.com - * @since 2.4 - */ -public class PropertyDiff { - - protected Class<?> propertyType; - - protected String sourceProperty; - - protected Object sourceValue; - - protected String targetProperty; - - protected Object targetValue; - - public PropertyDiff() { - } - - public PropertyDiff(String sourceProperty, - Object sourceValue, - String targetProperty, - Object targetValue, - Class<?> propertyType) { - this.sourceProperty = sourceProperty; - this.sourceValue = sourceValue; - this.targetProperty = targetProperty; - this.targetValue = targetValue; - this.propertyType = propertyType; - } - - public String getSourceProperty() { - return sourceProperty; - } - - public void setSourceProperty(String sourceProperty) { - this.sourceProperty = sourceProperty; - } - - public Object getSourceValue() { - return sourceValue; - } - - public void setSourceValue(Object sourceValue) { - this.sourceValue = sourceValue; - } - - public String getTargetProperty() { - return targetProperty; - } - - public void setTargetProperty(String targetProperty) { - this.targetProperty = targetProperty; - } - - public Object getTargetValue() { - return targetValue; - } - - public void setTargetValue(Object targetValue) { - this.targetValue = targetValue; - } - - public Class<?> getPropertyType() { - return propertyType; - } - - public void setPropertyType(Class<?> propertyType) { - this.propertyType = propertyType; - } - -} diff --git a/src/main/java/org/nuiton/util/beans/package-info.java b/src/main/java/org/nuiton/util/beans/package-info.java deleted file mode 100644 index 974cf82..0000000 --- a/src/main/java/org/nuiton/util/beans/package-info.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -/** - * Packages for all stuff of bean transformations (binder, and others...). - * - * This package contains two api : - * <ul> - * <li> the Binder api to copy objects</li> - * <li> Some javabeans compiliant api</li> - * </ul> - * - * <h1>The <b>Binder</b> api</h1> - * <p> - * This api permits to some object properties from an object to another one. - * </p> - * <h2>Obtain a binder</h2> - * <p>A {@link org.nuiton.util.beans.Binder} contains a safe model named - * {@link org.nuiton.util.beans.Binder.BinderModel} which knows - * all properties that can be copied. - * </p> - * To use this api, you have only to get a {@link org.nuiton.util.beans.Binder} - * object from the {@link org.nuiton.util.beans.BinderFactory} like this : - * <pre> - * Binder<A, A> binder = BinderFactory.newBinder(A.class); - * </pre> - * - * It is also possible to build a more sofisticated binder which will only copy - * some properties, using the {@link org.nuiton.util.beans.BinderModelBuilder}. - * - * <h2>Use a binder</h2> - * Once you have a binder, you use the {@link org.nuiton.util.beans.Binder} api : - * - * To copy all properties from an object to another one : - * <pre> - * binder.copy(source, target); - * </pre> - * - * To copy just some properties from an object to another one : - * <pre> - * binder.copy(source, target, "propertyOne", "propertyTwo"); - * </pre> - * - * To copy all properties except some : - * <pre> - * binder.copyExcluding(source, target, "propertyToExeclude"); - * </pre> - * - * To obtain some properties from an object, use the following code : - * <pre> - * Map<String, Object> properties = binder.obtainProperties(source, "propertyOne", "propertyTwo"); - * </pre> - * - * <h2>Building a new BinderModel</h2> - * <p> - * In two words, you have to use the - * {@link org.nuiton.util.beans.BinderModelBuilder} object to do this. - * then register your binder model into the - * {@link org.nuiton.util.beans.BinderFactory} using one of the method - * {@code org.nuiton.util.beans.BinderFactory#registerBinderModel(XXX)}. - * </p> - * More explainations will come soon... - * <p> - * You can go and look on the unit tests which describe it pretty well :) : - * </p> - * <pre> - * org.nuiton.util.beans.BinderModelBuilderTest - * </pre> - * - * <h1>JavaBeans api</h1> - * - * <h2>{@link org.nuiton.util.beans.BeanMonitor} class</h2> - * This object permits to listen javaBeans and keep modifications made on a bean. - * - * More explanations will come soon, meanwhile you can see the test class : - * <pre> - * org.nuiton.util.beans.BeanMonitorTest - * </pre> - * - * @since 1.1.5 - */ -package org.nuiton.util.beans; diff --git a/src/main/java/org/nuiton/util/converter/ColorConverter.java b/src/main/java/org/nuiton/util/converter/ColorConverter.java deleted file mode 100644 index 20aa2ea..0000000 --- a/src/main/java/org/nuiton/util/converter/ColorConverter.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.nuiton.util.converter; -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - - -import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.beanutils.Converter; - -import java.awt.Color; -import java.util.Scanner; - -/** - * Converter of {@link Color}. - * - * @author Matthieu Allon - * @author Tony Chemit - chemit@codelutin.com - * @since 2.5.3 - * @deprecated since 3.0 use instead {@link org.nuiton.converter.ColorConverter} (<strong>Note:</strong> This converter is no more loaded by the {@link ConverterUtil#initConverters()}) - */ -@Deprecated -public class ColorConverter implements Converter { - - @Override - public Object convert(Class aClass, Object value) { - if (!isEnabled(aClass)) { - throw new ConversionException("unsupported type: " + aClass); - } - - String valueToString = (String) value; - /* - * To get color from a formatted string - * Two formatting cases : - * - 'java.awt.Color[r=255,g=51,b=51]', for example - * - hexa, like '#000000' - */ - Color result; - try { - if (valueToString.length() == 7 && valueToString.charAt(0) == '#') { - result = new Color(Integer.parseInt(valueToString.substring(1), 16)); - } else { - Scanner sc = new Scanner(valueToString); - sc.useDelimiter("\\D+"); - result = new Color(sc.nextInt(), sc.nextInt(), sc.nextInt()); - } - return result; - } catch (Exception e) { - throw new ConversionException( - "colors must be of the form #xxxxxx ('#' followed by " + - "six hexadecimal digits), or the name of a constant " + - "field in java.awt.Color (found: '" + valueToString + "')", - e); - } - } - - protected boolean isEnabled(Class<?> aClass) { - return Color.class.equals(aClass); - } - - public Class<?> getType() { - return Color.class; - } -} diff --git a/src/main/java/org/nuiton/util/converter/ConverterUtil.java b/src/main/java/org/nuiton/util/converter/ConverterUtil.java deleted file mode 100644 index 0fa9b84..0000000 --- a/src/main/java/org/nuiton/util/converter/ConverterUtil.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.converter; - -import org.apache.commons.beanutils.ConvertUtils; -import org.apache.commons.beanutils.Converter; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.Method; -import java.util.ServiceLoader; - -/** - * Une classe contenant des méthodes utiles sur les converters et les conversions - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 (replace {@code org.nuiton.util.ConverterUtil}). - * @deprecated since 3.0 use instead {@link org.nuiton.converter.ConverterUtil} - */ -@Deprecated -public class ConverterUtil { - - /** Logger. */ - static private Log log = LogFactory.getLog(ConverterUtil.class); - - /** - * le paquetage où chercher les implentations de Converter, si non présents - * dans le système - */ - protected static final String CONVERTER_PACKAGE = "org.nuiton.util.converter"; - - /** un drapeau pour savoir si on doit charger les converters specifiques */ - protected static Boolean WAS_INIT = Boolean.FALSE; - - /** - * Cherche un converter pour un {@code type} donné. - * - * Recherche dans un premier temps dans les converteurs déjà connus. - * - * Si le type est une énum et qu'aucun converter, n'a été trouvé, on - * enregistre un nouveau convert d'enum. - * - * Sinon on tente d'instancier un converteur dans le paquetage dédié aux - * converteurs {@link #CONVERTER_PACKAGE}. - * - * @param <T> le type a convertir - * @param type le type a convertir - * @return le converter trouvé, ou null si non trouvé - */ - public static <T> Converter getConverter(Class<T> type) { - if (!WAS_INIT) { - initConverters(); - } - Converter converter = ConvertUtils.lookup(type); - if (converter != null) { - return converter; - } - if (type.isEnum()) { - registerEnumConverter(type); - return ConvertUtils.lookup(type); - } - // on essaye de trouver un converter dans le paquetage des converters - try { - registerConverter0(type); - converter = ConvertUtils.lookup(type); - } catch (Exception e) { - throw new RuntimeException(e); - } - return converter; - } - - /** - * Convertir une valeur! - * - * @param <T> le type de donnee recherchee - * @param type le type de donnee recherchee - * @param toConvert l'object a convertir - * @return la nouvelle instance de l'objet converti type ou null - */ - @SuppressWarnings({"unchecked"}) - public static <T> T convert(Class<T> type, Object toConvert) { - if (!WAS_INIT) { - initConverters(); - } - T result = null; - Converter converter = getConverter(type); - if (converter != null) { - return (T) converter.convert(type, toConvert); - } - return result; - } - - public static void registerConverter(Class<?> type) - throws IllegalAccessException, - InstantiationException, - ClassNotFoundException { - if (ConvertUtils.lookup(type) == null) { - registerConverter0(type); - } - } - - protected static void registerConverter0(Class<?> type) - throws IllegalAccessException, - InstantiationException, - ClassNotFoundException { - Class<?> aClass = Class.forName( - CONVERTER_PACKAGE + "." + type.getSimpleName() + "Converter"); - Converter converter = (Converter) aClass.newInstance(); - log.info("for type : " + type + " : " + converter); - ConvertUtils.register(converter, type); - } - - /** - * Enregistre un nouveau converter pour un type d'enum donné, avec une - * valeur par defaut. - * - * @param type le type d'enum à convertir - * @param defaultValue la valeur par defaut. - */ - public static void registerEnumConverter(Class<?> type, - Object defaultValue) { - if (EnumConverter.isEnabled(type, type) && - ConvertUtils.lookup(type) == null) { - Converter converter = new EnumConverter(type, defaultValue); - log.info("for type : " + type + " : " + converter); - ConvertUtils.register(converter, type); - } - } - - /** - * Enregistre un nouveau converter pour un type d'enum donné, sans utiliser - * de valeur par defaut. - * - * @param type le type d'enum à convertir - */ - public static void registerEnumConverter(Class<?> type) { - registerEnumConverter(type, null); - } - - public static byte[] convert(char[] chars) { - byte[] bytes = new byte[chars.length]; - for (int i = 0; i < chars.length; i++) { - bytes[i] = (byte) (chars[i] & 0xff); - } - return bytes; - } - - public static synchronized void deregister() { - ConvertUtils.deregister(); - WAS_INIT = false; - } - - public static synchronized void initConverters() { - if (WAS_INIT != null && WAS_INIT) { - return; - } - ServiceLoader<Converter> converters = - ServiceLoader.load(Converter.class); - for (Converter converter : converters) { - if (log.isDebugEnabled()) { - log.debug("discovered converter " + converter); - } - try { - Method m = converter.getClass().getDeclaredMethod("getType"); - m.setAccessible(true); - try { - Class<?> returnType = (Class<?>) m.invoke(converter); - log.info("register converter " + converter); - ConvertUtils.register(converter, returnType); - } catch (Exception ex) { - log.warn("could not obtain type of converter " + - converter + " for reason : " + ex.getMessage(), - ex); - } - } catch (NoSuchMethodException ex) { - log.warn("could not find method getType on converter " + - converter + ", will not be registred..."); - } catch (SecurityException ex) { - log.warn("could not find method getType on converter " + - converter + ", will not be registred..."); - } - - } - WAS_INIT = true; - } -} diff --git a/src/main/java/org/nuiton/util/converter/EnumConverter.java b/src/main/java/org/nuiton/util/converter/EnumConverter.java deleted file mode 100644 index 2ac9a0e..0000000 --- a/src/main/java/org/nuiton/util/converter/EnumConverter.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.converter; - -import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.beanutils.Converter; -import org.apache.commons.logging.Log; - -import java.util.EnumSet; - -import static org.apache.commons.logging.LogFactory.getLog; -import static org.nuiton.i18n.I18n.t; - -/** - * classe pour convertir une chaine en un objet Enum type-safe en - * connaissant le type d'enumération utilisée {@link #enumType}. - * - * Il est possible aussi de convertir une Enum à partir de sa valeur ordinal. - * - * Pour enregister un nouveau convertissemnt pour un type d'Enum utiliser les - * méthodes * {@link ConverterUtil#registerEnumConverter(Class)}, - * et {@link ConverterUtil#registerEnumConverter(Class, Object)} . - * - * @author Tony Chemit - chemit@codelutin.com - * @see Enum - * @see Enum#ordinal() - * @deprecated since 3.0 use instead {@link org.nuiton.converter.EnumConverter} - */ -@Deprecated -public class EnumConverter implements Converter { - - /** Logger. */ - static Log log = getLog(EnumConverter.class); - - /** valeur par default à utiliser, si pas non trouvée et {@link #useDefault} actif. */ - protected Object defaultValue; - - /** flag pour utiliser la valeur par defaut {@link #defaultValue} si non trouvé. */ - protected boolean useDefault; - - /** le type de l'énumération à convertir */ - protected Class<?> enumType; - - @Override - public Object convert(Class aClass, Object value) { - if (value == null) { - if (useDefault) { - return defaultValue; - } - throw new ConversionException( - t("nuitonutil.error.convertor.noValue", this)); - } - if (isEnabled(aClass, enumType)) { - Object result; - if (isEnabled(value.getClass(), enumType)) { - result = value; - return result; - } - if (value instanceof String) { - try { - result = valueOf(aClass, value); - } catch (IllegalArgumentException e) { - // try an ordinal conversion - result = convertFromOrdinal(aClass, value); - } - return result; - } - if (value instanceof Integer) { - // try a ordinal conversion - result = convertFromOrdinal(aClass, value); - return result; - } - } - throw new ConversionException( - t("nuitonutil.error.no.convertor", aClass.getName(), value)); - } - - public EnumConverter(Class<?> enumType, Object defaultValue) { - this.enumType = enumType; - this.defaultValue = defaultValue; - useDefault = defaultValue != null; - if (log.isDebugEnabled()) { - log.debug(toString() + '<' + enumType + '>'); - } - } - - public EnumConverter(Class<?> enumType) { - this(enumType, null); - } - - protected static boolean isEnabled(Class<?> aClass, Class<?> enumType) { - return aClass != null && aClass.isEnum() && aClass == enumType; - } - - protected Object convertFromOrdinal(Class<?> aClass, Object value) { - Object result = null; - try { - int ordinal = Integer.valueOf(value + ""); - EnumSet<?> vals = allOf(aClass); - if (ordinal > -1 && ordinal < vals.size()) { - for (Enum<?> val : vals) { - if (val.ordinal() == ordinal) { - result = val; - break; - } - } - } - } catch (NumberFormatException e1) { - // quiet conversion - result = null; - } - return result; - } - - protected Object valueOf(Class<?> aClass, Object value) { - Object result; - result = Enum.valueOf((Class<Enum>) aClass, (String) value); - return result; - } - - protected EnumSet<?> allOf(Class<?> aClass) { - EnumSet<?> vals; - vals = EnumSet.allOf((Class<Enum>) aClass); - return vals; - } - - public Class<?> getType() { - return enumType; - } - - -} diff --git a/src/main/java/org/nuiton/util/converter/FormatConverter.java b/src/main/java/org/nuiton/util/converter/FormatConverter.java deleted file mode 100644 index 5476531..0000000 --- a/src/main/java/org/nuiton/util/converter/FormatConverter.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.converter; - -import org.nuiton.util.converter.FormatMap.Format; - -/** - * Created: 14 septembre 2005 00:55:19 CEST - * <p> - * Un converter est un objet qui permet de passé d'une representation d'un - * objet vers une autre representation. Le mininum que converter doit savoir - * faire, est de converter une representation Java vers le format qu'il - * gère et inversement. Pour des raisons d'optimisation, il est possible - * qu'un converter sache passé d'un autre type que java vers sa representation - * pour eviter une conversion supplémentaire qui pourrait-etre couteuse. - * - * @param <A> le type de l'objet a convertir - * @author Benjamin Poussin - poussin@codelutin.com - * @deprecated since 3.0, will not pe replaced by anything (see https://forge.nuiton.org/issues/3326); will be removed later - */ -@Deprecated -public interface FormatConverter<A> { // FormatConverter - - Format FORMAT_JAVA = new Format("Format Java"); - - /** - * Convertie une valeur vers la representation FORMAT géré par cette classe - * - * @param factory la factory utilisable pour rechercher d'autre converter - * si la representation Java n'est pas presente dans values et que l'on - * en a besoin - * @param format le format souhaité en sortie - * @param values une map contenant les différentes representation de la - * meme valeur. Les cles de la map sont les valeurs retournés par la - * methode getFormat(). - * @param args des arguments qui peuvent-être utile pour la conversion. - * par exemple si dans une application on a construit son propre - * converter et que pour la conversion, on a besoin d'un Context applicatif - * il peut-etre passé dans les args. Si le converter a besoin d'autre - * converter les memes args lui seront passé. - * @return l'objet dans la representation demandés par type - * @throws IllegalArgumentException si auncun moyen n'est trouve pour - * convertir une des valeurs de values dans le format géré par cette classe. - * Ou s'il manque dans les args des objets utils pour la conversion. - */ - A convert(FormatConverterFactory factory, - Format format, FormatMap values, Object... args); - - /** - * Convertie une valeur vers le Java - * - * @param factory la factory utilisable pour rechercher d'autre converter - * si la representation Java n'est pas presente dans values et que l'on - * en a besoin - * @param format le format à utiliser comme valeur d'entré - * @param values une map contenant les différentes representation de la - * meme valeur. La valeur interessante dans la map pour cette methode - * est celle retournée par values.get(getFormat()) si cet appel, ne - * retourne pas quelque chose de valid, la methode doit lever une exception - * @param args des arguments qui peuvent-être utile pour la conversion. - * par exemple si dans une application on a construit son propre - * converter et que pour la conversion, on a besoin d'un Context applicatif - * il peut-etre passé dans les args. Si le converter a besoin d'autre - * converter les memes args lui seront passé. - * @return la valeur java - * @throws IllegalArgumentException si le format géré par cette classe n'est - * pas trouvé dans les values. Ou s'il manque dans les args des objets utils - * pour la conversion. - */ - Object unconvert(FormatConverterFactory factory, - Format format, FormatMap values, Object... args); - -} // FormatConverter - diff --git a/src/main/java/org/nuiton/util/converter/FormatConverterFactory.java b/src/main/java/org/nuiton/util/converter/FormatConverterFactory.java deleted file mode 100644 index 62442f7..0000000 --- a/src/main/java/org/nuiton/util/converter/FormatConverterFactory.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.converter; - -import org.apache.commons.collections4.map.MultiKeyMap; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.util.converter.FormatMap.Format; - -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedList; - -/** - * Factory permet d'enregistrer des objets de changement de format, et de - * les recupérer pour les utiliser. - * Les objets converter doivent au moins savoir convertir les objets depuis - * une representation Java. Pour des raisons d'optimisation, il est possible - * qu'il sache aussi convertir a partir d'autre representation, qui si elle - * existe sont moins couteuse a convertir. - * Il faut aussi que les converter sache convertir de leur representation vers - * un objet Java. - * par exemple si on enregistre les convertiseurs suivant: - * <pre> - * addConverter(new MatrixToXMLFormatConverter()); - * addConverter(new MatrixToSQLFormatConverter()); - * FormatConverterFactory.convert(Matrix.class, MatrixToXMLFormatConverter.TYPE, - * values, AppContext); - * </pre> - * Dans ce cas pour des raisons d'optimisation - * - * Created: 14 septembre 2005 00:19:51 CEST - * - * @author Benjamin Poussin - poussin@codelutin.com - * @since 1.3 replace the class {@code org.nuiton.util.FormatConverterFactory}. - * @deprecated since 3.0, will not pe replaced by anything (see https://forge.nuiton.org/issues/3326); will be removed later - */ -@Deprecated -public class FormatConverterFactory { // FormatConverterFactory - - /** Logger. */ - static private Log log = LogFactory.getLog(FormatConverterFactory.class); - - static protected FormatConverterFactory instance; - - /** <Class, from, to → FormatConverter> */ - protected MultiKeyMap converters = new MultiKeyMap(); - - synchronized public static FormatConverterFactory getInstance() { - if (instance == null) { - instance = new FormatConverterFactory(); - } - return instance; - } - - /** - * Permet d'enregitrer un converter pour permettre la convertion d'une - * certain type Java d'une representation vers une autre. - * par exemple le type String d'un objet Java vers une chaine XML - * - * @param clazz la class de la representation Java de l'objet - * @param format le format géré par le FormatConverter - * @param c le converter a enregistrer - */ - public void addConverter(Class<?> clazz, Format format, FormatConverter<?> c) { - converters.put(clazz, format, c); - } - - /** - * permet de recupere le converter pour la classe souhaitée. - * - * @param clazz la classe de l'objet dont on souhaite le converter - * @param format qui doit être géré par le converter - * @param defaultConverter si aucun converter trouvé, ce converter est - * retourné - * @return le converter souhaité ou defaultConverter - */ - public FormatConverter<?> getConverter(Class<?> clazz, Format format, - FormatConverter<?> defaultConverter) { - FormatConverter<?> result = (FormatConverter<?>) converters.get(clazz, format); - if (result == null) { - result = defaultConverter; - } - return result; - } - - /** - * @param clazz FIXME - * @param format FIXME - * @return retourne null si aucun converter trouvé - */ - public FormatConverter<?> getConverter(Class<?> clazz, Format format) { - return getConverter(clazz, format, null); - } - - /** - * Permet de retrouver le meilleur converter disponible pour l'argument - * clazz - * - * @param clazz la classe de l'objet dont on souhaite le converter - * @param format qui doit être géré par le converter - * @param defaultConverter si aucun converter trouvé, ce converter est - * retourné - * @return le converter souhaité ou defaultConverter - */ - public FormatConverter<?> findConverter(Class<?> clazz, Format format, - FormatConverter<?> defaultConverter) { - FormatConverter<?> result = null; - - LinkedList<Class<?>> interfaces = new LinkedList<Class<?>>(); - // On recherche la le transformer le plus spécifique sur les Class - Class<?> parent = clazz; - while (result == null && parent != null) { - Collections.addAll(interfaces, parent.getInterfaces()); - result = getConverter(parent, format); - parent = parent.getSuperclass(); - } - - // Si on a pas encore trouve de transformer on recherche - // un encodeur/decodeur pour les interfaces - for (Iterator<Class<?>> i = interfaces.iterator(); result == null && i.hasNext(); ) { - result = getConverter(i.next(), format); - } - - if (result == null) { - log.warn("Aucun converter trouvé pour le type: " + clazz); - result = defaultConverter; - } - log.debug("converter " + result + " utilisé pour le type: " + clazz); - - return result; - } - - /** - * @param clazz FIXME - * @param format FIXME - * @return retourne null si aucun converter trouvé - */ - public FormatConverter<?> findConverter(Class<?> clazz, Format format) { - return findConverter(clazz, format, null); - } - - public Object convert(Format format, FormatMap values, Object... args) { - FormatConverter<?> c = findConverter(values.getType(), format); - if (c == null) { - throw new IllegalArgumentException("Aucun converter utilisable pour les arguments donnés class: " + values.getType().getName() + " format: " + format); - } - return c.convert(this, format, values, args); - } - - public Object unconvert(Format format, FormatMap values, Object... args) { - FormatConverter<?> c = findConverter(values.getType(), format); - if (c == null) { - throw new IllegalArgumentException("Aucun converter utilisable pour les arguments donnés"); - } - return c.unconvert(this, format, values, args); - } - - public Object convert(FormatConverter<?> defaultConverter, - Format format, FormatMap values, Object... args) { - FormatConverter<?> c = findConverter(values.getType(), format, defaultConverter); - return c.convert(this, format, values, args); - } - - public Object unconvert(FormatConverter<?> defaultConverter, - Format format, FormatMap values, Object... args) { - FormatConverter<?> c = findConverter(values.getType(), format, defaultConverter); - return c.unconvert(this, format, values, args); - } - -} // FormatConverterFactory - diff --git a/src/main/java/org/nuiton/util/converter/FormatMap.java b/src/main/java/org/nuiton/util/converter/FormatMap.java deleted file mode 100644 index c16d1b8..0000000 --- a/src/main/java/org/nuiton/util/converter/FormatMap.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.converter; - -import java.util.HashMap; -import java.util.Map; - -/** - * Classe servant de conteneur pour les différentes representation d'un objet - * Les representations doivents être des instances de {@link Format}. Le mieux - * est lors de l'ecriture des convertisseurs pour un nouveau format est de - * créer une instance final static de {@link Format} Format pour representer - * ce format - * - * <h2>Utilisation</h2> - * <pre> - * FormatMap values = new FormatMap(MonObject.class); - * values.put(FormatConverter.FORMAT_JAVA, monInstance); - * Element xml = (Element)values.convert(XMLConverter.FORMAT_XML); - * Object sql = values.convert(SQLConverter.FORMAT_SQL); - * </pre> - * <pre> - * FormatMap values = new FormatMap(MonObject.class); - * values.put(FormatConverter.FORMAT_XML, monInstanceEnXML); - * Object sql = values.convert(SQLConverter.FORMAT_SQL); - * </pre> - * Dans ce second cas, la demande de la version SQL, transforme automatiquement - * la representation XML qui est la seul presente en Java, puis a partir de - * cette representation Java, on recupere la representation SQL. Bien sur - * Si le convertisseur SQL, peut directement convertir le XML en SQL, alors - * la conversion Java ne sera pas faite. - * - * Il est souvent plus simple de faire une petite classe avec les methodes - * getSQL() et getXML(), qui retourne les valeurs directement dans le bon type - * et qui n'ont pas besoin d'argument. - * - * - * Created: 16 septembre 2005 10:41:58 CEST - * - * @author Benjamin Poussin - poussin@codelutin.com - * @since 1.3 (replace {@code org.nuiton.util.FormatMap} class). - * @deprecated since 3.0, will not pe replaced by anything (see https://forge.nuiton.org/issues/3326); will be removed later - */ -@Deprecated -public class FormatMap extends HashMap<FormatMap.Format, Object> { // FormatMap - - private static final long serialVersionUID = 1L; - - public static class Format { - - protected String name; - - public Format(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } - } - - protected Class<?> clazz; - - public FormatMap(Class<?> clazz) { - this.clazz = clazz; - } - - public Class<?> getType() { - return clazz; - } - - /** - * Met a jour la valeur de l'objet. Toutes les autres valeurs calculées - * sont oubliées et seront recalculé en fonction de cette nouvelle valeur - * - * @param format le format a utiliser - * @param value FIXME - */ - public void setValue(Format format, Object value) { - clear(); - put(format, value); - } - - /** - * Utilise le FormatConverterFactory par defaut pour la conversion - * - * @param format le format a utiliser - * @param args les arguments - * @return l'objet converti - */ - public Object convert(Format format, Object... args) { - return convert(FormatConverterFactory.getInstance(), format, args); - } - - /** - * Recupere la valeur dans le format demandé - * - * @param factory la FormatConverterFactory a utiliser - * @param format le format souhaité - * @param args des arguments facultatifs en fonction du context d'utilisation - * @return l'objet converti - */ - public Object convert(FormatConverterFactory factory, Format format, - Object... args) { - Object result; - Map<Format, Object> values = this; - //if (!values.containsKey(format) || - // !format.equals(FormatConverter.FORMAT_JAVA)) { - // throw new IllegalArgumentException("Aucun valeur disponible"); - //} - - if (values.containsKey(format)) { - result = values.get(format); - } else if (format.equals(FormatConverter.FORMAT_JAVA)) { - // on recherche une representation, que l'on convertie en Java - if (values.isEmpty()) { - throw new IllegalArgumentException("Aucun valeur disponible"); - } - Format otherFormat = values.keySet().iterator().next(); - result = unconvert(factory, otherFormat, args); - values.put(format, result); - } else { - result = factory.convert(format, this, args); - // on stocke la valeur trouver pour les prochaines fois - values.put(format, result); - } - - return result; - } - - /** - * Utilise le FormatConverterFactory par defaut pour la conversion - * - * @param format le format utilise - * @param args FIXME - * @return l'objet java - */ - public Object unconvert(Format format, Object... args) { - return unconvert(FormatConverterFactory.getInstance(), format, args); - } - - /** - * Donne la representation Java de l'objet en essayant de partir de la - * representation passé en parametre. - * - * @param factory la factory a utiliser - * @param format le format de départ souhaité - * @param args des arguments facultatifs en fonction du context d'utilisation - * @return l'objet java - */ - public Object unconvert(FormatConverterFactory factory, Format format, - Object... args) { - Object result = null; - Map<Format, Object> values = this; - if (!values.containsKey(format) && - !values.containsKey(FormatConverter.FORMAT_JAVA)) { - throw new IllegalArgumentException("Aucun valeur disponible"); - } - - // si on a deja la representation Java on la retourne tout de suite - if (values.containsKey(FormatConverter.FORMAT_JAVA)) { - result = values.get(FormatConverter.FORMAT_JAVA); - } else if (values.containsKey(format)) { - result = factory.unconvert(format, this, args); - values.put(FormatConverter.FORMAT_JAVA, result); - } - - return result; - } -} // FormatMap - diff --git a/src/main/java/org/nuiton/util/converter/KeyStrokeConverter.java b/src/main/java/org/nuiton/util/converter/KeyStrokeConverter.java deleted file mode 100644 index 4d9feee..0000000 --- a/src/main/java/org/nuiton/util/converter/KeyStrokeConverter.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.converter; - -import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.beanutils.Converter; -import org.apache.commons.logging.Log; - -import javax.swing.KeyStroke; - -import static org.apache.commons.logging.LogFactory.getLog; -import static org.nuiton.i18n.I18n.t; - -/** - * Used to convert a {@link String} to {@link KeyStroke}. - * - * @author Sylvain Letellier - * @since 2.5.1 - * @deprecated since 3.0 use instead {@link org.nuiton.converter.KeyStrokeConverter} (<strong>Note:</strong> This converter is no more loaded by the {@link ConverterUtil#initConverters()}) - */ -@Deprecated -public class KeyStrokeConverter implements Converter { - - - /** Logger. */ - static Log log = getLog(KeyStrokeConverter.class); - - @Override - public Object convert(Class aClass, Object value) { - if (value == null) { - throw new ConversionException( - t("nuitonutil.error.convertor.noValue", this)); - } - if (isEnabled(aClass)) { - Object result; - if (isEnabled(value.getClass())) { - result = value; - return result; - } - if (value instanceof String) { - result = KeyStroke.getKeyStroke((String) value); - return result; - } - } - throw new ConversionException( - t("nuitonutil.error.no.convertor", aClass.getName(), value)); - } - - protected boolean isEnabled(Class<?> aClass) { - return KeyStroke.class.equals(aClass); - } - - public Class<?> getType() { - return KeyStroke.class; - } -} diff --git a/src/main/java/org/nuiton/util/converter/URIConverter.java b/src/main/java/org/nuiton/util/converter/URIConverter.java deleted file mode 100644 index 61a906f..0000000 --- a/src/main/java/org/nuiton/util/converter/URIConverter.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.converter; - -import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.beanutils.Converter; -import org.apache.commons.logging.Log; - -import java.net.URI; -import java.net.URISyntaxException; - -import static org.apache.commons.logging.LogFactory.getLog; -import static org.nuiton.i18n.I18n.t; - -/** - * classe pour convertir une chaine en un objet URI. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 (replace {@code org.nuiton.util.URIConverter}). - * @deprecated since 3.0 use instead {@link org.nuiton.converter.URIConverter} (<strong>Note:</strong> This converter is no more loaded by the {@link ConverterUtil#initConverters()}) - */ -@Deprecated -public class URIConverter implements Converter { - - /** Logger. */ - static Log log = getLog(URIConverter.class); - - @Override - public Object convert(Class aClass, Object value) { - if (value == null) { - throw new ConversionException( - t("nuitonutil.error.convertor.noValue", this)); - } - if (isEnabled(aClass)) { - Object result; - if (isEnabled(value.getClass())) { - result = value; - return result; - } - if (value instanceof String) { - result = valueOf((String) value); - return result; - } - } - throw new ConversionException( - t("nuitonutil.error.no.convertor", aClass.getName(), value)); - } - - protected URI valueOf(String value) { - try { - URI result; - result = new URI(value); - return result; - } catch (URISyntaxException e) { - throw new ConversionException( - t("nuitonutil.error.url.convertor", value, this, e.getMessage())); - } - } - - public URIConverter() { - if (log.isDebugEnabled()) { - log.debug("init uri converter " + this); - } - } - - protected boolean isEnabled(Class<?> aClass) { - return URI.class.equals(aClass); - } - - public Class<?> getType() { - return URI.class; - } -} diff --git a/src/main/java/org/nuiton/util/converter/URLConverter.java b/src/main/java/org/nuiton/util/converter/URLConverter.java deleted file mode 100644 index a4c85d2..0000000 --- a/src/main/java/org/nuiton/util/converter/URLConverter.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.converter; - -import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.beanutils.Converter; -import org.apache.commons.logging.Log; - -import java.net.MalformedURLException; -import java.net.URL; - -import static org.apache.commons.logging.LogFactory.getLog; -import static org.nuiton.i18n.I18n.t; - -/** - * classe pour convertir une chaine en un objet URL. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 (replace {@code org.nuiton.util.URLConverter}). - * @deprecated since 3.0 use instead {@link org.nuiton.converter.URLConverter} (<strong>Note:</strong> This converter is no more loaded by the {@link ConverterUtil#initConverters()}) - */ -@Deprecated -public class URLConverter implements Converter { - - /** Logger. */ - static Log log = getLog(URLConverter.class); - - @Override - public Object convert(Class aClass, Object value) { - if (value == null) { - throw new ConversionException( - t("nuitonutil.error.convertor.noValue", this)); - } - if (isEnabled(aClass)) { - Object result; - if (isEnabled(value.getClass())) { - result = value; - return result; - } - if (value instanceof String) { - result = valueOf((String) value); - return result; - } - } - throw new ConversionException( - t("nuitonutil.error.no.convertor", aClass.getName(), value)); - } - - protected URL valueOf(String value) { - try { - URL result; - result = new URL(value); - return result; - } catch (MalformedURLException e) { - throw new ConversionException( - t("nuitonutil.error.url.convertor", value, this, e.getMessage())); - } - } - - public URLConverter() { - if (log.isDebugEnabled()) { - log.debug("init url converter " + this); - } - } - - protected boolean isEnabled(Class<?> aClass) { - return URL.class.equals(aClass); - } - - public Class<?> getType() { - return URL.class; - } - - -} diff --git a/src/main/java/org/nuiton/util/converter/VersionConverter.java b/src/main/java/org/nuiton/util/converter/VersionConverter.java deleted file mode 100644 index 6d12f5a..0000000 --- a/src/main/java/org/nuiton/util/converter/VersionConverter.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.converter; - -import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.converter.NuitonConverter; -import org.nuiton.util.Version; -import org.nuiton.util.VersionUtil; - -import static org.nuiton.i18n.I18n.t; - -/** - * classe pour convertir une chaine en un objet Version. - * - * @author Tony Chemit - chemit@codelutin.com - * @see Version - * @since 1.3 (replace {@code org.nuiton.util.VersionConverter}). - * @deprecated since 3.0, prefer use the {@link org.nuiton.util.version.VersionConverter}. - */ -@Deprecated -public class VersionConverter implements NuitonConverter<Version> { - - /** Logger. */ - private static final Log log = LogFactory.getLog(VersionConverter.class); - - public VersionConverter() { - if (log.isDebugEnabled()) { - log.debug("init version converter " + this); - } - } - - @Override - public <T> T convert(Class<T> aClass, Object value) { - if (value == null) { - throw new ConversionException( - t("nuitonutil.error.convertor.noValue", this)); - } - if (isEnabled(aClass)) { - Object result; - if (isEnabled(value.getClass())) { - result = value; - return aClass.cast(result); - } - if (value instanceof String) { - try { - result = VersionUtil.valueOf((String) value); - return aClass.cast(result); - } catch (IllegalArgumentException e) { - throw new ConversionException( - t("nuitonutil.error.version.convertor", value, this, e.getMessage()), e); - } - } - } - throw new ConversionException( - t("nuitonutil.error.no.convertor", aClass.getName(), value)); - } - - @Override - public Class<Version> getType() { - return Version.class; - } - - protected boolean isEnabled(Class<?> aClass) { - return Version.class.equals(aClass); - } -} diff --git a/src/main/java/org/nuiton/util/converter/package-info.java b/src/main/java/org/nuiton/util/converter/package-info.java deleted file mode 100644 index 8a430c9..0000000 --- a/src/main/java/org/nuiton/util/converter/package-info.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -/** - * - * This package contains the converter api + the format api. - * - * <h1>Converter api</h1> - * This converter api is based on the - * http://commons.apache.org/beanutils {@code commons-beanutils}. - * - * Use the {@link org.nuiton.util.converter.ConverterUtil} to register or obtain a - * converter. - * - * <h1>Format api</h1> - * see {@link org.nuiton.util.converter.FormatConverter} and others - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - * @deprecated since 3.0 (see https://forge.nuiton.org/issues/3320), will be removed after version 3.0 - */ -package org.nuiton.util.converter; diff --git a/src/main/java/org/nuiton/util/package-info.java b/src/main/java/org/nuiton/util/package-info.java deleted file mode 100644 index 1ff2b48..0000000 --- a/src/main/java/org/nuiton/util/package-info.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -/** - * Ensemble de classe Java permettant de simplifier le développement en - * factorisant des besoins que l'on retrouve dans tous les développement. - * On y trouve de fontion de travail sur les chaînes de caractères. Des - * fonctions de parsage des arguements de la ligne de commande. Des fonctions - * permettant très simplement de rechercher une resource (images, fichier de - * propriétés, ...). - */ -package org.nuiton.util; diff --git a/src/main/java/org/nuiton/util/pagination/PaginationOrder.java b/src/main/java/org/nuiton/util/pagination/PaginationOrder.java deleted file mode 100644 index 5d294a4..0000000 --- a/src/main/java/org/nuiton/util/pagination/PaginationOrder.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.nuiton.util.pagination; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2014 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import java.io.Serializable; - -/** - * This class represents an 'order' information : order clause and asc/desc - * - * @author Arnaud Thimel (Code Lutin) - * @since 3.0 - */ -public class PaginationOrder implements Serializable { - - private static final long serialVersionUID = 1L; - - protected String clause; - protected boolean desc; - - public PaginationOrder(String clause, boolean desc) { - this.clause = clause; - this.desc = desc; - } - - public String getClause() { - return clause; - } - - public void setClause(String clause) { - this.clause = clause; - } - - public boolean isDesc() { - return desc; - } - - public void setDesc(boolean desc) { - this.desc = desc; - } - -} diff --git a/src/main/java/org/nuiton/util/pagination/PaginationParameter.java b/src/main/java/org/nuiton/util/pagination/PaginationParameter.java deleted file mode 100644 index e2d52fa..0000000 --- a/src/main/java/org/nuiton/util/pagination/PaginationParameter.java +++ /dev/null @@ -1,317 +0,0 @@ -package org.nuiton.util.pagination; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2014 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -import java.io.Serializable; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * This class represents the necessary information to do pagination (page number, size, ...). - * - * @author Arnaud Thimel (Code Lutin) - * @since 3.0 - */ -public class PaginationParameter implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * 0-based page number - */ - protected int pageNumber; - - /** - * The size of each page. Value can be -1 (for infinite pageSize) or greater than 0 - */ - protected int pageSize; - - /** - * The list of order clauses. This instance is unmodifiable and never null. - */ - protected List<PaginationOrder> orderClauses; - - protected PaginationParameter(int pageNumber, int pageSize) { - this(pageNumber, pageSize, new LinkedList<PaginationOrder>()); - } - - protected PaginationParameter(int pageNumber, int pageSize, List<PaginationOrder> orderClauses) { - Preconditions.checkArgument(pageNumber >= 0, "pageNumber cannot be lower than 0"); - Preconditions.checkArgument(pageSize == -1 || pageSize > 0, "pageSize can only be -1 or greater than 0"); - Preconditions.checkArgument(pageSize != -1 || pageNumber == 0, "This is non-sense to have pageNumber>1 if pageSize==-1"); - this.pageNumber = pageNumber; - this.pageSize = pageSize; - this.orderClauses = Collections.unmodifiableList(orderClauses); - } - - /** - * Method to create a PaginationParameter only based on pageNumber and pageSize (no order clauses). - * - * @param pageNumber the index (0-based) of the page - * @param pageSize the size of each page. Value can be -1 (for infinite pageSize) or greater than 0 - * @return an immutable PaginationParameter instance - */ - public static PaginationParameter of(int pageNumber, int pageSize) { - PaginationParameter result = new PaginationParameter(pageNumber, pageSize); - return result; - } - - /** - * Method to create a PaginationParameter based on pageNumber, pageSize and a single order clause. - * - * If you have an unknown number of order clauses, you should use the {@link #builder(int, int)} - * method together with {@link PaginationParameterBuilder#addOrder(String, boolean)} and - * {@link PaginationParameterBuilder#build()} methods. - * - * @param pageNumber the index (0-based) of the page - * @param pageSize the size of each page. Value can be -1 (for infinite pageSize) or greater than 0 - * @param orderClause1 an order clause attribute name. It comes together with {code}orderDesc1{/code} - * @param orderDesc1 the asc/desc property associated with {code}orderClause1{/code} - * @return an immutable PaginationParameter instance - * @see org.nuiton.util.pagination.PaginationOrder - * @see PaginationParameterBuilder - */ - public static PaginationParameter of(int pageNumber, int pageSize, - String orderClause1, boolean orderDesc1) { - return builder(pageNumber, pageSize) - .addOrder(orderClause1, orderDesc1) - .build(); - } - - /** - * Method to create a PaginationParameter based on pageNumber, pageSize and two order clauses. - * - * If you have an unknown number of order clauses, you should use the {@link #builder(int, int)} - * method together with {@link PaginationParameterBuilder#addOrder(String, boolean)} and - * {@link PaginationParameterBuilder#build()} methods. - * - * @param pageNumber the index (0-based) of the page - * @param pageSize the size of each page. Value can be -1 (for infinite pageSize) or greater than 0 - * @param orderClause1 an order clause attribute name. It comes together with {code}orderDesc1{/code} - * @param orderDesc1 the asc/desc property associated with {code}orderClause1{/code} - * @param orderClause2 an order clause attribute name. It comes together with {code}orderDesc2{/code} - * @param orderDesc2 the asc/desc property associated with {code}orderClause2{/code} - * @return an immutable PaginationParameter instance - * @see org.nuiton.util.pagination.PaginationOrder - * @see PaginationParameterBuilder - */ - public static PaginationParameter of(int pageNumber, int pageSize, - String orderClause1, boolean orderDesc1, - String orderClause2, boolean orderDesc2) { - return builder(pageNumber, pageSize) - .addOrder(orderClause1, orderDesc1) - .addOrder(orderClause2, orderDesc2) - .build(); - } - - /** - * Method to create a PaginationParameter based on pageNumber, pageSize and three order clauses. - * - * If you have more order clauses, or an unknown number of clauses, you should use the {@link #builder(int, int)} - * method together with {@link PaginationParameterBuilder#addOrder(String, boolean)} and - * {@link PaginationParameterBuilder#build()} methods. - * - * @param pageNumber the index (0-based) of the page - * @param pageSize the size of each page. Value can be -1 (for infinite pageSize) or greater than 0 - * @param orderClause1 an order clause attribute name. It comes together with {code}orderDesc1{/code} - * @param orderDesc1 the asc/desc property associated with {code}orderClause1{/code} - * @param orderClause2 an order clause attribute name. It comes together with {code}orderDesc2{/code} - * @param orderDesc2 the asc/desc property associated with {code}orderClause2{/code} - * @param orderClause3 an order clause attribute name. It comes together with {code}orderDesc3{/code} - * @param orderDesc3 the asc/desc property associated with {code}orderClause3{/code} - * @return an immutable PaginationParameter instance - * @see org.nuiton.util.pagination.PaginationOrder - * @see PaginationParameterBuilder - */ - public static PaginationParameter of(int pageNumber, int pageSize, - String orderClause1, boolean orderDesc1, - String orderClause2, boolean orderDesc2, - String orderClause3, boolean orderDesc3) { - return builder(pageNumber, pageSize) - .addOrder(orderClause1, orderDesc1) - .addOrder(orderClause2, orderDesc2) - .addOrder(orderClause3, orderDesc3) - .build(); - } - - /** - * Method to create a PaginationParameter using the {@link PaginationParameterBuilder}. - * - * @param pageNumber the index (0-based) of the page - * @param pageSize the size of each page. Value can be -1 (for infinite pageSize) or greater than 0 - * @return an immutable PaginationParameter.Builder instance - */ - public static PaginationParameterBuilder builder(int pageNumber, int pageSize) { - PaginationParameterBuilder result = new PaginationParameterBuilder(pageNumber, pageSize); - return result; - } - - public int getPageNumber() { - return pageNumber; - } - - public int getPageSize() { - return pageSize; - } - - public List<PaginationOrder> getOrderClauses() { - return orderClauses; - } - - /** - * Method that computes the start index of a page according to {@link #pageNumber} and {@link #pageSize}. - * - * @return the computed start index - */ - public int getStartIndex() { - if (pageNumber != 0) { - Preconditions.checkState(pageSize != -1, "This is non-sense to have pageNumber>1 if pageSize==-1"); - } - int startIndex = pageNumber * pageSize; - return startIndex; - } - - /** - * Method that computes the end index of a page according to {@link #pageNumber} and {@link #pageSize}. If the - * pageSize is -1, the end index will be {@link Integer#MAX_VALUE}. - * - * @return the computed end index - */ - public int getEndIndex() { - int endIndex = Integer.MAX_VALUE; - if (pageSize != -1) { - endIndex = getStartIndex() + pageSize - 1; - } - return endIndex; - } - - /** - * Class used to build an instance of PaginationParameter. Use the {@link #build()} method to create the - * {@link org.nuiton.util.pagination.PaginationParameter}. - * - * @author Arnaud Thimel (Code Lutin) - * @since 3.0 - */ - public static class PaginationParameterBuilder { - - protected int pageNumber; - protected int pageSize; - protected List<PaginationOrder> orderClauses; - - /** - * Creates a Builder instance - * - * @param pageNumber the index (0-based) of the page - * @param pageSize the size of each page. Value can be -1 (for infinite pageSize) or greater than 0 - */ - public PaginationParameterBuilder(int pageNumber, int pageSize) { - this.pageNumber = pageNumber; - this.pageSize = pageSize; - } - - /** - * Adds an order clause - * - * @param clause an order clause attribute name. It comes together with {code}desc{/code} - * @param desc the asc/desc property associated with {code}clause{/code} - * @return the current Builder for a Fluent usage - */ - public PaginationParameterBuilder addOrder(String clause, boolean desc) { - if (orderClauses == null) { - orderClauses = Lists.newLinkedList(); - } - PaginationOrder paginationOrder = new PaginationOrder(clause, desc); - orderClauses.add(paginationOrder); - return this; - } - - /** - * Adds an ASC order clause - * - * @param clause an order clause attribute name - * @return the current Builder for a Fluent usage - */ - public PaginationParameterBuilder addAscOrder(String clause) { - return addOrder(clause, false); - } - - /** - * Adds an DESC order clause - * - * @param clause an order clause attribute name - * @return the current Builder for a Fluent usage - */ - public PaginationParameterBuilder addDescOrder(String clause) { - return addOrder(clause, true); - } - - /** - * Adds an order clause. The asc/desc value is guessed from the given {code}clause{/code}. The expected format - * is "column asc" or "column desc" - * - * @param clause an order clause attribute name. It comes together with {code}desc{/code} - * @return the current Builder for a Fluent usage - */ - public PaginationParameterBuilder addOrder(String clause) { - boolean desc = false; - String cleanedClause = clause; - int spaceIndex = clause.indexOf(' '); - if (spaceIndex != -1) { - cleanedClause = clause.substring(0, spaceIndex).trim(); - desc = "desc".equalsIgnoreCase(clause.substring(spaceIndex + 1).trim()); - } - return addOrder(cleanedClause, desc); - } - - /** - * Adds an the given order clauses - * - * @param clauses an list of order clauses - * @return the current Builder for a Fluent usage - */ - public PaginationParameterBuilder addOrderClauses(Iterable<PaginationOrder> clauses) { - if (orderClauses == null) { - orderClauses = Lists.newLinkedList(); - } - if (clauses != null) { - Iterables.addAll(orderClauses, clauses); - } - return this; - } - - /** - * Final method that instantiates the immutable PaginationParameter - * - * @return the immutable PaginationParameter built - */ - public PaginationParameter build() { - PaginationParameter result = new PaginationParameter(pageNumber, pageSize, orderClauses); - return result; - } - } -} diff --git a/src/main/java/org/nuiton/util/pagination/PaginationResult.java b/src/main/java/org/nuiton/util/pagination/PaginationResult.java deleted file mode 100644 index 598247e..0000000 --- a/src/main/java/org/nuiton/util/pagination/PaginationResult.java +++ /dev/null @@ -1,149 +0,0 @@ -package org.nuiton.util.pagination; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2014 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import com.google.common.base.Preconditions; - -import java.io.Serializable; -import java.util.List; - -/** - * Represents the result of a pagination request. It contains the result elements together with the - * {@link org.nuiton.util.pagination.PaginationParameter} used to compute it. The class also contains methods to - * navigate through the other pages. - * - * @author Arnaud Thimel (Code Lutin) - * @since 3.0 - */ -public class PaginationResult<O> implements Serializable { - - private static final long serialVersionUID = 1L; - - protected List<O> elements; - protected long count; - protected PaginationParameter currentPage; - - protected PaginationResult(List<O> elements, long count, PaginationParameter currentPage) { - this.elements = elements; - this.count = count; - this.currentPage = currentPage; - } - - /** - * Creates an instance using the already computed list of {code}elements{/code} and {code}count{/count}, together - * with the {code}currentPage{/code} {@link org.nuiton.util.pagination.PaginationParameter} used to build it. - * - * @param elements the list of elements - * @param count the total number of elements (through all pages) - * @param currentPage the PaginationParameter used to build this paged result - * @param <T> any object type - * @return the built instance of PaginationResult - */ - public static <T> PaginationResult<T> of(List<T> elements, long count, PaginationParameter currentPage) { - PaginationResult<T> result = new PaginationResult<T>(elements, count, currentPage); - return result; - } - - public List<O> getElements() { - return elements; - } - - public long getCount() { - return count; - } - - public PaginationParameter getCurrentPage() { - return currentPage; - } - - public PaginationParameter getNextPage() { - int nextPageNumber = currentPage.getPageNumber() + 1; - int pageSize = currentPage.getPageSize(); - List<PaginationOrder> orderClauses = currentPage.getOrderClauses(); - PaginationParameter result = PaginationParameter. - builder(nextPageNumber, pageSize). - addOrderClauses(orderClauses). - build(); - return result; - } - - public PaginationParameter getPreviousPage() { - // XXX AThimel 21/05/14 Maybe, do not fail, just return the first page ? - Preconditions.checkState(hasPreviousPage(), "You cannot get a previous page to the first one"); - int previousPageNumber = currentPage.getPageNumber() - 1; - int pageSize = currentPage.getPageSize(); - List<PaginationOrder> orderClauses = currentPage.getOrderClauses(); - PaginationParameter result = PaginationParameter. - builder(previousPageNumber, pageSize). - addOrderClauses(orderClauses). - build(); - return result; - } - - public PaginationParameter getFirstPage() { - int firstPageNumber = 0; - int pageSize = currentPage.getPageSize(); - List<PaginationOrder> orderClauses = currentPage.getOrderClauses(); - PaginationParameter result = PaginationParameter. - builder(firstPageNumber, pageSize). - addOrderClauses(orderClauses). - build(); - return result; - } - - public PaginationParameter getLastPage() { - // AThimel 28/05/14 Math.max(0, ...) to make sure last page is working even if there is no result - int lastPageNumber = Math.max(0, getPageCount() - 1); - int pageSize = currentPage.getPageSize(); - List<PaginationOrder> orderClauses = currentPage.getOrderClauses(); - PaginationParameter result = PaginationParameter. - builder(lastPageNumber, pageSize). - addOrderClauses(orderClauses). - build(); - return result; - } - - public int getPageCount() { - int pageCount = 1; - int pageSize = currentPage.getPageSize(); - if (pageSize >= 1) { - double countDouble = Long.valueOf(count).doubleValue(); - double pageSizeDouble = Integer.valueOf(pageSize).doubleValue(); - double pageNumberDouble = Math.ceil(countDouble / pageSizeDouble); - pageCount = Double.valueOf(pageNumberDouble).intValue(); - } - return pageCount; - } - - public boolean hasNextPage() { - int lastPageNumber = getPageCount() - 1; - boolean result = currentPage.getPageNumber() < lastPageNumber; - return result; - } - - public boolean hasPreviousPage() { - boolean result = currentPage.getPageNumber() > 0; - return result; - } - -} diff --git a/src/main/java/org/nuiton/util/pagination/package-info.java b/src/main/java/org/nuiton/util/pagination/package-info.java deleted file mode 100644 index 6ae3907..0000000 --- a/src/main/java/org/nuiton/util/pagination/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * This package contains all about pagination : <ul> - * <li>{@link org.nuiton.util.pagination.PaginationParameter} to express the input pagination parameters when - * preparing a query</li> - * <li>{@link org.nuiton.util.pagination.PaginationOrder} represents an order clause together with asc/desc</li> - * <li>{@link org.nuiton.util.pagination.PaginationResult} represents a list together with the pagination parameters - * used to get the list of elements. It also contains methods to navigate throw the other pages</li> - * </ul> - */ -package org.nuiton.util.pagination; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2014 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ diff --git a/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutor.java b/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutor.java deleted file mode 100644 index a7c4126..0000000 --- a/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutor.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.rmi; - -import java.rmi.Remote; -import java.rmi.RemoteException; - -/** - * This class will act as an InvocationHandler except that it is distributed. - * - * @author Arnaud Thimel - thimel@codelutin.com - */ -public interface RemoteMethodExecutor extends Remote { - - /** - * Acts like an InvocationHandler. - * - * @param methodName name of the method to invoke - * @param parametersType parameters type to reliably identify the method - * @param args method arguments to process the effective call - * @return the result of the delegate method - * @throws RemoteException for any error. Business exceptions will be - * wrapped. - */ - Object execute(String methodName, Class<?>[] parametersType, Object[] args) - throws RemoteException; - -} diff --git a/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutorImpl.java b/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutorImpl.java deleted file mode 100644 index 7811173..0000000 --- a/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutorImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.rmi; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.rmi.RemoteException; - -/** - * RMI implementation of an invocation handler. This object will be exported to - * a RMI registry and will delegate method calls to some business service. The - * service is provided in the constructor. - * - * @author Arnaud Thimel - thimel@codelutin.com - */ -public class RemoteMethodExecutorImpl<T> implements RemoteMethodExecutor { - - /** The target service on which calls will be made */ - protected T service; - - /** - * This is the only available constructor. It is mandatory to specify a - * target service on which call will be - * delegated. - * - * @param service the mandatory service which calls will be delegated on - */ - public RemoteMethodExecutorImpl(T service) { - if (service == null) { - throw new NullPointerException("Service cannot be null"); - } - this.service = service; - } - - @Override - public Object execute( - String methodName, Class<?>[] parametersType, Object[] args) - throws RemoteException { - - Object result; - try { - - // Get the method on the target service then invoke it - Method method = service.getClass().getMethod( - methodName, parametersType); - result = method.invoke(service, args); - - } catch (InvocationTargetException ite) { - // This is the normal behaviour if a business exception is thrown - Throwable targetException = ite.getTargetException(); - throw new RemoteException( - "Business exception occurred", targetException); - } catch (NoSuchMethodException nsme) { - throw new RemoteException("Delegate method not found", nsme); - } catch (IllegalAccessException iae) { - throw new RemoteException("Delegate method not accessible", iae); - } - - return result; - } - -} diff --git a/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java b/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java deleted file mode 100644 index da30df7..0000000 --- a/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.rmi; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.rmi.ConnectException; -import java.rmi.NotBoundException; -import java.rmi.RemoteException; -import java.rmi.ServerException; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; - -/** - * Factory to create RMI proxies to some given services. - * - * @author Arnaud Thimel - thimel@codelutin.com - */ -public class RemoteProxyFactory { - - private final static Log log = LogFactory.getLog(RemoteProxyFactory.class); - - // TODO AThimel 12/01/2011 This settings has to be externalized - protected final static int PORT = 12345; - - protected final static String REGISTRY_IP = "127.0.0.1"; - - /** - * Create a RMI proxy on the wanted service interface. The default RMI name - * will be used to find this service in the Registry. - * - * @param serviceInterface The class of the service proxy to create - * @param <T> some interface class - * @return A newly created proxy which interface is <T> - * @throws RemoteException in case the registry is not reachable - * @throws NotBoundException if the default RMI name cannot be found in the - * registry - */ - public static <T> T createProxy(final Class<T> serviceInterface) - throws RemoteException, NotBoundException { - - // The default RMI name will be the FQN of the service interface - String rmiName = serviceInterface.getName(); - T result = createProxy(rmiName, serviceInterface); - - return result; - } - - /** - * Create a RMI proxy on the wanted service interface. The specific given - * RMI name will be used to find this service in the Registry. - * - * @param rmiName The specific RMI name to use to find the service - * in the registry - * @param serviceInterface The class of the service proxy to create - * @param <T> some interface class - * @return A newly created proxy which interface is <T> - * @throws RemoteException in case the registry is not reachable - * @throws NotBoundException if the default RMI name cannot be found in the - * registry - */ - public static <T> T createProxy(String rmiName, Class<T> serviceInterface) - throws RemoteException, NotBoundException { - - // Lookup the registry and the remote executor from the registry - Registry registry = LocateRegistry.getRegistry(REGISTRY_IP, PORT); - try { - registry.list(); - } catch (ConnectException ce) { - // That means the registry is not on the specified port, try the default one - registry = LocateRegistry.getRegistry(); - } - final RemoteMethodExecutor stub = - (RemoteMethodExecutor) registry.lookup(rmiName); - - InvocationHandler handler = new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - - // Get parameters types and values to prepare delegate call - String methodName = method.getName(); - Class<?>[] parametersType = method.getParameterTypes(); - - // Delegate the execution and manage business exception cases - Object result; - try { - result = stub.execute(methodName, parametersType, args); - } catch (ServerException se) { - if (log.isInfoEnabled()) { - log.info("Server exception: " + se.getMessage()); - } - Throwable cause = se.getCause(); - if (cause instanceof RemoteException) { - RemoteException re = (RemoteException) cause; - cause = re.getCause(); - } - throw cause; - } - - return result; - } - }; - - // Invocation handler is ready, now create the proxy - T proxy = (T) Proxy.newProxyInstance( - ServiceExporter.class.getClassLoader(), - new Class<?>[]{serviceInterface}, - handler); - - return proxy; - } - -} diff --git a/src/main/java/org/nuiton/util/rmi/ServiceExporter.java b/src/main/java/org/nuiton/util/rmi/ServiceExporter.java deleted file mode 100644 index c181c2b..0000000 --- a/src/main/java/org/nuiton/util/rmi/ServiceExporter.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.rmi; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.rmi.ConnectException; -import java.rmi.NotBoundException; -import java.rmi.Remote; -import java.rmi.RemoteException; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; -import java.rmi.server.ExportException; -import java.rmi.server.UnicastRemoteObject; - -/** - * This class allows to make some service available throw RMI. For each service, - * a wrapper will be created which will be put in the RMI registry. This wrapper - * will intercept calls to the service and delegate them to it. - * - * @author Arnaud Thimel - thimel@codelutin.com - */ -public final class ServiceExporter { - - private final static Log log = LogFactory.getLog(ServiceExporter.class); - - // TODO AThimel 12/01/2011 This settings has to be externalized - private static final int PORT = 12345; - - /** Does some checks on RMI configuration */ - protected static void testRmiConfig() { - String rmiHost = System.getProperty("java.rmi.server.hostname"); - if ((rmiHost == null || "".equals(rmiHost.trim())) - && log.isWarnEnabled()) { - log.warn("Server might not have been initialized properly, " + - "please specify '-Djava.rmi.server.hostname=<IP-address>'"); - } - } - - /** - * Will look for the RMI registry. It an external registry cannot be found, - * a new one will be created. - * - * @return the registry found or created - * @throws RemoteException in case it is not possible to get the registry - */ - protected static Registry getRegistry() throws RemoteException { - Registry result; - try { - result = LocateRegistry.getRegistry(PORT); - // To test that registry has been created. An exception will be - // thrown if registry cannot be called - result.list(); - } catch (ConnectException ce) { - if (log.isWarnEnabled()) { - log.warn("Registry not found, creating a new one"); - } - try { - result = LocateRegistry.createRegistry(PORT); - } catch (ExportException ee) { // This is the particular case when a registry is already running but not on the correct port. - if (log.isWarnEnabled()) { - log.warn("Unable to create registry, try using the default one", ee); - } - - // Try the default port - result = LocateRegistry.getRegistry(); - } - } - return result; - } - - /** - * Will register a service using the default name. - * - * @param serviceInterface the interface used to bind the service. The RMI - * name will be generated from this class name - * @param instance the service instance to bind - * @param <E> some interface class - * @throws RemoteException in case the registry is not reachable - */ - public static <E> void registerService(Class<E> serviceInterface, E instance) - throws RemoteException { - String rmiName = serviceInterface.getName(); - registerService(rmiName, instance); - } - - /** - * Will register a service using the given RMI name. - * - * @param rmiName the RMI name used to bind the service in the registry - * @param instance the service instance to bind - * @param <E> some interface class - * @throws RemoteException in case the registry is not reachable - */ - public static <E> void registerService(String rmiName, E instance) - throws RemoteException { - - testRmiConfig(); - - // Create the proxy and let him be a stub - RemoteMethodExecutorImpl<E> executor = - new RemoteMethodExecutorImpl<E>(instance); - Remote stub = UnicastRemoteObject.exportObject(executor, 0); - - // Bind into the registry - Registry registry = getRegistry(); - registry.rebind(rmiName, stub); - } - - /** - * Will unregister a service using the default name. - * - * @param serviceInterface the interface used to unbind the service. The RMI - * name will be generated from this class name - * @throws RemoteException in case the registry is not reachable - * @throws NotBoundException in case the given name is not bound - */ - public static void unregisterService(Class<?> serviceInterface) - throws RemoteException, NotBoundException { - String rmiName = serviceInterface.getName(); - unregisterService(rmiName); - } - - /** - * Will unregister a service using the given RMI name. - * - * @param rmiName the RMI name used to unbind the service in the registry - * @throws RemoteException in case the registry is not reachable - * @throws NotBoundException in case the given name is not bound - */ - public static void unregisterService(String rmiName) - throws RemoteException, NotBoundException { - - // Bind into the registry - Registry registry = getRegistry(); - registry.unbind(rmiName); - } - -} diff --git a/src/main/java/org/nuiton/util/rmi/package-info.java b/src/main/java/org/nuiton/util/rmi/package-info.java deleted file mode 100644 index c14098c..0000000 --- a/src/main/java/org/nuiton/util/rmi/package-info.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -/** - * This package contains classes to easily export services to a RMI registry - * then get a proxy to access them. The provided classes will hide RMI - * complexity. - * - * Use the {@link org.nuiton.util.rmi.ServiceExporter} to register an service to the RMI registry. - * - * Use the {@link org.nuiton.util.rmi.RemoteProxyFactory} to get a proxy an call the RMI exported - * service. - * - * @author Arnaud Thimel - thimel@codelutin.com - */ -package org.nuiton.util.rmi; diff --git a/src/main/java/org/nuiton/util/version/SemVer.java b/src/main/java/org/nuiton/version/SemVer.java similarity index 99% rename from src/main/java/org/nuiton/util/version/SemVer.java rename to src/main/java/org/nuiton/version/SemVer.java index 1d70292..974e9f6 100644 --- a/src/main/java/org/nuiton/util/version/SemVer.java +++ b/src/main/java/org/nuiton/version/SemVer.java @@ -1,10 +1,10 @@ -package org.nuiton.util.version; +package org.nuiton.version; /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2004 - 2013 CodeLutin + * Copyright (C) 2016 CodeLutin * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as @@ -66,7 +66,7 @@ import java.util.regex.Pattern; * </ul> * * @author Benjamin Poussin - poussin@codelutin.com - * @since 2.6.7 + * @since 1.0 */ public class SemVer implements Comparable<SemVer> { diff --git a/src/main/java/org/nuiton/util/version/Version.java b/src/main/java/org/nuiton/version/Version.java similarity index 99% rename from src/main/java/org/nuiton/util/version/Version.java rename to src/main/java/org/nuiton/version/Version.java index 56ab469..1a98869 100644 --- a/src/main/java/org/nuiton/util/version/Version.java +++ b/src/main/java/org/nuiton/version/Version.java @@ -1,8 +1,8 @@ /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2014 CodeLutin, Tony Chemit + * Copyright (C) 2016 CodeLutin, Tony Chemit * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as @@ -20,7 +20,7 @@ * #L% */ -package org.nuiton.util.version; +package org.nuiton.version; import com.google.common.base.Preconditions; import org.apache.commons.lang3.ObjectUtils; @@ -74,7 +74,7 @@ import java.util.List; * @author Tony Chemit - chemit@codelutin.com * @see VersionBuilder * @see VersionComparator - * @since 3.0 + * @since 1.0 */ public class Version implements Comparable<Version>, Serializable { diff --git a/src/main/java/org/nuiton/util/version/VersionBuilder.java b/src/main/java/org/nuiton/version/VersionBuilder.java similarity index 99% rename from src/main/java/org/nuiton/util/version/VersionBuilder.java rename to src/main/java/org/nuiton/version/VersionBuilder.java index 936d67c..b91d6b7 100644 --- a/src/main/java/org/nuiton/util/version/VersionBuilder.java +++ b/src/main/java/org/nuiton/version/VersionBuilder.java @@ -1,10 +1,10 @@ -package org.nuiton.util.version; +package org.nuiton.version; /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2014 CodeLutin, Tony Chemit + * Copyright (C) 2016 CodeLutin, Tony Chemit * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as @@ -54,7 +54,7 @@ import java.util.Set; * Created on 7/11/14. * * @author Tony Chemit - chemit@codelutin.com - * @since 3.0 + * @since 1.0 */ public class VersionBuilder { diff --git a/src/main/java/org/nuiton/util/version/VersionComparator.java b/src/main/java/org/nuiton/version/VersionComparator.java similarity index 98% rename from src/main/java/org/nuiton/util/version/VersionComparator.java rename to src/main/java/org/nuiton/version/VersionComparator.java index b969532..d816b90 100644 --- a/src/main/java/org/nuiton/util/version/VersionComparator.java +++ b/src/main/java/org/nuiton/version/VersionComparator.java @@ -1,10 +1,10 @@ -package org.nuiton.util.version; +package org.nuiton.version; /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2014 CodeLutin, Tony Chemit + * Copyright (C) 2016 CodeLutin, Tony Chemit * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as @@ -77,7 +77,7 @@ import java.util.List; * * @author Tony Chemit - chemit@codelutin.com * @see Version - * @since 3.0 + * @since 1.0 */ public class VersionComparator implements Comparator<Version>, Serializable { diff --git a/src/main/java/org/nuiton/util/version/VersionConverter.java b/src/main/java/org/nuiton/version/VersionConverter.java similarity index 96% rename from src/main/java/org/nuiton/util/version/VersionConverter.java rename to src/main/java/org/nuiton/version/VersionConverter.java index 1eb62ee..3d803ec 100644 --- a/src/main/java/org/nuiton/util/version/VersionConverter.java +++ b/src/main/java/org/nuiton/version/VersionConverter.java @@ -1,10 +1,10 @@ -package org.nuiton.util.version; +package org.nuiton.version; /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2014 CodeLutin, Tony Chemit + * Copyright (C) 2016 CodeLutin, Tony Chemit * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as @@ -35,7 +35,7 @@ import org.nuiton.converter.NuitonConverter; * * @author Tony Chemit - chemit@codelutin.com * @see Version - * @since 3.0 + * @since 1.0 */ public class VersionConverter implements NuitonConverter<Version> { diff --git a/src/main/java/org/nuiton/util/version/Versions.java b/src/main/java/org/nuiton/version/Versions.java similarity index 98% rename from src/main/java/org/nuiton/util/version/Versions.java rename to src/main/java/org/nuiton/version/Versions.java index 58bf035..c382cbf 100644 --- a/src/main/java/org/nuiton/util/version/Versions.java +++ b/src/main/java/org/nuiton/version/Versions.java @@ -1,4 +1,4 @@ -package org.nuiton.util.version; +package org.nuiton.version; import com.google.common.base.Preconditions; @@ -7,9 +7,9 @@ import java.util.List; /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2004 - 2014 CodeLutin + * Copyright (C) 2016 CodeLutin, Tony Chemit * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as @@ -33,7 +33,7 @@ import java.util.List; * Created on 8/23/14. * * @author Tony Chemit - chemit@codelutin.com - * @since 3.0-rc-6 + * @since 1.0 */ public class Versions { diff --git a/src/main/resources/META-INF/services/org.apache.commons.beanutils.Converter b/src/main/resources/META-INF/services/org.apache.commons.beanutils.Converter index f2594c8..f00aeef 100644 --- a/src/main/resources/META-INF/services/org.apache.commons.beanutils.Converter +++ b/src/main/resources/META-INF/services/org.apache.commons.beanutils.Converter @@ -1,3 +1,2 @@ -org.nuiton.util.converter.VersionConverter -org.nuiton.util.version.VersionConverter +org.nuiton.version.VersionConverter diff --git a/src/main/resources/META-INF/services/org.nuiton.converter.NuitonConverter b/src/main/resources/META-INF/services/org.nuiton.converter.NuitonConverter index f2594c8..f00aeef 100644 --- a/src/main/resources/META-INF/services/org.nuiton.converter.NuitonConverter +++ b/src/main/resources/META-INF/services/org.nuiton.converter.NuitonConverter @@ -1,3 +1,2 @@ -org.nuiton.util.converter.VersionConverter -org.nuiton.util.version.VersionConverter +org.nuiton.version.VersionConverter diff --git a/src/main/resources/i18n/nuiton-utils_en_GB.properties b/src/main/resources/i18n/nuiton-utils_en_GB.properties deleted file mode 100644 index 3c6b1b6..0000000 --- a/src/main/resources/i18n/nuiton-utils_en_GB.properties +++ /dev/null @@ -1,40 +0,0 @@ -nuitonutil.config.moving.conf=Moving old configuration file from %s to %s -nuitonutil.debug.objectutil.create=Try to create %s with %s -nuitonutil.debug.objectutil.instantiate=Can't instantiate %s with params %s -nuitonutil.debug.objectutil.invoke=Invoke %s with %s -nuitonutil.error.add.url.in.classloader=Can't add url in classloader %1$s for reason %2$s -nuitonutil.error.applicationconfig.save=Can't save config in file %s -nuitonutil.error.cant.instanciate.class=Class %s can't be instanciated with %s -nuitonutil.error.class.with.more.than.one.constructor=Your class %s has more than one constructor -nuitonutil.error.convert.file.to.url=Can't convert %s for reason %s -nuitonutil.error.convertor.noValue=No value specified for converter %s -nuitonutil.error.could.not.addPCL=Could not add the PropertychangeListener %1$s on object %2$s for following reason \: %3$s -nuitonutil.error.could.not.find.MD5=Could not find MD5 algorithm -nuitonutil.error.could.not.removePCL=Could remove the PropertychangeListener %1$s from object %2$s for following reason \: %3$s -nuitonutil.error.get.url.from.zip=Error while reading %s \: %s -nuitonutil.error.no.convertor=no convertor found for type %2$s and objet '%1$s' -nuitonutil.error.not.an.enum=The type %1$s ins not an Enum type -nuitonutil.error.null.parameter=The parameter %1$s is null\! -nuitonutil.error.resource.not.found=Can't find resource \: %s -nuitonutil.error.unfound.assignable.argument=Can't find assignable argument for %s in %s -nuitonutil.error.unfound.month=could not found month from '%s', use default month '%s' -nuitonutil.error.unknown.url.type=could not treate unknown type of url %1$s -nuitonutil.error.url.convertor=a problem occurs while converting value '%s' with url convertor %s for reason %s -nuitonutil.error.version.convertor=Could not convert version %1$s with converter %2$s for reason \: %3$s -nuitonutil.error.version.pattern=Pattern of version not found for %1$s -nuitonutil.fileCompletion.cancel=.. to cancel or return to parent directory -nuitonutil.fileCompletion.enter=Enter to display file list, or to complete path -nuitonutil.fileCompletion.exit=Enter "\!q" to exit -nuitonutil.fileCompletion.save=Enter "\!s" in the end of the file name to save -nuitonutil.month.april=april -nuitonutil.month.august=august -nuitonutil.month.december=december -nuitonutil.month.february=february -nuitonutil.month.january=january -nuitonutil.month.july=july -nuitonutil.month.june=june -nuitonutil.month.march=march -nuitonutil.month.may=may -nuitonutil.month.november=november -nuitonutil.month.october=october -nuitonutil.month.september=september diff --git a/src/main/resources/i18n/nuiton-utils_es_ES.properties b/src/main/resources/i18n/nuiton-utils_es_ES.properties deleted file mode 100644 index fd985cb..0000000 --- a/src/main/resources/i18n/nuiton-utils_es_ES.properties +++ /dev/null @@ -1,40 +0,0 @@ -nuitonutil.config.moving.conf=Colocar el fichero de configuración de %s hacia %s -nuitonutil.debug.objectutil.create=Probar la creación %s con %s -nuitonutil.debug.objectutil.instantiate=No se puede instanciar %s con los parámetros %s -nuitonutil.debug.objectutil.invoke=Invocación %s con %s -nuitonutil.error.add.url.in.classloader=Imposible adjuntar la URL en el classloader %s por la siguiente razón \: %s -nuitonutil.error.applicationconfig.save=Imposible guardar le fichero de configuración en %s -nuitonutil.error.cant.instanciate.class= -nuitonutil.error.class.with.more.than.one.constructor= -nuitonutil.error.convert.file.to.url=El archivo '%1$s' no puede ser convertido en URL debido a \: %2$S -nuitonutil.error.convertor.noValue=Cualquier valor a convertir por el convertidor %s -nuitonutil.error.could.not.addPCL=No se puede adjuntar la PropertychangeListener %1$s en el objeto %2$s debido a \: %3$s -nuitonutil.error.could.not.find.MD5=No se ha encontrado el algoritmo MD5\! -nuitonutil.error.could.not.removePCL=No se ha eliminado la PropertychangeListener %1$s en el objeto %2$s debido a \: %3$s -nuitonutil.error.get.url.from.zip=Eror al leer el archivo comprimido %1$s \: %2$s -nuitonutil.error.no.convertor=Ningún convertidor encontrado para el tipo %2$s y el objeto '%1$s' -nuitonutil.error.not.an.enum=El tipo %1$s no es una enumeración de java -nuitonutil.error.null.parameter=El parámetro '%1$s' es nulo\! -nuitonutil.error.resource.not.found=Imposible encontrar el recurso \: %s -nuitonutil.error.unfound.assignable.argument= -nuitonutil.error.unfound.month=No se encuentra el mes a partir de '%s', use el mes por defecto '%s' -nuitonutil.error.unknown.url.type=No se puede tratar el tipo desconocido de URL %1$s -nuitonutil.error.url.convertor=Problema encontrado en la converción de la URL de '%s' con el convertidor %s debido a \: %s -nuitonutil.error.version.convertor=No se puede convertir el valor %%1$s con el conversor %2$s debido a \: %3$s -nuitonutil.error.version.pattern=Patrón de versión no conocido por %1$s -nuitonutil.fileCompletion.cancel=.. para anular o regresar al directorio anterior -nuitonutil.fileCompletion.enter=Introducir para mostar la lista de archivos, o completar la ruta -nuitonutil.fileCompletion.exit=Pulsar "\!q" para salir -nuitonutil.fileCompletion.save=Pulsar "\!s" al final del nombre de archivo para guardar -nuitonutil.month.april=abril -nuitonutil.month.august=agosto -nuitonutil.month.december=diciembre -nuitonutil.month.february=febrero -nuitonutil.month.january=enero -nuitonutil.month.july=julio -nuitonutil.month.june=junio -nuitonutil.month.march=marzo -nuitonutil.month.may=mayo -nuitonutil.month.november=noviembre -nuitonutil.month.october=octubre -nuitonutil.month.september=septiembre diff --git a/src/main/resources/i18n/nuiton-utils_fr_FR.properties b/src/main/resources/i18n/nuiton-utils_fr_FR.properties deleted file mode 100644 index 82314ed..0000000 --- a/src/main/resources/i18n/nuiton-utils_fr_FR.properties +++ /dev/null @@ -1,40 +0,0 @@ -nuitonutil.config.moving.conf=Déplacement du fichier de configuration depuis %s vers %s -nuitonutil.debug.objectutil.create=Essaye de créer %s avec %s -nuitonutil.debug.objectutil.instantiate=Ne peut pas instancier %s avec les paramêtres %s -nuitonutil.debug.objectutil.invoke=Invocation de %s avec %s -nuitonutil.error.add.url.in.classloader=Impossible d'ajouter une url dans le classloader %s pour la raison \: %s -nuitonutil.error.applicationconfig.save=Impossible de sauvegarder le fichier de configuration dans %s -nuitonutil.error.cant.instanciate.class=La Classe %s n'a pas pu être instanciée avec %s -nuitonutil.error.class.with.more.than.one.constructor=Votre classe %s a plus d'un constructeur -nuitonutil.error.convert.file.to.url=Le fichier '%1$s' n'a pas pu être converti en URL pour la raison suivante \: %2$S -nuitonutil.error.convertor.noValue=Aucune valeur à convertir pour le convertisseur %s -nuitonutil.error.could.not.addPCL=N'a pas pu ajouté le PropertychangeListener %1$s sur l'objet %2$s pour la raison suivante \: %3$s -nuitonutil.error.could.not.find.MD5=L'algorithme MD5 n'a pas été trouvé\! -nuitonutil.error.could.not.removePCL=N'a pas pu enlevé le PropertychangeListener %1$s sur l'objet %2$s pour la raison suivante \: %3$s -nuitonutil.error.get.url.from.zip=Erreur lors de la lecture du fichier compressé %1$s \: %2$s -nuitonutil.error.no.convertor=Aucun convertisseur trouvé pour le type %2$s et l''objet '%1$s' -nuitonutil.error.not.an.enum=Le type %1$s n'est pas une enumeration java -nuitonutil.error.null.parameter=Le paramètre '%1$s' est null\! -nuitonutil.error.resource.not.found=Impossible de trouver la ressource \: %s -nuitonutil.error.unfound.assignable.argument=N'a pas pu trouver un argument assignable pour %s dans %s -nuitonutil.error.unfound.month=n'a pas pu trouvé le mois à partir de '%s', utilise le mois par défaut '%s' -nuitonutil.error.unknown.url.type=could not treate unknown type of url %1$s -nuitonutil.error.url.convertor=Un problème est apparu lors de la convertion en url de '%s' avec le convertisseur %s pour la raison suivante \: %s -nuitonutil.error.version.convertor=N'a pas pu convertir la valeur %1$s avec le converter %2$s pour la raison suivante \: %3$s -nuitonutil.error.version.pattern=Pattern de version non connu pour %1$s -nuitonutil.fileCompletion.cancel=.. pour annuler ou pour revenir au repertoire précédent -nuitonutil.fileCompletion.enter=Entrer pour afficher la liste des fichiers, ou pour compléter le chemin -nuitonutil.fileCompletion.exit=Saisir "\!q" pour quitter -nuitonutil.fileCompletion.save=Saisir "\!s" a la fin du nom de fichier pour l'enregistrer -nuitonutil.month.april=avril -nuitonutil.month.august=août -nuitonutil.month.december=décembre -nuitonutil.month.february=février -nuitonutil.month.january=janvier -nuitonutil.month.july=juillet -nuitonutil.month.june=juin -nuitonutil.month.march=mars -nuitonutil.month.may=mai -nuitonutil.month.november=novembre -nuitonutil.month.october=octobre -nuitonutil.month.september=septembre diff --git a/src/site/apt/index.apt b/src/site/apt/index.apt index badb23e..ff6f9e2 100644 --- a/src/site/apt/index.apt +++ b/src/site/apt/index.apt @@ -1,8 +1,8 @@ ~~~ ~~ #%L -~~ Nuiton Utils +~~ Nuiton Version ~~ %% -~~ Copyright (C) 2004 - 2010 CodeLutin +~~ Copyright (C) 2016 CodeLutin ~~ %% ~~ This program is free software: you can redistribute it and/or modify ~~ it under the terms of the GNU Lesser General Public License as @@ -20,175 +20,15 @@ ~~ #L% ~~~ ---- - Nuiton utils + Nuiton Version ---- ---- - 2009-08-23 + 2016-01-10 ---- Présentation - Ensemble de projets utilitaires. + Ensemble de classes autour de la notion de version. -Librairie Util - - Librairie regroupant les utilitaires classiques sur les fichiers, les tableaux, - les collections, les maps, les chaînes de caractères, ... - - * {{{./apidocs/org/nuiton/util/ArrayUtil.html}ArrayUtil}} - - * {{{./apidocs/org/nuiton/util/ClassLoaderUtil.html}ClassLoaderUtil}} - - * {{{./apidocs/org/nuiton/util/CollectionUtil.html}CollectionUtil}} - - * {{{./apidocs/org/nuiton/util/DateUtil.html}DateUtil}} - - * {{{./apidocs/org/nuiton/util/ExceptionUtil.html}ExceptionUtil}} - - * {{{./apidocs/org/nuiton/util/FileUtil.html}FileUtil}} - - * {{{./apidocs/org/nuiton/util/GZUtil.html}GZUtil}} - - * {{{./apidocs/org/nuiton/util/ObjectUtil.html}ObjectUtil}} - - * {{{./apidocs/org/nuiton/util/ReflectUtil.html}ReflectUtil}} - - * {{{./apidocs/org/nuiton/util/StringUtil.html}StringUtil}} - - * {{{./apidocs/org/nuiton/util/ZipUtil.html}ZipUtil}} - -Autres Collection - - * {{{./apidocs/org/nuiton/util/BoundedList.html}BoundedList}} : - permet de définir des bornes min et max aux éléments contenu dans la liste. - - * {{{./apidocs/org/nuiton/util/CategorisedListenerSet.html}CategorisedListenerSet}} : - permet de ranger des listeners en fonction d'une clé (catégorie). Les - catégories sont hiérarchiques, les évènements seront donc transmis en - cascade. - - * {{{./apidocs/org/nuiton/util/ListenerSet.html}ListenerSet}} : - permet d'enregistrer des listeners sans doublon et de facilement lancer des - évènements sur l'ensemble de ces listeners. - - * {{{./apidocs/org/nuiton/util/HashList.html}HashList}} : - une liste indexé sans doublon. - - * {{{./apidocs/org/nuiton/util/RecursiveProperties.html}RecursiveProperties}} : - permet d'injecter des valeurs de propriétés dans une autre. - - * {{{./apidocs/org/nuiton/util/SortedProperties.html}SortedProperties}} : - Properties itérant lexicographiquement sur les clés. - - * {{{./apidocs/org/nuiton/util/TransformedList.html}TransformedList}} : - permet d'avoir un état de stockage différent de l'état de l'objet retourné - ou ajouté. (Ex : stockage du null sous forme de String) - -Profiling - - * {{{./apidocs/org/nuiton/util/CallAnalyze.html}CallAnalyze}} : - trace les appels de méthodes par Thread (temps + mémoire utilisée). - - * {{{./apidocs/org/nuiton/util/TimeLog.html}TimeLog}} : - affiche un message suivant un certain seuil de temps d'exécution. Elle - s'appuie sur commons-logging pour afficher ces messages. - -Beans - - * TODO Doc - -Converter - - * TODO Doc - -Pagination - - * TODO Doc - -Rmi - - * TODO Doc - -Version - - * TODO Doc - -Autres - - * {{{./apidocs/org/nuiton/util/Resource.html}Resource}} : - permet de retrouver des fichiers dans le classpath de l'application ou en - cas d'échec, sur le système de fichier. - - * Checksum : deux classes sont disponibles pour faire du hash MD5 sur des flux - (MD5InputStream et MD5OutputStream), pour des chaînes vous pouvez utiliser - directement les méthodes dans StringUtil (encodeMD5 et encodeSHA1). - - * {{{./apidocs/org/nuiton/util/version/Version.html}Version}} : - représente un numéro de version d'une application, on peut y extraire ses - constituantes ainsi que comparer différentes versions. - - * {{{./apidocs/org/nuiton/util/PeriodDates.html}PeriodDates}} : - représente une période entre deux dates. Il contient plusieurs méthodes - utiles pour retrouver les mois constituant la période ou pour faire des - comparaison. - -Librairie Nuiton-decorator - - <<L'API decorator a été déplacé en version 2.7 vers http://doc.nuiton.org/nuiton-decorator>>. - - <<Le module sera supprimé en version 3.0.>> - - Cette librairie propose une Api de décorator simple. - -Librairie Nuiton-validator - - <<Ce module a été déplacé en version 2.7 vers http://doc.nuiton.org/nuiton-validator>>. - - <<Le module sera supprimé en version 3.0.>> - - Cette librairie propose une Api de validation plus complète que la JSR-303, - permettant nottament de préciser des scopes (info, erreur, warning, ...) - - {{{./nuiton-validator}Plus d'infos}} - -Librairie Nuiton-csv - - <<Ce module a été déplacé en version 2.7 vers http://doc.nuiton.org/nuiton-csv>>. - - <<Le module sera supprimé en version 3.0.>> - - Cette librairie propose une Api simple d'import export au format csv. - - {{{./nuiton-csv}Plus d'infos}} - -Librairie Nuiton-config - - <<Ce module a été déplacé en version 2.7 vers http://doc.nuiton.org/nuiton-config>>. - - <<Le module sera supprimé en version 3.0.>> - - Cette librairie propose une Api simple de configuration d'application. - - {{{./nuiton-config}Plus d'infos}} - -Librairie Nuiton-updater - - <<Ce module a été déplacé en version 2.7 vers http://doc.nuiton.org/nuiton-updater>>. - - <<Le module sera supprimé en version 3.0.>> - - Cette librairie propose une Api simple de mise à jour d'application. - - {{{./nuiton-updater}Plus d'infos}} - -Rapports Maven - - <<Ajouté en version 2.4.8>>, ce module permet la génération de rapports - Maven liés aux outils offerts par les librairies de ce projet - (ApplicationConfig,...). - - <<Ce module a été déplacé en version 2.7 vers http://doc.nuiton.org/nuiton-maven-report-plugin>>. - - <<Le module sera supprimé en version 3.0.>> diff --git a/src/site/apt/versions.apt b/src/site/apt/versions.apt deleted file mode 100644 index 4bdd5a4..0000000 --- a/src/site/apt/versions.apt +++ /dev/null @@ -1,34 +0,0 @@ -~~~ -~~ #%L -~~ Nuiton Utils -~~ %% -~~ Copyright (C) 2004 - 2013 CodeLutin -~~ %% -~~ This program is free software: you can redistribute it and/or modify -~~ it under the terms of the GNU Lesser General Public License as -~~ published by the Free Software Foundation, either version 3 of the -~~ License, or (at your option) any later version. -~~ -~~ This program is distributed in the hope that it will be useful, -~~ but WITHOUT ANY WARRANTY; without even the implied warranty of -~~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -~~ GNU General Lesser Public License for more details. -~~ -~~ You should have received a copy of the GNU General Lesser Public -~~ License along with this program. If not, see -~~ <http://www.gnu.org/licenses/lgpl-3.0.html>. -~~ #L% -~~~ - ---- - Nuiton util - ---- - ---- - 2013-07-23 - ---- - -Utilisation de la version 3.0 - - * Suppression des modules csv, config, updater, validator et maven-report-plugin. - * Suppression de l'api decorator - * Introduction nouvelle API de version - * Suppression de l'api converter (utiliser nuiton-converter à la place) diff --git a/src/site/site.xml b/src/site/site.xml index 733c606..f656faa 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -1,9 +1,9 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- #%L - Nuiton Utils + Nuiton Version %% - Copyright (C) 2004 - 2010 CodeLutin + Copyright (C) 2016 CodeLutin %% This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as @@ -51,19 +51,15 @@ <menu name="Utilisateur"> <item name="Accueil" href="index.html"/> - <item name="Note de versions" href="versions.html"/> </menu> <menu ref="reports"/> <footer> <div id='mavenProjectProperties' locale='fr' - platform='${project.platform}' projectId='${project.projectId}' version='${project.siteDeployClassifier}' - sourcesType='${project.siteSourcesType}' - scmUrl='${project.scm.connection}' - editorUrl='${project.scmwebeditorUrl}'/> + sourcesType='apt'/> </footer> </body> diff --git a/src/test/java/org/nuiton/util/AliasMapTest.java b/src/test/java/org/nuiton/util/AliasMapTest.java deleted file mode 100644 index 4f90e8f..0000000 --- a/src/test/java/org/nuiton/util/AliasMapTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.nuiton.util; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Test; - -import java.util.Arrays; -import java.util.Collection; - -/** - * @author Benjamin Poussin - poussin@codelutin.com - */ -public class AliasMapTest { - - /** - * Logger. - */ - static private Log log = LogFactory.getLog(AliasMapTest.class); - - protected Object[] toArray(Collection c) { - Object[] result = c.toArray(); - Arrays.sort(result); - return result; - } - - @Test - public void testAlias() { - AliasMap<String, String, String> map = new AliasMap<String, String, String>(); - map.put("a", "A", "à", "â", "ä", "commun"); - map.put("b", "B"); - map.put("e", "E", "é", "è", "ê", "ë", "commun"); - map.put("ebis", "EBIS", "é", "è", "commun"); - - Assert.assertEquals("A", map.get("a")); - Assert.assertArrayEquals(new String[]{"commun", "à", "â", "ä"}, toArray(map.getAlias("a"))); - Assert.assertArrayEquals(new String[]{"a"}, toArray(map.getKeyAlias("à"))); - Assert.assertArrayEquals(new String[]{"e", "ebis"}, toArray(map.getKeyAlias("é"))); - Assert.assertArrayEquals(new String[]{"E", "EBIS"}, toArray(map.getValueAlias("é", "è"))); - Assert.assertArrayEquals(new String[]{}, toArray(map.getValueAlias("é", "è", "à"))); - - String v = map.remove("e"); - Assert.assertEquals("E", v); - Assert.assertArrayEquals(new String[]{}, toArray(map.getAlias("e"))); - Assert.assertArrayEquals(new String[]{"ebis"}, toArray(map.getKeyAlias("é"))); - - Collection<String> cr = map.removeValue("à", "é"); - Assert.assertArrayEquals(new String[]{}, toArray(cr)); - - cr = map.removeValue("commun"); - Assert.assertArrayEquals(new String[]{"A", "EBIS"}, toArray(cr)); - } - -} diff --git a/src/test/java/org/nuiton/util/CallAnalyseTest.java b/src/test/java/org/nuiton/util/CallAnalyseTest.java deleted file mode 100644 index 983e25a..0000000 --- a/src/test/java/org/nuiton/util/CallAnalyseTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import junit.framework.TestCase; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created: 25 août 2005 21:03:50 CEST - * - * @author Benjamin Poussin - poussin@codelutin.com - */ -public class CallAnalyseTest extends TestCase { // CallAnalyseTest - - /** - * Logger. - */ - static private Log log = LogFactory.getLog(CallAnalyseTest.class); - - protected List<List<?>> memoryConsume = new ArrayList<List<?>>(); - - public void testCall() throws Exception { - CallAnalyse.activate(); - for (int i = 0; i < 10; i++) { - eatMemory(); - freeMemory(); - } - - assertEquals(10, CallAnalyse.getThreadStatistics().get("eatMemory").getCalls()); - assertEquals(10, CallAnalyse.getThreadStatistics().get("freeMemory").getCalls()); - - log.debug(CallAnalyse.getThreadStatistics()); - } - - protected void eatMemory() { - CallAnalyse.enter("eatMemory"); - try { - for (int i = 0; i < 100; i++) { - memoryConsume.add(new ArrayList(100)); - } - } catch (Exception eee) { - // do nothing - } finally { - CallAnalyse.exit("eatMemory"); - } - } - - protected void freeMemory() { - CallAnalyse.enter("freeMemory"); - try { - memoryConsume.clear(); - } catch (Exception eee) { - // do nothing - } finally { - CallAnalyse.exit("freeMemory"); - } - } - -} // CallAnalyseTest - diff --git a/src/test/java/org/nuiton/util/CardinalityHelperTest.java b/src/test/java/org/nuiton/util/CardinalityHelperTest.java deleted file mode 100644 index 832727a..0000000 --- a/src/test/java/org/nuiton/util/CardinalityHelperTest.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import junit.framework.TestCase; - -/** - * CardinalityHelper Tester. - * - * @author Tony Chemit - chemit@codelutin.com - * @version 1.0 - * @since <pre>12/17/2007</pre> - */ -public class CardinalityHelperTest extends TestCase { - - String txt; - Object[] result; - StringBuilder sb; - - public void testNoMaxParsing() { - txt = "*"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "", 0, -1); - - txt = "yo*"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo", 0, -1); - - txt = "yo+"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo", 1, -1); - - txt = "yo *"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo", 0, -1); - - txt = "yo +"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo", 1, -1); - } - - public void testExactlyParsing() { - txt = "{5}"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "", 5, 5); - - txt = "yo{1}"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo", 1, 1); - - txt = "yo {2}"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo", 2, 2); - - txt = "yo {12}"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo", 12, 12); - } - - public void testBoundedParsing() { - txt = "{1,2}"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "", 1, 2); - - txt = "{2,*}"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "", 2, -1); - - txt = "yo{1,2}"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo", 1, 2); - - txt = "yo {10,20}"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo", 10, 20); - - txt = "yo {10,*}"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo", 10, -1); - } - - public void testDefaultParsing() { - txt = "yo {a}"; - result = CardinalityHelper.parseCardinalite(txt, false); - assertCardinalite(result, "yo {a}", 0, 1); - - txt = "yo {a}"; - result = CardinalityHelper.parseCardinalite(txt, true); - assertCardinalite(result, "yo {a}", 1, 1); - } - - public void testPrintCardinality() { - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,1,true,"<",">","[","]"); - assertPrint(sb,"[yo]"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,5,false,"<",">","[","]"); - assertPrint(sb,"[yo]{0,5}"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,-1,false,"<",">","[","]"); - assertPrint(sb,"[yo]*"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,1,true,"<",">","",""); - assertPrint(sb,"yo{0,1}"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,1,false,"<",">","",""); - assertPrint(sb,"yo"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,5,false,"<",">","",""); - assertPrint(sb,"yo{0,5}"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,-1,false,"<",">","",""); - assertPrint(sb,"yo*"); - - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,1,false,"<",">","[","]"); - assertPrint(sb,"<yo>"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",5,5,true,"<",">","[","]"); - assertPrint(sb,"<yo>{5}"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,5,true,"<",">","[","]"); - assertPrint(sb,"<yo>{1,5}"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,-1,true,"<",">","[","]"); - assertPrint(sb,"<yo>+"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",3,-1,true,"<",">","[","]"); - assertPrint(sb,"<yo>{3,*}"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,1,false,"","","[","]"); - assertPrint(sb,"yo{1}"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,1,true,"","","[","]"); - assertPrint(sb,"yo"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",5,5,true,"","","[","]"); - assertPrint(sb,"yo{5}"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,5,true,"","","[","]"); - assertPrint(sb,"yo{1,5}"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,-1,true,"","","[","]"); - assertPrint(sb,"yo+"); - - CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",3,-1,true,"","","[","]"); - assertPrint(sb,"yo{3,*}"); - } - - private void assertPrint(StringBuilder sb, String expectedResult) { - assertEquals(expectedResult,sb.toString()); - } - - private void assertCardinalite(Object[] result, String key, Integer min, Integer max) { - assertEquals(key, (String) result[0]); - assertEquals(min, result[1]); - assertEquals(max, result[2]); - } - -} diff --git a/src/test/java/org/nuiton/util/CategorisedListenerSetTest.java b/src/test/java/org/nuiton/util/CategorisedListenerSetTest.java deleted file mode 100644 index bf2e73b..0000000 --- a/src/test/java/org/nuiton/util/CategorisedListenerSetTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import junit.framework.TestCase; - -/** - * Created: 3 janv. 2006 23:27:42 - * - * @author Benjamin Poussin - poussin@codelutin.com - */ -public class CategorisedListenerSetTest extends TestCase { - - /* - * Test method for - * 'org.nuiton.util.CategorisedListenerSet.getAllListeners(Object)' - */ - public void testGetAllListeners() { - - { - CategorisedListenerSet<Object> cls = new CategorisedListenerSet<Object>(); - - String[] ls = new String[]{"Double", "Long", "Number", "Object", - "LoggingException", "Throwable"}; - - cls.add(Double.class, ls[0]); - cls.add(Long.class, ls[1]); - cls.add(Number.class, ls[2]); - cls.add(Object.class, ls[3]); - - assertEquals(3, cls.getAllListeners(Double.class).size()); - assertEquals(3, cls.getAllListeners(Long.class).size()); - assertEquals(2, cls.getAllListeners(Number.class).size()); - assertEquals(1, cls.getAllListeners(Object.class).size()); - - cls.addCategory(LoggingException.class, Number.class); - - cls.add(LoggingException.class, ls[4]); - cls.add(Throwable.class, ls[5]); - - assertEquals(5, cls.getAllListeners(Double.class).size()); - assertEquals(5, cls.getAllListeners(Long.class).size()); - assertEquals(4, cls.getAllListeners(Number.class).size()); - assertEquals(1, cls.getAllListeners(Object.class).size()); - - assertEquals(3, cls.getAllListeners(LoggingException.class).size()); - assertEquals(2, cls.getAllListeners(Throwable.class).size()); - - } - { - CategorisedListenerSet<Object> cls = new CategorisedListenerSet<Object>(false); - - String[] ls = new String[]{"Double", "Long", "Number", "Object", - "LoggingException", "Throwable"}; - - cls.add(Double.class, ls[0]); - cls.add(Long.class, ls[1]); - cls.add(Number.class, ls[2]); - cls.add(Object.class, ls[3]); - - assertEquals(1, cls.getAllListeners(Double.class).size()); - assertEquals(1, cls.getAllListeners(Long.class).size()); - assertEquals(1, cls.getAllListeners(Number.class).size()); - assertEquals(1, cls.getAllListeners(Object.class).size()); - - cls.addCategory(LoggingException.class, Number.class); - - cls.add(LoggingException.class, ls[4]); - cls.add(Throwable.class, ls[5]); - - assertEquals(1, cls.getAllListeners(Double.class).size()); - assertEquals(1, cls.getAllListeners(Long.class).size()); - assertEquals(2, cls.getAllListeners(Number.class).size()); - assertEquals(1, cls.getAllListeners(Object.class).size()); - - assertEquals(1, cls.getAllListeners(LoggingException.class).size()); - assertEquals(1, cls.getAllListeners(Throwable.class).size()); - } - } - -} diff --git a/src/test/java/org/nuiton/util/CollectionUtilTest.java b/src/test/java/org/nuiton/util/CollectionUtilTest.java deleted file mode 100644 index 1c062d8..0000000 --- a/src/test/java/org/nuiton/util/CollectionUtilTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import junit.framework.TestCase; - -import java.util.ArrayList; -import java.util.List; - -/** - * CollectionUtil Tester. - * - * @author Tony Chemit - chemit@codelutin.com - * @version 1.0 - * @since <pre>02/04/2008</pre> - */ -public class CollectionUtilTest extends TestCase { - public CollectionUtilTest(String name) { - super(name); - } - - public void testToGenericList() throws Exception { - List<String> list = new ArrayList<String>(); - list.add("a"); - list.add("b"); - list.add("c"); - - assertEquals(CollectionUtil.toGenericList(list, String.class), list); - assertEquals(CollectionUtil.toGenericList(list, Object.class), list); - - try { - CollectionUtil.toGenericList(list, Integer.class); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - - } - -} diff --git a/src/test/java/org/nuiton/util/DateUtilTest.java b/src/test/java/org/nuiton/util/DateUtilTest.java deleted file mode 100644 index 12bc98e..0000000 --- a/src/test/java/org/nuiton/util/DateUtilTest.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.lang3.time.DateUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Test; - -import java.sql.Timestamp; -import java.text.ParseException; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -/** - * - * @author fdesbois - * @since 1.4.1 - */ -public class DateUtilTest { - - /** Logger */ - private static final Log log = LogFactory.getLog(DateUtilTest.class); - - /** - * Test of createDate method, of class DateUtil. - */ - @Test - public void testCreateDate() throws ParseException { - log.info("createDate"); - - Date newDate = DateUtil.createDate(3, 3, 2009); - Calendar calendar = DateUtil.getDefaultCalendar(newDate); - - Assert.assertEquals(3, calendar.get(Calendar.DAY_OF_MONTH)); - Assert.assertEquals(2, calendar.get(Calendar.MONTH)); - Assert.assertEquals(2009, calendar.get(Calendar.YEAR)); - - Assert.assertEquals(0, calendar.get(Calendar.HOUR)); - Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); - Assert.assertEquals(0, calendar.get(Calendar.SECOND)); - Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); - } - - /** - * Non regression test for bug #1157 - * @since 1.5.2 - */ - @Test - public void testCreateDateIsDeterministic() throws ParseException { - Date createdDate = DateUtil.createDate(0, 33, 18, 22, 12, 2010); - Date parsedDate = DateUtil.parseDate("22/12/2010 18:33", "dd/MM/yyyy HH:mm"); - log.info(createdDate.getTime() + " ?= " + parsedDate.getTime()); - Assert.assertEquals(createdDate, parsedDate); - } - - /** - * Test of setLastDayOfMonth method, of class DateUtil. - */ - @Test - public void testSetFistLastDayOfMonth() { - Date february = DateUtil.createDate(22, 2, 2011); - Date firstDayOfFebruary = DateUtil.setFirstDayOfMonth(february); - Date lastDayOfFebruary = DateUtil.setLastDayOfMonth(february); - - Date day1 = DateUtil.createDate(0, 0, 2, 1, 2, 2011); - Date day2 = DateUtil.createDate(67, 45, 23, 28, 2, 2011); - - if (log.isDebugEnabled()) { - log.debug("first day of february = " + firstDayOfFebruary + ", last day of february = " - + lastDayOfFebruary + ", day1 = " + day1 + ", day 2 = " + day2); - } - - Assert.assertTrue(DateUtil.between(day1, firstDayOfFebruary, lastDayOfFebruary)); - - // In this case, day2'hour is after lastDayOfMonth - Assert.assertFalse(DateUtil.between(day2, firstDayOfFebruary, lastDayOfFebruary)); - } - /** - * Test of setLastDayOfMonth method, of class DateUtil. - */ - @Test - public void testSetFistLastDayOfYear() { - Date february = DateUtil.createDate(22, 2, 2011); - Date firstDayOf2011 = DateUtil.setFirstDayOfYear(february); - Date lastDayOf2011 = DateUtil.setLastDayOfYear(february); - - Date day1 = DateUtil.createDate(0, 0, 2, 1, 2, 2011); - Date day2 = DateUtil.createDate(67, 45, 23, 28, 2, 2012); - - if (log.isDebugEnabled()) { - log.debug("first day of february = " + firstDayOf2011 + ", last day of february = " - + lastDayOf2011 + ", day1 = " + day1 + ", day 2 = " + day2); - } - - Assert.assertTrue(DateUtil.between(day1, firstDayOf2011, lastDayOf2011)); - Assert.assertFalse(DateUtil.between(day2, firstDayOf2011, lastDayOf2011)); - } - - /** - * Test of between method, of class DateUtil. - */ - @Test - public void testBetween() { - log.info("between"); - - Date middle = DateUtil.createDate(3, 3, 2009); - - // middle = begin, and end = null - Date begin = DateUtil.createDate(3, 3, 2009); - Date end = null; - - boolean result = DateUtil.between(middle, begin, end); - Assert.assertTrue(result); - - // middle between the period : march 2009 - PeriodDates period = new PeriodDates(begin, begin); - period.initDayOfMonthExtremities(); - - log.info("period : " + period); - - result = DateUtil.between(middle, period.getFromDate(), period.getThruDate()); - Assert.assertTrue(result); - - // middle = period begin - middle = DateUtil.setFirstDayOfMonth(middle); - result = DateUtil.between(middle, period.getFromDate(), period.getThruDate()); - Assert.assertTrue(result); - - // test with different implementation of Date - Timestamp middle2 = new Timestamp(middle.getTime()); - result = DateUtil.between(middle2, period.getFromDate(), period.getThruDate()); - Assert.assertTrue(result); - - // middle before begin - middle = DateUtil.createDate(2, 2, 2009); - result = DateUtil.between(middle, period.getFromDate(), period.getThruDate()); - Assert.assertFalse(result); - } - - @Test - public void testGetDifferenceInSeconds() { - log.info("getDifferenceInSecondes"); - - Date beginDate = DateUtil.createDate(30, 10, 0, 3, 2, 2009); - Date endDate = DateUtil.createDate(0, 11, 0, 3, 2, 2009); - - int result = DateUtil.getDifferenceInSeconds(beginDate, endDate); - Assert.assertEquals(30, result); - - beginDate = DateUtil.createDate(9, 28, 0, 28, 1, 2009); - endDate = DateUtil.createDate(50, 30, 0, 28, 1, 2009); - - result = DateUtil.getDifferenceInSeconds(beginDate, endDate); - Assert.assertEquals(161, result); - } - - @Test - public void testGetDifferenceInMinutes() { - log.info("getDifferenceInMinutes"); - - Date beginDate = DateUtil.createDate(30, 10, 0, 3, 2, 2009); - Date endDate = DateUtil.createDate(0, 12, 0, 3, 2, 2009); - - int result = DateUtil.getDifferenceInMinutes(beginDate, endDate); - Assert.assertEquals(1, result); - - beginDate = DateUtil.createDate(9, 28, 0, 28, 1, 2009); - endDate = DateUtil.createDate(50, 30, 0, 28, 1, 2009); - - result = DateUtil.getDifferenceInMinutes(beginDate, endDate); - Assert.assertEquals(2, result); - } - - @Test - public void testGetDifferenceInHours() { - log.info("getDifferenceInHours"); - - Date beginDate = DateUtil.createDate(30, 10, 0, 3, 2, 2009); - Date endDate = DateUtil.createDate(0, 11, 0, 4, 2, 2009); - - int result = DateUtil.getDifferenceInHours(beginDate, endDate); - Assert.assertEquals(24, result); - - beginDate = DateUtil.createDate(9, 28, 0, 28, 1, 2009); - endDate = DateUtil.createDate(50, 30, 8, 28, 1, 2009); - - result = DateUtil.getDifferenceInHours(beginDate, endDate); - Assert.assertEquals(8, result); - } - - @Test - public void testGetDifferenceInDays() { - log.info("getDifferenceInDays"); - - Date beginDate = DateUtil.createDate(3, 2, 2009); - Date endDate = DateUtil.createDate(8, 2, 2009); - - int result = DateUtil.getDifferenceInDays(beginDate, endDate); - Assert.assertEquals(5, result); - - beginDate = DateUtil.createDate(28, 1, 2009); - endDate = DateUtil.createDate(8, 2, 2009); - - result = DateUtil.getDifferenceInDays(beginDate, endDate); - Assert.assertEquals(11, result); - } - - @Test - public void testGetDifferenceInMonths() { - log.info("getDifferenceInMonths"); - - Date beginDate = DateUtil.createDate(3, 2, 2009); - Date endDate = DateUtil.createDate(8, 8, 2010); - - int result = DateUtil.getDifferenceInMonths(beginDate, endDate); - log.info("result1 : " + result); - Assert.assertEquals(19, result); - - beginDate = DateUtil.createDate(1, 1, 2009); - endDate = DateUtil.createDate(28, 2, 2009); - - result = DateUtil.getDifferenceInMonths(beginDate, endDate); - log.info("result2 : " + result); - Assert.assertEquals(2, result); - - beginDate = DateUtil.createDate(31, 1, 2009); - endDate = DateUtil.createDate(1, 2, 2009); - - result = DateUtil.getDifferenceInMonths(beginDate, endDate); - log.info("result3 : " + result); - Assert.assertEquals(1, result); - } - - @Test - public void testGetAge() { - log.info("getAge"); - - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.YEAR, -20); - calendar.add(Calendar.DAY_OF_YEAR, -1); - - int result = DateUtil.getAge(calendar.getTime()); - log.info("result1 : " + result); - Assert.assertEquals(20, result); - - calendar.add(Calendar.DATE, 2); - - result = DateUtil.getAge(calendar.getTime()); - log.info("result2 : " + result); - Assert.assertEquals(19, result); - - calendar.add(Calendar.YEAR, 25); - - result = DateUtil.getAge(calendar.getTime()); - log.info("result3 : " + result); - Assert.assertEquals(0, result); - } - - @Test - public void testGetMonthLibelle() { - log.info("getMonthLibelle"); - - Locale.setDefault(Locale.FRENCH); - String janvier = DateUtil.getMonthLibelle(1); - Assert.assertEquals("janvier", janvier); - - String juli = DateUtil.getMonthLibelle(7, Locale.GERMAN); - Assert.assertEquals("Juli", juli); - } - - /** - * Shows that {@link org.nuiton.util.DateUtil#truncateToDayOfWeek(java.util.Date)} works - * fine and that using commons library for this operation is not possible. - */ - @Test - public void testTruncateToDayOfWeek() { - - Date aDate = DateUtil.createDate(23, 45, 6, 19, 10, 2011); - Date expectedWeek = DateUtil.createDate(17, 10, 2011); - Date actualWeek; - - // show that commons-lang do not support this operation with truncate - try { - actualWeek = DateUtils.truncate(aDate, Calendar.DAY_OF_WEEK); - Assert.assertEquals(expectedWeek, actualWeek); - } catch (IllegalArgumentException e) { - Assert.assertEquals(String.format("The field %d is not supported", Calendar.DAY_OF_WEEK), e.getMessage()); - } - - actualWeek = DateUtil.truncateToDayOfWeek(aDate); - Assert.assertEquals(expectedWeek, actualWeek); - } - - @Test - public void testGetYesterday() { - - //Test normal yesterday - Date aDate = DateUtil.createDate(3,4,5); - Date expectedADate = DateUtil.createDate(2,4,5); - - //Test month change - Date bDate = DateUtil.createDate(1,12,12); - Date expectedBDate = DateUtil.createDate(30,11,12); - - //Test year change - Date cDate = DateUtil.createDate(1,1,12); - Date expectedCDate = DateUtil.createDate(31,12,11); - - //Test possible wrong change - Date dDate = DateUtil.createDate(3,1,12); - Date expectedDDate = DateUtil.createDate(2,1,12); - - - Assert.assertEquals(expectedADate, DateUtil.getYesterday(aDate)); - Assert.assertEquals(expectedBDate, DateUtil.getYesterday(bDate)); - Assert.assertEquals(expectedCDate, DateUtil.getYesterday(cDate)); - Assert.assertEquals(expectedDDate, DateUtil.getYesterday(dDate)); - - } -} diff --git a/src/test/java/org/nuiton/util/DesktopUtilTest.java b/src/test/java/org/nuiton/util/DesktopUtilTest.java deleted file mode 100644 index 02b3a2f..0000000 --- a/src/test/java/org/nuiton/util/DesktopUtilTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -public class DesktopUtilTest { - - // Test ignored because it can fail on continuous integration server or - // headless environment - //@Test - public void testBrowse() throws IOException, URISyntaxException { - DesktopUtil.browse(new URI("http://localhost")); - } -} diff --git a/src/test/java/org/nuiton/util/FileUtilTest.java b/src/test/java/org/nuiton/util/FileUtilTest.java deleted file mode 100644 index 9c2a00a..0000000 --- a/src/test/java/org/nuiton/util/FileUtilTest.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.io.FileUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Map; - -/** - * Created: 22 nov. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * @author Tony Chemit - chemit@codelutin.com - */ -public class FileUtilTest { // FileUtilTest - - public static final long TIMESTAMP = System.nanoTime(); - - @Rule - public final TestName testName = new TestName(); - - protected File parent; - - @Before - public void setUp() throws Exception { - - parent = FileUtil.getTestSpecificDirectory( - getClass(), - testName.getMethodName(), null, TIMESTAMP); - - } - - @Test - public void testFind() throws Exception { - List<File> result = FileUtil.find(new File("."), ".*FileUtil.*", true); - Assert.assertTrue(result.size() != 0); - } - - @Test - public void testBasename() throws Exception { - String result = FileUtil.basename(new File("/tmp/toto.xml"), ".xml"); - Assert.assertEquals("toto", result); - } - - @Test - public void testExtension() throws Exception { - String result = FileUtil.extension(new File("/tmp/toto.xml")); - Assert.assertEquals("xml", result); - result = FileUtil.extension(new File("/tmp/toto.xml"), ".", "o"); - Assert.assertEquals("xml", result); - result = FileUtil.extension(new File("/tmp/toto.xml"), "t", "."); - Assert.assertEquals("o.xml", result); - } - - @Test - public void testCopyRecursively() throws Exception { - File srcDir = FileUtil.createTempDirectory("test-copyRecursively", "", parent); - File destDir1 = FileUtil.createTempDirectory("test-copyRecursively", "", parent); - File destDir2 = FileUtil.createTempDirectory("test-copyRecursively", "", parent); - - new File(srcDir, "toto").createNewFile(); - new File(srcDir, "titi").createNewFile(); - new File(srcDir, "tutu").createNewFile(); - new File(srcDir, "tata").createNewFile(); - File subdir = new File(srcDir, "subdir"); - subdir.mkdirs(); - new File(subdir, "tyty").createNewFile(); - new File(subdir, "titi").createNewFile(); - - FileUtil.copyRecursively(srcDir, destDir1); - FileUtil.copyRecursively(srcDir, destDir2, ".*titi$"); - - // remove created temp dirs : - FileUtils.deleteDirectory(srcDir); - FileUtils.deleteDirectory(destDir1); - FileUtils.deleteDirectory(destDir2); - } - - /** - * Test grep on a single file. - * <p> - * Search for grep() method count. - * - * @throws IOException - */ - @Test - public void testGrepSingleFile() throws IOException { - - // search for - File testUtilFile = FileUtil.find(new File("."), ".*fileUtilData\\.txt", true).get(0); - - List<CharSequence> lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile, "UTF-8"); - - Assert.assertNotNull(lines); - Assert.assertEquals(4, lines.size()); - - // assert result are ordered - Assert.assertTrue(lines.get(0).toString().contains("CharBuffer")); - Assert.assertTrue(lines.get(1).toString().contains("File f,")); - Assert.assertTrue(lines.get(2).toString().contains("rootDirectory")); - Assert.assertTrue(lines.get(3).toString().contains("String searchRegex, String fileRegex, String encoding")); - } - - /** - * Test grep on a multiple files. - * <p> - * Try to find all java file containing "CodeLutin". Can fail if some - * src files are deleted. - * - * @throws IOException - */ - @Test - public void testGrepMultiple() throws IOException { - - File rootDir = new File("src"); - - Map<File, List<CharSequence>> results = FileUtil.grep("CodeLutin", rootDir, ".*\\.java", "UTF-8"); - - Assert.assertTrue("should have more than 50 files, but found : " + - results.size(), results.size() > 50); - - } - - /** - * Test sed method on a single file. - * - * @throws IOException - */ - @Test - public void testSedSingleFile() throws IOException { - //FIXME tchemit 20100924 Do tests in target, not in /tmp please! - - ResourceTest.assumeNotUnderWindows(getClass(), testName); - - // try to not make sed in real src dir ;) - File testDirectory = FileUtil.createTempDirectory("sed", "test"); - FileUtil.copyRecursively(new File("src").getAbsoluteFile(), testDirectory); - File testUtilFile = FileUtil.find(testDirectory, ".*fileUtilData\\.txt", true).get(0); - - List<CharSequence> lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile, "UTF-8"); - Assert.assertEquals(4, lines.size()); - - lines = FileUtil.grep("sedfoo", testUtilFile, "UTF-8"); - Assert.assertNull(lines); - - // real method to test here : sed - FileUtil.sed("grep", "sedfoo", testUtilFile, "UTF-8"); - - lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile, "UTF-8"); - Assert.assertNull(lines); - - lines = FileUtil.grep("sedfoo", testUtilFile, "UTF-8"); - Assert.assertEquals(9, lines.size()); - - // clean - FileUtils.deleteDirectory(testDirectory); - } - - /** - * Test sed on a multiple files. - * <p> - * Try to replace all "CodeLutin" by "nuiton" in all files. Can fail if some - * src files are deleted. - * - * @throws IOException - */ - @Test - public void testSedMultiple() throws IOException { - - //FIXME tchemit 20100924 Do tests in target, not in /tmp please! - - ResourceTest.assumeNotUnderWindows(getClass(), testName); - - // try to not make sed in real src dir ;) - File testDirectory = FileUtil.createTempDirectory("sed", "test"); - FileUtil.copyRecursively(new File("src").getAbsoluteFile(), testDirectory); - - Map<File, List<CharSequence>> results = FileUtil.grep("CodeLutin", testDirectory, ".*\\.java", "UTF-8"); - Assert.assertTrue("should have more than 50 files, but found : " + - results.size(), results.size() > 50); - - FileUtil.sed("CodeLutin", "Nuiton", testDirectory, ".*\\.java", "UTF-8"); - - results = FileUtil.grep("CodeLutin", testDirectory, ".*\\.java", "UTF-8"); - Assert.assertTrue(results.isEmpty()); - - results = FileUtil.grep("Nuiton", testDirectory, ".*\\.java", "UTF-8"); - Assert.assertTrue("should have more than 50 files, but found : " + - results.size(), results.size() > 50); - - - // clean - FileUtils.deleteDirectory(testDirectory); - } - - /** - * Test that sed result which produce shorter file work as well. - * - * @throws IOException - */ - @Test - public void testSedComment() throws IOException { - - ResourceTest.assumeNotUnderWindows(getClass(), testName); - - // try to not make sed in real src dir ;) - File testDirectory = FileUtil.createTempDirectory("sed", "test", parent); - FileUtil.copyRecursively(new File("src").getAbsoluteFile(), testDirectory); - File testUtilFile = FileUtil.find(testDirectory, ".*fileUtilData\\.txt", true).get(0); - - // real method to test here : sed - FileUtil.sed(".*\\*.*", "** skipped **", testUtilFile, "UTF-8"); - - List<CharSequence> lines = FileUtil.grep("/var/tmp/bidulle", testUtilFile, "UTF-8"); - Assert.assertNull(lines); - - // test une presence en debut et fin de fichier - List<CharSequence> lines2 = FileUtil.grep("// FileUtil", testUtilFile, "UTF-8"); - Assert.assertEquals(2, lines2.size()); - - // clean - FileUtils.deleteDirectory(testDirectory); - } - - public void testChangeExtension() throws IOException { - String name = "toto.yo"; - String exepectedName = "toto.ya"; - String newExtension = "ya"; - String actualName = FileUtil.changeExtension(name, newExtension); - - Assert.assertEquals(exepectedName, actualName); - - File file = new File(parent, name); - File expectedFile = new File(parent, exepectedName); - File actualFile = FileUtil.changeExtension(file, newExtension); - Assert.assertEquals(expectedFile, actualFile); - } - - public void testGetRelativeFile() { - File inputDirectory = new File(parent, "in"); - File outputDirectory = new File(parent, "out"); - File file = new File(inputDirectory, "yoyo.to"); - File expectedFile = new File(outputDirectory, file.getName()); - File actualFile = FileUtil.getRelativeFile(inputDirectory, outputDirectory, file); - Assert.assertEquals(expectedFile, actualFile); - - file = new File(inputDirectory, "rep" + File.separator + "yoyo.to"); - expectedFile = new File(outputDirectory, "rep" + File.separator + file.getName()); - actualFile = FileUtil.getRelativeFile(inputDirectory, outputDirectory, file); - Assert.assertEquals(expectedFile, actualFile); - } - - @Test - public void testGetFileFromPaths() { - File actual = FileUtil.getFileFromPaths(parent, "target", "surefire-workdir", "FileUtil"); - File expected = new File(parent, "target" + File.separator + "surefire-workdir" + File.separator + "FileUtil"); - Assert.assertEquals(expected, actual); - } - - @Test - public void testGetFileFromFQN() { - File actual = FileUtil.getFileFromFQN(parent, "target.surefire-workdir.FileUtil"); - File expected = new File(parent, "target" + File.separator + "surefire-workdir" + File.separator + "FileUtil"); - Assert.assertEquals(expected, actual); - } - -} // FileUtilTest diff --git a/src/test/java/org/nuiton/util/LRUMapMultiKeyTest.java b/src/test/java/org/nuiton/util/LRUMapMultiKeyTest.java deleted file mode 100644 index 361518f..0000000 --- a/src/test/java/org/nuiton/util/LRUMapMultiKeyTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import junit.framework.TestCase; - -import java.util.List; - -/** - * Created: 23 mai 2006 04:57:50 - * - * @author Benjamin Poussin - poussin@codelutin.com - */ -public class LRUMapMultiKeyTest extends TestCase { - - - /* - * Test method for 'org.nuiton.util.LRUMapMultiKey.clear()' - */ - public void testClear() { - System.out.println("testClear"); - LRUMapMultiKey map = new LRUMapMultiKey(10); - LRUMapMultiKey.Key key1 = map.createKey("testClear", "toto", "tyty", "tutu"); - LRUMapMultiKey.Key key2 = map.createKey("toto", "titi", "tutu"); - LRUMapMultiKey.Key key3 = map.createKey("toto", "titi", "tata"); - - map.put(key1, "value"); - map.put(key2, "value"); - map.put(key3, "value"); - - map.clear(); - - assertEquals(0, map.size()); - assertEquals(0, map.keys.size()); - } - - /* - * Test method for 'java.util.WeakHashMap.get(Object)' - */ - public void testGet() throws Exception { - System.out.println("testGet"); - LRUMapMultiKey map = new LRUMapMultiKey(1); - - LRUMapMultiKey.Key key1 = map.createKey("toto", "titi", "tutu"); - map.put(key1, "value1"); - - assertEquals("value1", map.get(map.createKey("toto", "titi", "tutu"))); - - - LRUMapMultiKey.Key key2 = map.createKey("tyty"); - map.put(key2, "value2"); - - assertEquals(null, map.get(key1)); - assertEquals("value2", map.get(key2)); - - assertEquals(1, map.size()); - assertEquals(1, map.keys.size()); - } - - /* - * Test method for 'java.util.WeakHashMap.remove(Object)' - */ - public void testRemoveObject() { - System.out.println("testRemoveObject"); - LRUMapMultiKey map = new LRUMapMultiKey(10); - LRUMapMultiKey.Key key1 = map.createKey("testRemoveObject", "toto", "tyty", "tutu"); - LRUMapMultiKey.Key key2 = map.createKey("toto", "titi", "tutu"); - LRUMapMultiKey.Key key3 = map.createKey("toto", "titi", "tata"); - - map.put(key1, "value"); - map.put(key2, "value"); - map.put(key3, "value"); - - Object l = map.remove("titi"); - - assertTrue(l instanceof List); - assertEquals(2, ((List) l).size()); - assertEquals(1, map.size()); - - map.remove(key1); - - assertEquals(0, map.size()); - } - -} - - diff --git a/src/test/java/org/nuiton/util/ListenerSetTest.java b/src/test/java/org/nuiton/util/ListenerSetTest.java deleted file mode 100644 index 8eb4b0e..0000000 --- a/src/test/java/org/nuiton/util/ListenerSetTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * - * ListenerSetTest.java - * - * Created: 10 mai 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * Copyright Code Lutin - * - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -import junit.framework.TestCase; - -public class ListenerSetTest extends TestCase { // ListenerSetTest - - int callCount; - - /** si la class n'est pas public fire ne retrouve pas les méthodes :( */ - public class Listener { - public void event1() { - callCount++; - } - - public void event2(Object o) { - callCount++; - } - } - - class PrivateListener { - public void event1() { - callCount++; - } - - public void event2(Object o) { - callCount++; - } - } - - public void testAdd() throws Exception { - ListenerSet<Object> set = new ListenerSet<Object>(); - Listener l = new Listener(); - - // ajout d'un listener - set.add(l); - - callCount = 0; - set.fire("event1"); - assertEquals(1, callCount); - - // ajout du meme listener - set.add(l); - callCount = 0; - set.fire("event1"); - assertEquals(1, callCount); - - // destruction de la reference sur le listener - l = null; - System.gc(); - - callCount = 0; - set.fire("event1"); - assertEquals(0, callCount); - } - - public void testAddContrained() throws Exception { - ListenerSet<Listener> set = new ListenerSet<Listener>(); - Listener l = new Listener(); - - // ajout d'un listener - set.add(l); - - callCount = 0; - set.fire("event1"); - assertEquals(1, callCount); - } - - public void testRemove() throws Exception { - ListenerSet<Object> set = new ListenerSet<Object>(); - Listener l = new Listener(); - set.add(l); - - callCount = 0; - set.fire("event1"); - assertEquals(1, callCount); - - set.remove(l); - - callCount = 0; - set.fire("event1"); - assertEquals(0, callCount); - } - - public void testFire() throws Exception { - ////////////////////////////////////////////////: - // avec le listener public - // - { - ListenerSet<Object> set = new ListenerSet<Object>(); - Listener l = new Listener(); - set.add(l); - - callCount = 0; - set.fire("event1"); - assertEquals(1, callCount); - - callCount = 0; - set.fire("event2", null); - assertEquals(1, callCount); - } - ////////////////////////////////////////////////: - // avec le listener privé - // - { - ListenerSet<Object> set = new ListenerSet<Object>(); - PrivateListener li = new PrivateListener(); - set.add(li); - - callCount = 0; - for (Object aSet : set) { - PrivateListener l = (PrivateListener) aSet; - l.event1(); - } - assertEquals(1, callCount); - - callCount = 0; - for (Object aSet : set) { - PrivateListener l = (PrivateListener) aSet; - l.event2(null); - } - assertEquals(1, callCount); - } - } - -} // ListenerSetTest - diff --git a/src/test/java/org/nuiton/util/MD5InputStreamTest.java b/src/test/java/org/nuiton/util/MD5InputStreamTest.java deleted file mode 100644 index 808f1a1..0000000 --- a/src/test/java/org/nuiton/util/MD5InputStreamTest.java +++ /dev/null @@ -1,1008 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Test; - -import java.io.*; -import java.net.URL; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public class MD5InputStreamTest { - - /** Logger */ - private static final Log log = LogFactory.getLog(MD5InputStreamTest.class); - - public static class MD5InputStreamOld extends FilterInputStream { - - /** MD5 context */ - protected MD5 md5; - - protected long streamLength; - - /** - * Creates a MD5InputStream - * - * @param in The input stream - */ - public MD5InputStreamOld(InputStream in) { - super(in); - - md5 = new MD5(); - } - - @Override - public int read() throws IOException { - int c = in.read(); - - if (c == -1) { - return -1; - } - - if ((c & ~0xff) != 0) { - log.warn("MD5InputStream.read() got character with (c & ~0xff) != 0)!"); - } else { - streamLength++; - md5.Update(c); - } - - return c; - } - - @Override - public int read(byte bytes[], int offset, int length) throws IOException { - int r; - - if ((r = in.read(bytes, offset, length)) == -1) { - return r; - } - streamLength += r; - - md5.Update(bytes, offset, r); - - return r; - } - - /** - * Returns array of bytes representing hash of the stream as finalized - * for the current state. - * - * @return hash - * @see MD5#Final - */ - public byte[] hash() { - return md5.Final(); - } - - public MD5 getMD5() { - return md5; - } - - public long getStreamLength() { - return streamLength; - } - } - - byte[] oldBytes; - - long oldLength; - - byte[] newBytes; - - long newLength; - - @Test - public void testRead() throws Exception { - - String txt = "jfdjskfjsdkljfdjfklsdjlfsdjlfjsdlfjlsdjlfsdjljklfsd"; - - buildMD5_old(new ByteArrayInputStream(txt.getBytes())); - - buildMD5_new(new ByteArrayInputStream(txt.getBytes())); - - assertMD5(); - - URL resource = getClass().getResource("/zip/test-uncompress.zip"); - - Assert.assertNotNull(resource); - - if (log.isInfoEnabled()) { - log.info(resource + " to test"); - } - - if (log.isInfoEnabled()) { - log.info("compute 10 times (new then old)"); - } - for (int i=0;i<10;i++) { - buildMD5_new(resource.openStream()); - buildMD5_old(resource.openStream()); - - assertMD5(); - } - if (log.isInfoEnabled()) { - log.info("compute 10 times (old then new)"); - } - for (int i=0;i<10;i++) { - buildMD5_old(resource.openStream()); - buildMD5_new(resource.openStream()); - - assertMD5(); - } - } - - protected void assertMD5() { - - Assert.assertNotNull(oldBytes); - Assert.assertNotNull(newBytes); - - Assert.assertEquals(oldLength, newLength); - - Assert.assertEquals(oldBytes.length, newBytes.length); - for (int i = 0, j = oldBytes.length; i < j; i++) { - byte oldB = oldBytes[i]; - byte newB = newBytes[i]; - Assert.assertEquals(oldB, newB); - } - } - - protected static final String logFormat = "computed for length %1$5d : %2$s"; - - protected void buildMD5_old(InputStream in) throws IOException { - - oldLength = -1; - oldBytes = null; - long t0 = System.nanoTime(); - MD5InputStreamOld md5Stream = new MD5InputStreamOld(in); - try { - while (md5Stream.read() != -1) { - // read me - } - - oldLength = md5Stream.getStreamLength(); - oldBytes = md5Stream.hash(); - } catch (IOException e) { - if (log.isDebugEnabled()) { - log.debug(e); - } - throw e; - } finally { - if (log.isInfoEnabled()) { - String message = String.format( - logFormat, - oldLength, - StringUtil.convertTime(System.nanoTime() - t0)); - log.info(message); - } - md5Stream.close(); - } - } - - protected void buildMD5_new(InputStream in) throws IOException { - newLength = -1; - newBytes = null; - long t0 = System.nanoTime(); - MD5InputStream md5Stream = new MD5InputStream(in); - try { - while (md5Stream.read() != -1) { - // read me - } - - newLength = md5Stream.getStreamLength(); - newBytes = md5Stream.hash(); - } catch (IOException e) { - if (log.isDebugEnabled()) { - log.debug(e); - } - throw e; - } finally { - if (log.isInfoEnabled()) { - String message = String.format( - logFormat, - newLength, - StringUtil.convertTime(System.nanoTime() - t0)); - log.info(message); - } - md5Stream.close(); - } - } - - - static class MD5State { - /** 128-bit state */ - int state[]; - - /** 64-bit character count */ - long count; - - /** 64-byte buffer (512 bits) for storing to-be-hashed characters */ - byte buffer[]; - - public MD5State() { - buffer = new byte[64]; - count = 0; - state = new int[4]; - - state[0] = 0x67452301; - state[1] = 0xefcdab89; - state[2] = 0x98badcfe; - state[3] = 0x10325476; - - } - - /** Create this State as a copy of another state */ - public MD5State(MD5State from) { - this(); - - int i; - - for (i = 0; i < buffer.length; i++) { - this.buffer[i] = from.buffer[i]; - } - - for (i = 0; i < state.length; i++) { - this.state[i] = from.state[i]; - } - - this.count = from.count; - } - } - - - public static class MD5 { - - /** - * MD5 state - **/ - MD5State state; - - /** - * If Final() has been called, finals is set to the current finals - * state. Any Update() causes this to be set to null. - **/ - MD5State finals; - - /** - * Padding for Final() - **/ - static byte padding[] = { - (byte) 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - private static boolean native_lib_loaded = false; - private static boolean native_lib_init_pending = true; - - /** - * Initialize MD5 internal state (object can be reused just by - * calling Init() after every Final() - **/ - public synchronized void Init () { - state = new MD5State(); - finals = null; - } - - /** - * Class constructor - **/ - public MD5 () { - if (native_lib_init_pending) _initNativeLibrary(); - this.Init(); - } - - /** - * Initialize class, and update hash with ob.toString() - * - * @param ob Object, ob.toString() is used to update hash - * after initialization - **/ - public MD5 (Object ob) { - this(); - Update(ob.toString()); - } - - private void Decode (byte buffer[], int shift, int[] out) { - /*len += shift; - for (int i = 0; shift < len; i++, shift += 4) { - out[i] = ((int) (buffer[shift] & 0xff)) | - (((int) (buffer[shift + 1] & 0xff)) << 8) | - (((int) (buffer[shift + 2] & 0xff)) << 16) | - (((int) buffer[shift + 3]) << 24); - }*/ - - // unrolled loop (original loop shown above) - - out[0] = ((int) (buffer[shift] & 0xff)) | - (((int) (buffer[shift + 1] & 0xff)) << 8) | - (((int) (buffer[shift + 2] & 0xff)) << 16) | - (((int) buffer[shift + 3]) << 24); - out[1] = ((int) (buffer[shift + 4] & 0xff)) | - (((int) (buffer[shift + 5] & 0xff)) << 8) | - (((int) (buffer[shift + 6] & 0xff)) << 16) | - (((int) buffer[shift + 7]) << 24); - out[2] = ((int) (buffer[shift + 8] & 0xff)) | - (((int) (buffer[shift + 9] & 0xff)) << 8) | - (((int) (buffer[shift + 10] & 0xff)) << 16) | - (((int) buffer[shift + 11]) << 24); - out[3] = ((int) (buffer[shift + 12] & 0xff)) | - (((int) (buffer[shift + 13] & 0xff)) << 8) | - (((int) (buffer[shift + 14] & 0xff)) << 16) | - (((int) buffer[shift + 15]) << 24); - out[4] = ((int) (buffer[shift + 16] & 0xff)) | - (((int) (buffer[shift + 17] & 0xff)) << 8) | - (((int) (buffer[shift + 18] & 0xff)) << 16) | - (((int) buffer[shift + 19]) << 24); - out[5] = ((int) (buffer[shift + 20] & 0xff)) | - (((int) (buffer[shift + 21] & 0xff)) << 8) | - (((int) (buffer[shift + 22] & 0xff)) << 16) | - (((int) buffer[shift + 23]) << 24); - out[6] = ((int) (buffer[shift + 24] & 0xff)) | - (((int) (buffer[shift + 25] & 0xff)) << 8) | - (((int) (buffer[shift + 26] & 0xff)) << 16) | - (((int) buffer[shift + 27]) << 24); - out[7] = ((int) (buffer[shift + 28] & 0xff)) | - (((int) (buffer[shift + 29] & 0xff)) << 8) | - (((int) (buffer[shift + 30] & 0xff)) << 16) | - (((int) buffer[shift + 31]) << 24); - out[8] = ((int) (buffer[shift + 32] & 0xff)) | - (((int) (buffer[shift + 33] & 0xff)) << 8) | - (((int) (buffer[shift + 34] & 0xff)) << 16) | - (((int) buffer[shift + 35]) << 24); - out[9] = ((int) (buffer[shift + 36] & 0xff)) | - (((int) (buffer[shift + 37] & 0xff)) << 8) | - (((int) (buffer[shift + 38] & 0xff)) << 16) | - (((int) buffer[shift + 39]) << 24); - out[10] = ((int) (buffer[shift + 40] & 0xff)) | - (((int) (buffer[shift + 41] & 0xff)) << 8) | - (((int) (buffer[shift + 42] & 0xff)) << 16) | - (((int) buffer[shift + 43]) << 24); - out[11] = ((int) (buffer[shift + 44] & 0xff)) | - (((int) (buffer[shift + 45] & 0xff)) << 8) | - (((int) (buffer[shift + 46] & 0xff)) << 16) | - (((int) buffer[shift + 47]) << 24); - out[12] = ((int) (buffer[shift + 48] & 0xff)) | - (((int) (buffer[shift + 49] & 0xff)) << 8) | - (((int) (buffer[shift + 50] & 0xff)) << 16) | - (((int) buffer[shift + 51]) << 24); - out[13] = ((int) (buffer[shift + 52] & 0xff)) | - (((int) (buffer[shift + 53] & 0xff)) << 8) | - (((int) (buffer[shift + 54] & 0xff)) << 16) | - (((int) buffer[shift + 55]) << 24); - out[14] = ((int) (buffer[shift + 56] & 0xff)) | - (((int) (buffer[shift + 57] & 0xff)) << 8) | - (((int) (buffer[shift + 58] & 0xff)) << 16) | - (((int) buffer[shift + 59]) << 24); - out[15] = ((int) (buffer[shift + 60] & 0xff)) | - (((int) (buffer[shift + 61] & 0xff)) << 8) | - (((int) (buffer[shift + 62] & 0xff)) << 16) | - (((int) buffer[shift + 63]) << 24); - } - - private native void Transform_native (int[] state, byte buffer[], int shift, int length); - - private void Transform (MD5State state, byte buffer[], int shift, int[] decode_buf) { - int - a = state.state[0], - b = state.state[1], - c = state.state[2], - d = state.state[3], - x[] = decode_buf; - - Decode(buffer, shift, decode_buf); - - /* Round 1 */ - a += ((b & c) | (~b & d)) + x[ 0] + 0xd76aa478; /* 1 */ - a = ((a << 7) | (a >>> 25)) + b; - d += ((a & b) | (~a & c)) + x[ 1] + 0xe8c7b756; /* 2 */ - d = ((d << 12) | (d >>> 20)) + a; - c += ((d & a) | (~d & b)) + x[ 2] + 0x242070db; /* 3 */ - c = ((c << 17) | (c >>> 15)) + d; - b += ((c & d) | (~c & a)) + x[ 3] + 0xc1bdceee; /* 4 */ - b = ((b << 22) | (b >>> 10)) + c; - - a += ((b & c) | (~b & d)) + x[ 4] + 0xf57c0faf; /* 5 */ - a = ((a << 7) | (a >>> 25)) + b; - d += ((a & b) | (~a & c)) + x[ 5] + 0x4787c62a; /* 6 */ - d = ((d << 12) | (d >>> 20)) + a; - c += ((d & a) | (~d & b)) + x[ 6] + 0xa8304613; /* 7 */ - c = ((c << 17) | (c >>> 15)) + d; - b += ((c & d) | (~c & a)) + x[ 7] + 0xfd469501; /* 8 */ - b = ((b << 22) | (b >>> 10)) + c; - - a += ((b & c) | (~b & d)) + x[ 8] + 0x698098d8; /* 9 */ - a = ((a << 7) | (a >>> 25)) + b; - d += ((a & b) | (~a & c)) + x[ 9] + 0x8b44f7af; /* 10 */ - d = ((d << 12) | (d >>> 20)) + a; - c += ((d & a) | (~d & b)) + x[10] + 0xffff5bb1; /* 11 */ - c = ((c << 17) | (c >>> 15)) + d; - b += ((c & d) | (~c & a)) + x[11] + 0x895cd7be; /* 12 */ - b = ((b << 22) | (b >>> 10)) + c; - - a += ((b & c) | (~b & d)) + x[12] + 0x6b901122; /* 13 */ - a = ((a << 7) | (a >>> 25)) + b; - d += ((a & b) | (~a & c)) + x[13] + 0xfd987193; /* 14 */ - d = ((d << 12) | (d >>> 20)) + a; - c += ((d & a) | (~d & b)) + x[14] + 0xa679438e; /* 15 */ - c = ((c << 17) | (c >>> 15)) + d; - b += ((c & d) | (~c & a)) + x[15] + 0x49b40821; /* 16 */ - b = ((b << 22) | (b >>> 10)) + c; - - - /* Round 2 */ - a += ((b & d) | (c & ~d)) + x[ 1] + 0xf61e2562; /* 17 */ - a = ((a << 5) | (a >>> 27)) + b; - d += ((a & c) | (b & ~c)) + x[ 6] + 0xc040b340; /* 18 */ - d = ((d << 9) | (d >>> 23)) + a; - c += ((d & b) | (a & ~b)) + x[11] + 0x265e5a51; /* 19 */ - c = ((c << 14) | (c >>> 18)) + d; - b += ((c & a) | (d & ~a)) + x[ 0] + 0xe9b6c7aa; /* 20 */ - b = ((b << 20) | (b >>> 12)) + c; - - a += ((b & d) | (c & ~d)) + x[ 5] + 0xd62f105d; /* 21 */ - a = ((a << 5) | (a >>> 27)) + b; - d += ((a & c) | (b & ~c)) + x[10] + 0x02441453; /* 22 */ - d = ((d << 9) | (d >>> 23)) + a; - c += ((d & b) | (a & ~b)) + x[15] + 0xd8a1e681; /* 23 */ - c = ((c << 14) | (c >>> 18)) + d; - b += ((c & a) | (d & ~a)) + x[ 4] + 0xe7d3fbc8; /* 24 */ - b = ((b << 20) | (b >>> 12)) + c; - - a += ((b & d) | (c & ~d)) + x[ 9] + 0x21e1cde6; /* 25 */ - a = ((a << 5) | (a >>> 27)) + b; - d += ((a & c) | (b & ~c)) + x[14] + 0xc33707d6; /* 26 */ - d = ((d << 9) | (d >>> 23)) + a; - c += ((d & b) | (a & ~b)) + x[ 3] + 0xf4d50d87; /* 27 */ - c = ((c << 14) | (c >>> 18)) + d; - b += ((c & a) | (d & ~a)) + x[ 8] + 0x455a14ed; /* 28 */ - b = ((b << 20) | (b >>> 12)) + c; - - a += ((b & d) | (c & ~d)) + x[13] + 0xa9e3e905; /* 29 */ - a = ((a << 5) | (a >>> 27)) + b; - d += ((a & c) | (b & ~c)) + x[ 2] + 0xfcefa3f8; /* 30 */ - d = ((d << 9) | (d >>> 23)) + a; - c += ((d & b) | (a & ~b)) + x[ 7] + 0x676f02d9; /* 31 */ - c = ((c << 14) | (c >>> 18)) + d; - b += ((c & a) | (d & ~a)) + x[12] + 0x8d2a4c8a; /* 32 */ - b = ((b << 20) | (b >>> 12)) + c; - - - /* Round 3 */ - a += (b ^ c ^ d) + x[ 5] + 0xfffa3942; /* 33 */ - a = ((a << 4) | (a >>> 28)) + b; - d += (a ^ b ^ c) + x[ 8] + 0x8771f681; /* 34 */ - d = ((d << 11) | (d >>> 21)) + a; - c += (d ^ a ^ b) + x[11] + 0x6d9d6122; /* 35 */ - c = ((c << 16) | (c >>> 16)) + d; - b += (c ^ d ^ a) + x[14] + 0xfde5380c; /* 36 */ - b = ((b << 23) | (b >>> 9)) + c; - - a += (b ^ c ^ d) + x[ 1] + 0xa4beea44; /* 37 */ - a = ((a << 4) | (a >>> 28)) + b; - d += (a ^ b ^ c) + x[ 4] + 0x4bdecfa9; /* 38 */ - d = ((d << 11) | (d >>> 21)) + a; - c += (d ^ a ^ b) + x[ 7] + 0xf6bb4b60; /* 39 */ - c = ((c << 16) | (c >>> 16)) + d; - b += (c ^ d ^ a) + x[10] + 0xbebfbc70; /* 40 */ - b = ((b << 23) | (b >>> 9)) + c; - - a += (b ^ c ^ d) + x[13] + 0x289b7ec6; /* 41 */ - a = ((a << 4) | (a >>> 28)) + b; - d += (a ^ b ^ c) + x[ 0] + 0xeaa127fa; /* 42 */ - d = ((d << 11) | (d >>> 21)) + a; - c += (d ^ a ^ b) + x[ 3] + 0xd4ef3085; /* 43 */ - c = ((c << 16) | (c >>> 16)) + d; - b += (c ^ d ^ a) + x[ 6] + 0x04881d05; /* 44 */ - b = ((b << 23) | (b >>> 9)) + c; - - a += (b ^ c ^ d) + x[ 9] + 0xd9d4d039; /* 33 */ - a = ((a << 4) | (a >>> 28)) + b; - d += (a ^ b ^ c) + x[12] + 0xe6db99e5; /* 34 */ - d = ((d << 11) | (d >>> 21)) + a; - c += (d ^ a ^ b) + x[15] + 0x1fa27cf8; /* 35 */ - c = ((c << 16) | (c >>> 16)) + d; - b += (c ^ d ^ a) + x[ 2] + 0xc4ac5665; /* 36 */ - b = ((b << 23) | (b >>> 9)) + c; - - - /* Round 4 */ - a += (c ^ (b | ~d)) + x[ 0] + 0xf4292244; /* 49 */ - a = ((a << 6) | (a >>> 26)) + b; - d += (b ^ (a | ~c)) + x[ 7] + 0x432aff97; /* 50 */ - d = ((d << 10) | (d >>> 22)) + a; - c += (a ^ (d | ~b)) + x[14] + 0xab9423a7; /* 51 */ - c = ((c << 15) | (c >>> 17)) + d; - b += (d ^ (c | ~a)) + x[ 5] + 0xfc93a039; /* 52 */ - b = ((b << 21) | (b >>> 11)) + c; - - a += (c ^ (b | ~d)) + x[12] + 0x655b59c3; /* 53 */ - a = ((a << 6) | (a >>> 26)) + b; - d += (b ^ (a | ~c)) + x[ 3] + 0x8f0ccc92; /* 54 */ - d = ((d << 10) | (d >>> 22)) + a; - c += (a ^ (d | ~b)) + x[10] + 0xffeff47d; /* 55 */ - c = ((c << 15) | (c >>> 17)) + d; - b += (d ^ (c | ~a)) + x[ 1] + 0x85845dd1; /* 56 */ - b = ((b << 21) | (b >>> 11)) + c; - - a += (c ^ (b | ~d)) + x[ 8] + 0x6fa87e4f; /* 57 */ - a = ((a << 6) | (a >>> 26)) + b; - d += (b ^ (a | ~c)) + x[15] + 0xfe2ce6e0; /* 58 */ - d = ((d << 10) | (d >>> 22)) + a; - c += (a ^ (d | ~b)) + x[ 6] + 0xa3014314; /* 59 */ - c = ((c << 15) | (c >>> 17)) + d; - b += (d ^ (c | ~a)) + x[13] + 0x4e0811a1; /* 60 */ - b = ((b << 21) | (b >>> 11)) + c; - - a += (c ^ (b | ~d)) + x[ 4] + 0xf7537e82; /* 61 */ - a = ((a << 6) | (a >>> 26)) + b; - d += (b ^ (a | ~c)) + x[11] + 0xbd3af235; /* 62 */ - d = ((d << 10) | (d >>> 22)) + a; - c += (a ^ (d | ~b)) + x[ 2] + 0x2ad7d2bb; /* 63 */ - c = ((c << 15) | (c >>> 17)) + d; - b += (d ^ (c | ~a)) + x[ 9] + 0xeb86d391; /* 64 */ - b = ((b << 21) | (b >>> 11)) + c; - - state.state[0] += a; - state.state[1] += b; - state.state[2] += c; - state.state[3] += d; - } - - /** - * Updates hash with the bytebuffer given (using at maximum length bytes from - * that buffer) - * - * @param stat Which state is updated - * @param buffer Array of bytes to be hashed - * @param offset Offset to buffer array - * @param length Use at maximum `length' bytes (absolute - * maximum is buffer.length) - */ - public void Update (MD5State stat, byte buffer[], int offset, int length) { - int index, partlen, i, start; - finals = null; - - /* Length can be told to be shorter, but not inter */ - if ((length - offset)> buffer.length) - length = buffer.length - offset; - - /* compute number of bytes mod 64 */ - - index = (int) (stat.count & 0x3f); - stat.count += length; - - partlen = 64 - index; - - if (length >= partlen) { - - // update state (using native method) to reflect input - - if (native_lib_loaded) { - if (partlen == 64) { - partlen = 0; - } else { - for (i = 0; i < partlen; i++) - stat.buffer[i + index] = buffer[i + offset]; - Transform_native(stat.state, stat.buffer, 0, 64); - } - i = partlen + ((length - partlen) / 64) * 64; - - // break into chunks to guard against stack overflow in JNI - - int transformLength = length - partlen; - int transformOffset = partlen + offset; - final int MAX_LENGTH = 65536; // prevent stack overflow in JNI - while (true) { - if (transformLength > MAX_LENGTH) { - Transform_native(stat.state, buffer, transformOffset, MAX_LENGTH); - transformLength -= MAX_LENGTH; - transformOffset += MAX_LENGTH; - } else { - Transform_native(stat.state, buffer, transformOffset, transformLength); - break; - } - } - } - - // update state (using only Java) to reflect input - - else { - int[] decode_buf = new int[16]; - if (partlen == 64) { - partlen = 0; - } else { - for (i = 0; i < partlen; i++) - stat.buffer[i + index] = buffer[i + offset]; - Transform(stat, stat.buffer, 0, decode_buf); - } - for (i = partlen; (i + 63) < length; i+= 64) { - Transform(stat, buffer, i + offset, decode_buf); - } - } - index = 0; - } else { - i = 0; - } - - /* buffer remaining input */ - if (i < length) { - start = i; - for (; i < length; i++) { - stat.buffer[index + i - start] = buffer[i + offset]; - } - } - } - - /* - * Update()s for other datatypes than byte[] also. Update(byte[], int) - * is only the main driver. - */ - - /** - * Plain update, updates this object - **/ - public void Update (byte buffer[], int offset, int length) { - Update(this.state, buffer, offset, length); - } - - public void Update (byte buffer[], int length) { - Update(this.state, buffer, 0, length); - } - - /** - * Updates hash with given array of bytes - * - * @param buffer Array of bytes to use for updating the hash - **/ - public void Update (byte buffer[]) { - Update(buffer, 0, buffer.length); - } - - /** - * Updates hash with a single byte - * - * @param b Single byte to update the hash - **/ - public void Update (byte b) { - byte buffer[] = new byte[1]; - buffer[0] = b; - - Update(buffer, 1); - } - - /** - * Update buffer with given string. Note that because the version of - * the s.getBytes() method without parameters is used to convert the - * string to a byte array, the results of this method may be different - * on different platforms. The s.getBytes() method converts the string - * into a byte array using the current platform's default character set - * and may therefore have different results on platforms with different - * default character sets. If a version that works consistently - * across platforms with different default character sets is desired, - * use the overloaded version of the Update() method which takes a - * string and a character encoding. - * - * @param s String to be update to hash (is used as s.getBytes()) - **/ - public void Update (String s) { - byte chars[] = s.getBytes(); - Update(chars, chars.length); - } - - /** - * Update buffer with given string using the given encoding. If the - * given encoding is null, the encoding "ISO8859_1" is used. - * - * @param s String to be update to hash (is used as - * s.getBytes(charset_name)) - * @param charset_name The character set to use to convert s to a - * byte array, or null if the "ISO8859_1" - * character set is desired. - * @exception java.io.UnsupportedEncodingException If the named - * charset is not supported. - **/ - public void Update (String s, String charset_name) throws java.io.UnsupportedEncodingException { - if (charset_name == null) charset_name = "ISO8859_1"; - byte chars[] = s.getBytes(charset_name); - Update(chars, chars.length); - } - - /** - * Update buffer with a single integer (only & 0xff part is used, - * as a byte) - * - * @param i Integer value, which is then converted to byte as i & 0xff - **/ - public void Update (int i) { - Update((byte) (i & 0xff)); - } - - private byte[] Encode (int input[], int len) { - int i, j; - byte out[]; - - out = new byte[len]; - - for (i = j = 0; j < len; i++, j += 4) { - out[j] = (byte) (input[i] & 0xff); - out[j + 1] = (byte) ((input[i] >>> 8) & 0xff); - out[j + 2] = (byte) ((input[i] >>> 16) & 0xff); - out[j + 3] = (byte) ((input[i] >>> 24) & 0xff); - } - - return out; - } - - /** - * Returns array of bytes (16 bytes) representing hash as of the - * current state of this object. Note: getting a hash does not - * invalidate the hash object, it only creates a copy of the real - * state which is finalized. - * - * @return Array of 16 bytes, the hash of all updated bytes - **/ - public synchronized byte[] Final () { - byte bits[]; - int index, padlen; - MD5State fin; - - if (finals == null) { - fin = new MD5State(state); - - int[] count_ints = {(int) (fin.count << 3), (int) (fin.count >> 29)}; - bits = Encode(count_ints, 8); - - index = (int) (fin.count & 0x3f); - padlen = (index < 56) ? (56 - index) : (120 - index); - - Update(fin, padding, 0, padlen); - Update(fin, bits, 0, 8); - - /* Update() sets finals to null */ - finals = fin; - } - - return Encode(finals.state, 16); - } - - private static final char[] HEX_CHARS = {'0', '1', '2', '3', - '4', '5', '6', '7', - '8', '9', 'a', 'b', - 'c', 'd', 'e', 'f',}; - - /** - * Turns array of bytes into string representing each byte as - * unsigned hex number. - * - * @param hash Array of bytes to convert to hex-string - * @return Generated hex string - */ - public static String asHex (byte hash[]) { - char buf[] = new char[hash.length * 2]; - for (int i = 0, x = 0; i < hash.length; i++) { - buf[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf]; - buf[x++] = HEX_CHARS[hash[i] & 0xf]; - } - return new String(buf); - } - - /** - * Returns 32-character hex representation of this objects hash - * - * @return String of this object's hash - */ - public String asHex () { - return asHex(this.Final()); - } - - public static synchronized final void initNativeLibrary (boolean disallow_lib_loading) { - if (disallow_lib_loading) { - native_lib_init_pending = false; - } else { - _initNativeLibrary(); - } - } - - private static synchronized final void _initNativeLibrary () { - if (!native_lib_init_pending) return; - native_lib_loaded = _loadNativeLibrary(); - native_lib_init_pending = false; - } - - private static synchronized final boolean _loadNativeLibrary () { - try { - - // don't try to load if the right property is set - - String prop = System.getProperty("com.twmacinta.util.MD5.NO_NATIVE_LIB"); - if (prop != null) { - prop = prop.trim(); - if (prop.equalsIgnoreCase("true") || prop.equals("1")) return false; - } - - // the library to load can be specified as a property - - File f; - prop = System.getProperty("com.twmacinta.util.MD5.NATIVE_LIB_FILE"); - if (prop != null) { - f = new File(prop); - if (f.canRead()) { - System.load(f.getAbsolutePath()); - return true; - } - } - - // determine the operating system and architecture - - String os_name = System.getProperty("os.name"); - String os_arch = System.getProperty("os.arch"); - if (os_name == null || os_arch == null) return false; - os_name = os_name.toLowerCase(); - os_arch = os_arch.toLowerCase(); - - // define settings which are OS arch architecture independent - - File arch_lib_path = null; - String arch_libfile_suffix; - - // fill in settings for Linux on x86 - - if (os_name.equals("linux") && - (os_arch.equals("x86") || - os_arch.equals("i386") || - os_arch.equals("i486") || - os_arch.equals("i586") || - os_arch.equals("i686"))) { - arch_lib_path = new File(new File(new File("lib"), "arch"), "linux_x86"); - arch_libfile_suffix = ".so"; - } - - // fill in settings for Windows on x86 - - else if (os_name.startsWith("windows ") && - (os_arch.equals("x86") || - os_arch.equals("i386") || - os_arch.equals("i486") || - os_arch.equals("i586") || - os_arch.equals("i686"))) { - arch_lib_path = new File(new File(new File("lib"), "arch"), "win32_x86"); - arch_libfile_suffix = ".dll"; - } - - // fill in settings for Mac OS X on PPC - - else if (os_name.startsWith("mac os x") && - (os_arch.equals("ppc"))) { - arch_lib_path = new File(new File(new File("lib"), "arch"), "darwin_ppc"); - arch_libfile_suffix = ".jnilib"; - } - - // fill in settings for Mac OS X on x86 - - else if (os_name.startsWith("mac os x") && - (os_arch.equals("x86") || - os_arch.equals("i386") || - os_arch.equals("i486") || - os_arch.equals("i586") || - os_arch.equals("i686"))) { - arch_lib_path = new File(new File(new File("lib"), "arch"), "darwin_x86"); - arch_libfile_suffix = ".jnilib"; - } - - // default to .so files with no architecture specific subdirectory - - else { - arch_libfile_suffix = ".so"; - } - - // build the required filename - - String fname = "MD5" + arch_libfile_suffix; - - // try the architecture specific directory - - if (arch_lib_path != null) { - f = new File(arch_lib_path, fname); - if (f.canRead()) { - System.load(f.getAbsolutePath()); - return true; - } - } - - // try the "lib" subdirectory - - f = new File(new File("lib"), fname); - if (f.canRead()) { - System.load(f.getAbsolutePath()); - return true; - } - - // try the working directory - - f = new File(fname); - if (f.canRead()) { - System.load(f.getAbsolutePath()); - return true; - } - } - - // discard SecurityExceptions - - catch (SecurityException e) {} - - // unable to load - - return false; - } - - /** - * Calculates and returns the hash of the contents of the given file. - **/ - public static byte[] getHash (File f) throws IOException { - if (!f.exists()) throw new FileNotFoundException(f.toString()); - InputStream close_me = null; - try { - long buf_size = f.length(); - if (buf_size < 512) buf_size = 512; - if (buf_size > 65536) buf_size = 65536; - byte[] buf = new byte[(int) buf_size]; - MD5InputStream in = new MD5InputStream(new FileInputStream(f)); - close_me = in; - while (in.read(buf) != -1); - in.close(); - return in.hash(); - } catch (IOException e) { - if (close_me != null) try { close_me.close(); } catch (Exception e2) {} - throw e; - } - } - - /** - * @return true iff the first 16 bytes of both hash1 and hash2 are - * equal; both hash1 and hash2 are null; or either hash - * array is less than 16 bytes in length and their lengths and - * all of their bytes are equal. - **/ - public static boolean hashesEqual (byte[] hash1, byte[] hash2) { - if (hash1 == null) return hash2 == null; - if (hash2 == null) return false; - int targ = 16; - if (hash1.length < 16) { - if (hash2.length != hash1.length) return false; - targ = hash1.length; - } else if (hash2.length < 16) { - return false; - } - for (int i = 0; i < targ; i++) { - if (hash1[i] != hash2[i]) return false; - } - return true; - } - -} -} diff --git a/src/test/java/org/nuiton/util/MatrixMapTest.java b/src/test/java/org/nuiton/util/MatrixMapTest.java deleted file mode 100644 index a80fe01..0000000 --- a/src/test/java/org/nuiton/util/MatrixMapTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -/* - * Copyright (c) 2011 poussin. All rights reserved. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ -package org.nuiton.util; - -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; - -/** - * - * @author Benjamin Poussin - poussin@codelutin.com - */ -public class MatrixMapTest { - - @Test - public void testSubMatrix() { - List<String> sem1 = Arrays.asList("xA", "xB", "xC", "xD"); - List<String> sem2 = Arrays.asList("ya", "yb", "yc", "yd", "ye"); - MatrixMap<String> m = MatrixMap.Factory.create(new List[]{sem1, sem2}); - - m.setValue("a1", "xA", "ya"); - m.setValue("a2", "xA", "yb"); - m.setValue("a3", "xA", "yc"); - m.setValue("a4", "xA", "yd"); - m.setValue("a5", "xA", "ye"); - - m.setValue("b1", "xB", "ya"); - m.setValue("b2", "xB", "yb"); - m.setValue("b3", "xB", "yc"); - m.setValue("b4", "xB", "yd"); - m.setValue("b5", "xB", "ye"); - - m.setValue("c1", "xC", "ya"); - m.setValue("c2", "xC", "yb"); - m.setValue("c3", "xC", "yc"); - m.setValue("c4", "xC", "yd"); - m.setValue("c5", "xC", "ye"); - - m.setValue("d1", "xD", "ya"); - m.setValue("d2", "xD", "yb"); - m.setValue("d3", "xD", "yc"); - m.setValue("d4", "xD", "yd"); - m.setValue("d5", "xD", "ye"); - - System.out.println(m.toString()); - - MatrixMap sub = m.getSubMatrix(0, "xA", "xC"); - - System.out.println(sub); - } - - @Test - public void testExtend() { - List<String> sem1 = Arrays.asList("xA", "xB", "xC"); - List<String> sem2 = Arrays.asList("ya", "yb", "yc", "yd", "ye"); - MatrixMap<String> m = MatrixMap.Factory.createElastic(new List[]{sem1, sem2}); - - m.setValue("a1", "xA", "ya"); - m.setValue("a2", "xA", "yb"); - m.setValue("a3", "xA", "yc"); - m.setValue("a4", "xA", "yd"); - m.setValue("a5", "xA", "ye"); - - m.setValue("b1", "xB", "ya"); - m.setValue("b2", "xB", "yb"); - m.setValue("b3", "xB", "yc"); - m.setValue("b4", "xB", "yd"); - m.setValue("b5", "xB", "ye"); - - m.setValue("c1", "xC", "ya"); - m.setValue("c2", "xC", "yb"); - m.setValue("c3", "xC", "yc"); - m.setValue("c4", "xC", "yd"); - m.setValue("c5", "xC", "ye"); - - System.out.println(m.toString()); - - m.setValue("d1", "xD", "ya"); - m.setValue("d2", "xD", "yb"); - m.setValue("d3", "xD", "yc"); - m.setValue("d4", "xD", "yd"); - m.setValue("d5", "xD", "ye"); - - System.out.println(m.toString()); - } - -} diff --git a/src/test/java/org/nuiton/util/NumberUtilTest.java b/src/test/java/org/nuiton/util/NumberUtilTest.java deleted file mode 100644 index 43d6cea..0000000 --- a/src/test/java/org/nuiton/util/NumberUtilTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.nuiton.util; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2014 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Test; - -/** - * @author Kevin Morin - morin@codelutin.com - * @since 3.0 - */ -public class NumberUtilTest { - - private static final Log log = LogFactory.getLog(NumberUtilTest.class); - - @Test - public void testDivideAndEnsureSum() { - log.debug("test divideAndEnsureSum"); - Assert.assertNull(NumberUtil.divideAndEnsureSum(100, 0)); - Assert.assertArrayEquals(new int[]{ 34, 33, 33 }, NumberUtil.divideAndEnsureSum(100, 3)); - Assert.assertArrayEquals(new int[]{ 17, 17, 17, 17, 16, 16 }, NumberUtil.divideAndEnsureSum(100, 6)); - } - - @Test - public void testRound3Digits() { - - assertRoundThreeDigits(1.2f, 1.2f); - assertRoundThreeDigits(1.22f, 1.22f); - assertRoundThreeDigits(1.222f, 1.222f); - assertRoundThreeDigits(1.2222f, 1.222f); - assertRoundThreeDigits(1.2225f, 1.222f); - assertRoundThreeDigits(1.2226f, 1.223f); - assertRoundThreeDigits(11.2226f, 11.223f); - assertRoundThreeDigits(111.2226f, 111.223f); - assertRoundThreeDigits(1111.2226f, 1111.223f); - - assertRoundThreeDigits(1111.999f, 1111.999f); - assertRoundThreeDigits(1111.9994f, 1111.999f); - assertRoundThreeDigits(1111.9995f, 1112f); - assertRoundThreeDigits(1111.9996f, 1112f); - } - - @Test - public void testRoundOneDigit() { - - assertRoundOneDigit(1.2f, 1.2f); - assertRoundOneDigit(1.22f, 1.2f); - assertRoundOneDigit(1.5f, 1.5f); - assertRoundOneDigit(1.55f, 1.5f); - assertRoundOneDigit(1.56f, 1.6f); - assertRoundOneDigit(1.9f, 1.9f); - assertRoundOneDigit(1.222f, 1.2f); - assertRoundOneDigit(11.2226f, 11.2f); - assertRoundOneDigit(111.2226f, 111.2f); - assertRoundOneDigit(1111.2226f, 1111.2f); - - assertRoundOneDigit(1111.999f, 1112.0f); - assertRoundOneDigit(1111.9994f, 1112.0f); - assertRoundOneDigit(1111.9995f, 1112.0f); - assertRoundOneDigit(1111.9996f, 1112.0f); - } - - protected void assertRoundThreeDigits(float number, float expected) { - float actual = NumberUtil.roundThreeDigits(number); - Assert.assertEquals("" + expected, "" + actual); - } - - protected void assertRoundOneDigit(float number, float expected) { - Float actual = NumberUtil.roundOneDigit(number); - Assert.assertEquals("" + expected, "" + actual); - } - -} diff --git a/src/test/java/org/nuiton/util/ObjectUtilTest.java b/src/test/java/org/nuiton/util/ObjectUtilTest.java deleted file mode 100644 index 622c265..0000000 --- a/src/test/java/org/nuiton/util/ObjectUtilTest.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.File; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Created: 19 nov. 07 12:39:28 - * - * @author Benjamin Poussin - poussin@codelutin.com - */ -public class ObjectUtilTest extends Assert { - - @Test - public void testCall() throws Exception { - Dummy dummy = new Dummy(); - - List<Method> methods = ObjectUtil.getMethod(Dummy.class, "setfile", true); - assertEquals(1, methods.size()); - ObjectUtil.call(dummy, methods.get(0), "/tmp"); - assertEquals(new File("/tmp"), dummy.getFile()); - - methods = ObjectUtil.getMethod(Dummy.class, "setAllFile", true); - assertEquals(1, methods.size()); - ObjectUtil.call(dummy, methods.get(0), "toto", "/tmp", "/tmp/titi"); - assertEquals("toto", dummy.getName()); - assertEquals(Arrays.asList(new File("/tmp"), new File("/tmp/titi")), - Arrays.asList(dummy.getAllFile())); - - ObjectUtil.call(dummy, methods.get(0), "toto"); - assertEquals("toto", dummy.getName()); - assertEquals(new ArrayList<File>(), - Arrays.asList(dummy.getAllFile())); - } - - @Test - public void testClone() throws Exception { - ArrayList c = new ArrayList(); - ArrayList inner = new ArrayList(); - c.add(inner); - - ArrayList n = ObjectUtil.clone(c); - Assert.assertNotSame(c, n); - Assert.assertSame(c.get(0), n.get(0)); - } - - @Test - public void testDeepClone() throws Exception { - ArrayList c = new ArrayList(); - ArrayList inner = new ArrayList(); - c.add(inner); - - ArrayList n = ObjectUtil.deepClone(c); - Assert.assertNotSame(c, n); - Assert.assertNotSame(c.get(0), n.get(0)); - } - - @Test - public void testCreate() throws Exception { - Object o = ObjectUtil.create("java.lang.StringBuffer"); - assertTrue(o != null); - assertTrue(o instanceof StringBuffer); - - Dummy dummy = (Dummy) ObjectUtil.create( - "org.nuiton.util.ObjectUtilTest$Dummy(name=\"coucou le monde\", file=/tmp/fileTest, integer=50)"); - assertTrue(dummy != null); - assertEquals("coucou le monde", dummy.getName()); - assertEquals(50, dummy.getInteger()); - assertEquals(new File("/tmp/fileTest"), dummy.getFile()); - } - - @Test - public void testGetNullValue() throws Exception { - - try { - assertNull(ObjectUtil.getNullValue(null)); - fail(); - } catch (Exception e) { - assertTrue(true); - } - - assertEquals(false, ObjectUtil.getNullValue(boolean.class)); - assertEquals(0, ObjectUtil.getNullValue(int.class)); - assertEquals((char) 0, ObjectUtil.getNullValue(char.class)); - assertEquals(0f, ObjectUtil.getNullValue(float.class)); - assertEquals(0d, ObjectUtil.getNullValue(double.class)); - assertEquals((byte) 0, ObjectUtil.getNullValue(byte.class)); - - assertNull(ObjectUtil.getNullValue(Boolean.class)); - assertNull(ObjectUtil.getNullValue(Integer.class)); - assertNull(ObjectUtil.getNullValue(Character.class)); - assertNull(ObjectUtil.getNullValue(Float.class)); - assertNull(ObjectUtil.getNullValue(Double.class)); - assertNull(ObjectUtil.getNullValue(Byte.class)); - } - - @Test - public void testIsNullValue() throws Exception { - - assertTrue(ObjectUtil.isNullValue(null)); - - assertTrue(ObjectUtil.isNullValue(false)); - assertTrue(ObjectUtil.isNullValue(0)); - assertTrue(ObjectUtil.isNullValue((char) 0)); - assertTrue(ObjectUtil.isNullValue(0f)); - assertTrue(ObjectUtil.isNullValue(0d)); - assertTrue(ObjectUtil.isNullValue((byte) 0)); - - assertFalse(ObjectUtil.isNullValue(Boolean.FALSE)); - assertFalse(ObjectUtil.isNullValue(Integer.valueOf(0))); - assertFalse(ObjectUtil.isNullValue(Character.valueOf((char) 0))); - assertFalse(ObjectUtil.isNullValue(Float.valueOf(0))); - assertFalse(ObjectUtil.isNullValue(Double.valueOf(0))); - assertFalse(ObjectUtil.isNullValue(Byte.valueOf((byte) 0))); - } - - public static class Dummy { - - String name; - int integer; - File file; - File[] allFile; - - public File[] getAllFile() { - return allFile; - } - - public void setAllFile(String name, File... allFile) { - this.name = name; - this.allFile = allFile; - } - - /** - * @return the file - */ - public File getFile() { - return this.file; - } - - /** - * @return the integer - */ - public int getInteger() { - return this.integer; - } - - /** - * @return the name - */ - public String getName() { - return this.name; - } - - /** - * @param file the file to set - */ - public void setFile(File file) { - this.file = file; - } - - /** - * @param integer the integer to set - */ - public void setInteger(int integer) { - this.integer = integer; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - } -} diff --git a/src/test/java/org/nuiton/util/PagerBeanUtilTest.java b/src/test/java/org/nuiton/util/PagerBeanUtilTest.java deleted file mode 100644 index 08e58d0..0000000 --- a/src/test/java/org/nuiton/util/PagerBeanUtilTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.nuiton.util; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import org.apache.commons.lang3.tuple.Pair; -import org.junit.Assert; -import org.junit.Test; - -/** - * Test {@link PagerBeanUtil}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.6.6 - */ -public class PagerBeanUtilTest { - - @Test - public void getPageBound() throws Exception { - - Pair<Long, Long> actualBound; - - // page size is greater than total count, only returns that is available - actualBound = PagerBeanUtil.getPageBound((long) Integer.MAX_VALUE * 2l, 1, 11); - Assert.assertEquals(Pair.of(0l, 11l), actualBound); - - } - - @Test - public void getPageBoundWithInfinityPageSize() throws Exception { - - Pair<Long, Long> actualBound; - - // page size is -1, get all content - long totalCount = (long) Integer.MAX_VALUE * 2L; - actualBound = PagerBeanUtil.getPageBound(totalCount, 1, -1); - Assert.assertEquals(Pair.of(0L, totalCount), actualBound); - - } - - @Test - public void getTotalPage() throws Exception { - long totalPage; - - totalPage = PagerBeanUtil.getTotalPage(9, 10); - Assert.assertEquals(1, totalPage); - - totalPage = PagerBeanUtil.getTotalPage(10, 10); - Assert.assertEquals(1, totalPage); - - totalPage = PagerBeanUtil.getTotalPage(11, 10); - Assert.assertEquals(2, totalPage); - - totalPage = PagerBeanUtil.getTotalPage( - (long) Integer.MAX_VALUE * 20, 10); - Assert.assertEquals(Integer.MAX_VALUE * 2l, totalPage); - - } -} diff --git a/src/test/java/org/nuiton/util/PeriodDatesTest.java b/src/test/java/org/nuiton/util/PeriodDatesTest.java deleted file mode 100644 index 9722515..0000000 --- a/src/test/java/org/nuiton/util/PeriodDatesTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import java.text.DateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.concurrent.TimeUnit; - -/** @author fdesbois */ -public class PeriodDatesTest { - - /** Logger */ - private static final Log log = LogFactory.getLog(PeriodDatesTest.class); - - /** Test of initDayOfMonthExtremities method, of class PeriodDates. */ - @Test - public void testInitDayOfMonthExtremities() { - PeriodDates period = new PeriodDates(); - period.setFromDate(DateUtil.createDate(9,8,7,23,12,2010)); - period.setThruDate(DateUtil.createDate(6,5,4,26,12,2010)); - - period.initDayOfMonthExtremities(); - - Assert.assertTrue(period.between(DateUtil.createDate(3,2,1,1,12,2010))); - - Calendar lastDayOf2010 = new GregorianCalendar(2010,11,31,23,59,59); - lastDayOf2010.set(Calendar.MILLISECOND, 999); - - Assert.assertEquals(DateUtil.createDate(0,0,0,1,12,2010), period.getFromDate()); - Assert.assertEquals(lastDayOf2010.getTime(), period.getThruDate()); - } - - /** Test of getMonths method, of class PeriodDates. */ - @Test - public void testGetMonths() { - // Prepare two calendars with time not equals to 0 - Calendar cal1 = DateUtil.getDefaultCalendar(new Date()); - cal1.set(Calendar.DAY_OF_MONTH, 3); - cal1.set(Calendar.MONTH, 2); - cal1.set(Calendar.YEAR, 2009); - cal1.set(Calendar.HOUR, 8); - - DateFormat timeFormat = DateFormat.getTimeInstance(); - log.info("getMonths:: time for calendarFrom : " + - timeFormat.format(cal1.getTime())); - - Calendar cal2 = DateUtil.getDefaultCalendar(new Date()); - cal2.set(Calendar.DAY_OF_MONTH, 22); - cal2.set(Calendar.MONTH, 6); - cal2.set(Calendar.YEAR, 2009); - cal2.set(Calendar.HOUR, 4); - - log.info("getMonths:: time for calendarThru : " + - timeFormat.format(cal2.getTime())); - - PeriodDates period = new PeriodDates(cal1, cal2); - - List<Date> months = period.getMonths(); - Assert.assertEquals(5, months.size()); - for (int i = 0; i < 5; i++) { - Date monthDate = months.get(i); - int month = DateUtil.getDefaultCalendar(monthDate).get(Calendar.MONTH); - Assert.assertEquals(i + 2, month); // 2, 3, 4, 5, 6 - } - } - - @Test(timeout = 60 * 1000, expected = IllegalArgumentException.class) - public void whatIfPeriodDatesIsNotInChronologicalOrder() { - Date january = DateUtil.createDate(1, 1, 2011); - Date december = DateUtil.createDate(1, 12, 2011); - - // trying to break PeriodDates by creating an anti-chronological period - try { - PeriodDates periodDates = new PeriodDates(december, january); - Assert.fail(); - } catch (IllegalArgumentException e) { - // as expected - } - - // got ya! - PeriodDates periodDates = new PeriodDates(); - periodDates.setFromDate(december); - periodDates.setThruDate(january); - } - - @Test(expected = IllegalArgumentException.class) - public void testSetFromDateAfterThruDate() { - Date january = DateUtil.createDate(1, 1, 2011); - Date december = DateUtil.createDate(1, 12, 2011); - - PeriodDates periodDates = new PeriodDates(); - // Set thruDate before setting fromDate - periodDates.setThruDate(january); - // FromDate is after thruDate : should throw IllegalArgumentException - periodDates.setFromDate(december); - } - - -} diff --git a/src/test/java/org/nuiton/util/RecursivePropertiesTest.java b/src/test/java/org/nuiton/util/RecursivePropertiesTest.java deleted file mode 100644 index 0be6157..0000000 --- a/src/test/java/org/nuiton/util/RecursivePropertiesTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.FileInputStream; -import java.io.IOException; - -/** - * Test recursives properties class. - * - * @author chatellier - */ -public class RecursivePropertiesTest { - - /** - * Test string by \\ in value. - * - * @throws IOException - */ - @Test - public void testWindowsFile() throws IOException { - RecursiveProperties props = new RecursiveProperties(); - props.load(new FileInputStream("src/test/resources/properties/windows.properties")); - - Assert.assertEquals("C:\\Documents and Settings\\guest\\.ssh\\id_rsa", props.getProperty("vcs.ssh.keyFile")); - } - - /** - * Test with recursive properties. - * - * @throws IOException - */ - @Test - public void testRecursive() throws IOException { - RecursiveProperties props = new RecursiveProperties(); - props.load(new FileInputStream("src/test/resources/properties/recursive.properties")); - - Assert.assertEquals("World", props.getProperty("username")); - Assert.assertEquals("Hello World !", props.getProperty("helloWorld")); - } -} diff --git a/src/test/java/org/nuiton/util/ReflectUtilTest.java b/src/test/java/org/nuiton/util/ReflectUtilTest.java deleted file mode 100644 index 81ce274..0000000 --- a/src/test/java/org/nuiton/util/ReflectUtilTest.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util; - -import org.junit.Assert; -import org.junit.Test; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.Set; - -/** - * To test the class {@link ReflectUtil}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.0 - */ -public class ReflectUtilTest { - - public static class MyClass { - - @SuppressWarnings("") - @Deprecated - public String publicField; - - @SuppressWarnings("") - @Deprecated - protected String protectedField; - - @SuppressWarnings("") - @Deprecated - private String privateField; - - @SuppressWarnings("") - @Deprecated - String field; - - @SuppressWarnings("") - String fieldSkipped; - - @SuppressWarnings("") - @Deprecated - public void publicMethod() { - - } - - @SuppressWarnings("") - @Deprecated - protected void protectedMethod() { - - } - - @SuppressWarnings("") - @Deprecated - private void privateMethod() { - - } - - @SuppressWarnings("") - @Deprecated - void method() { - - } - - @SuppressWarnings("") - void methodSkipped() { - - } - } - - public static class MySubClass extends MyClass { - - @SuppressWarnings("") - @Deprecated - String field2; - - @SuppressWarnings("") - @Deprecated - void method2() { - - } - } - - @Test - public void getAllDeclaredFields() throws NoSuchFieldException { - - Set<Field> fields; - - fields = ReflectUtil.getAllDeclaredFields(MyClass.class); - - assertGetAllDeclaredFields(fields, - "publicField", - "protectedField", - "privateField", - "field", - "fieldSkipped" - ); - - fields = ReflectUtil.getAllDeclaredFields(MySubClass.class); - - assertGetAllDeclaredFields(fields, - "publicField", - "protectedField", - "privateField", - "field", - "fieldSkipped", - "field2" - ); - - } - - @Test - public void getAllDeclaredMethods() throws NoSuchFieldException { - - Set<Method> methods; - - methods = ReflectUtil.getAllDeclaredMethods(MyClass.class); - - assertGetAllDeclaredMethods(methods, - "publicMethod", - "protectedMethod", - "privateMethod", - "method", - "methodSkipped" - ); - - methods = ReflectUtil.getAllDeclaredMethods(MySubClass.class); - - assertGetAllDeclaredMethods(methods, - "publicMethod", - "protectedMethod", - "privateMethod", - "method", - "methodSkipped", - "method2" - ); - - } - - @Test - public void getFieldAnnotation() throws NoSuchFieldException { - - Map<Field, ? extends Annotation> fieldAnnotation; - - // SuppressWarning is source scope so will disappear at compilation :) - fieldAnnotation = ReflectUtil.getFieldAnnotation(MyClass.class, - SuppressWarnings.class); - - assertFieldAnnotation(MyClass.class, fieldAnnotation); - - // SuppressWarning is source scope so will disappear at compilation :) - fieldAnnotation = ReflectUtil.getFieldAnnotation(MyClass.class, - SuppressWarnings.class, - true); - - assertFieldAnnotation(MyClass.class, fieldAnnotation); - - // SuppressWarning is source scope so will disappear at compilation :) - fieldAnnotation = ReflectUtil.getFieldAnnotation(MySubClass.class, - SuppressWarnings.class); - - assertFieldAnnotation(MySubClass.class, fieldAnnotation); - - // SuppressWarning is source scope so will disappear at compilation :) - fieldAnnotation = ReflectUtil.getFieldAnnotation(MySubClass.class, - SuppressWarnings.class, - true); - - assertFieldAnnotation(MySubClass.class, fieldAnnotation); - - fieldAnnotation = ReflectUtil.getFieldAnnotation(MyClass.class, - Deprecated.class); - - assertFieldAnnotation(MyClass.class, - fieldAnnotation, - "publicField", - "protectedField", - "privateField", - "field" - ); - - - fieldAnnotation = ReflectUtil.getFieldAnnotation(MyClass.class, - Deprecated.class, - true); - - assertFieldAnnotation(MyClass.class, - fieldAnnotation, - "publicField", - "protectedField", - "privateField", - "field" - ); - - fieldAnnotation = ReflectUtil.getFieldAnnotation(MySubClass.class, - Deprecated.class); - - assertFieldAnnotation(MySubClass.class, - fieldAnnotation, - "field2" - ); - - fieldAnnotation = ReflectUtil.getFieldAnnotation(MySubClass.class, - Deprecated.class, - true); - - assertFieldAnnotation(MySubClass.class, - fieldAnnotation, - "publicField", - "protectedField", - "privateField", - "field", - "field2" - ); - - } - - @Test - public void getMethodAnnotation() throws NoSuchMethodException { - - Map<Method, ? extends Annotation> methodAnnotation; - - // SuppressWarning is source scope so will disappear at compilation :) - methodAnnotation = ReflectUtil.getMethodAnnotation(MyClass.class, - SuppressWarnings.class); - - assertMethodAnnotation(MyClass.class, methodAnnotation); - - // SuppressWarning is source scope so will disappear at compilation :) - methodAnnotation = ReflectUtil.getMethodAnnotation(MyClass.class, - SuppressWarnings.class, - true); - - assertMethodAnnotation(MyClass.class, methodAnnotation); - - // SuppressWarning is source scope so will disappear at compilation :) - methodAnnotation = ReflectUtil.getMethodAnnotation(MySubClass.class, - SuppressWarnings.class); - - assertMethodAnnotation(MySubClass.class, methodAnnotation); - - // SuppressWarning is source scope so will disappear at compilation :) - methodAnnotation = ReflectUtil.getMethodAnnotation(MySubClass.class, - SuppressWarnings.class, - true); - - assertMethodAnnotation(MySubClass.class, methodAnnotation); - - methodAnnotation = ReflectUtil.getMethodAnnotation(MyClass.class, - Deprecated.class); - - assertMethodAnnotation(MyClass.class, - methodAnnotation, - "publicMethod", - "protectedMethod", - "privateMethod", - "method" - ); - - methodAnnotation = ReflectUtil.getMethodAnnotation(MyClass.class, - Deprecated.class, - true); - - assertMethodAnnotation(MyClass.class, - methodAnnotation, - "publicMethod", - "protectedMethod", - "privateMethod", - "method" - ); - - methodAnnotation = ReflectUtil.getMethodAnnotation(MySubClass.class, - Deprecated.class); - - assertMethodAnnotation(MySubClass.class, - methodAnnotation, - "method2" - ); - - methodAnnotation = ReflectUtil.getMethodAnnotation(MySubClass.class, - Deprecated.class, - true); - - assertMethodAnnotation(MySubClass.class, - methodAnnotation, - "publicMethod", - "protectedMethod", - "privateMethod", - "method", - "method2" - ); - - } - - protected void assertGetAllDeclaredFields(Set<Field> fields, - String... fieldNames) throws NoSuchFieldException { - - Assert.assertNotNull(fields); - Assert.assertEquals(fieldNames.length, fields.size()); - for (String fieldName : fieldNames) { - - Field field = getField(fieldName, fields); - - Assert.assertNotNull("Could not found field named " + fieldName, field); - } - } - - protected void assertGetAllDeclaredMethods(Set<Method> methods, - String... methodNames) throws NoSuchFieldException { - - Assert.assertNotNull(methods); - Assert.assertEquals(methodNames.length, methods.size()); - for (String methodName : methodNames) { - - Method method = getMethod(methodName, methods); - Assert.assertNotNull("Could not found method named " + methodName, method); - } - - } - - protected void assertFieldAnnotation(Class<?> type, - Map<Field, ? extends Annotation> fieldAnnotation, - String... fieldNames) throws NoSuchFieldException { - - Set<Field> allDeclaredFields = ReflectUtil.getAllDeclaredFields(type); - - Assert.assertNotNull(fieldAnnotation); - Assert.assertEquals(fieldNames.length, fieldAnnotation.size()); - for (String fieldName : fieldNames) { - Field field = getField(fieldName, allDeclaredFields); - Assert.assertNotNull(field); - Annotation annotation = fieldAnnotation.get(field); - Assert.assertNotNull("Could not found annotation for field " + fieldName, annotation); - } - } - - protected void assertMethodAnnotation(Class<?> type, - Map<Method, ? extends Annotation> fieldAnnotation, - String... methodNames) throws NoSuchMethodException { - - Set<Method> allDeclaredMethods = ReflectUtil.getAllDeclaredMethods(type); - - Assert.assertNotNull(fieldAnnotation); - Assert.assertEquals(methodNames.length, fieldAnnotation.size()); - for (String methodName : methodNames) { - Method method = getMethod(methodName, allDeclaredMethods); - Assert.assertNotNull(method); - Annotation annotation = fieldAnnotation.get(method); - Assert.assertNotNull("Could not found annotation for method " + methodName, annotation); - } - } - - protected Field getField(String fieldName, Set<Field> fields) { - for (Field field : fields) { - if (fieldName.equals(field.getName())) { - return field; - } - } - return null; - } - - protected Method getMethod(String methodName, Set<Method> methods) { - for (Method method : methods) { - if (methodName.equals(method.getName())) { - return method; - } - } - return null; - } -} diff --git a/src/test/java/org/nuiton/util/ResourceTest.java b/src/test/java/org/nuiton/util/ResourceTest.java deleted file mode 100644 index 14cfed4..0000000 --- a/src/test/java/org/nuiton/util/ResourceTest.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin, Chatellier Eric - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.lang3.SystemUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.*; -import org.junit.rules.TestName; - -import java.io.File; -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Test class for {@link Resource}. - * - * @author chatellier - * @author Tony Chemit - chemit@codelutin.com - */ -public class ResourceTest { // ResourceTest - - /** Logger. */ - private static final Log log = LogFactory.getLog(ResourceTest.class); - - @Test - public void testaddDefaultClassLoader() throws Exception { - String javaExecFilename = getJavaExecName(); - - Assert.assertNull(ResourceTest.class.getResource("/bin/" + javaExecFilename)); - - File repository = new File(System.getProperty("java.home")); - Resource.addDefaultClassLoader(repository.toURI().toURL()); - - //FIXME-tchemit-2012-07-23 On windows os java does not eixsts but java.exe does - File result = new File(repository, "bin" + File.separator + javaExecFilename); - - Assert.assertTrue(result.exists()); - - URL resultURL = Resource.getURL("bin/" + javaExecFilename); - Assert.assertEquals(result.toURI().toURL(), resultURL); - } - - @Test - public void testGetURL() throws Exception { - URL url; - - String javaExecFilename = getJavaExecName(); - - url = Resource.getURL("README.txt"); - Assert.assertNotNull(url); - - try { - Resource.getURL("bin/" + javaExecFilename); - Assert.fail(); - } catch (ResourceNotFoundException e) { - Assert.assertTrue(true); - } - File repository = new File(System.getProperty("java.home")); - Resource.addDefaultClassLoader(repository.toURI().toURL()); - url = Resource.getURL("bin/" + javaExecFilename); - Assert.assertNotNull(url); - - } - - @Test - public void testGetURLsFromDirectory() throws Exception { - - assumeNotUnderWindows(getClass(), testName); - - List<URL> list = new ArrayList<URL>(); - File repository = new File(System.getProperty("java.home")); - - // test lorsqu'aucun fichier du repertoire ne correspond au pattern - Assert.assertEquals(list, Resource.getURLsFromDirectory(repository, ".*.aucunFichierTrouve")); - - File file = new File(repository, "bin" + File.separator + "java"); - list.add(file.toURI().toURL()); - - // test qui prouve que la methode retourne le bon fichier - Assert.assertEquals(list, Resource.getURLsFromDirectory(new File(repository, "bin"), ".*" + File.separator + ".a.a$")); - - // test qui prouve la recursivite (va chercher en profondeur les fichiers) - Assert.assertEquals(list, Resource.getURLsFromDirectory(repository, ".*" + File.separator + "j.v.$")); - } - - @Test - public void testGetURLsFromJar() throws Exception { - File repository = new File(System.getProperty("java.home")); - File file = new File(repository, "lib" + File.separator + "rt.jar"); - - List<URL> result = Resource.getURLsFromJar(file, ".*OutOfMemoryError.*"); - Assert.assertNotNull(result); - Assert.assertEquals(1, result.size()); - } - - // unaltered classloader - static ClassLoader systemClassLoader; - - @BeforeClass - public static void beforeClass() { - systemClassLoader = ClassLoader.getSystemClassLoader(); - } - - @Before - public void beforeTest() throws NoSuchFieldException, IllegalAccessException { - URLClassLoader classLoader = (URLClassLoader) systemClassLoader; - ClassLoader parent = classLoader.getParent(); - ClassLoader currentClassLoader = new URLClassLoader(classLoader.getURLs(), parent); - Field field = ClassLoader.class.getDeclaredField("scl"); - field.setAccessible(true); - field.set(null, currentClassLoader); - } - - @After - public void afterTest() throws NoSuchFieldException, IllegalAccessException { - Field field = ClassLoader.class.getDeclaredField("scl"); - field.setAccessible(true); - field.set(null, systemClassLoader); - } - - @Test - public void testGetURLs() throws Exception { - if (log.isInfoEnabled()) { - log.info(Arrays.asList(((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs())); - } - - String javaExecFilename = getJavaExecName(); - String fileSeparatorRegex = StringUtil.getFileSeparatorRegex(); - File repository = new File(System.getProperty("java.home")); - Resource.addDefaultClassLoader(repository.toURI().toURL()); - List<URL> result; - - // comes - result = Resource.getURLs(".*bin" + fileSeparatorRegex + javaExecFilename); - Assert.assertNotNull(result); - Assert.assertEquals(1, result.size()); - - result = Resource.getURLs("META-INF/MANIFEST.MF"); - Assert.assertNotNull(result); - Assert.assertEquals(1, result.size()); - } - - @Test - public void testIsJar() throws Exception { - Assert.assertTrue(Resource.isJar("toto.jar")); - Assert.assertTrue(Resource.isJar("toto.JaR")); - Assert.assertFalse(Resource.isJar("totojar")); - Assert.assertFalse(Resource.isJar("")); - Assert.assertFalse(Resource.isJar(null)); - } - - @Test - public void testIsZip() throws Exception { - Assert.assertTrue(Resource.isZip("toto.zip")); - Assert.assertTrue(Resource.isZip("toto.zIp")); - Assert.assertFalse(Resource.isZip("totojarzip")); - Assert.assertFalse(Resource.isZip("")); - Assert.assertFalse(Resource.isZip(null)); - } - - @Test - public void testIsPattern() { - Assert.assertTrue(Resource.isPattern(".*.zip")); - Assert.assertTrue(Resource.isPattern(".?.zip")); - Assert.assertFalse(Resource.isPattern("toto.zip")); - } - - /** - * Test de recherche de resource dans le classpath (jar). - * - * @throws Exception - */ - @Test - public void testGetResourcesJarClassPath() throws Exception { - - assumeNotUnderWindows(getClass(), testName); - - // ce test peut echoué a chaque changement dans les dépendances - List<URL> urlsPattern = Resource.getResources("org/nuiton/util/Version.*Test\\.class"); - List<URL> urlsClass1 = Resource.getResources("org/nuiton/util/VersionTest.class"); - List<URL> urlsClass2 = Resource.getResources("org/nuiton/util/VersionUtilTest.class"); - Assert.assertEquals(2, urlsPattern.size()); - Assert.assertEquals(urlsPattern.size(), urlsClass1.size() + urlsClass2.size()); - - // test sans dossier de recherche (directement un pattern) - List<URL> urlsAllPattern = Resource.getResources("log4j\\..*"); - Assert.assertEquals(1, urlsAllPattern.size()); - } - - /** - * Test de recherche de resource dans le classpath (dossier hors jar). - * - * @throws Exception - */ - @Test - public void testGetResourcesFileSystemClassPath() throws Exception { - List<URL> urls = Resource.getResources("META-INF/services/.*apache.commons.*"); - // resources, test resources - Assert.assertEquals("Should have 2 urls but had: " + urls, 2, urls.size()); - } - - /** - * Test de recherche de resource dans le classpath (dossier hors jar) en - * utiliant le classloader de test. - * - * @throws Exception - */ - @Test - public void testGetTestResourcesClassPath() throws Exception { - - assumeNotUnderWindows(getClass(), testName); - - URL url1; - URL url2; - url1 = getClass().getResource("/org/nuiton/util/fileUtilData.txt"); - url2 = getClass().getResource("/org/nuiton/util/reverseread.txt"); - - List<URL> urls = Resource.getResources("org/nuiton/util/.*\\.txt"); - // there is at least two such files : fileUtilData.txt and - // reverseread.txt - Assert.assertTrue(urls.size() >= 2); - Assert.assertTrue(urls.contains(url1)); - Assert.assertTrue(urls.contains(url2)); - - urls = Resource.getResources("org/nuiton/util/.*\\.txt", ResourceTest.class.getClassLoader()); - - url1 = ResourceTest.class.getClassLoader().getResource("org/nuiton/util/fileUtilData.txt"); - url2 = ResourceTest.class.getClassLoader().getResource("org/nuiton/util/reverseread.txt"); - - // there is at least two such files : fileUtilData.txt and - // reverseread.txt - Assert.assertTrue(urls.size() >= 2); - Assert.assertTrue(urls.contains(url1)); - Assert.assertTrue(urls.contains(url2)); - } - - protected String getJavaExecName() { - String result; - if (SystemUtils.IS_OS_WINDOWS) { - result = "java.exe"; - } else { - result = "java"; - } - return result; - } - - @Rule - public final TestName testName = new TestName(); - - public static void assumeNotUnderWindows(Class<?> testClass, TestName testName) { - if (SystemUtils.IS_OS_WINDOWS) { - log.warn("This test " + testClass.getName() + "#" + testName.getMethodName() + - " is still not compatible with windows OS"); - Assume.assumeTrue(false); - } - } -} // ResourceTest diff --git a/src/test/java/org/nuiton/util/ReverseFileReaderTest.java b/src/test/java/org/nuiton/util/ReverseFileReaderTest.java deleted file mode 100644 index 1ab31dc..0000000 --- a/src/test/java/org/nuiton/util/ReverseFileReaderTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; -import java.net.URL; - -/** - * Test for reverse reader utility. - * - * @author chatellier - */ -public class ReverseFileReaderTest { - - /** - * Test to read test file in reverse order. - * - * @throws IOException - */ - @Test - public void testReverseRead() throws IOException { - URL url = ReverseFileReaderTest.class.getResource("reverseread.txt"); - String reverseFile = url.getFile(); - ReverseFileReader reader = new ReverseFileReader(reverseFile); - - String lastRead = reader.readLine(); - Assert.assertEquals("Line 4", lastRead); - - lastRead = reader.readLine(); - Assert.assertEquals("Line 3", lastRead); - - lastRead = reader.readLine(); - Assert.assertEquals("Line 2", lastRead); - - reader.close(); - } -} diff --git a/src/test/java/org/nuiton/util/SemVerTest.java b/src/test/java/org/nuiton/util/SemVerTest.java deleted file mode 100644 index 112f44b..0000000 --- a/src/test/java/org/nuiton/util/SemVerTest.java +++ /dev/null @@ -1,231 +0,0 @@ -package org.nuiton.util; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Test; - -import java.util.Arrays; - -/** - * @author Benjamin Poussin - poussin@codelutin.com - * @deprecated since 3.0 (use now {@link org.nuiton.util.version.SemVerTest}. - */ -@Deprecated -public class SemVerTest { - - /** - * Logger. - */ - static private Log log = LogFactory.getLog(SemVerTest.class); - - /** - * Liste de toutes les versions a tester, de la plus petite a la plus grande - */ - String[] versions = { - "0", - "0.0.0-SNAPSHOT", - "0.0.0", - "1.0.0-alpha-SNAPSHOT", - "1.0.0-alpha", - "1.0.0-alpha.1", - "1.0.0-beta.2 ", - " 1.0.0-beta.11 ", - " 1.0.0-rc.1 ", - " 1.0.0-rc.1+build.1-SNAPSHOT ", - " 1.0.0-rc.1+build.1 ", - " 1.0.0 ", - " 1.0.0+0.3.7 ", - " 1.0.0.23 ", - " 1.3.7+build ", - " 1.3.7+build.2.b8f12d7 ", - " 1.3.7+build.11.e0f985a", - "99.100-20130127+r123", - }; - - // on doit avoir ici les memes entrees que versions dans le meme ordre - String[][] versionSplits = { - {"0", null, null, null}, - {"0.0.0", null, null, "SNAPSHOT"}, - {"0.0.0", null, null, null}, - {"1.0.0", "alpha", null, "SNAPSHOT"}, - {"1.0.0", "alpha", null, null}, - {"1.0.0", "alpha.1", null, null}, - {"1.0.0", "beta.2", null, null}, - {"1.0.0", "beta.11", null, null}, - {"1.0.0", "rc.1", null, null}, - {"1.0.0", "rc.1", "build.1", "SNAPSHOT"}, - {"1.0.0", "rc.1", "build.1", null}, - {"1.0.0", null, null, null}, - {"1.0.0", null, "0.3.7", null}, - {"1.0.0.23", null, null, null}, - {"1.3.7", null, "build", null}, - {"1.3.7", null, "build.2.b8f12d7", null}, - {"1.3.7", null, "build.11.e0f985a", null}, - {"99.100", "20130127", "r123", null}, - }; - - @Test - public void testCreation() { - for (int i = 0; i < versions.length; i++) { - SemVer v = new SemVer(versions[i]); - SemVer vs = SemVer.creator(versionSplits[i]).done(); - Assert.assertEquals(v, vs); - - Assert.assertEquals(versionSplits[i][0], v.getVersion()); - Assert.assertEquals(versionSplits[i][1], v.getPrerelease()); - Assert.assertEquals(versionSplits[i][2], v.getBuild()); - Assert.assertEquals(versionSplits[i][3], v.getSnapshot()); - } - } - - @Test - public void testCreator() { - SemVer v = new SemVer(" 1.0.0-rc.1+build.1-SNAPSHOT "); - SemVer n = SemVer.creator(v).setVersion(1, 1, 3).setPrerelease("rc.2").setBuild("r123").setSnapshot(false).done(); - Assert.assertEquals("1.1.3-rc.2+r123", n.toString()); - } - - @Test - public void testInc() { - - String[][] testIncValue = { - {"0", "1"}, - {"0.0.0-SNAPSHOT", "1.0.0-SNAPSHOT", "0.1.0-SNAPSHOT", "0.0.1-SNAPSHOT"}, - {"0.0.0", "1.0.0", "0.1.0", "0.0.1"}, - {"1.0.0-alpha-SNAPSHOT", "2.0.0-alpha-SNAPSHOT", "1.1.0-alpha-SNAPSHOT", "1.0.1-alpha-SNAPSHOT"}, - {"1.0.0-alpha", "2.0.0-alpha", "1.1.0-alpha", "1.0.1-alpha"}, - {"1.0.0-alpha.1", "2.0.0-alpha.1", "1.1.0-alpha.1", "1.0.1-alpha.1"}, - {" 1.0.0.23 ", " 2.0.0.23 ", " 1.1.0.23 ", " 1.0.1.23 ", " 1.0.0.24 "}, - {"99.100-20130127+r123", "100.100-20130127+r123", "99.101-20130127+r123"}, - }; - - for (int i = 1; i < testIncValue.length; i++) { - SemVer version = new SemVer(testIncValue[i][0]); - Assert.assertEquals(String.format( - "Le nombre de composante doit correspondre au nombre de test a faire %s", - Arrays.toString(testIncValue[i])), - testIncValue[i].length - 1, version.getVersionCount()); - for (int x = 1; x < testIncValue[i].length; x++) { - SemVer expected = new SemVer(testIncValue[i][x]); - SemVer inc = SemVer.creator(version).incVersion(x - 1, 1).done(); - Assert.assertEquals(expected, inc); - } - } - } - - @Test - public void testIncMajorMinorPatch() { - // on test seulement sur un exemple, les autres cas sont gere par le testInc - SemVer version = new SemVer(" 1.0.0.23 "); - - SemVer incMajor = SemVer.creator(version).incMajor().done(); - Assert.assertEquals(new SemVer(" 2.0.0.23 "), incMajor); - - SemVer incMinor = SemVer.creator(version).incMinor().done(); - Assert.assertEquals(new SemVer(" 1.1.0.23 "), incMinor); - - SemVer incPatch = SemVer.creator(version).incPatch().done(); - Assert.assertEquals(new SemVer(" 1.0.1.23 "), incPatch); - } - - @Test - public void testGetComposant() { - SemVer v = new SemVer(" 1.0.3-rc.1+build.1-SNAPSHOT "); - Assert.assertEquals("1", v.getMajor()); - Assert.assertEquals("0", v.getMinor()); - Assert.assertEquals("3", v.getPatch()); - - Assert.assertEquals("rc", v.getPrerelease(0)); - Assert.assertEquals("1", v.getPrerelease(1)); - - Assert.assertEquals("build", v.getBuild(0)); - Assert.assertEquals("1", v.getBuild(1)); - - Assert.assertEquals("SNAPSHOT", v.getSnapshot()); - - } - - @Test - public void testToJavaIdentifier() { - SemVer v = new SemVer(" 1.0.3-rc.1+build.1-SNAPSHOT "); - Assert.assertEquals("1_0_3_rc_1_build_1_SNAPSHOT", v.toJavaIdentifier()); - } - - /** - * Ce test ne sert pas vraiment en temps normale, mais lorsqu'il y a un - * test qui fail dans testAll, il est pratique de remettre le test qui - * echoue plus specifiquement ici pour le debug - */ - @Test - public void testOne() { - SemVer vi = new SemVer(" 1.0.0+0.3.7 "); - SemVer vj = new SemVer(" 1.0.0.23 "); - - int result = normalize(vi.compareTo(vj)); - int expected = -1; - - Assert.assertTrue(String.format( - "Bad compare: Compare(%s, %s) = %s, expected %s", - vi, vj, result, expected), - expected == result); -// System.out.println(String.format( -// "Good compare: Compare(%s, %s) = %s, expected %s", -// vi, vj, result, expected)); - } - - @Test - public void testAll() { - for (int i = 0; i < versions.length; i++) { - for (int j = 0; j < versions.length; j++) { - SemVer vi = new SemVer(versions[i]); - SemVer vj = new SemVer(versions[j]); - - int result = normalize(vi.compareTo(vj)); - int expected = Integer.valueOf(i).compareTo(j); // AThimel 2013/02/26 Rewritten for JDK6 compatibility. Was: Integer.compare(i, j); - - Assert.assertTrue(String.format( - "Bad compare: Compare(%s, %s) = %s, expected %s", - vi, vj, result, expected), - expected == result); - } - } - } - - /** - * Si le comparator ne renvoi pas -1, 0, 1 on normalize pour avoir -1, 0, 1 - * - * @param v - * @return - */ - protected int normalize(int v) { - int result = v; - if (v != 0) { - result = v / Math.abs(v); - } - return result; - } -} diff --git a/src/test/java/org/nuiton/util/StringUtilTest.java b/src/test/java/org/nuiton/util/StringUtilTest.java deleted file mode 100644 index cbf4719..0000000 --- a/src/test/java/org/nuiton/util/StringUtilTest.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/******************************************************************************* - * StringUtilTest.java - * - * Created: 7 oct. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -import org.junit.Assert; -import org.junit.Test; - -import java.awt.Color; -import java.util.Arrays; -import java.util.Locale; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class StringUtilTest { - private static final String[] EMPTY_STRING_ARRAY = new String[0]; // StringUtilTest - - @Test - public void testSubstring() throws Exception { - String s = "Bonjour le monde"; - String r = StringUtil.substring(s, -5); - assertEquals("monde", r); - - r = StringUtil.substring(s, 7, -5); - assertEquals(" le ", r); - - r = StringUtil.substring(s, 0, s.length()); - assertEquals(s, r); - - r = StringUtil.substring(s, -5, s.length()); - assertEquals("monde", r); - - r = StringUtil.substring("a", 1, -1); - assertEquals("", r); - - r = StringUtil.substring("", 0, -1); - assertEquals("", r); - - } - - @Test - public void testToColor() throws Exception { - Color c; - - c = StringUtil.toColor("#FF55AA"); - assertEquals(c, new Color(255, 85, 170)); - - c = StringUtil.toColor("#FF55AA55"); - assertEquals(c, new Color(255, 85, 170, 85)); - - try { - c = null; - c = StringUtil.toColor("toto"); - assertFalse(true); - } catch (StringUtilException eee) { - assertNull(c); - } - - try { - c = null; - c = StringUtil.toColor("#ZRETJ4040R"); - assertFalse(true); - } catch (StringUtilException eee) { - assertNull(c); - } - } - - @Test - public void testSplit() { - assertTrue(Arrays.equals(StringUtil.split("'toto',titi,tutu"), new String[]{"'toto'", "titi", "tutu"})); - assertTrue(Arrays.equals(StringUtil.split("toto"), new String[]{"toto"})); - assertTrue(Arrays.equals(StringUtil.split(""), EMPTY_STRING_ARRAY)); - assertTrue(Arrays.equals(StringUtil.split(null), EMPTY_STRING_ARRAY)); - - String argTest = "toto, titi, titi($tru('roer'), erke), \"t|u(t{u\\\"ti[ti'\", fin"; - String[] arg = StringUtil.split(argTest); - assertEquals(5, arg.length); - - argTest = ""; - arg = StringUtil.split(argTest); - assertEquals(0, arg.length); - - argTest = "tptp"; - arg = StringUtil.split(argTest); - assertEquals(1, arg.length); - - argTest = ",ooo|ooo|o|,ooo'ooo(',ooo-"; - arg = StringUtil.split(argTest, "ooo"); - assertEquals(5, arg.length); - - argTest = "1,2,\"3,3\",\"4,4,4\",5"; - arg = StringUtil.split(argTest, ","); - assertEquals(5, arg.length); - - } - - @Test - public void testConvert() throws Exception { - assertEquals("365d", StringUtil.convertTime(31536000000000000L)); - assertEquals("2d", StringUtil.convertTime(172800000000000L)); - assertEquals("2h", StringUtil.convertTime(7200000000000L)); - assertEquals("2m", StringUtil.convertTime(120000000000L)); - - assertEquals("2s", StringUtil.convertTime(2000000002L)); - assertEquals("2s", StringUtil.convertTime(2000000000L)); - assertEquals("2ms", StringUtil.convertTime(2000000L)); - assertEquals("2ns", StringUtil.convertTime(2L)); - assertEquals("0ns", StringUtil.convertTime(0L)); - - assertEquals("0o", StringUtil.convertMemory(0L)); - assertEquals("2o", StringUtil.convertMemory(2L)); - assertEquals("2Ko", StringUtil.convertMemory(2048L)); - assertEquals("2Mo", StringUtil.convertMemory(2097152L)); - assertEquals("2Mo", StringUtil.convertMemory(2097154L)); - - assertEquals("2Go", StringUtil.convertMemory(2147483648L)); - assertEquals("2To", StringUtil.convertMemory(2199023255552L)); - assertEquals("2000To", StringUtil.convertMemory(2199023255552000L)); - - assertEquals("-2Mo", StringUtil.convertMemory(-2097152L)); - assertEquals("-2Mo", StringUtil.convertMemory(-2097154L)); - - Locale oldLocale = Locale.getDefault(); - // test in french locale - Locale.setDefault(Locale.FRENCH); - assertEquals("2,02s", StringUtil.convertTime(2020000002L)); - assertEquals("2,094Mo", StringUtil.convertMemory(2196152L)); - assertEquals("-2,094Mo", StringUtil.convertMemory(-2196152L)); - - // test in english locale - Locale.setDefault(Locale.ENGLISH); - assertEquals("2.02s", StringUtil.convertTime(2020000002L)); - assertEquals("2.094Mo", StringUtil.convertMemory(2196152L)); - assertEquals("-2.094Mo", StringUtil.convertMemory(-2196152L)); - - // push back previous locale - Locale.setDefault(oldLocale); - } - - @Test - public void testConvertToConstantName() throws Exception { - assertEquals("YES", StringUtil.convertToConstantName("yes")); - assertEquals("YES", StringUtil.convertToConstantName("*$$?YEs")); - assertEquals("YES", StringUtil.convertToConstantName("_yes!$*_")); - assertEquals("YES", StringUtil.convertToConstantName("_Yes____")); - - assertEquals("YES_OR_NO", StringUtil.convertToConstantName("__yesOrNo_")); - assertEquals("YES_OR_NO", StringUtil.convertToConstantName("Yes-or-!*=No")); - assertEquals("YES_OR_NO", StringUtil.convertToConstantName("_yes__or__no")); - assertEquals("YES_OR_NO", StringUtil.convertToConstantName("_YesOR___No")); - - } - - @Test - public void testEncodeMD5() throws Exception { - assertEquals("9c4fddff843d03cefe44421acf22c6ec", StringUtil.encodeMD5("natcho")); - } - - /** - * Test que le hash sha1 d'une chaine est celui attendu. - */ - @Test - public void testEncodeSHA1() { - assertEquals("36fde5ec018f636fdb246986ed2eaa2d64dc6b10", StringUtil.encodeSHA1("Test encodage sha1")); - assertEquals("639d6aeefd0e3c347e23408b0b47bdd7b928b78f", - StringUtil.encodeSHA1("Cela ressemblait aux gros ordinateurs que David avait pu voir dans des films de science fiction.")); - assertEquals("53776c1a117089016498c1162db30265baaac558", - StringUtil.encodeSHA1("Cela ressemblait aux gros ordinateurs que david avait pu voir dans des films de science fiction.")); - } - - @Test - public void testIsEmail() { - assertFalse(StringUtil.isEmail("abc.def+ghimonte.st")); - assertFalse(StringUtil.isEmail("abc.def+ghimonte.st")); - assertTrue(StringUtil.isEmail("a@monte.st")); - assertTrue(StringUtil.isEmail("a@monte.st".toUpperCase())); - assertTrue(StringUtil.isEmail("abc.def+ghi@monte.st")); - assertTrue(StringUtil.isEmail("abc.def+ghi@monte.st".toUpperCase())); - assertTrue(StringUtil.isEmail("aBc.def+ghi@monte.st")); - assertTrue(StringUtil.isEmail("aBC.def+ghi@monte.st")); - assertTrue(StringUtil.isEmail("ABC.def+ghi@monte.st")); - assertTrue(StringUtil.isEmail("ABC.Def+ghi@monte.st")); - assertTrue(StringUtil.isEmail("ABC.DEf+ghi@monte.st")); - assertTrue(StringUtil.isEmail("ABC.DEF+ghi@monte.st")); - assertTrue(StringUtil.isEmail("ABC.DEF+Ghi@monte.st")); - assertTrue(StringUtil.isEmail("ABC.DEF+GHi@monte.st")); - assertTrue(StringUtil.isEmail("ABC.DEF+GHI@monte.st")); - assertTrue(StringUtil.isEmail("ABC.DEF+GHI@Monte.st")); - assertTrue(StringUtil.isEmail("ABC.DEF+GHI@MOnte.st")); - assertTrue(StringUtil.isEmail("ABC.DEF+GHI@MONte.st")); - assertTrue(StringUtil.isEmail("ABC.DEF+GHI@MONTe.st")); - assertTrue(StringUtil.isEmail("ABC.DEF+GHI@MONTE.st")); - assertTrue(StringUtil.isEmail("ABC.DEF+GHI@MONTE.St")); - assertTrue(StringUtil.isEmail("ABC.DEF+GHI@MONTE.ST")); - assertTrue(StringUtil.isEmail("ABC.DEF+GHI@MONTE.STT")); - assertTrue(StringUtil.isEmail("abC.Def+Ghi@Monte.st")); - assertTrue(StringUtil.isEmail("abC.Def+Ghi@MOnte.st")); - assertTrue(StringUtil.isEmail("abC.Def+Ghi@Monte.St")); - assertTrue(StringUtil.isEmail("abC.Def+Ghi@Monte.SSt")); - assertTrue(StringUtil.isEmail("abC.Def+Ghi@Monte.SST")); - } - - /** - * Test les cas d'échapement des caracteres speciaux csv. - */ - @Test - public void testEscapeCsvValue() { - Assert.assertEquals("allo ?", StringUtil.escapeCsvValue("allo ?", ";")); - Assert.assertEquals("\"action;réaction\"", StringUtil.escapeCsvValue("action;réaction", ";")); - Assert.assertEquals("\"cause, effet\"", StringUtil.escapeCsvValue("cause, effet", ";")); - Assert.assertEquals("\"tee|/dev/null\"", StringUtil.escapeCsvValue("tee|/dev/null", "|")); - Assert.assertEquals("\"\"\"Amazing\"\" spiderman\"", StringUtil.escapeCsvValue("\"Amazing\" spiderman", ";")); - } -} // StringUtilTest - diff --git a/src/test/java/org/nuiton/util/TransparenteReferenceTest.java b/src/test/java/org/nuiton/util/TransparenteReferenceTest.java deleted file mode 100644 index df2d8cc..0000000 --- a/src/test/java/org/nuiton/util/TransparenteReferenceTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import junit.framework.TestCase; - -import java.util.HashMap; -import java.util.Map; - - -/** - * Created: 22 mai 2006 15:41:49 - * - * @author Benjamin Poussin - poussin@codelutin.com - */ -public class TransparenteReferenceTest extends TestCase { - - public void testHash() { - Map<TransparenteSoftReference<?>, TransparenteSoftReference<?>> map = new HashMap<TransparenteSoftReference<?>, TransparenteSoftReference<?>>(); - - String key = "key"; - TransparenteSoftReference<?> keyRef = new TransparenteSoftReference<String>(key); - - String value = "value"; - TransparenteSoftReference<?> valueRef = new TransparenteSoftReference<String>(value); - - map.put(keyRef, valueRef); - - - assertEquals(valueRef, map.get(keyRef)); - assertEquals(valueRef.get(), map.get(keyRef).get()); - key = null; - value = null; - - System.gc(); - Thread.yield(); - - assertEquals("value".hashCode(), map.get(keyRef).hashCode()); - } -} - - diff --git a/src/test/java/org/nuiton/util/VersionTest.java b/src/test/java/org/nuiton/util/VersionTest.java deleted file mode 100644 index cb6f3a1..0000000 --- a/src/test/java/org/nuiton/util/VersionTest.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.nuiton.util.VersionUtilTest.VERSIONS; -import static org.nuiton.util.VersionUtilTest.compareVersions; - -/** - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.1.0 - * @deprecated since 3.0 (use now {@link org.nuiton.util.version.VersionTest}). - */ -@Deprecated -public class VersionTest { - - /** - * Test of hasClassifier method, of class Version. - */ - @Test - public void testHasClassifier() { - Version instance = new Version(); - boolean expResult = false; - boolean result = instance.hasClassifier(); - assertEquals(expResult, result); - instance = new Version("yo", 1); - expResult = true; - result = instance.hasClassifier(); - assertEquals(expResult, result); - } - - /** - * Test of getValidName method, of class Version. - */ - @Test - public void testGetValidName() { - - getValidName("0", Version.VZERO, new Version(), new Version(0), new Version("0")); - getValidName("1", new Version(1), new Version("1")); - getValidName("1_1", new Version(1, 1), new Version("1.1")); - getValidName("1_1_alpha_1", new Version("alpha", 1, 1, 1), new Version("ALPHA", 1, 1, 1)); - getValidName("1_1_beta_1", new Version("BETA", 1, 1, 1), new Version("beta", 1, 1, 1)); - getValidName("2_1_rc_1", new Version("rC", 1, 2, 1), new Version("Rc", 1, 2, 1)); - } - - /** - * Test of getVersion method, of class Version. - */ - @Test - public void testGetVersion() { - - getVersion("0", Version.VZERO, new Version(), new Version(0), new Version("0")); - getVersion("1", new Version(1), new Version("1")); - getVersion("1.1", new Version(1, 1), new Version("1.1")); - getVersion("1.1-alpha-1", new Version("alpha", 1, 1, 1), new Version("ALPHA", 1, 1, 1), new Version("alPHA", 1, 1, 1)); - getVersion("1.1-beta-1", new Version("BETA", 1, 1, 1), new Version("beta", 1, 1, 1), new Version("BeTa", 1, 1, 1)); - getVersion("2.1-rc-1", new Version("rC", 1, 2, 1), new Version("Rc", 1, 2, 1)); - } - - /** - * Test of compareTo method, of class Version. - */ - @Test - public void testCompareTo() { - - // ------- - // o1 = o2 - // ------- - - compareVersions(0, Arrays.asList(Version.VZERO, new Version(), new Version(0), new Version("0"))); - compareVersions(0, Arrays.asList(new Version(1), new Version("1"))); - compareVersions(0, Arrays.asList(new Version(1, 1), new Version("1.1"))); - compareVersions(0, Arrays.asList(new Version("alpha", 1, 1, 1), new Version("ALPHA", 1, 1, 1))); - compareVersions(0, Arrays.asList(new Version("BETA", 1, 1, 1), new Version("beta", 1, 1, 1))); - compareVersions(0, Arrays.asList(new Version("rC", 1, 2, 1), new Version("Rc", 1, 2, 1))); - - - // ------- - // o1 > o2 - // ------- - - List<Version> sortedVersions = new ArrayList<Version>(VERSIONS); - - Collections.sort(sortedVersions); - - assertEquals(VERSIONS, sortedVersions); - - compareVersions(-1, sortedVersions); - - // ------- - // o1 < o2 - // ------- - - List<Version> reversedVersions = new ArrayList<Version>(VERSIONS); - Collections.reverse(reversedVersions); - Collections.reverse(sortedVersions); - - assertEquals(sortedVersions, reversedVersions); - - compareVersions(1, reversedVersions); - - } - - /** - * Test of equals method, of class Version. - */ - @Test - public void testEquals() { - - compareVersions(0, Arrays.asList(new Version(1), new Version("1"))); - compareVersions(0, Arrays.asList(new Version(1, 1), new Version("1.1"))); - compareVersions(0, Arrays.asList(new Version("alpha", 1, 1, 1), new Version("AlpHa", 1, 1, 1), new Version("ALPHA", 1, 1, 1))); - compareVersions(0, Arrays.asList(new Version("BETA", 1, 1, 1), new Version("beta", 1, 1, 1), new Version("BEtA", 1, 1, 1))); - compareVersions(0, Arrays.asList(new Version("rC", 1, 2, 1), new Version("Rc", 1, 2, 1))); - } - - protected void getValidName(String expected, Version... versions) { - for (Version v : versions) { - assertEquals(expected, v.getValidName()); - } - } - - protected void getVersion(String expected, Version... versions) { - for (Version v : versions) { - assertEquals(expected, v.getVersion()); - } - } -} diff --git a/src/test/java/org/nuiton/util/VersionUtilTest.java b/src/test/java/org/nuiton/util/VersionUtilTest.java deleted file mode 100644 index 983af76..0000000 --- a/src/test/java/org/nuiton/util/VersionUtilTest.java +++ /dev/null @@ -1,471 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Matcher; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.1.0 - * @deprecated since 3.0 (use now {@link org.nuiton.util.version.VersionTest}). - */ -@Deprecated -public class VersionUtilTest { - - /** Logger. */ - private static final Log log = LogFactory.getLog(VersionUtilTest.class); - - protected static final List<Version> VERSIONS = Collections.unmodifiableList(Arrays.asList( - new Version(), - new Version(0, 0, 1), - new Version(0, 1), - new Version(1), - new Version(1, 0), - new Version(1, 0, 0), - new Version(1, 1), - new Version("alPha", 0, 1, 1, 0), - new Version("alpHa", 1, 1, 1, 0), - new Version("alphA", 2, 1, 1, 0), - new Version("betA", 0, 1, 1, 0), - new Version("beTa", 1, 1, 1, 0), - new Version("bEta", 2, 1, 1, 0), - new Version("rc", 0, 1, 1, 0), - new Version("rC", 1, 1, 1, 0), - new Version("Rc", 2, 1, 1, 0), - new Version(1, 1, 0))); - protected static final List<Version> VERSIONS_INC = Collections.unmodifiableList(Arrays.asList( - new Version(1), - new Version(0, 0, 2), - new Version(0, 2), - new Version(2), - new Version(1, 1), - new Version(1, 0, 1), - new Version(1, 2), - new Version("alPha", 1, 1, 1, 0), - new Version("alpHa", 2, 1, 1, 0), - new Version("alphA", 3, 1, 1, 0), - new Version("betA", 1, 1, 1, 0), - new Version("beTa", 2, 1, 1, 0), - new Version("bEta", 3, 1, 1, 0), - new Version("rc", 1, 1, 1, 0), - new Version("rC", 2, 1, 1, 0), - new Version("Rc", 3, 1, 1, 0), - new Version(1, 1, 1))); - - @Test - public void testPatterns() { - - assertPattern("1-2.3.4", false); - assertPattern("1.a", false); - assertPattern("1.alpha", false); - assertPattern("1.alpha-", false); - assertPattern("1.alpha-4", false); - assertPattern("1-alpha", false); - assertPattern("1-alpha-", false); - assertPattern("1--3", false); - assertPattern("-alpha-1", false); - assertPattern("a-alpha-1", false); - assertPattern("-alpha-1-", false); - - assertPattern("1.2.3.4", true, "1.2.3.4", null, null, null); - assertPattern("1.2.3.4-SNAPSHOT", true, "1.2.3.4", null, null, "-SNAPSHOT"); - - assertPattern("1.2.3.4-alpha-1", true, "1.2.3.4", "alpha", "1", null); - assertPattern("1.2.3.4-alpha-1-SNAPSHOT", true, "1.2.3.4", "alpha", "1", "-SNAPSHOT"); - - assertPattern("1.2.3.4-classifier-9", true, "1.2.3.4", "classifier", "9", null); - assertPattern("1.2.3.4-classifier-9-SNAPSHOT", true, "1.2.3.4", "classifier", "9", "-SNAPSHOT"); - } - - @Test - public void testPatterns2() { - - assertPattern2("1-2.3.4", false); - assertPattern2("1.a", false); - assertPattern2("1.alpha", false); - assertPattern2("1.alpha-", false); - assertPattern2("1.alpha4", false); - assertPattern2("1-alpha", false); - assertPattern2("1-alpha-", false); - assertPattern2("1--3", false); - assertPattern2("-alpha1", false); - assertPattern2("a-alpha1", false); - assertPattern2("-alpha1-", false); - - assertPattern2("1.2.3.4", true, "1.2.3.4", null, null, null); - assertPattern2("1.2.3.4-SNAPSHOT", true, "1.2.3.4", null, null, "-SNAPSHOT"); - - assertPattern2("1.2.3.4-alpha1", true, "1.2.3.4", "alpha", "1", null); - assertPattern2("1.2.3.4-alpha1-SNAPSHOT", true, "1.2.3.4", "alpha", "1", "-SNAPSHOT"); - - assertPattern2("1.2.3.4-classifier9", true, "1.2.3.4", "classifier", "9", null); - assertPattern2("1.2.3.4-classifier9-SNAPSHOT", true, "1.2.3.4", "classifier", "9", "-SNAPSHOT"); - } - - /** Test of the {@link VersionUtil#DEFAULT_VERSION_COMPARATOR}. */ - @Test - public void testVersionComparotor() { - - // ------- - // o1 = o2 - // ------- - - compareVersions(0, Arrays.asList(Version.VZERO, new Version(), new Version(0), new Version("0"))); - - compareVersions(0, Arrays.asList(new Version(1), new Version("1"))); - compareVersions(0, Arrays.asList(new Version(1, 1), new Version("1.1"))); - compareVersions(0, Arrays.asList(new Version("alpha", 1, 1, 1), new Version("AlpHa", 1, 1, 1), new Version("ALPHA", 1, 1, 1))); - compareVersions(0, Arrays.asList(new Version("BETA", 1, 1, 1), new Version("beta", 1, 1, 1), new Version("BEtA", 1, 1, 1))); - compareVersions(0, Arrays.asList(new Version("rC", 1, 2, 1), new Version("Rc", 1, 2, 1))); - - // ------- - // o1 > o2 - // ------- - - List<Version> sortedVersions = new ArrayList<Version>(VERSIONS); - - Collections.sort(sortedVersions, VersionUtil.DEFAULT_VERSION_COMPARATOR); - - assertEquals(VERSIONS, sortedVersions); - - compareVersions(-1, sortedVersions); - - // ------- - // o1 < o2 - // ------- - - Collections.reverse(sortedVersions); - - compareVersions(1, sortedVersions); - - } - - @Test - public void testInc() { - int i = 0; - for (Version v : VERSIONS) { - Version incV = VERSIONS_INC.get(i++); - assertFalse(v.equals(incV)); - assertTrue(incV.compareTo(v) > 0); - assertTrue(v.compareTo(incV) < 0); - } - } - - @Test - public void testAddClassifier() { - String classifier = "test"; - Integer classifierNumber = 1; - - try { - VersionUtil.addClassifier(null, null, null); - fail(); - } catch (NullPointerException e) { - assertTrue(true); - } - try { - VersionUtil.addClassifier(Version.VZERO, null, null); - fail(); - } catch (NullPointerException e) { - assertTrue(true); - } - try { - VersionUtil.addClassifier(Version.VZERO, classifier, null); - fail(); - } catch (NullPointerException e) { - assertTrue(true); - } - - for (Version v : VERSIONS) { - - - if (v.hasClassifier()) { - // on ne peut pas ajouter un classifier si deja present - try { - VersionUtil.addClassifier(v, classifier, classifierNumber); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - continue; - } - - Version incV = VersionUtil.addClassifier(v, classifier, classifierNumber); - - assertFalse(v.equals(incV)); - - assertEquals(v.toString() + "-" + classifier + "-" + classifierNumber, incV.toString()); - - // classifier version est toujours plus ancienne - assertTrue(incV.compareTo(v) < 0); - assertTrue(v.compareTo(incV) > 0); - } - } - - @Test - public void testRemoveClassifier() { - - try { - VersionUtil.removeClassifier(null); - fail(); - } catch (NullPointerException e) { - assertTrue(true); - } - - for (Version v : VERSIONS) { - - - if (!v.hasClassifier()) { - // on ne peut pas supprimer le classifier non present - try { - VersionUtil.removeClassifier(v); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - continue; - } - - Version incV = VersionUtil.removeClassifier(v); - - assertFalse(v.equals(incV)); - - assertEquals(v.toString().substring(0, v.toString().indexOf("-")), incV.toString()); - - // classifier version est toujours plus ancienne - assertTrue(incV.compareTo(v) > 0); - assertTrue(v.compareTo(incV) < 0); - } - } - - /** Test of filterVersions method, of class VersionUtil. */ - @Test - public void testFilterVersions() { - - Set<Version> versions = new TreeSet<Version>(); - Version v1 = new Version(1); - Version v2 = new Version(2); - Version v3 = new Version(3); - Version v4 = new Version(4); - Version v5 = new Version(5); - versions.add(v1); - versions.add(v2); - versions.add(v3); - versions.add(v4); - versions.add(v5); - - List<Version> actual; - - // filter [0,0] = [] - actual = VersionUtil.filterVersions(versions, Version.VZERO, Version.VZERO, true, true); - assertVersionsEquals(actual); - - // filter [0,1[ = [] - actual = VersionUtil.filterVersions(versions, Version.VZERO, v1, true, false); - assertVersionsEquals(actual); - - // filter [0,1] = [1] - actual = VersionUtil.filterVersions(versions, Version.VZERO, v1, true, true); - assertVersionsEquals(actual, v1); - - // filter [0,2[ = [1] - actual = VersionUtil.filterVersions(versions, Version.VZERO, v2, true, false); - assertVersionsEquals(actual, v1); - - // filter [0,2] = [1,2] - actual = VersionUtil.filterVersions(versions, Version.VZERO, v2, true, true); - assertVersionsEquals(actual, v1, v2); - - // filter [1,2] = [1,2] - actual = VersionUtil.filterVersions(versions, v1, v2, true, true); - assertVersionsEquals(actual, v1, v2); - - // filter ]1,2] = [2] - actual = VersionUtil.filterVersions(versions, v1, v2, false, true); - assertVersionsEquals(actual, v2); - - // filter [2,2] = [2] - actual = VersionUtil.filterVersions(versions, v2, v2, true, true); - assertVersionsEquals(actual, v2); - - // filter ]2,2] = [2] - actual = VersionUtil.filterVersions(versions, v2, v2, false, true); - assertVersionsEquals(actual); - - // filter ]2,2[ = [] - actual = VersionUtil.filterVersions(versions, v2, v2, false, false); - assertVersionsEquals(actual); - - // filter ]Null,2[ = [1] - actual = VersionUtil.filterVersions(versions, null, v2, false, false); - assertVersionsEquals(actual, v1); - - // filter [Null,2[ = [1] - actual = VersionUtil.filterVersions(versions, null, v2, true, false); - assertVersionsEquals(actual, v1); - - // filter ]Null,2] = [1,2] - actual = VersionUtil.filterVersions(versions, null, v2, false, true); - assertVersionsEquals(actual, v1, v2); - - // filter ]Null,Null[ = [1,2,3,4,5] - actual = VersionUtil.filterVersions(versions, null, null, false, false); - assertVersionsEquals(actual, v1, v2, v3, v4, v5); - - // filter ]2,Null[ = [3,4,5] - actual = VersionUtil.filterVersions(versions, v2, null, false, false); - assertVersionsEquals(actual, v3, v4, v5); - - // filter [2,Null[ = [2,3,4,5] - actual = VersionUtil.filterVersions(versions, v2, null, true, false); - assertVersionsEquals(actual, v2, v3, v4, v5); - } - - @Test - public void testSnapshot() { - Version v = VersionUtil.valueOf("1"); - Assert.assertFalse(v.isSnapshot()); - - Version v2 = VersionUtil.addSnapshot(v); - Assert.assertTrue(v2.isSnapshot()); - - Assert.assertTrue(v2.before(v)); - - Version v3 = VersionUtil.removeSnapshot(v2); - Assert.assertFalse(v3.isSnapshot()); - - Version v4 = VersionUtil.addClassifier(v2, "a", 1); - - Assert.assertTrue(v4.isSnapshot()); - Assert.assertTrue(v4.before(v2)); - } - - @Test - public void testAnomalie1629() { - Version v1 = VersionUtil.valueOf("1-beta1"); - Version v2 = VersionUtil.valueOf("1-beta-1"); - Assert.assertEquals(v1, v2); - Assert.assertFalse(v1.toString().equals(v2.toString())); - v1.setClassifierNumberAttached(false); - Assert.assertEquals(v1, v2); - Assert.assertEquals(v1.toString(), v2.toString()); - - } - - protected static void compareVersions(int order, Iterable<Version> versions) { - - Iterator<Version> iterator = versions.iterator(); - - Version previous = iterator.next(); - - while (iterator.hasNext()) { - Version current = iterator.next(); - - int result = previous.compareTo(current); - int result2 = current.compareTo(previous); - - assertTrue(order != 0 || result == 0); - assertTrue(order != 0 || result2 == 0); - if (order != 0) { - assertTrue("not good order : required = " + order + " but find " + result + " between " + previous + " and " + current, order * result > 0); - assertTrue("not good order : required = " + -order + " but find " + result2 + " between " + current + " and " + previous, order * result2 < 0); - if (order > 0) { - assertTrue(current.before(previous)); - } else { - assertTrue(current.after(previous)); - } - } - - previous = current; - } - } - - protected void assertPattern(String t, boolean match, String... groups) { - if (log.isDebugEnabled()) { - log.debug("convert " + t + ", mustMatch : " + match); - } - Matcher m = VersionUtil.VERSION_PATTERN.matcher(t); - - assertEquals(match, m.matches()); - - if (match) { - assertEquals(groups.length, m.groupCount()); - for (int i = 1; i <= m.groupCount(); i++) { - String group = m.group(i); - assertEquals(groups[i - 1], group); - if (group != null) { - if (log.isDebugEnabled()) { - log.debug("group " + i + " : " + group); - } - } - } - } - } - - protected void assertPattern2(String t, boolean match, String... groups) { - if (log.isDebugEnabled()) { - log.debug("convert " + t + ", mustMatch : " + match); - } - Matcher m = VersionUtil.VERSION_PATTERN2.matcher(t); - - assertEquals(match, m.matches()); - - if (match) { - assertEquals(groups.length, m.groupCount()); - for (int i = 1; i <= m.groupCount(); i++) { - String group = m.group(i); - assertEquals(groups[i - 1], group); - if (group != null) { - if (log.isDebugEnabled()) { - log.debug("group " + i + " : " + group); - } - } - } - } - } - - private void assertVersionsEquals(List<Version> actual, Version... expected) { - assertEquals(expected.length, actual.size()); - int i = 0; - for (Version a : actual) { - Version e = expected[i++]; - assertEquals(a, e); - } - } -} diff --git a/src/test/java/org/nuiton/util/ZipUtilTest.java b/src/test/java/org/nuiton/util/ZipUtilTest.java deleted file mode 100644 index 999d5ad..0000000 --- a/src/test/java/org/nuiton/util/ZipUtilTest.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.net.URL; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -/** - * Created: 24 août 2006 10:47:21 - * - * @author Benjamin Poussin - poussin@codelutin.com - */ -public class ZipUtilTest { - - /** - * Logger. - */ - private static Log log = LogFactory.getLog(ZipUtilTest.class); - - protected static final File DIR = new File(System.getProperty("java.home"), - "bin"); - - protected static File testWorkDir; - - protected static File testResourcesDir; - - @BeforeClass - public static void initTest() throws IOException { - // get maven env basedir - String basedir = System.getenv("basedir"); - if (basedir == null) { - - // says basedir is where we start tests. - basedir = new File("").getAbsolutePath(); - } - File basedirFile = new File(basedir); - testWorkDir = new File(basedirFile, - "target" + File.separator + - "surefire-workdir"); - - boolean b = testWorkDir.exists() || testWorkDir.mkdirs(); - if (!b) { - throw new IOException( - "Could not create workdir directory " + testWorkDir); - } - - testResourcesDir = new File(basedirFile, - "src" + File.separator + - "test" + File.separator + - "resources" + File.separator + - "zip"); - } - - protected File createTempFile(String prefix, String suffix) throws IOException { - File file = File.createTempFile(prefix, suffix, testWorkDir); - return file; - } - - protected File createTempDirectory(String prefix, String suffix) throws IOException { - File file = FileUtil.createTempDirectory(prefix, suffix, testWorkDir); - return file; - } - - @Test - public void testUncompress() throws IOException { - //File dir = new File(System.getProperty("user.dir")); - File zipFile = createTempFile("testCompressZip", ".zip"); - zipFile.deleteOnExit(); - log.info("Compress " + DIR + " in zip file = " + zipFile); - - ZipUtil.compress(zipFile, DIR, null); - - File ucz = createTempDirectory("testUncompressZip", ""); - log.info("uncompress zip " + zipFile + " in " + ucz); - - ZipUtil.uncompress(zipFile, ucz); - - List<File> src = FileUtil.getFilteredElements(DIR, null, true); - List<File> dest = FileUtil.getFilteredElements(ucz, null, true); - - // +1 car il y a le rep lui meme dans dest - Assert.assertEquals(src.size() + 1, dest.size()); - - // remove created temp dirs : - FileUtils.deleteDirectory(ucz); - Assert.assertFalse(ucz.isDirectory()); - } - - /* - * Test method for 'org.nuiton.util.ZipUtil.compress(File, File, FileFilter)' - */ - - @Test - public void testCompress() throws IOException { - //File dir = new File(System.getProperty("user.dir")); - File zipFile = createTempFile("testCompressZip", ".zip"); - zipFile.deleteOnExit(); - log.info("Compress " + DIR + " in zip file = " + zipFile); - - ZipUtil.compress(zipFile, DIR, null); - - Assert.assertTrue(zipFile.exists()); - Assert.assertTrue(0 != zipFile.length()); - } - - @Test - public void testCompressFilter() throws IOException { - //File dir = new File(System.getProperty("user.dir")); - File zipFile = createTempFile("testCompressZip", ".zip"); - zipFile.deleteOnExit(); - log.info("Compress " + DIR + " in zip file = " + zipFile); - - FileFilter filter = new FileFilter() { - public boolean accept(File pathname) { - boolean result; - result = !pathname.getPath().contains("/target"); - return result; - } - - }; - - ZipUtil.compress(zipFile, DIR, filter); - - Assert.assertTrue(zipFile.exists()); - Assert.assertTrue(0 != zipFile.length()); - } - - @Test - public void testCompressFile() throws IOException { - File dir = new File(DIR, "java"); -// File dir = new File(System.getProperty("java.home"), "bin" -// + File.separator + "java"); - File zipFile = createTempFile("testCompressZip", ".zip"); - zipFile.deleteOnExit(); - log.info("Compress " + dir + " in zip file = " + zipFile); - - ZipUtil.compress(zipFile, dir, null); - - Assert.assertTrue(zipFile.exists()); - Assert.assertTrue(0 != zipFile.length()); - } - - @Test - public void testCompressFileMD5() throws IOException { - File dir = new File(DIR, "java"); - File zipFile = createTempFile("testCompressZip", ".zip"); - zipFile.deleteOnExit(); - log.info("Compress " + dir + " in zip file = " + zipFile); - - Collection<File> files = Collections.singleton(dir); - ZipUtil.compressFiles(zipFile, dir, files, true); - - Assert.assertTrue(zipFile.exists()); - Assert.assertTrue(zipFile.length() > 0); - File md5File = new File(zipFile.getAbsoluteFile() + ".md5"); - md5File.deleteOnExit(); - Assert.assertTrue(md5File.exists()); - Assert.assertTrue(md5File.length() > 0); - } - - /** - * Test la fonction de decompression sans filtres. - * - * @throws IOException - */ - @Test - public void testUncompressFiltredWithoutFilter() throws IOException { - File archive = new File(testResourcesDir, "test-uncompress.zip"); - File dest = new File(testWorkDir, "testunzip"); - - if (log.isInfoEnabled()) { - log.info("Extracting " + archive + " to " + dest); - } - - ZipUtil.uncompressFiltred(archive, dest); - File ruleFile = new File(dest, "test-nonregression-20090203" + File.separator + "scripts" + File.separator + "RuleUtil.java"); - Assert.assertTrue(ruleFile.exists()); - } - - /** - * Test la fonction de decompression avec filtres. - * - * @throws IOException - */ - @Test - public void testUncompressFiltredWithFilter() throws IOException { - File archive = new File(testResourcesDir, "test-uncompress.zip"); - File dest = new File(testWorkDir, "testunzip2"); - String pattern = ".*/scripts/.*"; - - if (log.isInfoEnabled()) { - log.info("Extracting " + archive + " to " + dest + " without " + pattern); - } - - ZipUtil.uncompressFiltred(archive, dest, pattern); - File ruleFile = new File(dest, "test-nonregression-20090203" + File.separator + "scripts" + File.separator + "RuleUtil.java"); - Assert.assertFalse(ruleFile.exists()); - } - - @Test - public void testIsZipFile() throws Exception { - - URL resource; - File file; - boolean actual; - - // a zip - resource = getClass().getResource("/zip/this-is-a-zip.zap"); - Assert.assertNotNull(resource); - file = new File(resource.toURI()); - Assert.assertNotNull(file); - actual = ZipUtil.isZipFile(file); - Assert.assertTrue(actual); - - // a zip - resource = getClass().getResource("/zip/test-uncompress.zip"); - Assert.assertNotNull(resource); - file = new File(resource.toURI()); - Assert.assertNotNull(file); - actual = ZipUtil.isZipFile(file); - Assert.assertTrue(actual); - - // not a zip - resource = getClass().getResource("/zip/not-a-zip.zip"); - Assert.assertNotNull(resource); - file = new File(resource.toURI()); - Assert.assertNotNull(file); - actual = ZipUtil.isZipFile(file); - Assert.assertFalse(actual); - - - } -} diff --git a/src/test/java/org/nuiton/util/beans/BeanA.java b/src/test/java/org/nuiton/util/beans/BeanA.java deleted file mode 100644 index c5768ef..0000000 --- a/src/test/java/org/nuiton/util/beans/BeanA.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.beans; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; - -public class BeanA { - - public static final String PROPERTY_AA = "aa"; - - public static final String PROPERTY_A = "a"; - - public static final String PROPERTY_B = "b"; - - public static final String PROPERTY_C = "c"; - - public static final String PROPERTY_D = "d"; - - public static final String PROPERTY_E = "e"; - - public static final String PROPERTY_F = "f"; - - protected String aa, a, b, c, d; - - protected int e, f; - - protected PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - public void setAa(String aa) { - this.aa = aa; - } - - public String getA() { - return a; - } - - public void setA(String a) { - Object oldValue = this.a; - this.a = a; - firePropertyChange(PROPERTY_A, oldValue, a); - } - - public String getB() { - return b; - } - - public void setB(String b) { - Object oldValue = this.b; - this.b = b; - firePropertyChange(PROPERTY_B, oldValue, b); - } - - public String getC() { - return c; - } - - public void setC(String c) { - Object oldValue = this.c; - this.c = c; - firePropertyChange(PROPERTY_C, oldValue, c); - } - - public String getD() { - return d; - } - - public void setD(String d) { - Object oldValue = this.d; - this.d = d; - firePropertyChange(PROPERTY_D, oldValue, d); - } - - public int getE() { - return e; - } - - public void setE(int e) { - Object oldValue = this.e; - this.e = e; - firePropertyChange(PROPERTY_E, oldValue, e); - } - - public int getF() { - return f; - } - - public void setF(int f) { - Object oldValue = this.f; - this.f = f; - firePropertyChange(PROPERTY_F, oldValue, f); - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - public void addPropertyChangeListener(String propertyName, - PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - public void removePropertyChangeListener(String propertyName, - PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - protected void firePropertyChange(String propertyName, Object oldValue, - Object newValue) { - pcs.firePropertyChange(propertyName, oldValue, newValue); - } - - protected PropertyChangeListener[] getPropertyChangeListeners() { - return pcs.getPropertyChangeListeners(); - } -} diff --git a/src/test/java/org/nuiton/util/beans/BeanAA.java b/src/test/java/org/nuiton/util/beans/BeanAA.java deleted file mode 100644 index 0e84b3c..0000000 --- a/src/test/java/org/nuiton/util/beans/BeanAA.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.beans; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; - -public class BeanAA { - - public static final String PROPERTY_AA = "aa"; - - public static final String PROPERTY_A = "a"; - - public static final String PROPERTY_B = "b"; - - public static final String PROPERTY_C = "c"; - - public static final String PROPERTY_D = "d"; - - public static final String PROPERTY_E = "e"; - - public static final String PROPERTY_F = "f"; - - protected String aa, b, c, d; - - protected int a, e, f; - - protected PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - public void setAa(String aa) { - this.aa = aa; - } - - public int getA() { - return a; - } - - public void setA(int a) { - Object oldValue = this.a; - this.a = a; - firePropertyChange(PROPERTY_A, oldValue, a); - } - - public String getB() { - return b; - } - - public void setB(String b) { - Object oldValue = this.b; - this.b = b; - firePropertyChange(PROPERTY_B, oldValue, b); - } - - public String getC() { - return c; - } - - public void setC(String c) { - Object oldValue = this.c; - this.c = c; - firePropertyChange(PROPERTY_C, oldValue, c); - } - - public String getD() { - return d; - } - - public void setD(String d) { - Object oldValue = this.d; - this.d = d; - firePropertyChange(PROPERTY_D, oldValue, d); - } - - public int getE() { - return e; - } - - public void setE(int e) { - Object oldValue = this.e; - this.e = e; - firePropertyChange(PROPERTY_E, oldValue, e); - } - - public int getF() { - return f; - } - - public void setF(int f) { - Object oldValue = this.f; - this.f = f; - firePropertyChange(PROPERTY_F, oldValue, f); - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - public void addPropertyChangeListener(String propertyName, - PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - public void removePropertyChangeListener(String propertyName, - PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - protected void firePropertyChange(String propertyName, Object oldValue, - Object newValue) { - pcs.firePropertyChange(propertyName, oldValue, newValue); - } - - protected PropertyChangeListener[] getPropertyChangeListeners() { - return pcs.getPropertyChangeListeners(); - } -} diff --git a/src/test/java/org/nuiton/util/beans/BeanB.java b/src/test/java/org/nuiton/util/beans/BeanB.java deleted file mode 100644 index 7f40c18..0000000 --- a/src/test/java/org/nuiton/util/beans/BeanB.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.beans; - -public class BeanB extends BeanA { - - public static final String PROPERTY_BB = "bb"; - - public static final String PROPERTY_A2 = "a2"; - - public static final String PROPERTY_B2 = "b2"; - - public static final String PROPERTY_C2 = "c2"; - - public static final String PROPERTY_D2 = "d2"; - - public static final String PROPERTY_E2 = "e2"; - - public static final String PROPERTY_F2 = "f2"; - - String bb; - - String a2, b2, c2, d2; - - int e2, f2; - - public String getBb() { - return bb; - } - - public String getA2() { - return a2; - } - - public void setA2(String a2) { - Object oldValue = this.a2; - this.a2 = a2; - firePropertyChange(PROPERTY_A2, oldValue, a2); - } - - public String getB2() { - return b2; - } - - public void setB2(String b2) { - Object oldValue = this.b2; - this.b2 = b2; - firePropertyChange(PROPERTY_B2, oldValue, b2); - } - - public String getC2() { - return c2; - } - - public void setC2(String c2) { - Object oldValue = this.c2; - this.c2 = c2; - firePropertyChange(PROPERTY_C2, oldValue, c2); - } - - public String getD2() { - return d2; - } - - public void setD2(String d2) { - Object oldValue = this.d2; - this.d2 = d2; - firePropertyChange(PROPERTY_D2, oldValue, d2); - } - - public int getE2() { - return e2; - } - - public void setE2(int e2) { - Object oldValue = this.e2; - this.e2 = e2; - firePropertyChange(PROPERTY_E2, oldValue, e2); - } - - public int getF2() { - return f2; - } - - public void setF2(int f2) { - Object oldValue = this.f2; - this.f2 = f2; - firePropertyChange(PROPERTY_F2, oldValue, f2); - } -} diff --git a/src/test/java/org/nuiton/util/beans/BeanC.java b/src/test/java/org/nuiton/util/beans/BeanC.java deleted file mode 100644 index 86041fe..0000000 --- a/src/test/java/org/nuiton/util/beans/BeanC.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.nuiton.util.beans; -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; - -/** - * To test http://nuiton.org/issues/2178. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.5.1 - */ -public class BeanC { - - public static final String PROPERTY_A = "a"; - - public static final String PROPERTY_AA = "aa"; - - public static final String PROPERTY_B = "b"; - - protected BeanA a; - - protected BeanAA aa; - - protected BeanB b; - - protected PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - - public BeanA getA() { - return a; - } - - public void setA(BeanA a) { - Object oldValue = this.a; - this.a = a; - firePropertyChange(PROPERTY_A, oldValue, a); - } - - public BeanAA getAa() { - return aa; - } - - public void setAa(BeanAA aa) { - Object oldValue = this.aa; - this.aa = aa; - firePropertyChange(PROPERTY_AA, oldValue, aa); - } - - public BeanB getB() { - return b; - } - - public void setB(BeanB b) { - Object oldValue = this.b; - this.b = b; - firePropertyChange(PROPERTY_B, oldValue, b); - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - public void addPropertyChangeListener(String propertyName, - PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - public void removePropertyChangeListener(String propertyName, - PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - protected void firePropertyChange(String propertyName, Object oldValue, - Object newValue) { - pcs.firePropertyChange(propertyName, oldValue, newValue); - } - - protected PropertyChangeListener[] getPropertyChangeListeners() { - return pcs.getPropertyChangeListeners(); - } -} diff --git a/src/test/java/org/nuiton/util/beans/BeanMonitorTest.java b/src/test/java/org/nuiton/util/beans/BeanMonitorTest.java deleted file mode 100644 index fc20711..0000000 --- a/src/test/java/org/nuiton/util/beans/BeanMonitorTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.beans; - -import org.junit.Assert; -import org.junit.Test; - -import java.util.Map; - -/** - * Tests {@link BeanMonitor}. - * - * @author Tony Chemit - chemit@codelutin.com - * @serial - * @since 1.4.1 - */ -public class BeanMonitorTest { - - @Test - public void testMonitor() throws Exception { - - BeanMonitor monitor = new BeanMonitor(BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_E - ); - - BeanA bean = new BeanA(); - monitor.setBean(bean); - - // nothing is monitored - assertMonitor(monitor); - - // property A was modified - bean.setA("A"); - assertMonitor(monitor, BeanA.PROPERTY_A, null); - - // clean monitor - monitor.clearModified(); - assertMonitor(monitor); - - // property A was not modified - bean.setA("A"); - assertMonitor(monitor); - - // property C is not monitored - bean.setC("C"); - assertMonitor(monitor); - - // property A was modified - bean.setA("AA"); - assertMonitor(monitor, BeanA.PROPERTY_A, "A"); - - // property A and B were modified - bean.setB("B"); - assertMonitor(monitor, - BeanA.PROPERTY_A, "A", - BeanA.PROPERTY_B, null); - - // property B is no more modified (came back to original value) - bean.setB(null); - assertMonitor(monitor, BeanA.PROPERTY_A, "A"); - - // property A and E were modified - bean.setE(1); - assertMonitor(monitor, BeanA.PROPERTY_A, "A", BeanA.PROPERTY_E, 0); - - // property A is no more modified (came back to original value) - bean.setA("A"); - assertMonitor(monitor, BeanA.PROPERTY_E, 0); - - // property E is no more modified (came back to original value) - bean.setE(0); - assertMonitor(monitor); - - // property B was modified - bean.setB("B"); - assertMonitor(monitor, BeanA.PROPERTY_B, null); - - // nothing is monitored (bean changed) - monitor.setBean(bean); - assertMonitor(monitor); - - } - - @Test - public void testMonitorAno2048() throws Exception { - - BeanMonitor monitor = new BeanMonitor(BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_E - ); - - BeanA bean = new BeanA(); - bean.setB(null); - - monitor.setBean(bean); - - // ano #2048 : no modification with two null properties - bean.setB(null); - assertMonitor(monitor); - } - - protected void assertMonitor(BeanMonitor monitor, - Object... propertyNamesAndOriginalValues) { - - if (propertyNamesAndOriginalValues.length % 2 != 0) { - throw new IllegalArgumentException( - "propertiesAndValues should be couple of (propertyName, originalValue)"); - } - String[] modifiedFields = monitor.getModifiedProperties(); - Map<String, Object> originalValues = monitor.getOriginalValues(); - - if (propertyNamesAndOriginalValues.length == 0) { - Assert.assertFalse(monitor.wasModified()); - Assert.assertEquals(0, modifiedFields.length); - } else { - Assert.assertTrue(monitor.wasModified()); - for (int i = 0; i < propertyNamesAndOriginalValues.length; i += 2) { - String propertyName = (String) propertyNamesAndOriginalValues[i]; - Object value = propertyNamesAndOriginalValues[i + 1]; - Assert.assertEquals(propertyName, modifiedFields[i / 2]); - Assert.assertEquals(value, originalValues.get(propertyName)); - } - } - } -} diff --git a/src/test/java/org/nuiton/util/beans/BeanUtilTest.java b/src/test/java/org/nuiton/util/beans/BeanUtilTest.java deleted file mode 100644 index f135816..0000000 --- a/src/test/java/org/nuiton/util/beans/BeanUtilTest.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.beans; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyDescriptor; -import java.beans.beancontext.BeanContextSupport; -import java.lang.reflect.InvocationTargetException; -import java.util.Set; - -/** - * To test the {@link BeanUtil} class. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.0 - */ -public class BeanUtilTest { - - @Test - public void isJavaBeanCompiliant() { - - boolean javaBeanCompiliant; - - javaBeanCompiliant = BeanUtil.isJavaBeanCompiliant(BeanA.class); - Assert.assertTrue(javaBeanCompiliant); - - javaBeanCompiliant = BeanUtil.isJavaBeanCompiliant(BeanB.class); - Assert.assertTrue(javaBeanCompiliant); - - javaBeanCompiliant = BeanUtil.isJavaBeanCompiliant(getClass()); - Assert.assertFalse(javaBeanCompiliant); - } - - @Test - public void getReadableProperties() { - - assertFoundReadableProperties(BeanA.class, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F); - - assertFoundReadableProperties(BeanB.class, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F, - BeanB.PROPERTY_BB, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - - assertFoundReadableProperties(getClass()); - } - - @Test - public void getDescriptors() { - - assertFoundDescriptors(BeanA.class, - BeanUtil.IS_READ_DESCRIPTOR, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F); - - assertFoundDescriptors(BeanB.class, - BeanUtil.IS_READ_DESCRIPTOR, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F, - BeanB.PROPERTY_BB, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - - assertFoundDescriptors(getClass(), BeanUtil.IS_READ_DESCRIPTOR); - - assertFoundDescriptors(BeanA.class, - BeanUtil.IS_WRITE_DESCRIPTOR, - BeanA.PROPERTY_AA, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F); - - assertFoundDescriptors(BeanB.class, - BeanUtil.IS_WRITE_DESCRIPTOR, - BeanA.PROPERTY_AA, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - - assertFoundDescriptors(getClass(), BeanUtil.IS_WRITE_DESCRIPTOR); - } - - @Test - public void getWriteableProperties() { - - assertFoundWriteableProperties(BeanA.class, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F); - - assertFoundWriteableProperties(BeanB.class, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F, - BeanB.PROPERTY_BB, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - - assertFoundWriteableProperties(getClass()); - } - - @Test - public void getNestedReadeableProperty() { - - assertFoundNestedReadableProperties(BeanA.class, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F); - - assertFoundNestedReadableProperties(BeanB.class, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F, - BeanB.PROPERTY_BB, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - - assertFoundNestedReadableProperties(BeanC.class, - BeanC.PROPERTY_A, - BeanC.PROPERTY_AA, - BeanC.PROPERTY_B, - BeanC.PROPERTY_A + "." + BeanA.PROPERTY_A, - BeanC.PROPERTY_A + "." + BeanA.PROPERTY_A, - BeanC.PROPERTY_A + "." + BeanA.PROPERTY_B, - BeanC.PROPERTY_A + "." + BeanA.PROPERTY_C, - BeanC.PROPERTY_A + "." + BeanA.PROPERTY_D, - BeanC.PROPERTY_A + "." + BeanA.PROPERTY_E, - BeanC.PROPERTY_A + "." + BeanA.PROPERTY_F, - BeanC.PROPERTY_B + "." + BeanB.PROPERTY_BB, - BeanC.PROPERTY_B + "." + BeanB.PROPERTY_A2, - BeanC.PROPERTY_B + "." + BeanB.PROPERTY_B2, - BeanC.PROPERTY_B + "." + BeanB.PROPERTY_C2, - BeanC.PROPERTY_B + "." + BeanB.PROPERTY_D2, - BeanC.PROPERTY_B + "." + BeanB.PROPERTY_E2, - BeanC.PROPERTY_B + "." + BeanB.PROPERTY_F2, - BeanC.PROPERTY_B + "." + BeanB.PROPERTY_A2 + ".class" - - ); - } - - @Test - public void addPropertyChangeListener() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { - - PropertyChangeListener l = new BeanContextSupport(); - - BeanA beanA = new BeanA(); - - BeanUtil.addPropertyChangeListener(l, beanA); - - PropertyChangeListener[] listeners; - listeners = beanA.getPropertyChangeListeners(); - - Assert.assertEquals(1, listeners.length); - Assert.assertEquals(l, listeners[0]); - - - BeanUtil.addPropertyChangeListener(l, beanA); - - listeners = beanA.getPropertyChangeListeners(); - - Assert.assertEquals(2, listeners.length); - Assert.assertEquals(l, listeners[0]); - Assert.assertEquals(l, listeners[1]); - } - - @Test - public void removePropertyChangeListener() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { - - PropertyChangeListener[] listeners; - - PropertyChangeListener l = new BeanContextSupport(); - - BeanA beanA = new BeanA(); - beanA.addPropertyChangeListener(l); - - listeners = beanA.getPropertyChangeListeners(); - Assert.assertEquals(1, listeners.length); - Assert.assertEquals(l, listeners[0]); - - BeanUtil.removePropertyChangeListener(l, beanA); - - listeners = beanA.getPropertyChangeListeners(); - - Assert.assertEquals(0, listeners.length); - } - - protected void assertFoundReadableProperties(Class<?> type, String... expectedproperties) { - Set<String> readableProperties = BeanUtil.getReadableProperties(type); - Assert.assertEquals(expectedproperties.length, readableProperties.size()); - for (String expectedproperty : expectedproperties) { - Assert.assertTrue("Did not found property " + expectedproperty, readableProperties.contains(expectedproperty)); - } - } - - protected void assertFoundWriteableProperties(Class<?> type, String... expectedproperties) { - Set<String> readableProperties = BeanUtil.getReadableProperties(type); - Assert.assertEquals(expectedproperties.length, readableProperties.size()); - for (String expectedproperty : expectedproperties) { - Assert.assertTrue(readableProperties.contains(expectedproperty)); - } - } - - protected void assertFoundNestedReadableProperties(Class<?> type, String... expectedproperties) { - for (String expectedproperty : expectedproperties) { - boolean actual = BeanUtil.isNestedReadableProperty(type, expectedproperty); - Assert.assertTrue("Did not found nested property " + expectedproperty, actual); - } - } - - protected void assertFoundDescriptors(Class<?> type, - Predicate<PropertyDescriptor> predicate, - String... expectedproperties) { - Set<PropertyDescriptor> actual = BeanUtil.getDescriptors(type, predicate); - Assert.assertEquals(expectedproperties.length, actual.size()); - - ImmutableMap<String, PropertyDescriptor> map = Maps.uniqueIndex(actual, new Function<PropertyDescriptor, String>() { - @Override - public String apply(PropertyDescriptor input) { - return input.getName(); - } - }); - for (String expectedproperty : expectedproperties) { - Assert.assertTrue("Did not found property " + expectedproperty, - map.containsKey(expectedproperty)); - } - } -} diff --git a/src/test/java/org/nuiton/util/beans/BinderFactoryTest.java b/src/test/java/org/nuiton/util/beans/BinderFactoryTest.java deleted file mode 100644 index 516917f..0000000 --- a/src/test/java/org/nuiton/util/beans/BinderFactoryTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.beans; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests the {@link BinderFactory}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.5.3 - */ - -public class BinderFactoryTest { - - @Before - public void setUp() throws Exception { - BinderFactory.clear(); - } - - @Test - public void testNewBinder() throws Exception { - - // Limit cases - try { - BinderFactory.newBinder(null); - Assert.fail(); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - - try { - BinderFactory.newBinder(null, (Class<?>) null); - Assert.fail(); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - - try { - BinderFactory.newBinder(BeanA.class, (Class<?>) null); - Assert.fail(); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - - try { - BinderFactory.newBinder(null, BeanA.class); - Assert.fail(); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - - Assert.assertTrue(BinderFactory.binderModels.isEmpty()); - - Binder<BeanA, BeanA> binderAA = BinderFactory.newBinder(BeanA.class); - - Assert.assertNotNull(binderAA); - Assert.assertNotNull(BinderFactory.binderModels); - Assert.assertEquals(1, BinderFactory.binderModels.size()); - - } - - - @Test - public void testRegisterBinderModel() throws Exception { - - Assert.assertNull(BinderFactory.binderModels); - - Binder.BinderModel<BeanA, BeanA> model = - BinderFactory.registerBinderModel(BinderModelBuilder.newDefaultBuilder(BeanA.class)); - - Assert.assertNotNull(BinderFactory.binderModels); - Assert.assertEquals(1, BinderFactory.binderModels.size()); - Assert.assertEquals(model, - BinderFactory.newBinder(BeanA.class).getModel()); - - Binder.BinderModel<BeanA, BeanA> model1 = - BinderFactory.registerBinderModel(BinderModelBuilder.newDefaultBuilder(BeanA.class)); - - Assert.assertNotNull(BinderFactory.binderModels); - Assert.assertEquals(1, BinderFactory.binderModels.size()); - Assert.assertNotSame(model, model1); - Assert.assertEquals(model1, - BinderFactory.newBinder(BeanA.class).getModel()); - - BinderFactory.registerBinderModel(model1, "context"); - - Assert.assertNotNull(BinderFactory.binderModels); - Assert.assertEquals(2, BinderFactory.binderModels.size()); - Assert.assertEquals( - model1, - BinderFactory.newBinder(BeanA.class, "context").getModel()); - - - BinderFactory.registerBinderModel(model, "context"); - - - Assert.assertNotNull(BinderFactory.binderModels); - Assert.assertEquals(2, BinderFactory.binderModels.size()); - Assert.assertEquals( - model, - BinderFactory.newBinder(BeanA.class, "context").getModel()); - - } - - - @Test - public void testClear() throws Exception { - Assert.assertNull(BinderFactory.binderModels); - BinderFactory.newBinder(BeanA.class); - Assert.assertNotNull(BinderFactory.binderModels); - Assert.assertEquals(1, BinderFactory.binderModels.size()); - - BinderFactory.clear(); - - Assert.assertNull(BinderFactory.binderModels); - - } -} diff --git a/src/test/java/org/nuiton/util/beans/BinderModelBuilderTest.java b/src/test/java/org/nuiton/util/beans/BinderModelBuilderTest.java deleted file mode 100644 index 685825b..0000000 --- a/src/test/java/org/nuiton/util/beans/BinderModelBuilderTest.java +++ /dev/null @@ -1,588 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.beans; - -import org.junit.Assert; -import org.junit.Test; - -import java.util.Map; - -/** - * Tests the {@link BinderModelBuilder}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.5.3 - */ -public class BinderModelBuilderTest { - - protected static final String PROPERTY_CLASS = "class"; - - BinderModelBuilder<BeanA, BeanA> builderAA; - - BinderModelBuilder<BeanA, BeanB> builderAB; - - BinderModelBuilder<BeanB, BeanB> builderBB; - - BinderModelBuilder<BeanB, BeanA> builderBA; - - @Test - public void newEmptyBuilder() throws Exception { - - // Limit cases - - try { - BinderModelBuilder.newEmptyBuilder(null); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - try { - BinderModelBuilder.newEmptyBuilder(null, null); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - try { - BinderModelBuilder.newEmptyBuilder(BeanA.class, null); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - try { - BinderModelBuilder.newEmptyBuilder(null, BeanA.class); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - - // A → A - - builderAA = BinderModelBuilder.newEmptyBuilder(BeanA.class); - assertBuilder(builderAA, BeanA.class, BeanA.class); - - assertDescriptor(builderAA.sourceDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F - ); - - assertDescriptor(builderAA.targetDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F - ); - - builderAA = BinderModelBuilder.newEmptyBuilder(BeanA.class, BeanA.class); - assertBuilder(builderAA, BeanA.class, BeanA.class); - - assertDescriptor(builderAA.sourceDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F - ); - - assertDescriptor(builderAA.targetDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F - ); - - // A → B - - builderAB = BinderModelBuilder.newEmptyBuilder(BeanA.class, BeanB.class); - assertBuilder(builderAB, BeanA.class, BeanB.class); - - assertDescriptor(builderAB.sourceDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F - ); - - assertDescriptor(builderAB.targetDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanB.PROPERTY_A, - BeanB.PROPERTY_B, - BeanB.PROPERTY_C, - BeanB.PROPERTY_D, - BeanB.PROPERTY_E, - BeanB.PROPERTY_F, - BeanB.PROPERTY_BB, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - - // B → B - - builderBB = BinderModelBuilder.newEmptyBuilder(BeanB.class); - assertBuilder(builderBB, BeanB.class, BeanB.class); - - assertDescriptor(builderBB.sourceDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanB.PROPERTY_A, - BeanB.PROPERTY_B, - BeanB.PROPERTY_C, - BeanB.PROPERTY_D, - BeanB.PROPERTY_E, - BeanB.PROPERTY_F, - BeanB.PROPERTY_BB, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - assertDescriptor(builderBB.targetDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanB.PROPERTY_A, - BeanB.PROPERTY_B, - BeanB.PROPERTY_C, - BeanB.PROPERTY_D, - BeanB.PROPERTY_E, - BeanB.PROPERTY_F, - BeanB.PROPERTY_BB, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - - builderBB = BinderModelBuilder.newEmptyBuilder(BeanB.class, BeanB.class); - assertBuilder(builderBB, BeanB.class, BeanB.class); - - assertDescriptor(builderBB.sourceDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanB.PROPERTY_A, - BeanB.PROPERTY_B, - BeanB.PROPERTY_C, - BeanB.PROPERTY_D, - BeanB.PROPERTY_E, - BeanB.PROPERTY_F, - BeanB.PROPERTY_BB, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - assertDescriptor(builderBB.targetDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanB.PROPERTY_A, - BeanB.PROPERTY_B, - BeanB.PROPERTY_C, - BeanB.PROPERTY_D, - BeanB.PROPERTY_E, - BeanB.PROPERTY_F, - BeanB.PROPERTY_BB, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - - // B → A - - builderBA = BinderModelBuilder.newEmptyBuilder(BeanB.class, BeanA.class); - assertBuilder(builderBA, BeanB.class, BeanA.class); - - assertDescriptor(builderBA.sourceDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanB.PROPERTY_A, - BeanB.PROPERTY_B, - BeanB.PROPERTY_C, - BeanB.PROPERTY_D, - BeanB.PROPERTY_E, - BeanB.PROPERTY_F, - BeanB.PROPERTY_BB, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - assertDescriptor(builderBA.targetDescriptors, - PROPERTY_CLASS, - BeanA.PROPERTY_AA, - BeanB.PROPERTY_A, - BeanB.PROPERTY_B, - BeanB.PROPERTY_C, - BeanB.PROPERTY_D, - BeanB.PROPERTY_E, - BeanB.PROPERTY_F - ); - } - - - @Test - public void newDefaultBuilder() throws Exception { - - // Limit cases - - try { - BinderModelBuilder.newDefaultBuilder(null); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - try { - BinderModelBuilder.newDefaultBuilder(null, null); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - try { - BinderModelBuilder.newDefaultBuilder(BeanA.class, null); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - try { - BinderModelBuilder.newDefaultBuilder(null, BeanA.class); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - - // A → A - - builderAA = BinderModelBuilder.newDefaultBuilder(BeanA.class); - assertBuilder(builderAA, BeanA.class, BeanA.class); - assertDescriptor(builderAA.getModel().propertiesMapping, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F - ); - - builderAA = BinderModelBuilder.newDefaultBuilder(BeanA.class, BeanA.class); - assertBuilder(builderAA, BeanA.class, BeanA.class); - assertDescriptor(builderAA.getModel().propertiesMapping, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F - ); - - // A → B - - builderAB = BinderModelBuilder.newDefaultBuilder(BeanA.class, BeanB.class); - assertBuilder(builderAB, BeanA.class, BeanB.class); - assertDescriptor(builderAB.getModel().propertiesMapping, - BeanA.PROPERTY_A, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F - ); - - // B → B - - builderBB = BinderModelBuilder.newDefaultBuilder(BeanB.class); - assertBuilder(builderBB, BeanB.class, BeanB.class); - - assertDescriptor(builderBB.getModel().propertiesMapping, - BeanB.PROPERTY_A, - BeanB.PROPERTY_B, - BeanB.PROPERTY_C, - BeanB.PROPERTY_D, - BeanB.PROPERTY_E, - BeanB.PROPERTY_F, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - - builderBB = BinderModelBuilder.newDefaultBuilder(BeanB.class, BeanB.class); - assertBuilder(builderBB, BeanB.class, BeanB.class); - assertDescriptor(builderBB.getModel().propertiesMapping, - BeanB.PROPERTY_A, - BeanB.PROPERTY_B, - BeanB.PROPERTY_C, - BeanB.PROPERTY_D, - BeanB.PROPERTY_E, - BeanB.PROPERTY_F, - BeanB.PROPERTY_A2, - BeanB.PROPERTY_B2, - BeanB.PROPERTY_C2, - BeanB.PROPERTY_D2, - BeanB.PROPERTY_E2, - BeanB.PROPERTY_F2 - ); - - // B → A - - builderBA = BinderModelBuilder.newDefaultBuilder(BeanB.class, BeanA.class); - assertBuilder(builderBA, BeanB.class, BeanA.class); - assertDescriptor(builderBA.getModel().propertiesMapping, - BeanB.PROPERTY_A, - BeanB.PROPERTY_B, - BeanB.PROPERTY_C, - BeanB.PROPERTY_D, - BeanB.PROPERTY_E, - BeanB.PROPERTY_F - ); - - } - - @Test - public void testAddSimpleProperties() throws Exception { - - builderAA = BinderModelBuilder.newEmptyBuilder(BeanA.class); - - Binder.BinderModel<BeanA, BeanA> model = builderAA.getModel(); - - // limit case - try { - builderAA.addSimpleProperties((String) null); - Assert.fail(); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - - // not existing source property - try { - builderAA.addSimpleProperties(BeanB.PROPERTY_A2); - Assert.fail(); - } catch (IllegalArgumentException e) { - Assert.assertTrue(true); - } - - builderAA.addSimpleProperties(BeanA.PROPERTY_A); - Assert.assertEquals(1, model.getSourceDescriptors().length); - Assert.assertEquals(1, model.getTargetDescriptors().length); - Map<String, String> map = model.getPropertiesMapping(); - assertDescriptor(map, BeanB.PROPERTY_A); - Assert.assertEquals(BeanA.PROPERTY_A, map.get(BeanA.PROPERTY_A)); - - builderAA.addSimpleProperties(BeanA.PROPERTY_A); - Assert.assertEquals(1, model.getSourceDescriptors().length); - Assert.assertEquals(1, model.getTargetDescriptors().length); - assertDescriptor(map, BeanB.PROPERTY_A); - Assert.assertEquals(BeanA.PROPERTY_A, map.get(BeanA.PROPERTY_A)); - - builderAA.addSimpleProperties(BeanA.PROPERTY_B); - Assert.assertEquals(2, model.getSourceDescriptors().length); - Assert.assertEquals(2, model.getTargetDescriptors().length); - assertDescriptor(map, BeanB.PROPERTY_A, BeanB.PROPERTY_B); - Assert.assertEquals(BeanA.PROPERTY_B, map.get(BeanA.PROPERTY_B)); - - } - - @Test - public void testAddProperty() throws Exception { - builderAB = - BinderModelBuilder.newEmptyBuilder(BeanA.class, BeanB.class); - - Binder.BinderModel<BeanA, BeanB> model = builderAB.getModel(); - - // limit cases - - try { - builderAB.addProperty(null, null); - Assert.fail(); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - try { - builderAB.addProperty(BeanA.PROPERTY_A, null); - Assert.fail(); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - try { - builderAB.addProperty(null, BeanA.PROPERTY_A); - Assert.fail(); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - - // not existing source property - try { - builderAB.addProperty(BeanB.PROPERTY_A2, BeanB.PROPERTY_A); - Assert.fail(); - } catch (IllegalArgumentException e) { - Assert.assertTrue(true); - } - - builderAB.addProperty(BeanA.PROPERTY_A, BeanA.PROPERTY_A); - Assert.assertEquals(1, model.getSourceDescriptors().length); - Assert.assertEquals(1, model.getTargetDescriptors().length); - Map<String, String> map = model.getPropertiesMapping(); - assertDescriptor(map, BeanB.PROPERTY_A); - Assert.assertEquals(BeanA.PROPERTY_A, map.get(BeanA.PROPERTY_A)); - - builderAB.addProperty(BeanB.PROPERTY_A, BeanB.PROPERTY_A2); - Assert.assertEquals(1, model.getSourceDescriptors().length); - Assert.assertEquals(1, model.getTargetDescriptors().length); - assertDescriptor(map, BeanB.PROPERTY_A); - Assert.assertEquals(BeanB.PROPERTY_A2, map.get(BeanA.PROPERTY_A)); - - builderAB.addProperty(BeanA.PROPERTY_B, BeanB.PROPERTY_B2); - Assert.assertEquals(2, model.getSourceDescriptors().length); - Assert.assertEquals(2, model.getTargetDescriptors().length); - assertDescriptor(map, BeanB.PROPERTY_A, BeanB.PROPERTY_B); - Assert.assertEquals(BeanB.PROPERTY_B2, map.get(BeanB.PROPERTY_B)); - } - - @Test - public void testAddProperties() throws Exception { - builderAB = - BinderModelBuilder.newEmptyBuilder(BeanA.class, BeanB.class); - - try { - builderAB.addProperties(BeanB.PROPERTY_A, BeanB.PROPERTY_A2, - BeanB.PROPERTY_B); - Assert.fail(); - } catch (IllegalArgumentException e) { - Assert.assertTrue(true); - } - - try { - builderAB.addProperties(BeanB.PROPERTY_A, null, - BeanB.PROPERTY_B, BeanB.PROPERTY_B); - Assert.fail(); - } catch (NullPointerException e) { - Assert.assertTrue(true); - } - - builderAB.addProperties(BeanB.PROPERTY_A, BeanB.PROPERTY_A, - BeanB.PROPERTY_B, BeanB.PROPERTY_B2); - - Binder.BinderModel<?, ?> model = builderAB.getModel(); - - Assert.assertEquals(2, model.getSourceDescriptors().length); - Assert.assertEquals(2, model.getTargetDescriptors().length); - Map<String, String> map = model.getPropertiesMapping(); - assertDescriptor(map, BeanB.PROPERTY_A, BeanB.PROPERTY_B); - Assert.assertEquals(BeanA.PROPERTY_A, map.get(BeanA.PROPERTY_A)); - Assert.assertEquals(BeanB.PROPERTY_B2, map.get(BeanA.PROPERTY_B)); - } - - protected void assertDescriptor(Map<String, ?> descriptors, - String... propertyNames) { - Assert.assertNotNull(descriptors); - Assert.assertEquals(propertyNames.length, descriptors.size()); - for (String propertyName : propertyNames) { - Assert.assertTrue(descriptors.containsKey(propertyName)); - } - } - - protected <S, T> void assertBuilder(BinderModelBuilder<S, T> builder, - Class<S> sourceType, - Class<T> targetType) { - Assert.assertNotNull(builder); - Assert.assertNotNull(builder.getModel()); - Assert.assertEquals(sourceType, builder.getModel().getSourceType()); - Assert.assertEquals(targetType, builder.getModel().getTargetType()); - } - - @Test - public void testBug1713() throws Exception { - - // This is test for http://nuiton.org/issues/1713 - - BinderModelBuilder<Source, Destination> builder = - BinderModelBuilder.newDefaultBuilder(Source.class, Destination.class); - builder.addProperty("salutationCode", "gender"); - - Binder<Source, Destination> binder = builder.toBinder(); - - String salutationCode = "youhou"; - - Source source = new Source(salutationCode); - Destination destination = new Destination(); - binder.copy(source, destination); - - Assert.assertEquals(salutationCode, destination.getGender()); - } - - @Test - public void testEvol1913() throws Exception { - - // This is test for http://nuiton.org/issues/1913 - - // A → AA - - BinderModelBuilder<BeanA, BeanAA> builderAAA; - - builderAAA = BinderModelBuilder.newDefaultBuilder(BeanA.class, BeanAA.class); - assertBuilder(builderAAA, BeanA.class, BeanAA.class); - assertDescriptor(builderAAA.getModel().propertiesMapping, - BeanA.PROPERTY_B, - BeanA.PROPERTY_C, - BeanA.PROPERTY_D, - BeanA.PROPERTY_E, - BeanA.PROPERTY_F - ); - - try { - // property a is not the same, will fail - builderAAA = BinderModelBuilder.newDefaultBuilder(BeanA.class, BeanAA.class, false); - Assert.fail(); - } catch (IllegalArgumentException e) { - Assert.assertTrue(true); - } - } - -} diff --git a/src/test/java/org/nuiton/util/beans/BinderTest.java b/src/test/java/org/nuiton/util/beans/BinderTest.java deleted file mode 100644 index b2daae4..0000000 --- a/src/test/java/org/nuiton/util/beans/BinderTest.java +++ /dev/null @@ -1,394 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.beans; - -import com.google.common.collect.ImmutableMap; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.List; -import java.util.Map; - -public class BinderTest { - - BeanA a; - - BeanB b; - - BeanC c; - - Binder<BeanA, BeanA> binderA; - - Binder<BeanA, BeanB> binderB; - - Binder<BeanC, BeanC> binderC; - - private static final String VALUE_A = "a"; - - private static final String VALUE_B = "b"; - - private static final String VALUE_C = "c"; - - private static final int VALUE_E = 10; - - @BeforeClass - public static void beforeClass() { - - // remove all previous models from the factory - BinderFactory.clear(); - - // creates a mirrored binder model from A → A with only one property - - BinderModelBuilder<BeanA, BeanA> builder = - BinderModelBuilder.newEmptyBuilder(BeanA.class). - addSimpleProperties(BeanA.PROPERTY_A); - - // register the model into factory - BinderFactory.registerBinderModel(builder); - - // creates a binder model from A → B with more properties - - BinderModelBuilder<BeanA, BeanB> builder1 = - BinderModelBuilder.newEmptyBuilder(BeanA.class, BeanB.class). - addSimpleProperties(BeanA.PROPERTY_A, BeanA.PROPERTY_B). - addProperty(BeanA.PROPERTY_C, BeanB.PROPERTY_C2). - addProperty(BeanA.PROPERTY_E, BeanB.PROPERTY_E2); - - // register the model into factory - BinderFactory.registerBinderModel(builder1); - - // creates a binder model from A → B with more properties - - BinderModelBuilder<BeanC, BeanC> builder2 = - BinderModelBuilder.newEmptyBuilder(BeanC.class, BeanC.class). - addSimpleProperties(BeanC.PROPERTY_A). - addBinder(BeanC.PROPERTY_A, builder.toBinder()); - - // register the model into factory - BinderFactory.registerBinderModel(builder2); - - } - - @AfterClass - public static void tearDown() { - - // remove all models from the factory - BinderFactory.clear(); - - } - - @Before - public void setUp() { - - // get the binder A → A - binderA = BinderFactory.newBinder(BeanA.class); - - // get the binder A → B - binderB = BinderFactory.newBinder(BeanA.class, BeanB.class); - - // get the binder C → C - binderC = BinderFactory.newBinder(BeanC.class); - - a = new BeanA(); - b = new BeanB(); - c = new BeanC(); - } - - @Test - public void testObtainProperties() { - Map<String, Object> map; - map = binderA.obtainProperties(a); - Assert.assertEquals(0, map.size()); - - map = binderA.obtainProperties(a, true); - Assert.assertEquals(1, map.size()); - - map = binderB.obtainProperties(a); - Assert.assertEquals(0, map.size()); - - a.setA(VALUE_A); - map = binderA.obtainProperties(a); - Assert.assertEquals(1, map.size()); - Assert.assertTrue(map.containsKey(BeanA.PROPERTY_A)); - Assert.assertTrue(map.containsValue(VALUE_A)); - Assert.assertEquals(VALUE_A, map.get(BeanA.PROPERTY_A)); - - map = binderB.obtainProperties(a); - Assert.assertEquals(1, map.size()); - Assert.assertTrue(map.containsKey(BeanA.PROPERTY_A)); - Assert.assertTrue(map.containsValue(VALUE_A)); - Assert.assertEquals(VALUE_A, map.get(BeanA.PROPERTY_A)); - - a.setB(VALUE_B); - map = binderA.obtainProperties(a); - Assert.assertEquals(1, map.size()); - Assert.assertTrue(map.containsKey(BeanA.PROPERTY_A)); - Assert.assertFalse(map.containsKey(BeanA.PROPERTY_B)); - Assert.assertTrue(map.containsValue(VALUE_A)); - Assert.assertFalse(map.containsValue(VALUE_B)); - Assert.assertEquals(VALUE_A, map.get(BeanA.PROPERTY_A)); - - map = binderB.obtainProperties(a); - Assert.assertEquals(2, map.size()); - Assert.assertTrue(map.containsKey(BeanA.PROPERTY_A)); - Assert.assertTrue(map.containsKey(BeanA.PROPERTY_B)); - Assert.assertTrue(map.containsValue(VALUE_A)); - Assert.assertTrue(map.containsValue(VALUE_B)); - Assert.assertEquals(VALUE_A, map.get(BeanA.PROPERTY_A)); - Assert.assertEquals(VALUE_B, map.get(BeanA.PROPERTY_B)); - } - - @Test - public void testObtainSourceProperty() { - - { - String value = binderA.obtainSourceProperty(a, BeanA.PROPERTY_A); - Assert.assertNull(value); - } - a.setA(VALUE_A); - { - String value = binderA.obtainSourceProperty(a, BeanA.PROPERTY_A); - Assert.assertEquals(VALUE_A, value); - } - - // Binder A has no property e declared - try { - binderA.obtainSourceProperty(a, BeanA.PROPERTY_E); - Assert.fail(); - } catch (Exception e) { - Assert.assertTrue(true); - } - - { - int value = binderB.obtainSourceProperty(a, BeanA.PROPERTY_E); - Assert.assertEquals(0, value); - } - a.setE(VALUE_E); - { - int value = binderB.obtainSourceProperty(a, BeanA.PROPERTY_E); - Assert.assertEquals(VALUE_E, value); - } - - } - - @Test - public void testObtainTargetProperty() { - - { - String value = binderA.obtainTargetProperty(a, BeanA.PROPERTY_A); - Assert.assertNull(value); - } - a.setA(VALUE_A); - { - String value = binderA.obtainTargetProperty(a, BeanA.PROPERTY_A); - Assert.assertEquals(VALUE_A, value); - } - - // Binder A has no property e declared - try { - binderA.obtainTargetProperty(a, BeanA.PROPERTY_E); - Assert.fail(); - } catch (Exception e) { - Assert.assertTrue(true); - } - - { - int value = binderB.obtainTargetProperty(b, BeanB.PROPERTY_E2); - Assert.assertEquals(0, value); - } - b.setE2(VALUE_E); - { - int value = binderB.obtainTargetProperty(b, BeanB.PROPERTY_E2); - Assert.assertEquals(VALUE_E, value); - } - - } - - @Test - public void testInjectProperties() { - - ImmutableMap.Builder<String, Object> builder = new ImmutableMap.Builder<>(); - builder.put(BeanA.PROPERTY_A, "a"); - - Assert.assertNull(a.getA()); - - { - ImmutableMap<String, Object> properties = builder.build(); - binderA.injectProperties(properties, a); - - Assert.assertEquals(a.getA(), properties.get(BeanA.PROPERTY_A)); - - } - - builder.put(BeanA.PROPERTY_B, "b"); - - { - - ImmutableMap<String, Object> properties = builder.build(); - try { - binderA.injectProperties(properties, a); - Assert.fail(); - } catch (IllegalStateException e) { - // Ok normal case binder does not have properties b - } - - } - - { - - Assert.assertNull(b.getA()); - Assert.assertNull(b.getB()); - - ImmutableMap<String, Object> properties = builder.build(); - binderB.injectProperties(properties, b); - - Assert.assertEquals(b.getA(), properties.get(BeanB.PROPERTY_A)); - Assert.assertEquals(b.getB(), properties.get(BeanB.PROPERTY_B)); - - } - - } - - @Test - public void testCopy() { - - a.setA(VALUE_A); - a.setB(VALUE_B); - a.setC(VALUE_C); - a.setE(VALUE_E); - - binderA.copy(a, b); - Assert.assertEquals(VALUE_A, b.getA()); - Assert.assertNull(b.getB()); - Assert.assertNull(b.getB2()); - Assert.assertNull(b.getC()); - Assert.assertEquals(0, b.getE2()); - - binderB.copy(a, b); - Assert.assertEquals(VALUE_A, b.getA()); - Assert.assertEquals(VALUE_B, b.getB()); - Assert.assertNull(b.getC()); - Assert.assertEquals(VALUE_C, b.getC2()); - Assert.assertEquals(VALUE_E, b.getE2()); - - binderB.copy(null, b); - Assert.assertNull(b.getA()); - Assert.assertNull(b.getB()); - Assert.assertNull(b.getC2()); - Assert.assertEquals(0, b.getE2()); - - c.setA(a); - BeanC cTarget = new BeanC(); - binderC.copy(c, cTarget); - Assert.assertNotEquals(c.getA(), cTarget.getA()); - Assert.assertEquals(c.getA().getA(), cTarget.getA().getA()); - Assert.assertNull(cTarget.getA().getB()); - Assert.assertNull(cTarget.getA().getC()); - Assert.assertNull(cTarget.getA().getD()); - - c.setA(null); - cTarget = new BeanC(); - binderC.copy(c, cTarget); - Assert.assertNull(cTarget.getA()); - - } - - @Test - public void testCopyIncluding() { - - a.setA(VALUE_A); - a.setB(VALUE_B); - a.setC(VALUE_C); - a.setE(VALUE_E); - - // copy only the property A - binderA.copy(a, b, BeanA.PROPERTY_A); - Assert.assertEquals(VALUE_A, b.getA()); - Assert.assertNull(b.getB()); - Assert.assertNull(b.getB2()); - Assert.assertNull(b.getC()); - Assert.assertEquals(0, b.getE2()); - } - - @Test - public void testCopyExcluding() { - - a.setA(VALUE_A); - a.setB(VALUE_B); - a.setC(VALUE_C); - a.setE(VALUE_E); - - // #1 : Copy all properties defined by binderB instead of PROPERTY_A - binderB.copyExcluding(a, b, BeanA.PROPERTY_A); - Assert.assertNull(b.getA()); - // same result as copy - Assert.assertEquals(VALUE_B, b.getB()); - Assert.assertNull(b.getC()); - Assert.assertEquals(VALUE_C, b.getC2()); - Assert.assertEquals(VALUE_E, b.getE2()); - - // #2 : Copy all properties : same as binderB.copy(a, b); - binderB.copyExcluding(a, b); - // same result as copy - Assert.assertEquals(VALUE_A, b.getA()); - Assert.assertEquals(VALUE_B, b.getB()); - Assert.assertNull(b.getC()); - Assert.assertEquals(VALUE_C, b.getC2()); - Assert.assertEquals(VALUE_E, b.getE2()); - - // #3 : Copy all properties, excluding one is not considered from source - binderB.copyExcluding(a, b, BeanB.PROPERTY_C2); - // same result as copy - Assert.assertEquals(VALUE_A, b.getA()); - Assert.assertEquals(VALUE_B, b.getB()); - Assert.assertNull(b.getC()); - Assert.assertEquals(VALUE_C, b.getC2()); - Assert.assertEquals(VALUE_E, b.getE2()); - - } - - @Test - public void testDiff() { - a.setA(VALUE_A); - b.setA(VALUE_A); - a.setB(VALUE_A); - b.setB(VALUE_B); - - List<PropertyDiff> diff = binderB.diff(a, b); - - // only one property has changed - Assert.assertEquals(1, diff.size()); - - // names of the properties used for comparison - PropertyDiff propertyDiff = diff.get(0); - Assert.assertEquals(BeanA.PROPERTY_B, propertyDiff.getSourceProperty()); - Assert.assertEquals(BeanB.PROPERTY_B, propertyDiff.getTargetValue()); - - // old and new values - Assert.assertEquals(VALUE_A, propertyDiff.getSourceValue()); - Assert.assertEquals(VALUE_B, propertyDiff.getTargetValue()); - } -} diff --git a/src/test/java/org/nuiton/util/beans/Destination.java b/src/test/java/org/nuiton/util/beans/Destination.java deleted file mode 100644 index 2a52ae8..0000000 --- a/src/test/java/org/nuiton/util/beans/Destination.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.beans; - -/** - * Destination bean used to fix http://nuiton.org/issues/1713 - */ -public class Destination { - - private String gender; - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - -} diff --git a/src/test/java/org/nuiton/util/beans/Source.java b/src/test/java/org/nuiton/util/beans/Source.java deleted file mode 100644 index c22be64..0000000 --- a/src/test/java/org/nuiton/util/beans/Source.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.beans; - -/** - * Source bean used to fix http://nuiton.org/issues/1713 - */ -public class Source { - - private String salutationCode; - - public Source(String salutationCode) { - this.salutationCode = salutationCode; - } - - public String getSalutationCode() { - return salutationCode; - } - -} diff --git a/src/test/java/org/nuiton/util/converter/ConverterUtilTest.java b/src/test/java/org/nuiton/util/converter/ConverterUtilTest.java deleted file mode 100644 index d9b5d04..0000000 --- a/src/test/java/org/nuiton/util/converter/ConverterUtilTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.converter; - -import org.apache.commons.beanutils.ConvertUtils; -import org.apache.commons.beanutils.Converter; -import org.junit.Assert; -import org.junit.Test; -import org.nuiton.util.Version; - -/** - * ConverterUtil Tester. - * - * @author Tony Chemit - chemit@codelutin.com - * @version 1.3 (replace class {@code org.nuiton.util.ConverterUtilTest}). - * @since <pre>02/13/2008</pre> - */ -@Deprecated -public class ConverterUtilTest { - - @Test - public void testInitConverters() { - - ConverterUtil.deregister(); - - Converter t = ConvertUtils.lookup(Version.class); - Assert.assertNull(t); - ConverterUtil.initConverters(); - t = ConvertUtils.lookup(Version.class); - Assert.assertNotNull(t); - } - - @Test - public void testConvert() throws Exception { - String s; - s = ""; - Assert.assertEquals( - new String(s.getBytes()), - new String(ConverterUtil.convert(s.toCharArray()))); - - s = "a"; - Assert.assertEquals( - new String(s.getBytes()), - new String(ConverterUtil.convert(s.toCharArray()))); - - s = "kZZFIOFEIOFEfdskdfmldsfjklsfjldfldfjdsfiosabcd4567'''`~teAZEst"; - Assert.assertEquals( - new String(s.getBytes()), - new String(ConverterUtil.convert(s.toCharArray()))); - - s = "]{}{}{{[#{[{#[#]{][{^#][^]#{^[]{#][#]{]@[{#][^#{][^]#{teAZEst"; - Assert.assertEquals( - new String(s.getBytes()), - new String(ConverterUtil.convert(s.toCharArray()))); - - // FIXME following test won't pass - //s = "éééééé]{}{}{{[#{[{#[#]{][{^#][^]#{^[]{#][#]{]@[{#][^#{][^]#{teAZEst"; - //assertEquals(new String(s.getBytes()), new String(ConverterUtil.convert(s.toCharArray()))); - - } -} diff --git a/src/test/java/org/nuiton/util/converter/UnregistreableConverter.java b/src/test/java/org/nuiton/util/converter/UnregistreableConverter.java deleted file mode 100644 index db6b182..0000000 --- a/src/test/java/org/nuiton/util/converter/UnregistreableConverter.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.converter; - -import org.apache.commons.beanutils.Converter; - -/** - * A converter with no getType method, so not registreable via {@link ConverterUtil#initConverters()} - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 (replace class {@code org.nuiton.util.UnregistreableConverter}). - */ -@Deprecated -public class UnregistreableConverter implements Converter{ - - @Override - public Object convert(Class type, Object value) { - return value; - } - -} diff --git a/src/test/java/org/nuiton/util/converter/VersionConverterTest.java b/src/test/java/org/nuiton/util/converter/VersionConverterTest.java deleted file mode 100644 index 39018a1..0000000 --- a/src/test/java/org/nuiton/util/converter/VersionConverterTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.util.converter; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.util.Version; - -import static org.junit.Assert.*; - -/** - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 (replace class {@code org.nuiton.util.VersionConverterTest}). - */ -@Deprecated -public class VersionConverterTest { - - VersionConverter converter; - - @BeforeClass - public static void setUpClass() throws Exception { - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - @Before - public void setUp() { - converter = new VersionConverter(); - } - - @After - public void tearDown() { - } - - /** - * Test of convert method, of class VersionConverter. - */ - @Test - public void testConvert() { - Object value; - Object expResult; - Object result; - - value = ""; - expResult = new Version(); - result = converter.convert(Version.class, value); - assertEquals(expResult, result); - - value = "0"; - expResult = new Version(); - result = converter.convert(Version.class, value); - assertEquals(expResult, result); - - value = "1.2.3.4"; - expResult = new Version(1, 2, 3, 4); - result = converter.convert(Version.class, value); - assertEquals(expResult, result); - - value = "1.2.3.4-alpha-11"; - expResult = new Version("alpha", 11, 1, 2, 3, 4); - result = converter.convert(Version.class, value); - assertEquals(expResult, result); - } - - /** - * Test of isEnabled method, of class VersionConverter. - */ - @Test - public void testIsEnabled() { - - boolean expResult = true; - boolean result = converter.isEnabled(Version.class); - assertEquals(expResult, result); - } -} diff --git a/src/test/java/org/nuiton/util/pagination/PaginationParameterTest.java b/src/test/java/org/nuiton/util/pagination/PaginationParameterTest.java deleted file mode 100644 index 5b39cd6..0000000 --- a/src/test/java/org/nuiton/util/pagination/PaginationParameterTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.nuiton.util.pagination; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2014 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import org.junit.Assert; -import org.junit.Test; - -/** - * @author Arnaud Thimel (Code Lutin) - */ -public class PaginationParameterTest { - - @Test - public void testIndexes() { - { - PaginationParameter paginationParameter = PaginationParameter.of(0, 50); - Assert.assertEquals(0, paginationParameter.getStartIndex()); - Assert.assertEquals(49, paginationParameter.getEndIndex()); - } - { - PaginationParameter paginationParameter = PaginationParameter.of(2, 50); - Assert.assertEquals(100, paginationParameter.getStartIndex()); - Assert.assertEquals(149, paginationParameter.getEndIndex()); - } - { - PaginationParameter paginationParameter = PaginationParameter.of(0, -1); - Assert.assertEquals(0, paginationParameter.getStartIndex()); - Assert.assertEquals(Integer.MAX_VALUE, paginationParameter.getEndIndex()); - } - { - PaginationParameter paginationParameter = PaginationParameter.of(0, 19); - Assert.assertEquals(0, paginationParameter.getStartIndex()); - Assert.assertEquals(18, paginationParameter.getEndIndex()); - } - { - PaginationParameter paginationParameter = PaginationParameter.of(1, 19); - Assert.assertEquals(19, paginationParameter.getStartIndex()); - Assert.assertEquals(37, paginationParameter.getEndIndex()); - } - { - PaginationParameter paginationParameter = PaginationParameter.of(2, 19); - Assert.assertEquals(38, paginationParameter.getStartIndex()); - Assert.assertEquals(56, paginationParameter.getEndIndex()); - } - } - - @Test(expected = IllegalArgumentException.class) - public void testIncoherentNumbers() { - PaginationParameter paginationParameter = PaginationParameter.of(2, -1); - paginationParameter.getStartIndex(); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidPageSizeTo0() { - PaginationParameter paginationParameter = PaginationParameter.of(5, 0); - paginationParameter.getStartIndex(); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidPageSizeToMinus5() { - PaginationParameter paginationParameter = PaginationParameter.of(5, -5); - paginationParameter.getStartIndex(); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidPageNumber() { - PaginationParameter paginationParameter = PaginationParameter.of(-3, 25); - paginationParameter.getStartIndex(); - } - -} diff --git a/src/test/java/org/nuiton/util/pagination/PaginationResultTest.java b/src/test/java/org/nuiton/util/pagination/PaginationResultTest.java deleted file mode 100644 index bfc0683..0000000 --- a/src/test/java/org/nuiton/util/pagination/PaginationResultTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.nuiton.util.pagination; - -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2014 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import java.util.List; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.google.common.collect.Lists; - -/** - * @author Arnaud Thimel (Code Lutin) - */ -public class PaginationResultTest { - - protected PaginationResult<Object> paginationResult; - - @Before - public void init() { - List<Object> elements = Lists.newArrayList(); - PaginationParameter page = PaginationParameter.of(2, 50); - paginationResult = PaginationResult.of(elements, 204, page); - } - - @Test - public void testGetFirstPage() { - Assert.assertEquals(0, paginationResult.getFirstPage().getPageNumber()); - Assert.assertEquals(50, paginationResult.getFirstPage().getPageSize()); - Assert.assertEquals(0, paginationResult.getFirstPage().getStartIndex()); - Assert.assertEquals(49, paginationResult.getFirstPage().getEndIndex()); - - List<Object> elements = Lists.newArrayList(); - PaginationResult<Object> firstPageResult = PaginationResult.of(elements, paginationResult.getCount(), paginationResult.getFirstPage()); - Assert.assertTrue(firstPageResult.hasNextPage()); - } - - @Test - public void testGetPreviousPage() { - Assert.assertEquals(1, paginationResult.getPreviousPage().getPageNumber()); - Assert.assertEquals(50, paginationResult.getPreviousPage().getPageSize()); - Assert.assertEquals(50, paginationResult.getPreviousPage().getStartIndex()); - Assert.assertEquals(99, paginationResult.getPreviousPage().getEndIndex()); - - List<Object> elements = Lists.newArrayList(); - PaginationResult<Object> previousPageResult = PaginationResult.of(elements, paginationResult.getCount(), paginationResult.getPreviousPage()); - Assert.assertTrue(previousPageResult.hasNextPage()); - } - - @Test - public void testCurrentPage() { - Assert.assertEquals(5, paginationResult.getPageCount()); - Assert.assertEquals(2, paginationResult.getCurrentPage().getPageNumber()); - Assert.assertEquals(50, paginationResult.getCurrentPage().getPageSize()); - Assert.assertEquals(100, paginationResult.getCurrentPage().getStartIndex()); - Assert.assertEquals(149, paginationResult.getCurrentPage().getEndIndex()); - - Assert.assertTrue(paginationResult.hasNextPage()); - } - - @Test - public void testGeNextPage() { - Assert.assertEquals(3, paginationResult.getNextPage().getPageNumber()); - Assert.assertEquals(50, paginationResult.getNextPage().getPageSize()); - Assert.assertEquals(150, paginationResult.getNextPage().getStartIndex()); - Assert.assertEquals(199, paginationResult.getNextPage().getEndIndex()); - - List<Object> elements = Lists.newArrayList(); - PaginationResult<Object> nextPageResult = PaginationResult.of(elements, paginationResult.getCount(), paginationResult.getNextPage()); - Assert.assertTrue(nextPageResult.hasNextPage()); - } - - @Test - public void testGetLastPage() { - Assert.assertEquals(4, paginationResult.getLastPage().getPageNumber()); - Assert.assertEquals(50, paginationResult.getLastPage().getPageSize()); - Assert.assertEquals(200, paginationResult.getLastPage().getStartIndex()); - Assert.assertEquals(249, paginationResult.getLastPage().getEndIndex()); - - List<Object> elements = Lists.newArrayList(); - PaginationResult<Object> lastPageResult = PaginationResult.of(elements, paginationResult.getCount(), paginationResult.getLastPage()); - Assert.assertFalse(lastPageResult.hasNextPage()); - } - - @Test - public void testGetLastPageOnEmptyElements() { - List<Object> elements = Lists.newArrayList(); - PaginationResult<Object> pageResult = PaginationResult.of(elements, 0, PaginationParameter.of(0, 20)); - PaginationParameter lastPage = pageResult.getLastPage(); - Assert.assertEquals(0, lastPage.getPageNumber()); - } - - @Test - public void testPageSizeOne() { - List<Object> elements = Lists.newArrayList(); - PaginationParameter page0 = PaginationParameter.of(0, 1); - PaginationResult<Object> pageResult = PaginationResult.of(elements, 5, page0); - - Assert.assertEquals(5, pageResult.getCount()); - Assert.assertEquals(5, pageResult.getPageCount()); - } - -} diff --git a/src/test/java/org/nuiton/util/rmi/AnyException.java b/src/test/java/org/nuiton/util/rmi/AnyException.java deleted file mode 100644 index 7f9b62c..0000000 --- a/src/test/java/org/nuiton/util/rmi/AnyException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.rmi; - -/** - * @author Arnaud Thimel - thimel@codelutin.com - */ -public class AnyException extends Exception { - - public AnyException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/src/test/java/org/nuiton/util/rmi/RmiExporterAndProxyTest.java b/src/test/java/org/nuiton/util/rmi/RmiExporterAndProxyTest.java deleted file mode 100644 index 1df6b89..0000000 --- a/src/test/java/org/nuiton/util/rmi/RmiExporterAndProxyTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.rmi; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.InvalidObjectException; -import java.rmi.NotBoundException; - -/** - * @author Arnaud Thimel - thimel@codelutin.com - */ -@Ignore -public class RmiExporterAndProxyTest { - - /** Logger. */ - static private Log log = LogFactory.getLog(RmiExporterAndProxyTest.class); - - @Test(expected = NullPointerException.class) - public void testExportNullService() throws Exception { - - // It is mandatory to provide a service instance - ServiceExporter.registerService(SomeService.class, null); - } - - @Test(expected = NotBoundException.class) - public void testProxyWithoutService() throws Exception { - - // Register and unregister (to make sure RMI registry is created) - SomeServiceImpl impl = new SomeServiceImpl(); - ServiceExporter.registerService(SomeService.class, impl); - ServiceExporter.unregisterService(SomeService.class); - - // This will throw an exception because service is not registered - RemoteProxyFactory.createProxy(SomeService.class); - } - - @Test - public void testObjectIdentity() throws Exception { - - // Create and bind the service - SomeServiceImpl impl = new SomeServiceImpl(); - int realServiceIdentity = System.identityHashCode(impl); - ServiceExporter.registerService(SomeService.class, impl); - - // Get a proxy on this service and make sure this is not the same object - SomeService clientSide = RemoteProxyFactory.createProxy(SomeService.class); - int proxyIdentity = System.identityHashCode(clientSide); - Assert.assertNotSame(proxyIdentity, realServiceIdentity); - - // Get the remote identifier and compare - int serviceIdentityFromProxy = clientSide.getInstanceId(); - Assert.assertEquals(realServiceIdentity, serviceIdentityFromProxy); - - ServiceExporter.unregisterService(SomeService.class); - } - - @Test - public void testComplexType() throws Exception { - - // Create and bind the service - SomeServiceImpl impl = new SomeServiceImpl(); - int realServiceIdentity = System.identityHashCode(impl); - ServiceExporter.registerService(SomeService.class, impl); - - // Get a proxy on this service and do the call to createComplexTypeObject - SomeService clientSide = RemoteProxyFactory.createProxy(SomeService.class); - SomeBean bean = clientSide.createComplexTypeObject(); - - // Now check that the bean is exactly as expected - SomeBean father = bean.getFather(); - Assert.assertNotNull(father); - Assert.assertEquals("I'm your father !", father.getMessage()); - Assert.assertEquals(realServiceIdentity, father.getCreatedBy()); - Assert.assertNull(father.getFather()); - Assert.assertNull(father.getCreatedOn()); // transient value - Assert.assertEquals(0L, father.getNumber()); // transient value - - Assert.assertEquals("Son", bean.getMessage()); - Assert.assertEquals(realServiceIdentity, bean.getCreatedBy()); - Assert.assertNull(bean.getCreatedOn()); // transient value - Assert.assertEquals(0L, bean.getNumber()); // transient value - - ServiceExporter.unregisterService(SomeService.class); - } - - @Test - public void testExceptionPropagation() throws Exception { - - // Create and bind the service - SomeServiceImpl impl = new SomeServiceImpl(); - ServiceExporter.registerService(SomeService.class, impl); - - // Get a proxy on this service and do the call to createComplexTypeObject - SomeService clientSide = RemoteProxyFactory.createProxy(SomeService.class); - - // Does not fail - clientSide.throwAnExceptionIfFalse(true); - - try { - clientSide.throwAnExceptionIfFalse(false); - Assert.fail("An axeption should have been thrown"); - } catch (AnyException ae) { - - Assert.assertEquals("Please provide 'true'", ae.getMessage()); - - // Exception is the good one. Now check its cause - InvalidObjectException cause = (InvalidObjectException)ae.getCause(); - Assert.assertEquals("Wrong parameter !", cause.getMessage()); - } - - ServiceExporter.unregisterService(SomeService.class); - } - -} diff --git a/src/test/java/org/nuiton/util/rmi/SomeBean.java b/src/test/java/org/nuiton/util/rmi/SomeBean.java deleted file mode 100644 index 8ab7109..0000000 --- a/src/test/java/org/nuiton/util/rmi/SomeBean.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.rmi; - -import java.io.Serializable; -import java.util.Date; - -/** - * @author Arnaud Thimel - thimel@codelutin.com - */ -public class SomeBean implements Serializable { - - protected SomeBean father; - protected String message; - protected int createdBy; - protected transient Date createdOn; - protected transient long number; - - public SomeBean(String message, Object creator, long number) { - this.message = message; - this.createdBy = System.identityHashCode(creator); - this.createdOn = new Date(); - this.number = number; - } - - public SomeBean getFather() { - return father; - } - - public void setFather(SomeBean father) { - this.father = father; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public int getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(int createdBy) { - this.createdBy = createdBy; - } - - public Date getCreatedOn() { - return createdOn; - } - - public void setCreatedOn(Date createdOn) { - this.createdOn = createdOn; - } - - public long getNumber() { - return number; - } - - public void setNumber(long number) { - this.number = number; - } - -} diff --git a/src/test/java/org/nuiton/util/rmi/SomeService.java b/src/test/java/org/nuiton/util/rmi/SomeService.java deleted file mode 100644 index b1fc8ab..0000000 --- a/src/test/java/org/nuiton/util/rmi/SomeService.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.rmi; - -/** - * Any service interface which will be used to test the RMI proxy. - * - * @author Arnaud Thimel - thimel@codelutin.com - */ -public interface SomeService { - - /** - * This method will return a String that can only be known by itself - * - * @return an instance identifier - */ - int getInstanceId(); - - /** - * This method will return a complex object to validate that this is not - * working only with primitive types - * - * @return a newly created SomeBean - */ - SomeBean createComplexTypeObject(); - - /** - * Will throw an AnyException to test exception propagation - * - * @param bool true : will not fail, false will fail - * @throws AnyException if the given boolean is false - */ - void throwAnExceptionIfFalse(Boolean bool) throws AnyException; - -} diff --git a/src/test/java/org/nuiton/util/rmi/SomeServiceImpl.java b/src/test/java/org/nuiton/util/rmi/SomeServiceImpl.java deleted file mode 100644 index 61679c4..0000000 --- a/src/test/java/org/nuiton/util/rmi/SomeServiceImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * #%L - * Nuiton Utils - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.util.rmi; - -import java.io.InvalidObjectException; - -/** - * @author Arnaud Thimel - thimel@codelutin.com - */ -public class SomeServiceImpl implements SomeService { - - @Override - public int getInstanceId() { - return System.identityHashCode(this); - } - - @Override - public SomeBean createComplexTypeObject() { - SomeBean father = new SomeBean("I'm your father !", this, 123); - SomeBean result = new SomeBean("Son", this, 456); - result.setFather(father); - return result; - } - - @Override - public void throwAnExceptionIfFalse(Boolean bool) throws AnyException { - if (!bool) { - InvalidObjectException ioe = new InvalidObjectException("Wrong parameter !"); - throw new AnyException("Please provide 'true'", ioe); - } - } - -} diff --git a/src/test/java/org/nuiton/util/version/SemVerTest.java b/src/test/java/org/nuiton/version/SemVerTest.java similarity index 98% rename from src/test/java/org/nuiton/util/version/SemVerTest.java rename to src/test/java/org/nuiton/version/SemVerTest.java index 3ddaf15..ec3d1ed 100644 --- a/src/test/java/org/nuiton/util/version/SemVerTest.java +++ b/src/test/java/org/nuiton/version/SemVerTest.java @@ -1,10 +1,10 @@ -package org.nuiton.util.version; +package org.nuiton.version; /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2004 - 2013 CodeLutin + * Copyright (C) 2016 CodeLutin * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as diff --git a/src/test/java/org/nuiton/util/version/VersionBuilderTest.java b/src/test/java/org/nuiton/version/VersionBuilderTest.java similarity index 97% rename from src/test/java/org/nuiton/util/version/VersionBuilderTest.java rename to src/test/java/org/nuiton/version/VersionBuilderTest.java index 6e08f6f..72ab2bb 100644 --- a/src/test/java/org/nuiton/util/version/VersionBuilderTest.java +++ b/src/test/java/org/nuiton/version/VersionBuilderTest.java @@ -1,10 +1,10 @@ -package org.nuiton.util.version; +package org.nuiton.version; /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2014 CodeLutin, Tony Chemit + * Copyright (C) 2016 CodeLutin, Tony Chemit * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as diff --git a/src/test/java/org/nuiton/util/version/VersionComparatorTest.java b/src/test/java/org/nuiton/version/VersionComparatorTest.java similarity index 96% rename from src/test/java/org/nuiton/util/version/VersionComparatorTest.java rename to src/test/java/org/nuiton/version/VersionComparatorTest.java index 4c7664e..d3bbaa1 100644 --- a/src/test/java/org/nuiton/util/version/VersionComparatorTest.java +++ b/src/test/java/org/nuiton/version/VersionComparatorTest.java @@ -1,10 +1,10 @@ -package org.nuiton.util.version; +package org.nuiton.version; /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2014 CodeLutin, Tony Chemit + * Copyright (C) 2016 CodeLutin, Tony Chemit * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as diff --git a/src/test/java/org/nuiton/util/version/VersionTest.java b/src/test/java/org/nuiton/version/VersionTest.java similarity index 95% rename from src/test/java/org/nuiton/util/version/VersionTest.java rename to src/test/java/org/nuiton/version/VersionTest.java index f434daa..86d1270 100644 --- a/src/test/java/org/nuiton/util/version/VersionTest.java +++ b/src/test/java/org/nuiton/version/VersionTest.java @@ -1,10 +1,10 @@ -package org.nuiton.util.version; +package org.nuiton.version; /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2014 CodeLutin, Tony Chemit + * Copyright (C) 2016 CodeLutin, Tony Chemit * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as diff --git a/src/test/java/org/nuiton/util/version/VersionsTest.java b/src/test/java/org/nuiton/version/VersionsTest.java similarity index 97% rename from src/test/java/org/nuiton/util/version/VersionsTest.java rename to src/test/java/org/nuiton/version/VersionsTest.java index accbfff..4ff885e 100644 --- a/src/test/java/org/nuiton/util/version/VersionsTest.java +++ b/src/test/java/org/nuiton/version/VersionsTest.java @@ -1,13 +1,13 @@ -package org.nuiton.util.version; +package org.nuiton.version; import org.junit.Assert; import org.junit.Test; /* * #%L - * Nuiton Utils + * Nuiton Version * %% - * Copyright (C) 2014 CodeLutin, Chatellier Eric + * Copyright (C) 2016 CodeLutin, Chatellier Éric * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as diff --git a/src/test/resources/META-INF/services/org.apache.commons.beanutils.Converter b/src/test/resources/META-INF/services/org.apache.commons.beanutils.Converter deleted file mode 100644 index dce81c1..0000000 --- a/src/test/resources/META-INF/services/org.apache.commons.beanutils.Converter +++ /dev/null @@ -1 +0,0 @@ -org.nuiton.util.converter.UnregistreableConverter \ No newline at end of file diff --git a/src/test/resources/log4j.properties b/src/test/resources/log4j.properties index 1d27876..1706946 100644 --- a/src/test/resources/log4j.properties +++ b/src/test/resources/log4j.properties @@ -1,8 +1,8 @@ ### # #%L -# Nuiton Utils +# Nuiton Version # %% -# Copyright (C) 2004 - 2011 CodeLutin, Chatellier Eric +# Copyright (C) 2016 CodeLutin # %% # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as @@ -28,5 +28,4 @@ log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) %M - %m%n # package level -log4j.logger.org.nuiton.util=INFO -log4j.logger.org.nuiton.util.beans.Binder=DEBUG +log4j.logger.org.nuiton.version=INFO diff --git a/src/test/resources/org/nuiton/util/fileUtilData.txt b/src/test/resources/org/nuiton/util/fileUtilData.txt deleted file mode 100644 index c15700d..0000000 --- a/src/test/resources/org/nuiton/util/fileUtilData.txt +++ /dev/null @@ -1,1421 +0,0 @@ -/* - * #%L - * Nuiton Utils - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * - * FileUtil.java - * - * Created: 22 nov. 2004 - * - * @author Benjamin Poussin <poussin@codelutin.com> - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : */ - -package org.nuiton.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JFileChooser; -import java.awt.Component; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileFilter; -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.io.OutputStreamWriter; -import java.io.PrintStream; -import java.nio.CharBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Opérations sur des fichiers. Copie, suppression, renommage, - * recherche, fichiers d'un répertoire, sous-répertoires d'un répertoire, - * récupération du basename ou de l'extension, création d'un fichier - * temporaire, comparaison de dates de création, récupération d'une chaîne, - * d'un Reader ou d'un Writer à partir d'un fichier, récupération du fichier - * saisi dans une boîte de dialogue, conversions en byte[], en Stream... - * - * Created: 22 novembre 2004 - * - * @author bpoussin <poussin@codelutin.com> - * $Id$ - */ -public class FileUtil { // FileUtil - - /** Logger. */ - static private Log log = LogFactory.getLog(FileUtil.class); - - /** Encoding utilisé (peut être redéfini) */ - // TODO fdesbois 2011-04-16 : Perhaps change ISO encoding by UTF-8 - public static String ENCODING = "ISO-8859-1"; - static protected File currentDirectory = new File("."); - - public static void setCurrentDirectory(File dir) { - currentDirectory = dir; - } - - public static File getCurrentDirectory() { - return currentDirectory; - } - - public static class PatternChooserFilter extends javax.swing.filechooser.FileFilter { - protected String pattern; - protected String description; - - public PatternChooserFilter(String pattern, String description) { - this.pattern = pattern; - this.description = description; - } - - @Override - public boolean accept(File f) { - return f.isDirectory() || f.getAbsolutePath().matches(pattern); - } - - @Override - public String getDescription() { - return description; - } - - } - - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données - * par deux, le pattern du filtre + la description du filtre - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - * @see #getFile(javax.swing.filechooser.FileFilter...) - */ - public static File getFile(String... patternOrDescriptionFilters) { - File result; - result = getFile(null, patternOrDescriptionFilters); - return result; - } - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param filters les filtres a ajouter - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - */ - public static File getFile(javax.swing.filechooser.FileFilter... filters) { - File result = getFile(null, filters); - return result; - } - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param parent le component parent du dialog - * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données - * par deux, le pattern du filtre + la description du filtre - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - * @see #getFile(javax.swing.filechooser.FileFilter...) - */ - public static File getFile(Component parent, - String... patternOrDescriptionFilters) { - File result; - result = getFile("Ok", "Ok", parent, patternOrDescriptionFilters); - return result; - } - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param title le titre de la boite de dialogue - * @param approvalText le label du boutton d'acceptation - * @param parent le component parent du dialog - * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données - * par deux, le pattern du filtre + la description du filtre - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - * @see #getFile(javax.swing.filechooser.FileFilter...) - */ - public static File getFile(String title, - String approvalText, - Component parent, - String... patternOrDescriptionFilters) { - - if (patternOrDescriptionFilters.length % 2 != 0) { - throw new IllegalArgumentException("Arguments must be (pattern, description) couple"); - } - javax.swing.filechooser.FileFilter[] filters = - new javax.swing.filechooser.FileFilter[patternOrDescriptionFilters.length / 2]; - for (int i = 0; i < filters.length; i++) { - String pattern = patternOrDescriptionFilters[i * 2]; - String description = patternOrDescriptionFilters[i * 2 + 1]; - filters[i] = new PatternChooserFilter(pattern, description); - } - File result; - result = getFile(title, approvalText, parent, filters); - return result; - } - - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param parent le component parent du dialog - * @param filters les filtres a ajouter - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - */ - public static File getFile(Component parent, - javax.swing.filechooser.FileFilter... filters) { - File result = getFile("Ok", "Ok", parent, filters); - return result; - } - - /** - * Retourne le nom du fichier entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. - * - * @param title le titre de la boite de dialogue - * @param approvalText le label du boutton d'acceptation - * @param parent le component parent du dialog - * @param filters les filtres a ajouter - * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé - */ - public static File getFile(String title, - String approvalText, - Component parent, - javax.swing.filechooser.FileFilter... filters) { - try { - JFileChooser chooser = new JFileChooser(currentDirectory); - - chooser.setDialogType(JFileChooser.CUSTOM_DIALOG); - if (filters.length > 0) { - if (filters.length == 1) { - chooser.setFileFilter(filters[0]); - } else { - for (javax.swing.filechooser.FileFilter filter : filters) { - chooser.addChoosableFileFilter(filter); - } - } - } - chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - chooser.setDialogTitle(title); - int returnVal = chooser.showDialog(parent, approvalText); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File theFile = chooser.getSelectedFile(); - if (theFile != null) { - currentDirectory = theFile; - return theFile.getAbsoluteFile(); - } - } - } - catch (Exception eee) { - log.warn("Erreur:", eee); - } - return null; - } - - /** - * @return le nom du repertoire entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne - * null. - */ - public static String getDirectory() { - return getDirectory(null,"Ok", "Ok"); - } - - /** - * @param title le nom de la boite de dialogue - * @param approvalText le texte de l'action d'acceptation du répertoire dans le file chooser - * @return le nom du repertoire entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne - * null. - */ - public static String getDirectory(String title, String approvalText) { - String result = getDirectory(null, title, approvalText); - return result; - } - - /** - * @param parent le component parent du dialog - * @param title le nom de la boite de dialogue - * @param approvalText le texte de l'action d'acceptation du répertoire dans le file chooser - * @return le nom du repertoire entre dans la boite de dialogue. - * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne - * null. - */ - public static String getDirectory(Component parent, - String title, - String approvalText) { - try { - JFileChooser chooser = new JFileChooser(currentDirectory); - chooser.setDialogType(JFileChooser.CUSTOM_DIALOG); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setDialogTitle(title); - int returnVal = chooser.showDialog(parent, approvalText); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File theFile = chooser.getSelectedFile(); - if (theFile != null) { - currentDirectory = theFile; - if (theFile.isDirectory()) { - return theFile.getAbsolutePath(); - } - } - } else { - return null; - } - } catch (Exception eee) { - log.warn("Erreur:", eee); - } - return null; - } - - /** - * Permet de convertir un fichier en un tableau de byte - * - * @param file le fichier source à convertire - * @return le contenu du fichier sous la forme d'un tableau de bytes. - * @throws IOException if any io pb - */ - public static byte[] fileToByte(File file) throws IOException { - ByteArrayOutputStream result; - InputStream in = new BufferedInputStream(new FileInputStream(file)); - try { - result = new ByteArrayOutputStream(); - BufferedOutputStream tmp = new BufferedOutputStream(result); - try { - for (int b = in.read(); b != -1; b = in.read()) { - tmp.write(b); - } - } finally { - tmp.close(); - } - } finally { - in.close(); - } - return result.toByteArray(); - } - - /** - * Permet de recopier un stream dans un fichier - * - * @param src the incoming stream to grab - * @param dst the dst file - * @return the file filled by incoming input stream - * @throws IOException if any io pb - * @throws NullPointerException if src or dst parameter is null - */ - public static File inputStreamToFile(InputStream src, File dst) throws IOException, NullPointerException { - if (src == null) { - throw new NullPointerException("parameter 'src' can not be null"); - } - if (dst == null) { - throw new NullPointerException("parameter 'dst' can not be null"); - } - - ByteArrayOutputStream result = new ByteArrayOutputStream(); - BufferedOutputStream tmp = new BufferedOutputStream(result); - try { - for (int b = src.read(); b != -1; b = src.read()) { - tmp.write(b); - } - src.close(); - } finally { - tmp.close(); - } - byteToFile(result.toByteArray(), dst); - return dst; - } - - /** - * Permet de convertir des bytes en fichier, le fichier sera automatiquement - * supprimé a la fin de la JVM. - * - * @param bytes the array of bytes to copy in dstination file - * @return le fichier temporaire contenant les bytes - * @throws IOException if any io pb - */ - public static File byteToFile(byte[] bytes) throws IOException { - File file = File.createTempFile("FileUtil-byteToFile", ".tmp"); - byteToFile(bytes, file); - return file; - } - - /** - * Permet de convertir des bytes en fichier - * - * @param bytes the array of bytes to put in the given destination file - * @param file le fichier dans lequel il faut ecrire les bytes - * @return le fichier passé en parametre - * @throws IOException if any io pb - */ - public static File byteToFile(byte[] bytes, - File file) throws IOException { - OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); - try { - out.write(bytes); - } finally { - out.close(); - } - return file; - } - - /** - * Retourne un Reader utilisant l'encoding par defaut {@link #ENCODING}. - * - * @param file the given reader - * @return the reader on the given file - * @throws IOException if any io pb - */ - public static BufferedReader getReader(File file) throws IOException { - return getReader(file, ENCODING); - } - - /** - * Retourne un reader utilisant l'encoding choisi et placé dans un - * BufferedReader - * - * @param file the given file - * @param encoding (ISO-8859-1, UTF-8, ...) - * @return the buffered reader in the given encoding - * @throws IOException if any io pb - */ - public static BufferedReader getReader(File file, - String encoding) throws IOException { - FileInputStream inf = new FileInputStream(file); - InputStreamReader in = new InputStreamReader(inf, encoding); - BufferedReader result = new BufferedReader(in); - return result; - } - - /** - * Retourne un Writer utilisant l'encoding par defaut {@link #ENCODING}. - * - * @param file the given file - * @return the writer on the given file - * @throws IOException if any io pb - */ - public static BufferedWriter getWriter(File file) throws IOException { - return getWriter(file, ENCODING); - } - - /** - * Retourne un writer utilisant l'encoding choisi et placé dans un - * BufferedWriter - * - * @param file the given file - * @param encoding (ISO-8859-1, UTF-8, ...) - * @return the buffered writer on the given file with given encoding - * @throws IOException if any io pb - */ - public static BufferedWriter getWriter(File file, - String encoding) throws IOException { - FileOutputStream outf = new FileOutputStream(file); - OutputStreamWriter out = new OutputStreamWriter(outf, encoding); - BufferedWriter result = new BufferedWriter(out); - return result; - } - - - /** - * Permet de creer un nouveu repertoire temporaire, l'effacement du - * répertoire est a la charge de l'appelant - * - * @param prefix le prefix du fichier - * @param suffix le suffix du fichier - * @param tmpdir le répertoire temporaire ou il faut creer le repertoire - * si null on utilise java.io.tmpdir - * @return le fichier pointant sur le nouveau repertoire - * @throws IOException if any io pb - */ - public static File createTempDirectory(String prefix, - String suffix, - File tmpdir) throws IOException { - if (tmpdir == null) { - tmpdir = new File(System.getProperty("java.io.tmpdir")); - } - File result = new File(tmpdir, prefix + System.currentTimeMillis() + suffix); - while (result.exists()) { - result = new File(tmpdir, prefix + System.currentTimeMillis() + suffix); - } - if (!result.mkdirs()) { - throw new IOException("Can't create temporary directory: " + result); - } - return result; - } - - /** - * Permet de creer un nouveu repertoire temporaire, l'effacement du - * répertoire est a la charge de l'appelant - * - * @param prefix le prefix du repertoire a creer - * @param suffix le suffix du repertoire a creer. - * @return the temprary created file - * @throws IOException if any io pb - */ - public static File createTempDirectory(String prefix, - String suffix) throws IOException { - return createTempDirectory(prefix, suffix, null); - } - - /** - * Regarde si le fichier f1 est plus recent que le fichier f2 - * - * @param f1 the first file - * @param f2 the second file - * @return vrai si f1 est plus recent que f2 - */ - public static boolean isNewer(File f1, File f2) { - boolean result = f1.lastModified() > f2.lastModified(); - return result; - } - - /** - * Permet de lire un fichier et de retourner sont contenu sous forme d'une - * chaine de carateres - * - * @param file le fichier a lire - * @return le contenu du fichier - * @throws IOException if any io pb - */ - public static String readAsString(File file) throws IOException { - StringBuffer result = new StringBuffer(); - char[] cbuf = new char[2000]; - BufferedReader in = getReader(file); - int nb = in.read(cbuf); - while (nb != -1) { - result.append(cbuf, 0, nb); - nb = in.read(cbuf); - } - in.close(); - return result.toString(); - } - - /** - * Permet de sauver une chaine directement dans un fichier - * - * Use default enconding : {@link #ENCODING}. - * - * @param file Le fichier dans lequel il faut ecrire la chaine - * @param content Le texte a ecrire dans le fichier - * @throws IOException if any pb while writing - */ - public static void writeString(File file, - String content) throws IOException { - //fixme on doit tester le retour de la méthode, car il se peut que le répertoire - // ne puisse etre cree. - File parentFile = file.getParentFile(); - //TODO tchemit 2011-05-15 Must test if directory was created (use - // the #createDirectoryIfNecessary method). - if (parentFile != null) { - parentFile.mkdirs(); - } - - BufferedWriter out = getWriter(file); - out.write(content); - out.close(); - } - - /** - * Permet de sauver une chaine directement dans un fichier - * - * @param file Le fichier dans lequel il faut ecrire la chaine - * @param content Le texte a ecrire dans le fichier - * @param encoding encoding to use - * @throws IOException if any pb while writing - */ - public static void writeString(File file, - String content, - String encoding) throws IOException { - //fixme on doit tester le retour de la méthode, car il se peut que le répertoire - // ne puisse être crée. - File parentFile = file.getParentFile(); - //TODO tchemit 2011-05-15 Must test if directory was created (use - // the #createDirectoryIfNecessary method). - if (parentFile != null) { - parentFile.mkdirs(); - } - - BufferedWriter out = getWriter(file, encoding); - out.write(content); - out.close(); - } - - /** - * Permet de donner une representation fichier pour une chaine de caractere. - * Le fichier sera automatiquement effacé à la fin de la JVM. - * - * @param content le contenu du fichier temporaire - * @return le fichier qui contient content - * @throws IOException if any io pb - */ - public static File getTempFile(String content) throws IOException { - return getTempFile(content, ""); - } - - /** - * Permet de donner une representation fichier pour une chaine de caractere. - * Le fichier sera automatiquement effacé à la fin de la JVM. - * - * @param content le contenu du fichier temporaire - * @param fileSuffix l'extension du fichier créé - * @return le fichier qui contient content - * @throws IOException if any io pb - */ - public static File getTempFile(String content, - String fileSuffix) throws IOException { - File result = File.createTempFile("tmp-" + FileUtil.class.getName(), - fileSuffix); - result.deleteOnExit(); - writeString(result, content); - return result; - } - - /** - * Equivalent de la methode basename unix. - * basename("/tmp/toto.xml", ".xml") → "toto" - * - * @param file le fichier dont on souhaite le nom sans le chemin - * @param suffixes si present represente le suffixe a eliminer du fichier - * s'il est trouvé - * @return le nom du fichier sans le suffixe si trouvé. - */ - public static String basename(File file, String... suffixes) { - String result = basename(file.getName(), suffixes); - return result; - } - - /** - * Equivalent de la methode basename unix. - * basename("/tmp/toto.xml", ".xml") → "toto" - * - * @param name le nom du fichier dont on souhaite le nom sans le chemin - * @param suffixes si present represente le suffixe a eliminer du fichier - * s'il est trouvé - * @return le nom du fichier sans le suffixe si trouvé. - * @since 1.4.2 - */ - public static String basename(String name, String... suffixes) { - String result = name; - for (String suffixe : suffixes) { - if (result.endsWith(suffixe)) { - result = result.substring(0, - result.length() - suffixe.length()); - break; - } - } - return result; - } - - /** - * Permet de récupérer l'extension d'un fichier - * - * @param file le fichier dont on souhaite l'extension - * @param extchars la liste des caracteres pouvant former l'extension - * dans l'ordre de preference. Si vide on utilise ".". - * @return l'extension ou la chaine vide si le fichier n'a pas d'extension - * l'extension ne contient pas le chaine de delimitation - */ - public static String extension(File file, String... extchars) { - String name = file.getName(); - String result = extension(name, extchars); - return result; - } - - /** - * Permet de récupérer l'extension d'un nom de fichier - * - * @param name le nom du fichier dont on souhaite l'extension - * @param extchars la liste des caracteres pouvant former l'extension - * dans l'ordre de preference. Si vide on utilise ".". - * @return l'extension ou la chaine vide si le fichier n'a pas d'extension - * l'extension ne contient pas le chaine de delimitation - * @since 1.4.2 - */ - public static String extension(String name, String... extchars) { - String result = ""; - - if (extchars.length == 0) { - extchars = new String[]{"."}; - } - for (String extchar : extchars) { - int pos = name.lastIndexOf(extchar); - if (pos != -1) { - result = name.substring(pos + extchar.length()); - break; - } - } - return result; - } - - /** - * Recupère le fichier dans le même répertoire que le fichier donné et dont - * on a changé l'extension. - * - * @param file le fichier d'origine - * @param newExtension la nouvelle extension à utiliser - * @param extchars la liste des extensions possibles - * @return le fichier dont on a changé l'extension - * @throws IOException si aucune extension trouvé dans le fichier d'origine - * @since 1.4.2 - */ - public static File changeExtension(File file, - String newExtension, - String... extchars) throws IOException { - String name = file.getName(); - String newName = changeExtension(name, newExtension, extchars); - File newFile = new File(file.getParentFile(), newName); - return newFile; - } - - /** - * Change l'extension du fichier en entrée avec la nouvelle extension - * - * @param name le nom de fichier à transformer - * @param newExtension la nouvelle extension à utiliser - * @param extchars la liste des extensions possibles - * @return le nouveau nom de fichier - * @throws IOException si aucune extension trouvé dans le fichier d'origine - * @since 1.4.2 - */ - public static String changeExtension(String name, - String newExtension, - String... extchars) throws IOException { - String extension = extension(name, extchars); - if (extension == null) { - throw new IOException("Could not find extension for name " + - name + " within " + Arrays.toString(extchars)); - } - String nameWithoutExtension = name.substring( - 0, name.length() - extension.length()); - String newName = nameWithoutExtension + newExtension; - return newName; - } - - /** - * Recupère le fichier mirroir du fichier {@code file} donnée qui est dans - * l'arborescence de {@code inputDirectory} dans le répertoire - * {@code ouputDirectory}. - * - * @param inputDirectory le répertoire de départ - * @param outputDirectory le répertoire cible - * @param file le fichier - * @return le fichier mirroir dans le répertoire cible - * @since 1.4.2 - */ - public static File getRelativeFile(File inputDirectory, - File outputDirectory, - File file) { - String inputPath = inputDirectory.getAbsolutePath(); - String s = file.getAbsolutePath(); - int index = s.indexOf(inputPath); - if (index == -1) { - throw new IllegalArgumentException( - "File " + file + " is not in " + inputDirectory); - } - String relativePath = s.substring(inputPath.length()); - File result = new File(outputDirectory, relativePath); - return result; - } - - public interface FileAction { - boolean doAction(File f); - } - - /** - * Retourne tous les sous répertoires du répertoire passé en argument. - * - * @param directory un répertoire - * @return une liste d'objet {@link File} de répertoires et ceci - * recursivement à partir de directory, si directory - * n'est pas un répertoire la liste est vide. - */ - public static List<File> getSubDirectories(File directory) { - class DirectoryFilter implements FileFilter { - @Override - public boolean accept(File f) { - return f.isDirectory(); - } - } - return getFilteredElements(directory, new DirectoryFilter(), true); - } - - /** - * Retourne tous les fichiers du répertoire passé en argument. - * - * @param directory un répertoire - * @return une liste d'objet {@link File} des fichiers et ceci - * recursivement à partir de directory, si directory n'est pas un - * répertoire la liste est vide - */ - public static List<File> getFiles(File directory) { - class NormalFileFilter implements FileFilter { - @Override - public boolean accept(File f) { - return f.isFile(); - } - } - return getFilteredElements(directory, new NormalFileFilter(), true); - } - - /** - * Retourne les fichiers d'un répertoire qui satisfont un certain pattern. - * La recherche est faite récursivement dans les sous répertoires - * - * @param directory le répertoire à partir duquel il faut faire la recherche - * @param pattern le pattern que doit respecter le fichier pour être dans la - * liste résultante - * @param recursively flag pour indiquer si on doit descendre dans les sous répertoires - * @return une liste d'objet {@link File} qui ont s'attisfait le - * pattern. - */ - public static List<File> find(File directory, - final String pattern, - boolean recursively) { - final String root = directory.getAbsolutePath(); - final int rootLength = root.length(); - - return getFilteredElements(directory, new FileFilter() { - @Override - public boolean accept(File f) { - String longFilename = f.getAbsolutePath(); - // + 1 to remove the first / or \ - String filename = longFilename.substring(rootLength + 1); - return filename.matches(pattern); - } - }, recursively); - } - - /** - * Retourne la liste de toutes les fichiers ou répertoire qui s'attisfont - * le filtre - * - * @param directory repertoire à partir duquel il faut faire la recherche - * @param ff le filtre à appliquer pour savoir si le fichier parcouru doit - * être conservé dans les résultats, ou null pour tous les fichiers - * @param recursively un flag pour indiquer si on doit descendre dans les répertoires - * @return une liste d'objet {@link File}, qui s'attisfont le filtre - */ - public static List<File> getFilteredElements(File directory, - FileFilter ff, - boolean recursively) { - ArrayList<File> result = new ArrayList<File>(); - LinkedList<File> todo = new LinkedList<File>(); - if (directory.isDirectory()) { - todo.addAll(Arrays.asList(directory.listFiles())); - } - while (todo.size() > 0) { - File file = todo.removeFirst(); - if (recursively && file.isDirectory()) { - File[] childs = file.listFiles(); - if (childs != null) { - // null if we don't have access to directory - todo.addAll(Arrays.asList(childs)); - } - } - if (ff == null || ff.accept(file)) { - result.add(file); - } - } - return result; - } - - /** - * Supprime recursivement tout le contenu d'un répertoire. - * - * @param directory le chemin du répertoire à supprimer - * @return vrai si tout se passe bien, false si la suppression d'un élement - * se passe mal - */ - public static boolean deleteRecursively(String directory) { - return deleteRecursively(new File(directory)); - } - - /** - * Supprime recursivement tout le contenu d'un répertoire. - * - * @param directory le répertoire à supprimer - * @return vrai si tout se passe bien, false si la suppression d'un élement - * se passe mal - */ - public static boolean deleteRecursively(File directory) { - return walkBefore(directory, new FileAction() { - @Override - public boolean doAction(File f) { - return f.delete(); - } - }); - } - - /** - * Permet de faire une action avant le parcours des fichiers, c-a-d que - * l'on fera l'action sur les fichiers contenu dans un répertoire - * après l'action sur le répertoire lui même. - * - * @param f le fichier ou répertoire à partir duquel il faut commencer - * @param fileAction l'action à effectuer sur chaque fichier - * @return le résultat des fileAction executé sur les fichiers, chaque - * résultat de FileAction sont assemblé par un ET logique pour donner - * le résultat final - */ - public static boolean walkAfter(File f, FileAction fileAction) { - boolean result = fileAction.doAction(f); - if (f.isDirectory()) { - File list[] = f.listFiles(); - for (File aList : list) { - result = result && walkAfter(aList, fileAction); - } - } - return result; - } - - /** - * Permet de faire une action apès le parcours des fichiers, c-a-d que - * l'on fera l'action sur les fichiers contenu dans un répertoire - * avant l'action sur le répertoire lui même. - * - * @param f le fichier ou répertoire à partir duquel il faut commencer - * @param fileAction l'action à effectuer sur chaque fichier - * @return le résultat des fileAction executé sur les fichiers, chaque - * résultat de FileAction sont assemblé par un ET logique pour donner - * le résultat final - */ - public static boolean walkBefore(File f, FileAction fileAction) { - boolean result = true; - if (f.isDirectory()) { - File list[] = f.listFiles(); - for (File aList : list) { - result = result && walkBefore(aList, fileAction); - } - } - return result && fileAction.doAction(f); - } - - /** - * Permet de copier le fichier source vers le fichier cible. - * - * @param source le fichier source - * @param target le fichier cible - * @throws IOException Erreur de copie - */ - public static void copy(File source, File target) throws IOException { - //fixme on doit tester le retour de la méthode, car il se peut que le répertoire - // ne puisse être copié. - //TODO tchemit 2011-05-15 Must test if directory was created (use - // the #createDirectoryIfNecessary method). - target.getParentFile().mkdirs(); - FileInputStream fileInputStream = new FileInputStream(source); - try { - FileChannel sourceChannel = fileInputStream.getChannel(); - FileOutputStream fileOutputStream = new FileOutputStream(target); - try { - FileChannel targetChannel = fileOutputStream.getChannel(); - sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); - // or - // targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); - targetChannel.close(); - } finally { - fileOutputStream.close(); - } - sourceChannel.close(); - } finally { - fileInputStream.close(); - } - } - - /** - * Permet de copier le fichier source vers le fichier cible. - * - * @param source le fichier source - * @param target le fichier cible - * @throws IOException Erreur de copie - */ - public static void copy(String source, String target) throws IOException { - copy(new File(source), new File(target)); - } - - /** - * Copie recursivement le repertoire source dans le repertoire destination - * - * copyRecursively("/truc/titi", "/var/tmp") donnera le repertoire - * "/var/tmp/titi" - * - * @param srcDir le répertoire source à copier - * @param destDir le répertoire destination où copier - * @param includePatterns les patterns que doivent resperter les - * fichiers/repertoires pour etre copié. Si vide alors tout est copié - * @throws IOException if any io pb - */ - public static void copyRecursively(File srcDir, - File destDir, - String... includePatterns) throws IOException { - copyAndRenameRecursively(srcDir, destDir, null, null, includePatterns); - } - - /** - * Copie recursivement le repertoire source dans le repertoire destination - * - * copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire - * "/var/tmp/bidulle", 'bidulle' remplacant 'titi' - * - * @param srcDir le répertoire source à copier - * @param destDir le répertoire destination où copier - * @param renameFrom pattern to permit rename file before uncompress it - * @param renameTo new name for file if renameFrom is applicable to it - * you can use $1, $2, ... if you have '(' ')' in renameFrom - * @param includePatterns les patterns que doivent resperter les - * fichiers/repertoires pour etre copié. Si vide alors tout est copié - * @throws IOException if any io pb - */ - public static void copyAndRenameRecursively(File srcDir, File destDir, - String renameFrom, - String renameTo, - String... includePatterns) throws IOException { - copyAndRenameRecursively(srcDir, - destDir, - true, - renameFrom, - renameTo, - false, - includePatterns - ); - } - - /** - * Copie recursivement le repertoire source dans le repertoire destination - * - * copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire - * "/var/tmp/bidulle", 'bidulle' remplacant 'titi' - * - * @param srcDir le répertoire source à copier - * @param destDir le répertoire destination où copier - * @param includeSrcDir si vrai alors le repertoire source est copie dans le - * repertoire destination et non pas seulement les fichiers qu'il contient - * @param renameFrom pattern to permit rename file before uncompress it - * @param renameTo new name for file if renameFrom is applicable to it - * you can use $1, $2, ... if you have '(' ')' in renameFrom - * @param exclude inverse include pattern interpretation - * @param includePatterns les patterns que doivent resperter les - * fichiers/repertoires pour etre copié. Si vide alors tout est copié - * @throws IOException if any io pb - */ - public static void copyAndRenameRecursively(File srcDir, - File destDir, - boolean includeSrcDir, - String renameFrom, - String renameTo, - boolean exclude, - String... includePatterns) throws IOException { - String rootSrc; - if (includeSrcDir) { - rootSrc = srcDir.getParent(); - } else { - rootSrc = srcDir.getPath(); - } - List<File> files = getFilteredElements(srcDir, null, true); - log.debug("copyRecursively: " + files); - for (File file : files) { - boolean doCopy = copyRecursivelyAccept(file, includePatterns); - if (exclude ^ doCopy) { - String path = file.getPath().substring(rootSrc.length()); - if (renameFrom != null && renameTo != null) { - String tmp = path.replaceAll(renameFrom, renameTo); - if (log.isDebugEnabled()) { - log.debug("rename " + path + " → " + tmp); - } - path = tmp; - } - - File destFile = new File(destDir, path); - if (file.isDirectory()) { - log.debug("create directory: " + destFile); - //fixme on doit tester le retour de la méthode, car il se peut que le répertoire - // ne puisse être copié. - destFile.mkdirs(); - } else { - log.debug("copy " + path + " to " + destFile); - copy(file, destFile); - } - } - } - } - - /** - * Get a ByteArrayOutputStream containing all data that could be read from the given InputStream - * @param inputStream the stream to read - * @param defaultBufferSize the buffer size - * @return the input stream read for input - * @throws IOException if any pb while reading or writing - */ - public static ByteArrayOutputStream readBytesFrom(InputStream inputStream, - int defaultBufferSize) throws IOException { - - ByteArrayOutputStream outputStream = new ByteArrayOutputStream( - defaultBufferSize); - byte[] buffer = new byte[defaultBufferSize]; - - int readBytes = inputStream.read(buffer); - while (readBytes > 0) { - outputStream.write(buffer, 0, readBytes); - readBytes = inputStream.read(buffer); - } - - return outputStream; - } - - /** - * @param file le fichier à tester. - * @param includePatterns les patterns pour accepeter le fichier depuis son nom - * @return <code>true</code> si le fichier est accepté, <code>false> autrement. - */ - private static boolean copyRecursivelyAccept(File file, - String[] includePatterns) { - boolean result = includePatterns.length == 0; - String filename = file.getAbsolutePath(); - for (String pattern : includePatterns) { - result = filename.matches(pattern); - if (result) { - break; - } - } - return result; - } - - /** - * Use the linePattern to break the given CharBuffer into lines, applying - * the input pattern to each line to see if we have a match - * - * Code taken from : - * - * http://java.sun.com/javase/6/docs/technotes/guides/io/example/Grep.java - * - * @param regex regex to search into file - * @param cb nio buffer - * @return matching lines (or {code null} if no matching lines) - * @throws IOException - * @since 1.1.2 - */ - protected static List<CharSequence> grep(String regex, CharBuffer cb) { - - List<CharSequence> linesList = null; - - Pattern pattern = Pattern.compile(regex); - - Pattern linePattern = Pattern.compile(".*\r?\n"); - - Matcher lm = linePattern.matcher(cb); // Line matcher - Matcher pm = null; // Pattern matcher - //int lines = 0; - while (lm.find()) { - //lines++; - CharSequence cs = lm.group(); // The current line - if (pm == null) { - pm = pattern.matcher(cs); - } - else { - pm.reset(cs); - } - if (pm.find()) { - // init - if (linesList == null) { - linesList = new ArrayList<CharSequence>(); - } - linesList.add(cs); - } - if (lm.end() == cb.limit()) { - break; - } - } - - return linesList; - } - - /** - * Java implementation for the unix grep command. - * - * Code taken from : - * - * http://java.sun.com/javase/6/docs/technotes/guides/io/example/Grep.java - * - * @param searchRegex regex to search into file - * @param f file to search into - * @param encoding encoding to use - * @return matching lines (or {code null} if no matching lines) - * @throws IOException - * @since 1.1.2 - */ - public static List<CharSequence> grep(String searchRegex, File f, String encoding) throws IOException { - - List<CharSequence> lines = null; - - FileInputStream fis = null; - FileChannel fc = null; - - try { - // Open the file and then get a channel from the stream - fis = new FileInputStream(f); - fc = fis.getChannel(); - - // Get the file's size and then map it into memory - int sz = (int)fc.size(); - MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); - - // Decode the file into a char buffer - Charset charset = Charset.forName(encoding); - CharsetDecoder decoder = charset.newDecoder(); - CharBuffer cb = decoder.decode(bb); - - // Perform the search - lines = grep(searchRegex, cb); - } - finally { - // Close the channel and the stream - if (fc != null) { - fc.close(); - } - if (fis != null) { - fis.close(); - } - } - - return lines; - } - - /** - * Java implementation for the unix grep command. - * - * @param searchRegex regex to search into file - * @param rootDirectory directory to seacrh into - * @param fileRegex regex for file to find in {@code rootDirectory} - * @param encoding encoding to use - * @return all matching lines for each files - * @throws IOException - * @since 1.1.2 - */ - public static Map<File, List<CharSequence>> grep(String searchRegex, File rootDirectory, String fileRegex, String encoding) throws IOException { - Map<File, List<CharSequence>> results = - new HashMap<File, List<CharSequence>>(); - List<File> files = find(rootDirectory, fileRegex, true); - for (File file : files) { - List<CharSequence> lines = grep(searchRegex, file, encoding); - if (lines != null) { - results.put(file, lines); - } - } - return results; - } - - /** - * Search for files matching regex in current directory. - * - * @param searchRegex regex to search into file - * @param fileRegex regex for file to find in current dir - * @param encoding encoding to use - * @return all matching lines for each files - * @throws IOException - * @since 1.1.2 - */ - public static Map<File, List<CharSequence>> grep(String searchRegex, String fileRegex, String encoding) throws IOException { - Map<File, List<CharSequence>> results = grep(searchRegex, - new File("."), - fileRegex, - encoding); - return results; - } - - /** - * Sed implementation for a single file. - * - * Oginal source code from http://kickjava.com/src/org/apache/lenya/util/SED.java.htm. - * - * @param searchRegex Prefix which shall be replaced - * @param replace Prefix which is going to replace the original - * @param file File which sed shall be applied - * @param encoding charset encoding - * @throws IOException - * @since 1.1.2 - */ - public static void sed(String searchRegex, - String replace, - File file, - String encoding) throws IOException { - - Pattern pattern = Pattern.compile(searchRegex); - - String outString = null; - FileInputStream fis = new FileInputStream(file); - try { - // Open the file and then get a channel from the stream - FileChannel fc = fis.getChannel(); - - // Get the file's size and then map it into memory - int sz = (int)fc.size(); - MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); - - // Decode the file into a char buffer - // Charset and decoder for encoding - Charset charset = Charset.forName(encoding); - CharsetDecoder decoder = charset.newDecoder(); - CharBuffer cb = decoder.decode(bb); - - Matcher matcher = pattern.matcher(cb); - outString = matcher.replaceAll(replace); - } finally { - fis.close(); - } - - if (outString != null) { - PrintStream ps = new PrintStream(new FileOutputStream(file)); - try { - ps.print(outString); - } finally { - ps.close(); - } - } - } - - /** - * Java implementation for the unix sed command. - * - * @param searchRegex regex to search into file - * @param replace string to replace matching patterns - * @param rootDirectory directory to search into - * @param fileRegex regex for file to find in {@code rootDirectory} - * @param encoding encoding to use - * @throws IOException - * @since 1.1.2 - */ - public static void sed(String searchRegex, - String replace, - File rootDirectory, - String fileRegex, - String encoding) throws IOException { - List<File> files = find(rootDirectory, fileRegex, true); - for (File file : files) { - sed(searchRegex, replace, file, encoding); - } - } - - /** - * Java implementation for the unix sed command. - * - * @param searchRegex regex to search into file - * @param replace string to replace matching patterns - * @param fileRegex regex for file to find in current dir - * @param encoding encoding to use - * @throws IOException - * @since 1.1.2 - */ - public static void sed(String searchRegex, - String replace, - String fileRegex, - String encoding) throws IOException { - sed(searchRegex, replace, new File("."), fileRegex, encoding); - } - - /** - * Create the directory (and his parents) if necessary. - * - * @param dir the directory to create if not exisiting - * @return {@code true} if directory was created, {@code false} if was no - * need to create it - * @throws IOException if could not create directory - * @since 1.3.2 - */ - public static boolean createDirectoryIfNecessary(File dir) - throws IOException { - if (!dir.exists()) { - boolean b = dir.mkdirs(); - if (!b) { - throw new IOException("Could not create directory " + dir); - } - return true; - } - return false; - } - - /** - * Obtain a file from the given {@code rootDirectory}, applying given paths. - * - * For example with paths = a, b and c, then result is : - * <pre> - * root/a/b/c - * </pre> - * - * @param rootDirectory the root directory - * @param paths paths to apply - * @return the final file - * @since 2.2 - */ - public static File getFileFromPaths(File rootDirectory, String... paths) { - File result = rootDirectory; - for (String path : paths) { - result = new File(result, path); - } - return result; - } - - /** - * Obtain a file fro the given {@code rootDirectory}, applying the fqn. - * - * For example with fqn = a.b.c, the result is : - * <pre> - * root/a/b/c - * </pre> - * - * @param rootDirectory the root directory - * @param fqn fqn of searched file - * @return the final file - * @since 2.2 - */ - public static File getFileFromFQN(File rootDirectory, String fqn) { - String[] paths = fqn.split("\\."); - - File result = getFileFromPaths(rootDirectory, paths); - return result; - } - -} // FileUtil diff --git a/src/test/resources/org/nuiton/util/reverseread.txt b/src/test/resources/org/nuiton/util/reverseread.txt deleted file mode 100644 index e73e515..0000000 --- a/src/test/resources/org/nuiton/util/reverseread.txt +++ /dev/null @@ -1,4 +0,0 @@ -Line 1 -Line 2 -Line 3 -Line 4 \ No newline at end of file diff --git a/src/test/resources/properties/recursive.properties b/src/test/resources/properties/recursive.properties deleted file mode 100644 index 7dace3a..0000000 --- a/src/test/resources/properties/recursive.properties +++ /dev/null @@ -1,23 +0,0 @@ -### -# #%L -# Nuiton Utils -# %% -# Copyright (C) 2004 - 2010 CodeLutin -# %% -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Lesser Public License for more details. -# -# You should have received a copy of the GNU General Lesser Public -# License along with this program. If not, see -# <http://www.gnu.org/licenses/lgpl-3.0.html>. -# #L% -### -username=World -helloWorld=Hello ${username} ! diff --git a/src/test/resources/properties/windows.properties b/src/test/resources/properties/windows.properties deleted file mode 100644 index 658dcf8..0000000 --- a/src/test/resources/properties/windows.properties +++ /dev/null @@ -1,27 +0,0 @@ -### -# #%L -# Nuiton Utils -# %% -# Copyright (C) 2004 - 2010 CodeLutin -# %% -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Lesser Public License for more details. -# -# You should have received a copy of the GNU General Lesser Public -# License along with this program. If not, see -# <http://www.gnu.org/licenses/lgpl-3.0.html>. -# #L% -### -vcs.ssh.keyFile=C\:\\Documents and Settings\\guest\\.ssh\\id_rsa -compilation.directory=E\:\\isis-build -simulator.password=guest -locale=fr_FR -simulationShowOnlyError=true -configFileName=C\:\\Documents and Settings\\guest\\.isis-config-3 diff --git a/src/test/resources/zip/not-a-zip.zip b/src/test/resources/zip/not-a-zip.zip deleted file mode 100644 index 678acb4..0000000 --- a/src/test/resources/zip/not-a-zip.zip +++ /dev/null @@ -1 +0,0 @@ -This is not a zip file... \ No newline at end of file diff --git a/src/test/resources/zip/test-uncompress.zip b/src/test/resources/zip/test-uncompress.zip deleted file mode 100644 index 626fda4..0000000 Binary files a/src/test/resources/zip/test-uncompress.zip and /dev/null differ diff --git a/src/test/resources/zip/this-is-a-zip.zap b/src/test/resources/zip/this-is-a-zip.zap deleted file mode 100644 index c15c5a4..0000000 Binary files a/src/test/resources/zip/this-is-a-zip.zap and /dev/null differ -- To stop receiving notification emails like this one, please contact nuiton.org SCM administrator <admin+scm@nuiton.org>.
participants (1)
-
nuiton.org scm