commons-beanutils-1.9.1-src/build.properties.sample100644 0 0 3045 12262570613 17600 0ustar 0 0 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Repository base path repository=${user.home}/.m2/repository # The pathname of the collections classes JAR file commons-collections.home=${repository}/commons-collections commons-collections.jar=${commons-collections.home}/commons-collections/3.2.1/commons-collections-3.2.1.jar commons-collections-testframework.jar=${commons-collections.home}/commons-collections-testframework/3.2.1/commons-collections-testframework-3.2.1.jar # The pathname of the Commons Logging JAR file commons-logging.home=${repository}/commons-logging/commons-logging commons-logging.jar=${commons-logging.home}/1.1.1/commons-logging-1.1.1.jar # The pathname of the "junit.jar" JAR file junit.home=${repository}/junit/junit junit.jar=${junit.home}/3.8.1/junit-3.8.1.jar commons-beanutils-1.9.1-src/build.xml100644 0 0 30073 12262570613 14745 0ustar 0 0 commons-beanutils-1.9.1-src/checkstyle.xml100644 0 0 4307 12262570613 15765 0ustar 0 0 commons-beanutils-1.9.1-src/license-header.txt100644 0 0 1463 12262570606 16520 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ commons-beanutils-1.9.1-src/LICENSE.txt100644 0 0 26450 12262570613 14753 0ustar 0 0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. commons-beanutils-1.9.1-src/NOTICE.txt100644 0 0 267 12262570613 14610 0ustar 0 0 Apache Commons BeanUtils Copyright 2000-2014 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). commons-beanutils-1.9.1-src/pom.xml100644 0 0 33360 12262570613 14443 0ustar 0 0 org.apache.commons commons-parent 32 4.0.0 commons-beanutils commons-beanutils 1.9.1 Apache Commons BeanUtils 2000 Apache Commons BeanUtils provides an easy-to-use but flexible wrapper around reflection and introspection. http://commons.apache.org/proper/commons-beanutils/ jira http://issues.apache.org/jira/browse/BEANUTILS scm:svn:http://svn.apache.org/repos/asf/commons/proper/beanutils/tags/BEANUTILS_1_9_1/ scm:svn:https://svn.apache.org/repos/asf/commons/proper/beanutils/tags/BEANUTILS_1_9_1/ http://svn.apache.org/viewvc/commons/proper/beanutils/tags/BEANUTILS_1_9_1/ apache.website Apache Commons Beanutils Site scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-beanutils Robert Burrell Donkin rdonkin rdonkin@apache.org The Apache Software Foundation Dion Gillard dion dion@apache.org The Apache Software Foundation Craig McClanahan craigmcc craigmcc@apache.org The Apache Software Foundation Geir Magnusson Jr. geirm geirm@apache.org The Apache Software Foundation Scott Sanders sanders sanders@apache.org The Apache Software Foundation James Strachan jstrachan jstrachan@apache.org The Apache Software Foundation Rodney Waldhoff rwaldhoff rwaldhoff@apache.org The Apache Software Foundation Martin van den Bemt mvdb mvdb@apache.org The Apache Software Foundation Yoav Shapira yoavs yoavs@apache.org The Apache Software Foundation Niall Pemberton niallp niallp@apache.org The Apache Software Foundation Simon Kitching skitching skitching@apache.org The Apache Software Foundation James Carman jcarman jcarman@apache.org The Apache Software Foundation Benedikt Ritter britter britter@apache.org The Apache Software Foundation Tim O'Brien tobrien tobrien@apache.org The Apache Software Foundation David Eric Pugh epugh epugh@apache.org The Apache Software Foundation Rodney Waldhoff rwaldhoff rwaldhoff@apache.org The Apache Software Foundation Morgan James Delagrange morgand morgand@apache.org The Apache Software Foundation John E. Conlon jconlon jconlon@apache.org The Apache Software Foundation Stephen Colebourne scolebourne scolebourne@apache.org The Apache Software Foundation Paul Jack Stephen Colebourne Berin Loritsch Alex Crown Marcus Zander Paul Hamamnt Rune Johannesen Clebert Suconic Norm Deane Ralph Schaer Chris Audley Rey François Gregor Raýman Jan Sorensen Eric Pabst Paulo Gaspar Michael Smith George Franciscus Erik Meade Tomas Viberg Yauheny Mikulski Michael Szlapa Juozas Baliuka commons-logging commons-logging 1.1.1 commons-collections commons-collections 3.2.1 commons-collections commons-collections-testframework 3.2.1 test junit junit 3.8.1 test org.apache.maven.plugins maven-surefire-plugin pertest -Xmx25M **/*TestCase.java **/*MemoryTestCase.java true org.apache.commons.logging.impl.LogFactoryImpl org.apache.commons.logging.impl.SimpleLog> WARN maven-assembly-plugin src/main/assembly/bin.xml src/main/assembly/src.xml gnu org.apache.maven.plugins maven-scm-publish-plugin javadocs** release-notes** 1.5 1.5 beanutils 1.9.1 BEANUTILS 12310460 org.apache.maven.plugins maven-checkstyle-plugin 2.6 ${basedir}/checkstyle.xml false ${basedir}/license-header.txt org.apache.maven.plugins maven-javadoc-plugin true http://download.oracle.com/javase/1.4.2/docs/api/ http://commons.apache.org/collections/api-release/ org.apache.maven.plugins maven-changes-plugin 2.9 %URL%/%ISSUE% changes-report commons-beanutils-1.9.1-src/README.txt100644 0 0 2005 12262570613 14574 0ustar 0 0 README ====== Jars ---- BeanUtils now comes packaged (into jars) in two different ways: an all-in-one jar (commons-beanutils.jar); and as modular component jars: commons-beanutils-core.jar (core classes) commons-beanutils-bean-collections.jar (additional dependency on commons-collections 3.0) Those who want it all should grab the all-in-one jar (and the optional dependencies) whereas those who need minimal dependencies should use commons-beanutils-core.jar plus any optional jars they plan to use. All classes that were in the last release are in commons-beanutils-core except for BeanComparator. Commons-Collections ------------------- BeanUtils now ships with a small number of commons collections classes. This is a temporary measure intended to allow BeanUtils core to be used with either commons-collections 2 or commons-collections-3 without a dependency on either. It is intended that soon BeanUtils core will have no dependency on any commons collection packaged classes.commons-beanutils-1.9.1-src/RELEASE-NOTES.txt100644 0 0 21260 12262570606 15633 0ustar 0 0 $Id: RELEASE-NOTES.txt 1555941 2014-01-06 17:45:14Z oheger $ 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. Commons BeanUtils Package Version 1.9.1 Release Notes INTRODUCTION: ============ This document contains the release notes for this version of the Commons BeanUtils package, and highlights changes since the previous version. For more information on Commons BeanUtils, see o http://commons.apache.org/beanutils/ Release 1.9.1 is a bug fix release which addresses a problem with the new feature of custom introspection introduced with release 1.9.0. It is fully binary compatible with the previous release. The minimum required Java version is 1.5. BUGFIXES in version 1.9.1 ========================= * [BEANUTILS-456] For PropertyDescriptors obtained via custom introspection now additional information is stored to prevent that write methods are lost during garbage collection. Release Notes for version 1.9.0 Release 1.9.0 contains some bug fixes and improvements that have accumulated after the 1.8.3 release. The most obvious change is that the new version now requires JDK 1.5 or higher, and that language features introduced with Java 5 (mainly generics) are used. A new feature has been introduced, too: the support for customizing bean introspection. Compatibility with 1.8.3 ======================== Adding generics to the BeanUtils API has been done in a backwards compatible way. This means that after type erasure the resulting classes look the same as in the previous version. A drawback of this approach is that sometimes it is not possible to use the logically correct type parameters because then backwards compatibility would be broken. One example is the BeanMap class: The class is now a Map while its keys actually are strings. However, implementing Map would change the signatures of some methods in an incompatible way. More details about limitations of the generification can be found at https://issues.apache.org/jira/browse/BEANUTILS-452 One exception from the compatibility rule is the ResultSetIterator class which now implements the Iterator interface. This causes a change in the return value of its next() method. ResultSetIterator is used internally as the iterator implementation within ResultSetDynaClass (it is probably a mistake that it is public). So chances are minimal that this change affects existing code. Another change which may affect compatibility is [BEANUTILS-379] (details can be found at https://issues.apache.org/jira/browse/BEANUTILS-379). Older versions of BeanUtils contained some classes that were copied from Commons Collections. These classes have now been removed, and a dependency to Commons Collections has been added; the collections jar now has to be contained in the classpath, too. Except for the change on ResultSetIterator and the additional dependency to Commons Collections, Commons BeanUtils 1.9.0 is fully binary compatible with the previous version 1.8.3. Changes on Converters ===================== The convert() method in the Converter interface now uses a type parameter in the following way: T convert(Class type, Object value); This makes it possible to access the converter's result in a type-safe way. Applying generics in this way revealed some inconsistencies in the Converter implementations. There were situations in which converters could return a result object of a different type as was requested. This was not a problem before because the result type was just Object. Now the compiler complains if a converter's result is not compatible with the desired target type. Because of that Converter implementations have been made more strict. A converter now checks the passed in target type, and if it cannot handle it, throws a ConversionException. This prevents unexpected results and makes converters more reliable (it could be considered a bug that a converter returns a result object of a different data type as the passed in target type). In a typical scenario, when converters are accessed via ConvertUtils, this change should not cause any problems because the converters are only called for the data types they have been registered for. But if converters are used directly, they might now throw ConversionExceptions when they did not in a previous version. BUGFIXES in version 1.9.0 ========================= * [BEANUTILS-454] BeanUtilsBean.copyProperties() no longer throws a ConversionException for null properties of certain data types. This fixes a regression introduced in version 1.8.0. The issue is related to [BEANUTILS-387]. * [BEANUTILS-411] BeanUtilsBean.setProperty throws IllegalArgumentException if getter of nested property returns null. * [BEANUTILS-408] MethodUtils.invokeMethod() throws NullPointerException when args==null. * [BEANUTILS-426] ConstructorUtils.invokeConstructor(Class klass, Object arg) throws NullPointerException when arg==null. * [BEANUTILS-380] BeanMap methods should initialize the root cause of exceptions that are thrown when running on JDK 1.4+. * [BEANUTILS-379] Remove copied Collection classes. * [BEANUTILS-378] BeanMap does not work in osgi (fixed by BEANUTILS-378). * [BEANUTILS-381] MethodUtils getMatchingAccessibleMethod() does not correctly handle inheritance and method overloading. New features in version 1.9.0 ============================= * [BEANUTILS-425] Support customization of introspection mechanism. * [BEANUTILS-428] Provide a BeanIntrospector implementation which supports properties in a fluent API. * [BEANUTILS-455] WrapDynaBeans can now be configured to use a specific instance of PropertyUtilsBean for introspection or property access. Other changes in version 1.9.0 ============================== * [BEANUTILS-452] Add generics. * [BEANUTILS-449] LocaleConverters do not take the target type into account. * [BEANUTILS-448] LocaleConverters do not check their default value. * [BEANUTILS-447] LazyDynaList.toArray() is not conform to the contract defined by the Collection interface. * [BEANUTILS-446] Some of the converters ignore the passed in target type. * [BEANUTILS-445] Converters can return an invalid result object if a default value is set. * [BEANUTILS-441] Replace UnmodifiableSet.decorate with Collections.unModifiableSet. * [BEANUTILS-436] Replace package.html with package-info.java. * [BEANUTILS-438] Add @Deprecated and @Override Annotations. * [BEANUTILS-437] Replace Date and Revision SVN keywords with Id. * [BEANUTILS-431] Remove @author tags and move missing authors to pom.xml. * [BEANUTILS-432] Switch to Java 1.5. * [BEANUTILS-429] Delete trailing white spaces and white spaces on empty lines from all files. * [BEANUTILS-427] Configure Checkstyle to check for trailing white spaces and white spaces on empty lines. Release Notes for version 1.8.3 Compatibility with 1.8.2 ======================== BeanUtils 1.8.3 is binary compatible release with Beanutils 1.8.2, containing only bug fixes. BeanUtils 1.8.3 requires a minimum of JDK 1.3. Memory Leak =========== A memory leak was found in BeanUtils 1.7.0 (see BEANUTILS-291) which was fixed in BeanUtils 1.8.0 for JDK 1.5+. Testing of BeanUtils 1.8.1 revealed that the leak still appears to exist in IBM's JDK 1.6 implementation. see http://issues.apache.org/jira/browse/BEANUTILS-291 http://issues.apache.org/jira/browse/BEANUTILS-366 BUGS FIXED: =========== The following is a list of the bugs fixed in this release, with their Jira issue number: * [BEANUTILS-373] - MethodUtils is not thread safe because WeakFastHashMap which uses WeakHashMap is not thread-safe * [BEANUTILS-371] - Add constructors which have useColumnLabel parameter to ResultSetDynaClass and RowSetDynaClass commons-beanutils-1.9.1-src/src/ 40755 0 0 0 12262570612 13572 5ustar 0 0 commons-beanutils-1.9.1-src/src/changes/ 40755 0 0 0 12262570613 15203 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/ 40755 0 0 0 12262570610 14514 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/assembly/ 40755 0 0 0 12262570610 16333 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/java/ 40755 0 0 0 12262570613 15440 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/ 40755 0 0 0 12262570610 16224 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/ 40755 0 0 0 12262570610 17445 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/ 40755 0 0 0 12262570610 21120 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/ 40755 0 0 0 12262570613 23111 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ 40755 0 0 0 12262570611 25301 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/expression/ 40755 0 0 0 12262570611 25306 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/ 40755 0 0 0 12262570612 24347 5ustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/ 40755 0 0 0 12262570612 26541 5ustar 0 0 commons-beanutils-1.9.1-src/src/media/ 40755 0 0 0 12262570606 14654 5ustar 0 0 commons-beanutils-1.9.1-src/src/site/ 40755 0 0 0 12262570613 14537 5ustar 0 0 commons-beanutils-1.9.1-src/src/site/resources/ 40755 0 0 0 12262570613 16551 5ustar 0 0 commons-beanutils-1.9.1-src/src/site/resources/images/ 40755 0 0 0 12262570612 20015 5ustar 0 0 commons-beanutils-1.9.1-src/src/site/xdoc/ 40755 0 0 0 12262570613 15474 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/ 40755 0 0 0 12262570606 14554 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/ 40755 0 0 0 12262570606 15475 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/ 40755 0 0 0 12262570606 16264 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/ 40755 0 0 0 12262570606 17505 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/ 40755 0 0 0 12262570606 21160 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/ 40755 0 0 0 12262570610 23141 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/ 40755 0 0 0 12262570610 24101 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/ 40755 0 0 0 12262570610 25222 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ 40755 0 0 0 12262570610 25333 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/expression/ 40755 0 0 0 12262570607 25346 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/ 40755 0 0 0 12262570607 24406 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/ 40755 0 0 0 12262570607 26600 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/memoryleaktests/ 40755 0 0 0 12262570607 26377 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/memoryleaktests/pojotests/ 40755 0 0 0 12262570607 30431 5ustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/priv/ 40755 0 0 0 12262570607 24127 5ustar 0 0 commons-beanutils-1.9.1-src/src/changes/changes.xml100644 0 0 66376 12262570613 17474 0ustar 0 0 Release Notes Write methods for PropertyDescriptors created during custom introspection are lost WrapDynaBeans always use the default PropertyUtilsBean instance BeanUtilsBean.copyProperties() throws conversion exception for null Date Add generics LocaleConverters do not take the target type into account LocaleConverters do not check their default value LazyDynaList.toArray() is not conform to the contract defined by the Collection interface Some of the converters ignore the passed in target type Converters can return an invalid result object if a default value is set Replace UnmodifiableSet.decorate with Collections.unModifiableSet Replace package.html with package-info.java Add @Deprecated and @Override Annotations Replace Date and Revision SVN keywords with Id Remove @author tags and move missing authors to pom.xml Switch to Java 1.5 Provide a BeanIntrospector implementation which supports properties in a fluent API Support customization of introspection mechanism BeanUtilsBean.setProperty throws IllegalArgumentException if getter of nested property returns null Delete trailing white spaces and white spaces on empty lines from all files Configure Checkstyle to check for trailing white spaces and white spaces on empty lines MethodUtils.invokeMethod() throws NullPointerException when args==null ConstructorUtils.invokeConstructor(Class klass, Object arg) throws NullPointerException when arg==null BeanMap methods should initialize the root cause of exceptions that are thrown when running on JDK 1.4+ Remove copied Collection classes. BeanMap does not work in osgi (fixed by BEANUTILS-379) MethodUtils getMatchingAccessibleMethod() does not correctly handle inheritance and method overloading. MethodUtils is not thread safe because WeakFastHashMap which uses WeakHashMap is not thread-safe (duplicate of BEANUTILS-318 which was not fixed properly in BeanUtils 1.8.0). Add constructors which have useColumnLabel parameter to ResultSetDynaClass and RowSetDynaClass. NullPointerException in BeanUtilsBean .setProperty() NPE in LazyDynaList JDBCDynaClass throws class not found exception under java6 MappedPropertyDescriptor#reLoadClass() possible NPE / odd code; also swallows Throwable BeanUtilsBean.setProperty throws IllegalArgumentException if value is null BeanUtilsBean.setProperty does not handle some kind of nested properties MappedPropertyDescriptor throws an exception after method reference has been garbage collected copyProperties throws NullPointerException if an IllegalArgumentException is thrown due to a null value parameter for a primitive FloatLocaleConverter cannot parse 0 Type in BooleanConverter: "Cna't convert value" Avoid calling setAccessible() if not needed Method createDynaProperty of JDBCDynaClass should first look for column label instead of column name in ResultSetMetadata object.. change visibility of method "evaluateValue" belongs to the class BeanPropertyValueEqualsPredicate to "protected". Allow access to non public class's public methods from a public sub-classes. Circular Reference on WeakHashMap. BeanUtilsBean.setProperty() does not support nested map. Unnecessary Garbage Objects in Class PropertyUtilsBean. ConvertingWrapDynaBean hides cause exceptions. MethodUtils.getAccessibleMethod(Method method) could not find right public method. NPE in ArrayConverter when converting a non-quoted string with underscores to a string array. LocaleConvertUtilsBean.convert throws NPE on null Locale when debug logging is enabled. Fix WeakHashMap is not thread safe in MethodUtils using new FastWeakHashMap. PropertyUtils.getPropertyType fails for DynaBeans contained within a normal bean. Iterating by a Map' key/value pairs in BeanUtilsBean and PropertyUtilsBean. Add plugable property name expression Resolver. General Converter implementation improvements: New AbstractConverter which provides a basic structure for Converter implementations and new NumberConverter implementation. Add new generic ArrayConverter implementation. Add new generic DateTimeConverter implementation. Better implementation of SqlDateConverter. Modified SqlDateConverter, SqlTimeConverter and SqlTimestampConverter to accept java.util.Date and Calendar object instances. Added tests. New Facade converter implementation - hide non-Converter public APIs. Add "t/f" to BooleanConverter. Support Mapped property inside a mapped property. Support Indexed property inside a mapped property. Support Arrays with multiple dimension. Include bean class in the message of PropertyUtilsBean exceptions. Provide better error message for "argument type mismatch". Improved messages for unknown properties. MethodUtils.invoke for static methods. Log or throw exception in PropertyUtilsBean. Added mechanism to initialize the "cause" on an Exception using reflection for JDK 1.4+ (copied from Commons HttpClient). Add lazyDynaList. Provide a Map decorator for a DynaBean (enables DynaBean to be used with other teechnologies such as JSTL). Implement equals() and hashCode() methods for DynaProperty. BeanUtils's tests fail to compile under JDK 1.6 Lock in BeanUtilsBean.getInstance( Beanutils's describe() method cannot determine reader methods for anonymous class. Added warning about describe behaviour to the javadocs. BeanUtilsBean's setProperty() does not convert objects using custom converters properly. Fix javadoc - IllegalArgumentException in BeanUtils.copyProperties when property types don't match. Writing to a mapped property requires a setter for a map, but never uses it. BeanUtilsBean.getArrayProperty() does not use ConvertUtils. MappedPropertyDescriptor - replace copied code. MappedPropertyDescriptor: Add comments re: * use of static variable safe in shared classloader * memory leak possible on webapp undeploy. MappedPropertyDescriptor doesn't recognize boolean property accessor. Add test for MappedPropertyDescriptor with different types on get/set methods. LocaleBeanUtils setProperty does not work on nested property. Package scope implementation of a public interface for mapped property fails (fixed by changes to MappedPropertyDescriptor associated with BEANUTILS-6) PropertyUtils incosistency - can't use "dot" in mapped properties for setProperty or getPropertyDescriptor (fixed by the changes for BEANUTILS-259 Plugable Property Name Expression Resolver). Public methods overriden in anonymous or private subclasses are not recognized by PropertyUtils. PropertyUtilsBean's isReadable() / isWriteable() always return false for mapped properties. PropertyUtilsBean isReadable() and isWriteable() methods do not work correctly for WrapDynaBean. PropertyUtils.isReadable() and PropertyUtils.getProperty() not consistent. PropertyUtilsBean.copyProperties does not catch NoSuchMethodException PropertyUtilsBean.getIndexedProperty()'s javadoc should indicate IndexOutOufBoundsException can be thrown rather than just ArrayIndexOutOufBoundsException. Create new methods getPropertyOfMapBean and setPropertyOfMapBean that the existing setNestedProperty and getNestedProperty methods now call when they discover the bean they are accessing implements Map. This makes it much easier for users to subclass and customise this behaviour of PropertyUtilsBean, eg in order to restore pre-1.5 behaviour. This patch also causes an exception to be thrown when the propertyName passed to getPropertyOfMapBean or setPropertyOfMapBean has MAPPED_DELIM or INDEXED_DELIM chars in it. This never worked as expected before (the whole string was treated literally as the propertyName), so throwing an exception here should not break any existing code. It should be of help to future developers who make this mistake though... Ignore simple properties on java.util.Map objects - Map methods are always used on a Map object. Reverts BEANUTILS-144. See BEANUTILS-162 for discussion. Correct getPropertyDescriptor() and setNestedProperty() methods to throw a NestedNullException rather than just IllegalArgumentException (consistent with the getNestedProperty() method). Problems on indexed property with JDK 1.4. BooleanArrayConverter: Use new AbstractArrayConverter constructors and Convert strings to booleans by invoking a BooleanConverter rather than hard-wiring the conversion. BooleanConverter: Add facility for user to override the default set of true and false string definitions and provide ability to pass special NO_DEFAULT object as the "defaultValue" constructor parameter. AbstractArrayConverter: provide ability to pass special NO_DEFAULT object as the "defaultValue" constructor parameter. DecimalLocaleConverter and subClasses never throw a ConversionException. FloatLocaleConverter cannot parse negative values. Improve ClassConverter robustness. DateLocaleConverter does not always throw an Exception for invalid dates. Don't try parsing values that are already Dates/Numbers in Date/Number locale Converters. WrapDynaClass: Added comment re potential memory leak, and safety when using shared classloader Make WrapDynaBean Serializable. WrapDynaBeanTestCase failing with jikes/kaffe because of static List in TestBean. Misleading error message in ConvertingWrapDynaBean. LazyDynaBean: don't try and instantiate properties of type Object.class. LazyDynabean JavaDoc corrections. LazyDynaClass can create a DynaProperty with a "null" type. JDBCDynaClass "lowerCase" option causes problems in RowSetDynaClass and ResultSetIterator. RowSetDynaClass fails to copy ResultSet to DynaBean with Oracle 10g JDBC driver. Fix BeanComparator throws wrong exception and hides cause. Deprecate the public static defaultTransformers HashMap and make it unmodifiable. Merge Bean-Collections back into core BeanUtils and remove Bean-Collections sub-project. Fixi the build to include all the tests and change the build.properties.sample so it's easier to use for the default maven user (ie: it looks by default in the .maven repository) Improvements to maven build. Add Implementation-Vendor-Id entry to jar's manifest. Resolve compiler warnings: Unused imports, un-read local variables, field hiding, empty block, improperly used statics, uncessary semi colons, unnecessary casts. Replace use of static Log objects with instance or local variables. It isn't safe to use static Log objects in code that might be deployed via a shared classloader as they will bind to the Log object from the context classloader in use when the first use happens. BeanMap: Fix internal variable to not include non-existant write methods. - ported from Commons Collections. Change MethodUtils to make getMatchingAccessibleMethod() method selection more rational. See href="http://commons.apache.org/beanutils/commons-beanutils-1.7.0/RELEASE-NOTES.txt See http://commons.apache.org/beanutils/commons-beanutils-1.6.1/RELEASE-NOTES.txt See http://commons.apache.org/beanutils/commons-beanutils-1.6/RELEASE-NOTES.txt See http://commons.apache.org/beanutils/commons-beanutils-1.5/RELEASE-NOTES.txt See http://commons.apache.org/beanutils/commons-beanutils-1.4.1/RELEASE-NOTES.txt See http://commons.apache.org/beanutils/commons-beanutils-1.4/RELEASE-NOTES.txt See http://commons.apache.org/beanutils/commons-beanutils-1.3/RELEASE-NOTES.txt See http://commons.apache.org/beanutils/commons-beanutils-1.2/RELEASE-NOTES.txt Version 1.1 Initial Release commons-beanutils-1.9.1-src/src/main/assembly/bin.xml100644 0 0 3135 12262570610 17724 0ustar 0 0 bin tar.gz zip false LICENSE.txt NOTICE.txt RELEASE-NOTES.txt target *.jar target/site/apidocs apidocs commons-beanutils-1.9.1-src/src/main/assembly/src.xml100644 0 0 3157 12262570610 17747 0ustar 0 0 src tar.gz zip ${artifactId}-${version}-src build.properties.sample build.xml checkstyle.xml LICENSE.txt license-header.txt NOTICE.txt pom.xml README.txt RELEASE-NOTES.txt src ././@LongLink100644 0 0 145 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BaseDynaBeanMapDecorator.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BaseDynaBeanMapDecorator.java100644 0 0 31314 12262570612 30647 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** *

A base class for decorators providing Map behavior on * {@link DynaBean}s.

* *

The motivation for this implementation is to provide access to {@link DynaBean} * properties in technologies that are unaware of BeanUtils and {@link DynaBean}s - * such as the expression languages of JSTL and JSF.

* *

This rather technical base class implements the methods of the * {@code Map} interface on top of a {@code DynaBean}. It was introduced * to handle generic parameters in a meaningful way without breaking * backwards compatibility of the {@link DynaBeanMapDecorator} class: A * map wrapping a {@code DynaBean} should be of type {@code Map}. * However, when using these generic parameters in {@code DynaBeanMapDecorator} * this would be an incompatible change (as method signatures would have to * be adapted). To solve this problem, this generic base class is added * which allows specifying the key type as parameter. This makes it easy to * have a new subclass using the correct generic parameters while * {@code DynaBeanMapDecorator} could still remain with compatible * parameters.

* * @param the type of the keys in the decorated map * @since BeanUtils 1.9.0 * @version $Id: BaseDynaBeanMapDecorator.java 1540332 2013-11-09 15:29:18Z oheger $ */ public abstract class BaseDynaBeanMapDecorator implements Map { private final DynaBean dynaBean; private final boolean readOnly; private transient Set keySet; // ------------------- Constructors ---------------------------------- /** * Constructs a read only Map for the specified * {@link DynaBean}. * * @param dynaBean The dyna bean being decorated * @throws IllegalArgumentException if the {@link DynaBean} is null. */ public BaseDynaBeanMapDecorator(DynaBean dynaBean) { this(dynaBean, true); } /** * Construct a Map for the specified {@link DynaBean}. * * @param dynaBean The dyna bean being decorated * @param readOnly true if the Map is read only * otherwise false * @throws IllegalArgumentException if the {@link DynaBean} is null. */ public BaseDynaBeanMapDecorator(DynaBean dynaBean, boolean readOnly) { if (dynaBean == null) { throw new IllegalArgumentException("DynaBean is null"); } this.dynaBean = dynaBean; this.readOnly = readOnly; } // ------------------- public Methods -------------------------------- /** * Indicate whether the Map is read only. * * @return true if the Map is read only, * otherwise false. */ public boolean isReadOnly() { return readOnly; } // ------------------- java.util.Map Methods ------------------------- /** * clear() operation is not supported. * * @throws UnsupportedOperationException */ public void clear() { throw new UnsupportedOperationException(); } /** * Indicate whether the {@link DynaBean} contains a specified * value for one (or more) of its properties. * * @param key The {@link DynaBean}'s property name * @return true if one of the {@link DynaBean}'s * properties contains a specified value. */ public boolean containsKey(Object key) { DynaClass dynaClass = getDynaBean().getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(toString(key)); return (dynaProperty == null ? false : true); } /** * Indicates whether the decorated {@link DynaBean} contains * a specified value. * * @param value The value to check for. * @return true if one of the the {@link DynaBean}'s * properties contains the specified value, otherwise * false. */ public boolean containsValue(Object value) { DynaProperty[] properties = getDynaProperties(); for (int i = 0; i < properties.length; i++) { String key = properties[i].getName(); Object prop = getDynaBean().get(key); if (value == null) { if (prop == null) { return true; } } else { if (value.equals(prop)) { return true; } } } return false; } /** *

Returns the Set of the property/value mappings * in the decorated {@link DynaBean}.

* *

Each element in the Set is a Map.Entry * type.

* * @return An unmodifiable set of the DynaBean * property name/value pairs */ public Set> entrySet() { DynaProperty[] properties = getDynaProperties(); Set> set = new HashSet>(properties.length); for (int i = 0; i < properties.length; i++) { K key = convertKey(properties[i].getName()); Object value = getDynaBean().get(properties[i].getName()); set.add(new MapEntry(key, value)); } return Collections.unmodifiableSet(set); } /** * Return the value for the specified key from * the decorated {@link DynaBean}. * * @param key The {@link DynaBean}'s property name * @return The value for the specified property. */ public Object get(Object key) { return getDynaBean().get(toString(key)); } /** * Indicate whether the decorated {@link DynaBean} has * any properties. * * @return true if the {@link DynaBean} has * no properties, otherwise false. */ public boolean isEmpty() { return (getDynaProperties().length == 0); } /** *

Returns the Set of the property * names in the decorated {@link DynaBean}.

* *

N.B.For {@link DynaBean}s whose associated {@link DynaClass} * is a {@link MutableDynaClass} a new Set is created every * time, otherwise the Set is created only once and cached.

* * @return An unmodifiable set of the {@link DynaBean}s * property names. */ public Set keySet() { if (keySet != null) { return keySet; } // Create a Set of the keys DynaProperty[] properties = getDynaProperties(); Set set = new HashSet(properties.length); for (int i = 0; i < properties.length; i++) { set.add(convertKey(properties[i].getName())); } set = Collections.unmodifiableSet(set); // Cache the keySet if Not a MutableDynaClass DynaClass dynaClass = getDynaBean().getDynaClass(); if (!(dynaClass instanceof MutableDynaClass)) { keySet = set; } return set; } /** * Set the value for the specified property in * the decorated {@link DynaBean}. * * @param key The {@link DynaBean}'s property name * @param value The value for the specified property. * @return The previous property's value. * @throws UnsupportedOperationException if * isReadOnly() is true. */ public Object put(K key, Object value) { if (isReadOnly()) { throw new UnsupportedOperationException("Map is read only"); } String property = toString(key); Object previous = getDynaBean().get(property); getDynaBean().set(property, value); return previous; } /** * Copy the contents of a Map to the decorated {@link DynaBean}. * * @param map The Map of values to copy. * @throws UnsupportedOperationException if * isReadOnly() is true. */ public void putAll(Map map) { if (isReadOnly()) { throw new UnsupportedOperationException("Map is read only"); } for (Map.Entry e : map.entrySet()) { put(e.getKey(), e.getValue()); } } /** * remove() operation is not supported. * * @param key The {@link DynaBean}'s property name * @return the value removed * @throws UnsupportedOperationException */ public Object remove(Object key) { throw new UnsupportedOperationException(); } /** * Returns the number properties in the decorated * {@link DynaBean}. * @return The number of properties. */ public int size() { return getDynaProperties().length; } /** * Returns the set of property values in the * decorated {@link DynaBean}. * * @return Unmodifiable collection of values. */ public Collection values() { DynaProperty[] properties = getDynaProperties(); List values = new ArrayList(properties.length); for (int i = 0; i < properties.length; i++) { String key = properties[i].getName(); Object value = getDynaBean().get(key); values.add(value); } return Collections.unmodifiableList(values); } // ------------------- protected Methods ----------------------------- /** * Provide access to the underlying {@link DynaBean} * this Map decorates. * * @return the decorated {@link DynaBean}. */ public DynaBean getDynaBean() { return dynaBean; } /** * Converts the name of a property to the key type of this decorator. * * @param propertyName the name of a property * @return the converted key to be used in the decorated map */ protected abstract K convertKey(String propertyName); // ------------------- private Methods ------------------------------- /** * Convenience method to retrieve the {@link DynaProperty}s * for this {@link DynaClass}. * * @return The an array of the {@link DynaProperty}s. */ private DynaProperty[] getDynaProperties() { return getDynaBean().getDynaClass().getDynaProperties(); } /** * Convenience method to convert an Object * to a String. * * @param obj The Object to convert * @return String representation of the object */ private String toString(Object obj) { return (obj == null ? null : obj.toString()); } /** * Map.Entry implementation. */ private static class MapEntry implements Map.Entry { private final K key; private final Object value; MapEntry(K key, Object value) { this.key = key; this.value = value; } @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry)o; return ((key.equals(e.getKey())) && (value == null ? e.getValue() == null : value.equals(e.getValue()))); } @Override public int hashCode() { return key.hashCode() + (value == null ? 0 : value.hashCode()); } public K getKey() { return key; } public Object getValue() { return value; } public Object setValue(Object value) { throw new UnsupportedOperationException(); } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BasicDynaBean.java100644 0 0 36274 12262570612 26527 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.Serializable; import java.lang.reflect.Array; import java.util.HashMap; import java.util.List; import java.util.Map; /** *

Minimal implementation of the DynaBean interface. Can be * used as a convenience base class for more sophisticated implementations.

* *

IMPLEMENTATION NOTE - Instances of this class that are * accessed from multiple threads simultaneously need to be synchronized.

* *

IMPLEMENTATION NOTE - Instances of this class can be * successfully serialized and deserialized ONLY if all * property values are Serializable.

* * @version $Id: BasicDynaBean.java 1540504 2013-11-10 18:22:57Z niallp $ */ public class BasicDynaBean implements DynaBean, Serializable { // ---------------------------------------------------------- Constructors /** * Construct a new DynaBean associated with the specified * DynaClass instance. * * @param dynaClass The DynaClass we are associated with */ public BasicDynaBean(DynaClass dynaClass) { super(); this.dynaClass = dynaClass; } // ---------------------------------------------------- Instance Variables /** * The DynaClass "base class" that this DynaBean * is associated with. */ protected DynaClass dynaClass = null; /** * The set of property values for this DynaBean, keyed by property name. */ protected HashMap values = new HashMap(); /** Map decorator for this DynaBean */ private transient Map mapDecorator; /** * Return a Map representation of this DynaBean. *

* This, for example, could be used in JSTL in the following way to access * a DynaBean's fooProperty: *
  • ${myDynaBean.map.fooProperty}
* * @return a Map representation of this DynaBean * @since 1.8.0 */ public Map getMap() { // cache the Map if (mapDecorator == null) { mapDecorator = new DynaBeanPropertyMapDecorator(this); } return mapDecorator; } // ------------------------------------------------------ DynaBean Methods /** * Does the specified mapped property contain a value for the specified * key value? * * @param name Name of the property to check * @param key Name of the key to check * @return true if the mapped property contains a value for * the specified key, otherwise false * * @exception IllegalArgumentException if there is no property * of the specified name */ public boolean contains(String name, String key) { Object value = values.get(name); if (value == null) { throw new NullPointerException ("No mapped value for '" + name + "(" + key + ")'"); } else if (value instanceof Map) { return (((Map) value).containsKey(key)); } else { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'"); } } /** * Return the value of a simple property with the specified name. * * @param name Name of the property whose value is to be retrieved * @return The property's value * * @exception IllegalArgumentException if there is no property * of the specified name */ public Object get(String name) { // Return any non-null value for the specified property Object value = values.get(name); if (value != null) { return (value); } // Return a null value for a non-primitive property Class type = getDynaProperty(name).getType(); if (!type.isPrimitive()) { return (value); } // Manufacture default values for primitive properties if (type == Boolean.TYPE) { return (Boolean.FALSE); } else if (type == Byte.TYPE) { return (new Byte((byte) 0)); } else if (type == Character.TYPE) { return (new Character((char) 0)); } else if (type == Double.TYPE) { return (new Double(0.0)); } else if (type == Float.TYPE) { return (new Float((float) 0.0)); } else if (type == Integer.TYPE) { return (new Integer(0)); } else if (type == Long.TYPE) { return (new Long(0)); } else if (type == Short.TYPE) { return (new Short((short) 0)); } else { return (null); } } /** * Return the value of an indexed property with the specified name. * * @param name Name of the property whose value is to be retrieved * @param index Index of the value to be retrieved * @return The indexed property's value * * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property * @exception NullPointerException if no array or List has been * initialized for this property */ public Object get(String name, int index) { Object value = values.get(name); if (value == null) { throw new NullPointerException ("No indexed value for '" + name + "[" + index + "]'"); } else if (value.getClass().isArray()) { return (Array.get(value, index)); } else if (value instanceof List) { return ((List) value).get(index); } else { throw new IllegalArgumentException ("Non-indexed property for '" + name + "[" + index + "]'"); } } /** * Return the value of a mapped property with the specified name, * or null if there is no value for the specified key. * * @param name Name of the property whose value is to be retrieved * @param key Key of the value to be retrieved * @return The mapped property's value * * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public Object get(String name, String key) { Object value = values.get(name); if (value == null) { throw new NullPointerException ("No mapped value for '" + name + "(" + key + ")'"); } else if (value instanceof Map) { return (((Map) value).get(key)); } else { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'"); } } /** * Return the DynaClass instance that describes the set of * properties available for this DynaBean. * * @return The associated DynaClass */ public DynaClass getDynaClass() { return (this.dynaClass); } /** * Remove any existing value for the specified key on the * specified mapped property. * * @param name Name of the property for which a value is to * be removed * @param key Key of the value to be removed * * @exception IllegalArgumentException if there is no property * of the specified name */ public void remove(String name, String key) { Object value = values.get(name); if (value == null) { throw new NullPointerException ("No mapped value for '" + name + "(" + key + ")'"); } else if (value instanceof Map) { ((Map) value).remove(key); } else { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'"); } } /** * Set the value of a simple property with the specified name. * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception NullPointerException if an attempt is made to set a * primitive property to null */ public void set(String name, Object value) { DynaProperty descriptor = getDynaProperty(name); if (value == null) { if (descriptor.getType().isPrimitive()) { throw new NullPointerException ("Primitive value for '" + name + "'"); } } else if (!isAssignable(descriptor.getType(), value.getClass())) { throw new ConversionException ("Cannot assign value of type '" + value.getClass().getName() + "' to property '" + name + "' of type '" + descriptor.getType().getName() + "'"); } values.put(name, value); } /** * Set the value of an indexed property with the specified name. * * @param name Name of the property whose value is to be set * @param index Index of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property */ public void set(String name, int index, Object value) { Object prop = values.get(name); if (prop == null) { throw new NullPointerException ("No indexed value for '" + name + "[" + index + "]'"); } else if (prop.getClass().isArray()) { Array.set(prop, index, value); } else if (prop instanceof List) { try { @SuppressWarnings("unchecked") // This is safe to cast because list properties are always // of type Object List list = (List) prop; list.set(index, value); } catch (ClassCastException e) { throw new ConversionException(e.getMessage()); } } else { throw new IllegalArgumentException ("Non-indexed property for '" + name + "[" + index + "]'"); } } /** * Set the value of a mapped property with the specified name. * * @param name Name of the property whose value is to be set * @param key Key of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public void set(String name, String key, Object value) { Object prop = values.get(name); if (prop == null) { throw new NullPointerException ("No mapped value for '" + name + "(" + key + ")'"); } else if (prop instanceof Map) { @SuppressWarnings("unchecked") // This is safe to cast because mapped properties are always // maps of types String -> Object Map map = (Map) prop; map.put(key, value); } else { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'"); } } // ------------------------------------------------------ Protected Methods /** * Return the property descriptor for the specified property name. * * @param name Name of the property for which to retrieve the descriptor * @return The property descriptor * * @exception IllegalArgumentException if this is not a valid property * name for our DynaClass */ protected DynaProperty getDynaProperty(String name) { DynaProperty descriptor = getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new IllegalArgumentException ("Invalid property name '" + name + "'"); } return (descriptor); } /** * Is an object of the source class assignable to the destination class? * * @param dest Destination class * @param source Source class * @return true if the source class is assignable to the * destination class, otherwise false */ protected boolean isAssignable(Class dest, Class source) { if (dest.isAssignableFrom(source) || ((dest == Boolean.TYPE) && (source == Boolean.class)) || ((dest == Byte.TYPE) && (source == Byte.class)) || ((dest == Character.TYPE) && (source == Character.class)) || ((dest == Double.TYPE) && (source == Double.class)) || ((dest == Float.TYPE) && (source == Float.class)) || ((dest == Integer.TYPE) && (source == Integer.class)) || ((dest == Long.TYPE) && (source == Long.class)) || ((dest == Short.TYPE) && (source == Short.class))) { return (true); } else { return (false); } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BasicDynaClass.java100644 0 0 22775 12262570612 26730 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; /** *

Minimal implementation of the DynaClass interface. Can be * used as a convenience base class for more sophisticated implementations.

* *

IMPLEMENTATION NOTE - The DynaBean * implementation class supplied to our constructor MUST have a one-argument * constructor of its own that accepts a DynaClass. This is * used to associate the DynaBean instance with this DynaClass.

* * @version $Id: BasicDynaClass.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class BasicDynaClass implements DynaClass, Serializable { // ----------------------------------------------------------- Constructors /** * Construct a new BasicDynaClass with default parameters. */ public BasicDynaClass() { this(null, null, null); } /** * Construct a new BasicDynaClass with the specified parameters. * * @param name Name of this DynaBean class * @param dynaBeanClass The implementation class for new instances */ public BasicDynaClass(String name, Class dynaBeanClass) { this(name, dynaBeanClass, null); } /** * Construct a new BasicDynaClass with the specified parameters. * * @param name Name of this DynaBean class * @param dynaBeanClass The implementation class for new intances * @param properties Property descriptors for the supported properties */ public BasicDynaClass(String name, Class dynaBeanClass, DynaProperty[] properties) { super(); if (name != null) { this.name = name; } if (dynaBeanClass == null) { dynaBeanClass = BasicDynaBean.class; } setDynaBeanClass(dynaBeanClass); if (properties != null) { setProperties(properties); } } // ----------------------------------------------------- Instance Variables /** * The constructor of the dynaBeanClass that we will use * for creating new instances. */ protected transient Constructor constructor = null; /** * The method signature of the constructor we will use to create * new DynaBean instances. */ protected static Class[] constructorTypes = { DynaClass.class }; /** * The argument values to be passed to the constructore we will use * to create new DynaBean instances. */ protected Object[] constructorValues = { this }; /** * The DynaBean implementation class we will use for * creating new instances. */ protected Class dynaBeanClass = BasicDynaBean.class; /** * The "name" of this DynaBean class. */ protected String name = this.getClass().getName(); /** * The set of dynamic properties that are part of this DynaClass. */ protected DynaProperty[] properties = new DynaProperty[0]; /** * The set of dynamic properties that are part of this DynaClass, * keyed by the property name. Individual descriptor instances will * be the same instances as those in the properties list. */ protected HashMap propertiesMap = new HashMap(); // ------------------------------------------------------ DynaClass Methods /** * Return the name of this DynaClass (analogous to the * getName() method of java.lang.ClassDynaClass implementation class to support * different dynamic classes, with different sets of properties. * * @return the name of the DynaClass */ public String getName() { return (this.name); } /** * Return a property descriptor for the specified property, if it exists; * otherwise, return null. * * @param name Name of the dynamic property for which a descriptor * is requested * @return The descriptor for the specified property * * @exception IllegalArgumentException if no property name is specified */ public DynaProperty getDynaProperty(String name) { if (name == null) { throw new IllegalArgumentException ("No property name specified"); } return propertiesMap.get(name); } /** *

Return an array of ProperyDescriptors for the properties * currently defined in this DynaClass. If no properties are defined, a * zero-length array will be returned.

* *

FIXME - Should we really be implementing * getBeanInfo() instead, which returns property descriptors * and a bunch of other stuff?

* * @return the set of properties for this DynaClass */ public DynaProperty[] getDynaProperties() { return (properties); } /** * Instantiate and return a new DynaBean instance, associated * with this DynaClass. * * @return A new DynaBean instance * @exception IllegalAccessException if the Class or the appropriate * constructor is not accessible * @exception InstantiationException if this Class represents an abstract * class, an array class, a primitive type, or void; or if instantiation * fails for some other reason */ public DynaBean newInstance() throws IllegalAccessException, InstantiationException { try { // Refind the constructor after a deserialization (if needed) if (constructor == null) { setDynaBeanClass(this.dynaBeanClass); } // Invoke the constructor to create a new bean instance return ((DynaBean) constructor.newInstance(constructorValues)); } catch (InvocationTargetException e) { throw new InstantiationException (e.getTargetException().getMessage()); } } // --------------------------------------------------------- Public Methods /** * Return the Class object we will use to create new instances in the * newInstance() method. This Class MUST * implement the DynaBean interface. * * @return The class of the {@link DynaBean} */ public Class getDynaBeanClass() { return (this.dynaBeanClass); } // ------------------------------------------------------ Protected Methods /** * Set the Class object we will use to create new instances in the * newInstance() method. This Class MUST * implement the DynaBean interface. * * @param dynaBeanClass The new Class object * * @exception IllegalArgumentException if the specified Class does not * implement the DynaBean interface */ protected void setDynaBeanClass(Class dynaBeanClass) { // Validate the argument type specified if (dynaBeanClass.isInterface()) { throw new IllegalArgumentException ("Class " + dynaBeanClass.getName() + " is an interface, not a class"); } if (!DynaBean.class.isAssignableFrom(dynaBeanClass)) { throw new IllegalArgumentException ("Class " + dynaBeanClass.getName() + " does not implement DynaBean"); } // Identify the Constructor we will use in newInstance() try { this.constructor = dynaBeanClass.getConstructor(constructorTypes); } catch (NoSuchMethodException e) { throw new IllegalArgumentException ("Class " + dynaBeanClass.getName() + " does not have an appropriate constructor"); } this.dynaBeanClass = dynaBeanClass; } /** * Set the list of dynamic properties supported by this DynaClass. * * @param properties List of dynamic properties to be supported */ protected void setProperties(DynaProperty[] properties) { this.properties = properties; propertiesMap.clear(); for (int i = 0; i < properties.length; i++) { propertiesMap.put(properties[i].getName(), properties[i]); } } } ././@LongLink100644 0 0 150 12262571655 10262 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanAccessLanguageException.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanAccessLanguageException.j100644 0 0 3447 12262570611 30701 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * Thrown to indicate that the Bean Access Language cannot execute query * against given bean. This is a runtime exception and access langauges are encouraged * to subclass to create custom exceptions whenever appropriate. * * @since 1.7 * @version $Id: BeanAccessLanguageException.java 1454597 2013-03-08 21:58:12Z britter $ */ public class BeanAccessLanguageException extends IllegalArgumentException { // --------------------------------------------------------- Constuctors /** * Constructs a BeanAccessLanguageException without a detail message. */ public BeanAccessLanguageException() { super(); } /** * Constructs a BeanAccessLanguageException without a detail message. * * @param message the detail message explaining this exception */ public BeanAccessLanguageException(String message) { super(message); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanComparator.java100644 0 0 20676 12262570612 27000 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.Comparator; import org.apache.commons.collections.comparators.ComparableComparator; /** *

* This comparator compares two beans by the specified bean property. * It is also possible to compare beans based on nested, indexed, * combined, mapped bean properties. Please see the {@link PropertyUtilsBean} * documentation for all property name possibilities. * *

* Note: The BeanComparator passes the values of the specified * bean property to a ComparableComparator, if no comparator is * specified in the constructor. If you are comparing two beans based * on a property that could contain "null" values, a suitable Comparator * or ComparatorChain should be supplied in the constructor. * Note that the passed in {@code Comparator} must be able to handle the * passed in objects. Because the type of the property to be compared is not * known at compile time no type checks can be performed by the compiler. * Thus {@code ClassCastException} exceptions can be thrown if unexpected * property values occur. *

* * @param the type of beans to be compared by this {@code Comparator} * @version $Id: BeanComparator.java 1540510 2013-11-10 18:39:37Z oheger $ */ public class BeanComparator implements Comparator, Serializable { private String property; private final Comparator comparator; /** *

Constructs a Bean Comparator without a property set. *

* Note that this is intended to be used * only in bean-centric environments. *

* Until {@link #setProperty} is called with a non-null value. * this comparator will compare the Objects only. *

*/ public BeanComparator() { this( null ); } /** *

Constructs a property-based comparator for beans. * This compares two beans by the property * specified in the property parameter. This constructor creates * a BeanComparator that uses a ComparableComparator * to compare the property values. *

* *

Passing "null" to this constructor will cause the BeanComparator * to compare objects based on natural order, that is * java.lang.Comparable. *

* * @param property String Name of a bean property, which may contain the * name of a simple, nested, indexed, mapped, or combined * property. See {@link PropertyUtilsBean} for property query language syntax. * If the property passed in is null then the actual objects will be compared */ public BeanComparator( String property ) { this( property, ComparableComparator.getInstance() ); } /** * Constructs a property-based comparator for beans. * This constructor creates * a BeanComparator that uses the supplied Comparator to compare * the property values. * * @param property Name of a bean property, can contain the name * of a simple, nested, indexed, mapped, or combined * property. See {@link PropertyUtilsBean} for property query language * syntax. * @param comparator BeanComparator will pass the values of the * specified bean property to this Comparator. * If your bean property is not a comparable or * contains null values, a suitable comparator * may be supplied in this constructor. */ public BeanComparator( String property, Comparator comparator ) { setProperty( property ); if (comparator != null) { this.comparator = comparator; } else { this.comparator = ComparableComparator.getInstance(); } } /** * Sets the method to be called to compare two JavaBeans * * @param property String method name to call to compare * If the property passed in is null then the actual objects will be compared */ public void setProperty( String property ) { this.property = property; } /** * Gets the property attribute of the BeanComparator * * @return String method name to call to compare. * A null value indicates that the actual objects will be compared */ public String getProperty() { return property; } /** * Gets the Comparator being used to compare beans. * * @return the Comparator being used to compare beans */ public Comparator getComparator() { return comparator; } /** * Compare two JavaBeans by their shared property. * If {@link #getProperty} is null then the actual objects will be compared. * * @param o1 Object The first bean to get data from to compare against * @param o2 Object The second bean to get data from to compare * @return int negative or positive based on order */ public int compare( T o1, T o2 ) { if ( property == null ) { // compare the actual objects return internalCompare( o1, o2 ); } try { Object value1 = PropertyUtils.getProperty( o1, property ); Object value2 = PropertyUtils.getProperty( o2, property ); return internalCompare( value1, value2 ); } catch ( IllegalAccessException iae ) { throw new RuntimeException( "IllegalAccessException: " + iae.toString() ); } catch ( InvocationTargetException ite ) { throw new RuntimeException( "InvocationTargetException: " + ite.toString() ); } catch ( NoSuchMethodException nsme ) { throw new RuntimeException( "NoSuchMethodException: " + nsme.toString() ); } } /** * Two BeanComparator's are equals if and only if * the wrapped comparators and the property names to be compared * are equal. * @param o Comparator to compare to * @return whether the the comparators are equal or not */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BeanComparator)) { return false; } final BeanComparator beanComparator = (BeanComparator) o; if (!comparator.equals(beanComparator.comparator)) { return false; } if (property != null) { if (!property.equals(beanComparator.property)) { return false; } } else { return (beanComparator.property == null); } return true; } /** * Hashcode compatible with equals. * @return the hash code for this comparator */ @Override public int hashCode() { int result; result = comparator.hashCode(); return result; } /** * Compares the given values using the internal {@code Comparator}. * Note: This comparison cannot be performed in a type-safe way; so * {@code ClassCastException} exceptions may be thrown. * * @param val1 the first value to be compared * @param val2 the second value to be compared * @return the result of the comparison */ private int internalCompare(Object val1, Object val2) { @SuppressWarnings("rawtypes") // to make the compiler happy Comparator c = comparator; return c.compare(val1, val2); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanIntrospectionData.java100644 0 0 14127 12262570612 30315 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** *

* An internally used helper class for storing introspection information about a bean * class. *

*

* This class is used by {@link PropertyUtilsBean}. When accessing bean properties via * reflection information about the properties available and their types and access * methods must be present. {@code PropertyUtilsBean} stores this information in a cache * so that it can be accessed quickly. The cache stores instances of this class. *

*

* This class mainly stores information about the properties of a bean class. Per default, * this is contained in {@code PropertyDescriptor} objects. Some additional information * required by the {@code BeanUtils} library is also stored here. *

* * @version $Id: BeanIntrospectionData.java 1555233 2014-01-03 19:41:04Z oheger $ * @since 1.9.1 */ class BeanIntrospectionData { /** An array with property descriptors for the managed bean class. */ private final PropertyDescriptor[] descriptors; /** A map for remembering the write method names for properties. */ private final Map writeMethodNames; /** * Creates a new instance of {@code BeanIntrospectionData} and initializes its * completely. * * @param descs the array with the descriptors of the available properties */ public BeanIntrospectionData(PropertyDescriptor[] descs) { this(descs, setUpWriteMethodNames(descs)); } /** * Creates a new instance of {@code BeanIntrospectionData} and allows setting the map * with write method names. This constructor is mainly used for testing purposes. * * @param descs the array with the descriptors of the available properties * @param writeMethNames the map with the names of write methods */ BeanIntrospectionData(PropertyDescriptor[] descs, Map writeMethNames) { descriptors = descs; writeMethodNames = writeMethNames; } /** * Returns the array with property descriptors. * * @return the property descriptors for the associated bean class */ public PropertyDescriptor[] getDescriptors() { return descriptors; } /** * Returns the {@code PropertyDescriptor} for the property with the specified name. If * this property is unknown, result is null. * * @param name the name of the property in question * @return the {@code PropertyDescriptor} for this property or null */ public PropertyDescriptor getDescriptor(String name) { for (PropertyDescriptor pd : getDescriptors()) { if (name.equals(pd.getName())) { return pd; } } return null; } /** * Returns the write method for the property determined by the given * {@code PropertyDescriptor}. This information is normally available in the * descriptor object itself. However, at least by the ORACLE implementation, the * method is stored as a {@code SoftReference}. If this reference has been freed by * the GC, it may be the case that the method cannot be obtained again. Then, * additional information stored in this object is necessary to obtain the method * again. * * @param beanCls the class of the affected bean * @param desc the {@code PropertyDescriptor} of the desired property * @return the write method for this property or null if there is none */ public Method getWriteMethod(Class beanCls, PropertyDescriptor desc) { Method method = desc.getWriteMethod(); if (method == null) { String methodName = writeMethodNames.get(desc.getName()); if (methodName != null) { method = MethodUtils.getAccessibleMethod(beanCls, methodName, desc.getPropertyType()); if (method != null) { try { desc.setWriteMethod(method); } catch (IntrospectionException e) { // ignore, in this case the method is not cached } } } } return method; } /** * Initializes the map with the names of the write methods for the supported * properties. The method names - if defined - need to be stored separately because * they may get lost when the GC claims soft references used by the * {@code PropertyDescriptor} objects. * * @param descs the array with the descriptors of the available properties * @return the map with the names of write methods for properties */ private static Map setUpWriteMethodNames(PropertyDescriptor[] descs) { Map methods = new HashMap(); for (PropertyDescriptor pd : descs) { Method method = pd.getWriteMethod(); if (method != null) { methods.put(pd.getName(), method.getName()); } } return methods; } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanIntrospector.java100644 0 0 4530 12262570612 27333 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IntrospectionException; /** *

* Definition of an interface for components that can perform introspection on * bean classes. *

*

* Before {@link PropertyUtils} can be used for interaction with a specific Java * class, the class's properties have to be determined. This is called * introspection and is initiated automatically on demand. * PropertyUtils does not perform introspection on its own, but * delegates this task to one or more objects implementing this interface. This * makes it possible to customize introspection which may be useful for certain * code bases using non-standard conventions for accessing properties. *

* * @version $Id: BeanIntrospector.java 1540359 2013-11-09 18:10:52Z oheger $ * @since 1.9 */ public interface BeanIntrospector { /** * Performs introspection on a Java class. The current class to be inspected * can be queried from the passed in IntrospectionContext * object. A typical implementation has to obtain this class, determine its * properties according to the rules it implements, and add them to the * passed in context object. * * @param icontext the context object for interaction with the initiator of * the introspection request * @throws IntrospectionException if an error occurs during introspection */ void introspect(IntrospectionContext icontext) throws IntrospectionException; } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanMap.java100644 0 0 100615 12262570612 25416 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.keyvalue.AbstractMapEntry; /** * An implementation of Map for JavaBeans which uses introspection to * get and put properties in the bean. *

* If an exception occurs during attempts to get or set a property then the * property is considered non existent in the Map * * @version $Id: BeanMap.java 1540518 2013-11-10 19:04:04Z oheger $ */ public class BeanMap extends AbstractMap implements Cloneable { private transient Object bean; private transient HashMap readMethods = new HashMap(); private transient HashMap writeMethods = new HashMap(); private transient HashMap> types = new HashMap>(); /** * An empty array. Used to invoke accessors via reflection. */ public static final Object[] NULL_ARGUMENTS = {}; /** * Maps primitive Class types to transformers. The transformer * transform strings into the appropriate primitive wrapper. * * N.B. private & unmodifiable replacement for the (public & static) defaultTransformers instance. */ private static final Map, Transformer> typeTransformers = Collections.unmodifiableMap(createTypeTransformers()); /** * This HashMap has been made unmodifiable to prevent issues when * loaded in a shared ClassLoader enviroment. * * @see "http://issues.apache.org/jira/browse/BEANUTILS-112" * @deprecated Use {@link BeanMap#getTypeTransformer(Class)} method */ @Deprecated public static HashMap defaultTransformers = new HashMap() { @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean containsKey(Object key) { return typeTransformers.containsKey(key); } @Override public boolean containsValue(Object value) { return typeTransformers.containsValue(value); } @Override public Set entrySet() { return typeTransformers.entrySet(); } @Override public Object get(Object key) { return typeTransformers.get(key); } @Override public boolean isEmpty() { return false; } @Override public Set keySet() { return typeTransformers.keySet(); } @Override public Object put(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public void putAll(Map m) { throw new UnsupportedOperationException(); } @Override public Object remove(Object key) { throw new UnsupportedOperationException(); } @Override public int size() { return typeTransformers.size(); } @Override public Collection values() { return typeTransformers.values(); } }; private static Map, Transformer> createTypeTransformers() { Map, Transformer> defaultTransformers = new HashMap, Transformer>(); defaultTransformers.put( Boolean.TYPE, new Transformer() { public Object transform( Object input ) { return Boolean.valueOf( input.toString() ); } } ); defaultTransformers.put( Character.TYPE, new Transformer() { public Object transform( Object input ) { return new Character( input.toString().charAt( 0 ) ); } } ); defaultTransformers.put( Byte.TYPE, new Transformer() { public Object transform( Object input ) { return Byte.valueOf( input.toString() ); } } ); defaultTransformers.put( Short.TYPE, new Transformer() { public Object transform( Object input ) { return Short.valueOf( input.toString() ); } } ); defaultTransformers.put( Integer.TYPE, new Transformer() { public Object transform( Object input ) { return Integer.valueOf( input.toString() ); } } ); defaultTransformers.put( Long.TYPE, new Transformer() { public Object transform( Object input ) { return Long.valueOf( input.toString() ); } } ); defaultTransformers.put( Float.TYPE, new Transformer() { public Object transform( Object input ) { return Float.valueOf( input.toString() ); } } ); defaultTransformers.put( Double.TYPE, new Transformer() { public Object transform( Object input ) { return Double.valueOf( input.toString() ); } } ); return defaultTransformers; } // Constructors //------------------------------------------------------------------------- /** * Constructs a new empty BeanMap. */ public BeanMap() { } /** * Constructs a new BeanMap that operates on the * specified bean. If the given bean is null, then * this map will be empty. * * @param bean the bean for this map to operate on */ public BeanMap(Object bean) { this.bean = bean; initialise(); } // Map interface //------------------------------------------------------------------------- /** * Renders a string representation of this object. * @return a String representation of this object */ @Override public String toString() { return "BeanMap<" + String.valueOf(bean) + ">"; } /** * Clone this bean map using the following process: * *

    *
  • If there is no underlying bean, return a cloned BeanMap without a * bean. * *
  • Since there is an underlying bean, try to instantiate a new bean of * the same type using Class.newInstance(). * *
  • If the instantiation fails, throw a CloneNotSupportedException * *
  • Clone the bean map and set the newly instantiated bean as the * underlying bean for the bean map. * *
  • Copy each property that is both readable and writable from the * existing object to a cloned bean map. * *
  • If anything fails along the way, throw a * CloneNotSupportedException. * *
      * * @return a cloned instance of this bean map * @throws CloneNotSupportedException if the underlying bean * cannot be cloned */ @Override public Object clone() throws CloneNotSupportedException { BeanMap newMap = (BeanMap)super.clone(); if(bean == null) { // no bean, just an empty bean map at the moment. return a newly // cloned and empty bean map. return newMap; } Object newBean = null; Class beanClass = bean.getClass(); // Cannot throw Exception try { newBean = beanClass.newInstance(); } catch (Exception e) { // unable to instantiate CloneNotSupportedException cnse = new CloneNotSupportedException ("Unable to instantiate the underlying bean \"" + beanClass.getName() + "\": " + e); BeanUtils.initCause(cnse, e); throw cnse; } try { newMap.setBean(newBean); } catch (Exception exception) { CloneNotSupportedException cnse = new CloneNotSupportedException ("Unable to set bean in the cloned bean map: " + exception); BeanUtils.initCause(cnse, exception); throw cnse; } try { // copy only properties that are readable and writable. If its // not readable, we can't get the value from the old map. If // its not writable, we can't write a value into the new map. Iterator readableKeys = readMethods.keySet().iterator(); while(readableKeys.hasNext()) { Object key = readableKeys.next(); if(getWriteMethod(key) != null) { newMap.put(key, get(key)); } } } catch (Exception exception) { CloneNotSupportedException cnse = new CloneNotSupportedException ("Unable to copy bean values to cloned bean map: " + exception); BeanUtils.initCause(cnse, exception); throw cnse; } return newMap; } /** * Puts all of the writable properties from the given BeanMap into this * BeanMap. Read-only and Write-only properties will be ignored. * * @param map the BeanMap whose properties to put */ public void putAllWriteable(BeanMap map) { Iterator readableKeys = map.readMethods.keySet().iterator(); while (readableKeys.hasNext()) { Object key = readableKeys.next(); if (getWriteMethod(key) != null) { this.put(key, map.get(key)); } } } /** * This method reinitializes the bean map to have default values for the * bean's properties. This is accomplished by constructing a new instance * of the bean which the map uses as its underlying data source. This * behavior for clear() differs from the Map contract in that * the mappings are not actually removed from the map (the mappings for a * BeanMap are fixed). */ @Override public void clear() { if(bean == null) { return; } Class beanClass = null; try { beanClass = bean.getClass(); bean = beanClass.newInstance(); } catch (Exception e) { UnsupportedOperationException uoe = new UnsupportedOperationException("Could not create new instance of class: " + beanClass); BeanUtils.initCause(uoe, e); throw uoe; } } /** * Returns true if the bean defines a property with the given name. *

      * The given name must be a String; if not, this method * returns false. This method will also return false if the bean * does not define a property with that name. *

      * Write-only properties will not be matched as the test operates against * property read methods. * * @param name the name of the property to check * @return false if the given name is null or is not a String; * false if the bean does not define a property with that name; or * true if the bean does define a property with that name */ @Override public boolean containsKey(Object name) { Method method = getReadMethod(name); return method != null; } /** * Returns true if the bean defines a property whose current value is * the given object. * * @param value the value to check * @return false true if the bean has at least one property whose * current value is that object, false otherwise */ @Override public boolean containsValue(Object value) { // use default implementation return super.containsValue(value); } /** * Returns the value of the bean's property with the given name. *

      * The given name must be a {@link String} and must not be * null; otherwise, this method returns null. * If the bean defines a property with the given name, the value of * that property is returned. Otherwise, null is * returned. *

      * Write-only properties will not be matched as the test operates against * property read methods. * * @param name the name of the property whose value to return * @return the value of the property with that name */ @Override public Object get(Object name) { if ( bean != null ) { Method method = getReadMethod( name ); if ( method != null ) { try { return method.invoke( bean, NULL_ARGUMENTS ); } catch ( IllegalAccessException e ) { logWarn( e ); } catch ( IllegalArgumentException e ) { logWarn( e ); } catch ( InvocationTargetException e ) { logWarn( e ); } catch ( NullPointerException e ) { logWarn( e ); } } } return null; } /** * Sets the bean property with the given name to the given value. * * @param name the name of the property to set * @param value the value to set that property to * @return the previous value of that property * @throws IllegalArgumentException if the given name is null; * if the given name is not a {@link String}; if the bean doesn't * define a property with that name; or if the bean property with * that name is read-only * @throws ClassCastException if an error occurs creating the method args */ @Override public Object put(Object name, Object value) throws IllegalArgumentException, ClassCastException { if ( bean != null ) { Object oldValue = get( name ); Method method = getWriteMethod( name ); if ( method == null ) { throw new IllegalArgumentException( "The bean of type: "+ bean.getClass().getName() + " has no property called: " + name ); } try { Object[] arguments = createWriteMethodArguments( method, value ); method.invoke( bean, arguments ); Object newValue = get( name ); firePropertyChange( name, oldValue, newValue ); } catch ( InvocationTargetException e ) { IllegalArgumentException iae = new IllegalArgumentException(e.getMessage()); if (BeanUtils.initCause(iae, e) == false) { logInfo(e); } throw iae; } catch ( IllegalAccessException e ) { IllegalArgumentException iae = new IllegalArgumentException(e.getMessage()); if (BeanUtils.initCause(iae, e) == false) { logInfo(e); } throw iae; } return oldValue; } return null; } /** * Returns the number of properties defined by the bean. * * @return the number of properties defined by the bean */ @Override public int size() { return readMethods.size(); } /** * Get the keys for this BeanMap. *

      * Write-only properties are not included in the returned set of * property names, although it is possible to set their value and to get * their type. * * @return BeanMap keys. The Set returned by this method is not * modifiable. */ @SuppressWarnings({ "unchecked", "rawtypes" }) // The set actually contains strings; however, because it cannot be // modified there is no danger in selling it as Set @Override public Set keySet() { return Collections.unmodifiableSet((Set) readMethods.keySet()); } /** * Gets a Set of MapEntry objects that are the mappings for this BeanMap. *

      * Each MapEntry can be set but not removed. * * @return the unmodifiable set of mappings */ @Override public Set> entrySet() { return Collections.unmodifiableSet(new AbstractSet>() { @Override public Iterator> iterator() { return entryIterator(); } @Override public int size() { return BeanMap.this.readMethods.size(); } }); } /** * Returns the values for the BeanMap. * * @return values for the BeanMap. The returned collection is not * modifiable. */ @Override public Collection values() { ArrayList answer = new ArrayList( readMethods.size() ); for ( Iterator iter = valueIterator(); iter.hasNext(); ) { answer.add( iter.next() ); } return Collections.unmodifiableList(answer); } // Helper methods //------------------------------------------------------------------------- /** * Returns the type of the property with the given name. * * @param name the name of the property * @return the type of the property, or null if no such * property exists */ public Class getType(String name) { return types.get( name ); } /** * Convenience method for getting an iterator over the keys. *

      * Write-only properties will not be returned in the iterator. * * @return an iterator over the keys */ public Iterator keyIterator() { return readMethods.keySet().iterator(); } /** * Convenience method for getting an iterator over the values. * * @return an iterator over the values */ public Iterator valueIterator() { final Iterator iter = keyIterator(); return new Iterator() { public boolean hasNext() { return iter.hasNext(); } public Object next() { Object key = iter.next(); return get(key); } public void remove() { throw new UnsupportedOperationException( "remove() not supported for BeanMap" ); } }; } /** * Convenience method for getting an iterator over the entries. * * @return an iterator over the entries */ public Iterator> entryIterator() { final Iterator iter = keyIterator(); return new Iterator>() { public boolean hasNext() { return iter.hasNext(); } public Map.Entry next() { Object key = iter.next(); Object value = get(key); @SuppressWarnings("unchecked") // This should not cause any problems; the key is actually a // string, but it does no harm to expose it as Object Map.Entry tmpEntry = new Entry( BeanMap.this, key, value ); return tmpEntry; } public void remove() { throw new UnsupportedOperationException( "remove() not supported for BeanMap" ); } }; } // Properties //------------------------------------------------------------------------- /** * Returns the bean currently being operated on. The return value may * be null if this map is empty. * * @return the bean being operated on by this map */ public Object getBean() { return bean; } /** * Sets the bean to be operated on by this map. The given value may * be null, in which case this map will be empty. * * @param newBean the new bean to operate on */ public void setBean( Object newBean ) { bean = newBean; reinitialise(); } /** * Returns the accessor for the property with the given name. * * @param name the name of the property * @return the accessor method for the property, or null */ public Method getReadMethod(String name) { return readMethods.get(name); } /** * Returns the mutator for the property with the given name. * * @param name the name of the property * @return the mutator method for the property, or null */ public Method getWriteMethod(String name) { return writeMethods.get(name); } // Implementation methods //------------------------------------------------------------------------- /** * Returns the accessor for the property with the given name. * * @param name the name of the property * @return null if the name is null; null if the name is not a * {@link String}; null if no such property exists; or the accessor * method for that property */ protected Method getReadMethod( Object name ) { return readMethods.get( name ); } /** * Returns the mutator for the property with the given name. * * @param name the name of the * @return null if the name is null; null if the name is not a * {@link String}; null if no such property exists; null if the * property is read-only; or the mutator method for that property */ protected Method getWriteMethod( Object name ) { return writeMethods.get( name ); } /** * Reinitializes this bean. Called during {@link #setBean(Object)}. * Does introspection to find properties. */ protected void reinitialise() { readMethods.clear(); writeMethods.clear(); types.clear(); initialise(); } private void initialise() { if(getBean() == null) { return; } Class beanClass = getBean().getClass(); try { //BeanInfo beanInfo = Introspector.getBeanInfo( bean, null ); BeanInfo beanInfo = Introspector.getBeanInfo( beanClass ); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); if ( propertyDescriptors != null ) { for ( int i = 0; i < propertyDescriptors.length; i++ ) { PropertyDescriptor propertyDescriptor = propertyDescriptors[i]; if ( propertyDescriptor != null ) { String name = propertyDescriptor.getName(); Method readMethod = propertyDescriptor.getReadMethod(); Method writeMethod = propertyDescriptor.getWriteMethod(); Class aType = propertyDescriptor.getPropertyType(); if ( readMethod != null ) { readMethods.put( name, readMethod ); } if ( writeMethod != null ) { writeMethods.put( name, writeMethod ); } types.put( name, aType ); } } } } catch ( IntrospectionException e ) { logWarn( e ); } } /** * Called during a successful {@link #put(Object,Object)} operation. * Default implementation does nothing. Override to be notified of * property changes in the bean caused by this map. * * @param key the name of the property that changed * @param oldValue the old value for that property * @param newValue the new value for that property */ protected void firePropertyChange( Object key, Object oldValue, Object newValue ) { } // Implementation classes //------------------------------------------------------------------------- /** * Map entry used by {@link BeanMap}. */ protected static class Entry extends AbstractMapEntry { private final BeanMap owner; /** * Constructs a new Entry. * * @param owner the BeanMap this entry belongs to * @param key the key for this entry * @param value the value for this entry */ protected Entry( BeanMap owner, Object key, Object value ) { super( key, value ); this.owner = owner; } /** * Sets the value. * * @param value the new value for the entry * @return the old value for the entry */ @Override public Object setValue(Object value) { Object key = getKey(); Object oldValue = owner.get( key ); owner.put( key, value ); Object newValue = owner.get( key ); super.setValue( newValue ); return oldValue; } } /** * Creates an array of parameters to pass to the given mutator method. * If the given object is not the right type to pass to the method * directly, it will be converted using {@link #convertType(Class,Object)}. * * @param method the mutator method * @param value the value to pass to the mutator method * @return an array containing one object that is either the given value * or a transformed value * @throws IllegalAccessException if {@link #convertType(Class,Object)} * raises it * @throws IllegalArgumentException if any other exception is raised * by {@link #convertType(Class,Object)} * @throws ClassCastException if an error occurs creating the method args */ protected Object[] createWriteMethodArguments( Method method, Object value ) throws IllegalAccessException, ClassCastException { try { if ( value != null ) { Class[] types = method.getParameterTypes(); if ( types != null && types.length > 0 ) { Class paramType = types[0]; if ( ! paramType.isAssignableFrom( value.getClass() ) ) { value = convertType( paramType, value ); } } } Object[] answer = { value }; return answer; } catch ( InvocationTargetException e ) { IllegalArgumentException iae = new IllegalArgumentException(e.getMessage()); if (BeanUtils.initCause(iae, e) == false) { logInfo(e); } throw iae; } catch ( InstantiationException e ) { IllegalArgumentException iae = new IllegalArgumentException(e.getMessage()); if (BeanUtils.initCause(iae, e) == false) { logInfo(e); } BeanUtils.initCause(iae, e); throw iae; } } /** * Converts the given value to the given type. First, reflection is * is used to find a public constructor declared by the given class * that takes one argument, which must be the precise type of the * given value. If such a constructor is found, a new object is * created by passing the given value to that constructor, and the * newly constructed object is returned.

      * * If no such constructor exists, and the given type is a primitive * type, then the given value is converted to a string using its * {@link Object#toString() toString()} method, and that string is * parsed into the correct primitive type using, for instance, * {@link Integer#valueOf(String)} to convert the string into an * int.

      * * If no special constructor exists and the given type is not a * primitive type, this method returns the original value. * * @param newType the type to convert the value to * @param value the value to convert * @return the converted value * @throws NumberFormatException if newType is a primitive type, and * the string representation of the given value cannot be converted * to that type * @throws InstantiationException if the constructor found with * reflection raises it * @throws InvocationTargetException if the constructor found with * reflection raises it * @throws IllegalAccessException never * @throws IllegalArgumentException never */ protected Object convertType( Class newType, Object value ) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // try call constructor Class[] types = { value.getClass() }; try { Constructor constructor = newType.getConstructor( types ); Object[] arguments = { value }; return constructor.newInstance( arguments ); } catch ( NoSuchMethodException e ) { // try using the transformers Transformer transformer = getTypeTransformer( newType ); if ( transformer != null ) { return transformer.transform( value ); } return value; } } /** * Returns a transformer for the given primitive type. * * @param aType the primitive type whose transformer to return * @return a transformer that will convert strings into that type, * or null if the given type is not a primitive type */ protected Transformer getTypeTransformer( Class aType ) { return typeTransformers.get( aType ); } /** * Logs the given exception to System.out. Used to display * warnings while accessing/mutating the bean. * * @param ex the exception to log */ protected void logInfo(Exception ex) { // Deliberately do not use LOG4J or Commons Logging to avoid dependencies System.out.println( "INFO: Exception: " + ex ); } /** * Logs the given exception to System.err. Used to display * errors while accessing/mutating the bean. * * @param ex the exception to log */ protected void logWarn(Exception ex) { // Deliberately do not use LOG4J or Commons Logging to avoid dependencies System.out.println( "WARN: Exception: " + ex ); ex.printStackTrace(); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanPredicate.java100644 0 0 11130 12262570612 26552 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import org.apache.commons.collections.Predicate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.lang.reflect.InvocationTargetException; /** *

      Predicate implementation that applies the given Predicate * to the result of calling the given property getter. *

      * * @version $Id: BeanPredicate.java 1454597 2013-03-08 21:58:12Z britter $ */ public class BeanPredicate implements Predicate { private final Log log = LogFactory.getLog(this.getClass()); /** Name of the property whose value will be predicated */ private String propertyName; /** Predicate to be applied to the property value */ private Predicate predicate; /** * Constructs a BeanPredicate that applies the given * Predicate to the named property value. * @param propertyName the name of the property whose value is to be predicated, * not null * @param predicate the Predicate to be applied, * not null */ public BeanPredicate(String propertyName, Predicate predicate) { this.propertyName = propertyName; this.predicate = predicate; } /** * Evaluates the given object by applying the {@link #getPredicate()} * to a property value named by {@link #getPropertyName()}. * * @param object The object being evaluated * @return the result of the predicate evaluation * @throws IllegalArgumentException when the property cannot be evaluated */ public boolean evaluate(Object object) { boolean evaluation = false; try { Object propValue = PropertyUtils.getProperty( object, propertyName ); evaluation = predicate.evaluate(propValue); } catch (IllegalArgumentException e) { final String errorMsg = "Problem during evaluation."; log.error("ERROR: " + errorMsg, e); throw e; } catch (IllegalAccessException e) { final String errorMsg = "Unable to access the property provided."; log.error(errorMsg, e); throw new IllegalArgumentException(errorMsg); } catch (InvocationTargetException e) { final String errorMsg = "Exception occurred in property's getter"; log.error(errorMsg, e); throw new IllegalArgumentException(errorMsg); } catch (NoSuchMethodException e) { final String errorMsg = "Property not found."; log.error(errorMsg, e); throw new IllegalArgumentException(errorMsg); } return evaluation; } /** * Gets the name of the property whose value is to be predicated. * in the evaluation. * @return the property name, not null */ public String getPropertyName() { return propertyName; } /** * Sets the name of the property whose value is to be predicated. * @param propertyName the name of the property whose value is to be predicated, * not null */ public void setPropertyName(String propertyName) { this.propertyName = propertyName; } /** * Gets the Predicate to be applied to the value of the named property * during {@link #evaluate}. * @return Predicate, not null */ public Predicate getPredicate() { return predicate; } /** * Sets the Predicate to be applied to the value of the named property * during {@link #evaluate(Object)}. * @param predicate Predicate, not null */ public void setPredicate(Predicate predicate) { this.predicate = predicate; } } ././@LongLink100644 0 0 153 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanPropertyValueChangeClosure.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanPropertyValueChangeClosur100644 0 0 25262 12262570612 31064 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import org.apache.commons.collections.Closure; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.lang.reflect.InvocationTargetException; /** *

      Closure that sets a property.

      *

      * An implementation of org.apache.commons.collections.Closure that updates * a specified property on the object provided with a specified value. * The BeanPropertyValueChangeClosure constructor takes two parameters which determine * what property will be updated and with what value. *

      *
      * *
      public BeanPropertyValueChangeClosure( String propertyName, Object propertyValue )
      *
      *
      *
      * Will create a Closure that will update an object by setting the property * specified by propertyName to the value specified by propertyValue. *
      *
      * *

      * Note: Property names can be a simple, nested, indexed, or mapped property as defined by * org.apache.commons.beanutils.PropertyUtils. If any object in the property path * specified by propertyName is null then the outcome is based on the * value of the ignoreNull attribute. * *

      * A typical usage might look like: *

       * // create the closure
       * BeanPropertyValueChangeClosure closure =
       *    new BeanPropertyValueChangeClosure( "activeEmployee", Boolean.TRUE );
       *
       * // update the Collection
       * CollectionUtils.forAllDo( peopleCollection, closure );
       * 
      *

      * * This would take a Collection of person objects and update the * activeEmployee property of each object in the Collection to * true. Assuming... *

        *
      • * The top level object in the peopleCollection is an object which represents a * person. *
      • *
      • * The person object has a setActiveEmployee( boolean ) method which updates * the value for the object's activeEmployee property. *
      • *
      * * @version $Id: BeanPropertyValueChangeClosure.java 1454597 2013-03-08 21:58:12Z britter $ * @see org.apache.commons.beanutils.PropertyUtils * @see org.apache.commons.collections.Closure */ public class BeanPropertyValueChangeClosure implements Closure { /** For logging. */ private final Log log = LogFactory.getLog(this.getClass()); /** * The name of the property which will be updated when this Closure executes. */ private String propertyName; /** * The value that the property specified by propertyName * will be updated to when this Closure executes. */ private Object propertyValue; /** * Determines whether null objects in the property path will genenerate an * IllegalArgumentException or not. If set to true then if any objects * in the property path leading up to the target property evaluate to null then the * IllegalArgumentException throw by PropertyUtils will be logged but * not rethrown. If set to false then if any objects in the property path leading * up to the target property evaluate to null then the * IllegalArgumentException throw by PropertyUtils will be logged and * rethrown. */ private boolean ignoreNull; /** * Constructor which takes the name of the property to be changed, the new value to set * the property to, and assumes ignoreNull to be false. * * @param propertyName The name of the property that will be updated with the value specified by * propertyValue. * @param propertyValue The value that propertyName will be set to on the target * object. * @throws IllegalArgumentException If the propertyName provided is null or empty. */ public BeanPropertyValueChangeClosure(String propertyName, Object propertyValue) { this(propertyName, propertyValue, false); } /** * Constructor which takes the name of the property to be changed, the new value to set * the property to and a boolean which determines whether null objects in the * property path will genenerate an IllegalArgumentException or not. * * @param propertyName The name of the property that will be updated with the value specified by * propertyValue. * @param propertyValue The value that propertyName will be set to on the target * object. * @param ignoreNull Determines whether null objects in the property path will * genenerate an IllegalArgumentException or not. * @throws IllegalArgumentException If the propertyName provided is null or empty. */ public BeanPropertyValueChangeClosure(String propertyName, Object propertyValue, boolean ignoreNull) { super(); if ((propertyName != null) && (propertyName.length() > 0)) { this.propertyName = propertyName; this.propertyValue = propertyValue; this.ignoreNull = ignoreNull; } else { throw new IllegalArgumentException("propertyName cannot be null or empty"); } } /** * Updates the target object provided using the property update criteria provided when this * BeanPropertyValueChangeClosure was constructed. If any object in the property * path leading up to the target property is null then the outcome will be based on * the value of the ignoreNull attribute. By default, ignoreNull is * false and would result in an IllegalArgumentException if an object * in the property path leading up to the target property is null. * * @param object The object to be updated. * @throws IllegalArgumentException If an IllegalAccessException, InvocationTargetException, or * NoSuchMethodException is thrown when trying to access the property specified on the object * provided. Or if an object in the property path provided is null and * ignoreNull is set to false. */ public void execute(Object object) { try { PropertyUtils.setProperty(object, propertyName, propertyValue); } catch (IllegalArgumentException e) { final String errorMsg = "Unable to execute Closure. Null value encountered in property path..."; if (ignoreNull) { log.warn("WARNING: " + errorMsg + e); } else { IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } } catch (IllegalAccessException e) { final String errorMsg = "Unable to access the property provided."; IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } catch (InvocationTargetException e) { final String errorMsg = "Exception occurred in property's getter"; IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } catch (NoSuchMethodException e) { final String errorMsg = "Property not found"; IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } } /** * Returns the name of the property which will be updated when this Closure executes. * * @return The name of the property which will be updated when this Closure executes. */ public String getPropertyName() { return propertyName; } /** * Returns the value that the property specified by propertyName * will be updated to when this Closure executes. * * @return The value that the property specified by propertyName * will be updated to when this Closure executes. */ public Object getPropertyValue() { return propertyValue; } /** * Returns the flag that determines whether null objects in the property path will * genenerate an IllegalArgumentException or not. If set to true then * if any objects in the property path leading up to the target property evaluate to * null then the IllegalArgumentException throw by * PropertyUtils will be logged but not rethrown. If set to false then * if any objects in the property path leading up to the target property evaluate to * null then the IllegalArgumentException throw by * PropertyUtils will be logged and rethrown. * * @return The flag that determines whether null objects in the property path will * genenerate an IllegalArgumentException or not. */ public boolean isIgnoreNull() { return ignoreNull; } } ././@LongLink100644 0 0 155 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanPropertyValueEqualsPredicate.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanPropertyValueEqualsPredic100644 0 0 31061 12262570612 31062 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.InvocationTargetException; import org.apache.commons.collections.Predicate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

      Predicate that evaluates a property value against a specified value.

      *

      * An implementation of org.apache.commons.collections.Predicate that evaluates a * property value on the object provided against a specified value and returns true * if equal; false otherwise. * The BeanPropertyValueEqualsPredicate constructor takes two parameters which * determine what property will be evaluated on the target object and what its expected value should * be. *

      *
      * *
      public BeanPropertyValueEqualsPredicate( String propertyName, Object propertyValue )
      *
      *
      *
      * Will create a Predicate that will evaluate the target object and return * true if the property specified by propertyName has a value which * is equal to the the value specified by propertyValue. Or return * false otherwise. *
      *
      *

      *

      * Note: Property names can be a simple, nested, indexed, or mapped property as defined by * org.apache.commons.beanutils.PropertyUtils. If any object in the property path * specified by propertyName is null then the outcome is based on the * value of the ignoreNull attribute. *

      *

      * A typical usage might look like: *

       * // create the closure
       * BeanPropertyValueEqualsPredicate predicate =
       *    new BeanPropertyValueEqualsPredicate( "activeEmployee", Boolean.FALSE );
       *
       * // filter the Collection
       * CollectionUtils.filter( peopleCollection, predicate );
       * 
      *

      *

      * This would take a Collection of person objects and filter out any people whose * activeEmployee property is false. Assuming... *

        *
      • * The top level object in the peeopleCollection is an object which represents a * person. *
      • *
      • * The person object has a getActiveEmployee() method which returns * the boolean value for the object's activeEmployee property. *
      • *
      *

      *

      * Another typical usage might look like: *

       * // create the closure
       * BeanPropertyValueEqualsPredicate predicate =
       *    new BeanPropertyValueEqualsPredicate( "personId", "456-12-1234" );
       *
       * // search the Collection
       * CollectionUtils.find( peopleCollection, predicate );
       * 
      *

      *

      * This would search a Collection of person objects and return the first object whose * personId property value equals 456-12-1234. Assuming... *

        *
      • * The top level object in the peeopleCollection is an object which represents a * person. *
      • *
      • * The person object has a getPersonId() method which returns * the value for the object's personId property. *
      • *
      *

      * * @version $Id: BeanPropertyValueEqualsPredicate.java 1540509 2013-11-10 18:39:11Z oheger $ * @see org.apache.commons.beanutils.PropertyUtils * @see org.apache.commons.collections.Predicate */ public class BeanPropertyValueEqualsPredicate implements Predicate { /** For logging. */ private final Log log = LogFactory.getLog(this.getClass()); /** * The name of the property which will be evaluated when this Predicate is executed. */ private String propertyName; /** * The value that the property specified by propertyName * will be compared to when this Predicate executes. */ private Object propertyValue; /** *

      Should null objects in the property path be ignored?

      *

      * Determines whether null objects in the property path will genenerate an * IllegalArgumentException or not. If set to true then if any objects * in the property path evaluate to null then the * IllegalArgumentException throw by PropertyUtils will be logged but * not rethrown and false will be returned. If set to false then if * any objects in the property path evaluate to null then the * IllegalArgumentException throw by PropertyUtils will be logged and * rethrown. *

      */ private boolean ignoreNull; /** * Constructor which takes the name of the property, its expected value to be used in evaluation, * and assumes ignoreNull to be false. * * @param propertyName The name of the property that will be evaluated against the expected value. * @param propertyValue The value to use in object evaluation. * @throws IllegalArgumentException If the property name provided is null or empty. */ public BeanPropertyValueEqualsPredicate(String propertyName, Object propertyValue) { this(propertyName, propertyValue, false); } /** * Constructor which takes the name of the property, its expected value * to be used in evaluation, and a boolean which determines whether null objects in * the property path will genenerate an IllegalArgumentException or not. * * @param propertyName The name of the property that will be evaluated against the expected value. * @param propertyValue The value to use in object evaluation. * @param ignoreNull Determines whether null objects in the property path will * genenerate an IllegalArgumentException or not. * @throws IllegalArgumentException If the property name provided is null or empty. */ public BeanPropertyValueEqualsPredicate(String propertyName, Object propertyValue, boolean ignoreNull) { super(); if ((propertyName != null) && (propertyName.length() > 0)) { this.propertyName = propertyName; this.propertyValue = propertyValue; this.ignoreNull = ignoreNull; } else { throw new IllegalArgumentException("propertyName cannot be null or empty"); } } /** * Evaulates the object provided against the criteria specified when this * BeanPropertyValueEqualsPredicate was constructed. Equality is based on * either reference or logical equality as defined by the property object's equals method. If * any object in the property path leading up to the target property is null then * the outcome will be based on the value of the ignoreNull attribute. By default, * ignoreNull is false and would result in an * IllegalArgumentException if an object in the property path leading up to the * target property is null. * * @param object The object to be evaluated. * @return True if the object provided meets all the criteria for this Predicate; * false otherwise. * @throws IllegalArgumentException If an IllegalAccessException, InvocationTargetException, or * NoSuchMethodException is thrown when trying to access the property specified on the object * provided. Or if an object in the property path provided is null and * ignoreNull is set to false. */ public boolean evaluate(Object object) { boolean evaluation = false; try { evaluation = evaluateValue(propertyValue, PropertyUtils.getProperty(object, propertyName)); } catch (IllegalArgumentException e) { final String errorMsg = "Problem during evaluation. Null value encountered in property path..."; if (ignoreNull) { log.warn("WARNING: " + errorMsg + e); } else { IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } } catch (IllegalAccessException e) { final String errorMsg = "Unable to access the property provided."; IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } catch (InvocationTargetException e) { final String errorMsg = "Exception occurred in property's getter"; IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } catch (NoSuchMethodException e) { final String errorMsg = "Property not found."; IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } return evaluation; } /** * Utility method which evaluates whether the actual property value equals the expected property * value. * * @param expected The expected value. * @param actual The actual value. * @return True if they are equal; false otherwise. */ protected boolean evaluateValue(Object expected, Object actual) { return (expected == actual) || ((expected != null) && expected.equals(actual)); } /** * Returns the name of the property which will be evaluated when this Predicate is * executed. * * @return The name of the property which will be evaluated when this Predicate is * executed. */ public String getPropertyName() { return propertyName; } /** * Returns the value that the property specified by propertyName will be compared to * when this Predicate executes. * * @return The value that the property specified by propertyName will be compared to * when this Predicate executes. */ public Object getPropertyValue() { return propertyValue; } /** * Returns the flag which determines whether null objects in the property path will * genenerate an IllegalArgumentException or not. If set to true then * if any objects in the property path evaluate to null then the * IllegalArgumentException throw by PropertyUtils will be logged but * not rethrown and false will be returned. If set to false then if * any objects in the property path evaluate to null then the * IllegalArgumentException throw by PropertyUtils will be logged and * rethrown. * * @return The flag which determines whether null objects in the property path will * genenerate an IllegalArgumentException or not. */ public boolean isIgnoreNull() { return ignoreNull; } } ././@LongLink100644 0 0 153 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanToPropertyValueTransformer.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanToPropertyValueTransforme100644 0 0 23447 12262570612 31135 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import org.apache.commons.collections.Transformer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.lang.reflect.InvocationTargetException; /** *

      Transformer that outputs a property value.

      * *

      An implementation of org.apache.commons.collections.Transformer that transforms * the object provided by returning the value of a specified property of the object. The * constructor for BeanToPropertyValueTransformer requires the name of the property * that will be used in the transformation. The property can be a simple, nested, indexed, or * mapped property as defined by org.apache.commons.beanutils.PropertyUtils. If any * object in the property path specified by propertyName is null then the * outcome is based on the value of the ignoreNull attribute. *

      * *

      * A typical usage might look like: *

       * // create the transformer
       * BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer( "person.address.city" );
       *
       * // transform the Collection
       * Collection peoplesCities = CollectionUtils.collect( peopleCollection, transformer );
       * 
      *

      * *

      * This would take a Collection of person objects and return a Collection * of objects which represents the cities in which each person lived. Assuming... *

        *
      • * The top level object in the peeopleCollection is an object which represents a * person. *
      • *
      • * The person object has a getAddress() method which returns an object which * represents a person's address. *
      • *
      • * The address object has a getCity() method which returns an object which * represents the city in which a person lives. *
      • *
      * * @version $Id: BeanToPropertyValueTransformer.java 1454597 2013-03-08 21:58:12Z britter $ * @see org.apache.commons.beanutils.PropertyUtils * @see org.apache.commons.collections.Transformer */ public class BeanToPropertyValueTransformer implements Transformer { /** For logging. */ private final Log log = LogFactory.getLog(this.getClass()); /** The name of the property that will be used in the transformation of the object. */ private String propertyName; /** *

      Should null objects on the property path throw an IllegalArgumentException?

      *

      * Determines whether null objects in the property path will genenerate an * IllegalArgumentException or not. If set to true then if any objects * in the property path evaluate to null then the * IllegalArgumentException throw by PropertyUtils will be logged but * not rethrown and null will be returned. If set to false then if any * objects in the property path evaluate to null then the * IllegalArgumentException throw by PropertyUtils will be logged and * rethrown. *

      */ private boolean ignoreNull; /** * Constructs a Transformer which does not ignore nulls. * Constructor which takes the name of the property that will be used in the transformation and * assumes ignoreNull to be false. * * @param propertyName The name of the property that will be used in the transformation. * @throws IllegalArgumentException If the propertyName is null or * empty. */ public BeanToPropertyValueTransformer(String propertyName) { this(propertyName, false); } /** * Constructs a Transformer and sets ignoreNull. * Constructor which takes the name of the property that will be used in the transformation and * a boolean which determines whether null objects in the property path will * genenerate an IllegalArgumentException or not. * * @param propertyName The name of the property that will be used in the transformation. * @param ignoreNull Determines whether null objects in the property path will * genenerate an IllegalArgumentException or not. * @throws IllegalArgumentException If the propertyName is null or * empty. */ public BeanToPropertyValueTransformer(String propertyName, boolean ignoreNull) { super(); if ((propertyName != null) && (propertyName.length() > 0)) { this.propertyName = propertyName; this.ignoreNull = ignoreNull; } else { throw new IllegalArgumentException( "propertyName cannot be null or empty"); } } /** * Returns the value of the property named in the transformer's constructor for * the object provided. If any object in the property path leading up to the target property is * null then the outcome will be based on the value of the ignoreNull * attribute. By default, ignoreNull is false and would result in an * IllegalArgumentException if an object in the property path leading up to the * target property is null. * * @param object The object to be transformed. * @return The value of the property named in the transformer's constructor for the object * provided. * @throws IllegalArgumentException If an IllegalAccessException, InvocationTargetException, or * NoSuchMethodException is thrown when trying to access the property specified on the object * provided. Or if an object in the property path provided is null and * ignoreNull is set to false. */ public Object transform(Object object) { Object propertyValue = null; try { propertyValue = PropertyUtils.getProperty(object, propertyName); } catch (IllegalArgumentException e) { final String errorMsg = "Problem during transformation. Null value encountered in property path..."; if (ignoreNull) { log.warn("WARNING: " + errorMsg + e); } else { IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } } catch (IllegalAccessException e) { final String errorMsg = "Unable to access the property provided."; IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } catch (InvocationTargetException e) { final String errorMsg = "Exception occurred in property's getter"; IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } catch (NoSuchMethodException e) { final String errorMsg = "No property found for name [" + propertyName + "]"; IllegalArgumentException iae = new IllegalArgumentException(errorMsg); if (!BeanUtils.initCause(iae, e)) { log.error(errorMsg, e); } throw iae; } return propertyValue; } /** * Returns the name of the property that will be used in the transformation of the bean. * * @return The name of the property that will be used in the transformation of the bean. */ public String getPropertyName() { return propertyName; } /** * Returns the flag which determines whether null objects in the property path will * genenerate an IllegalArgumentException or not. If set to true then * if any objects in the property path evaluate to null then the * IllegalArgumentException throw by PropertyUtils will be logged but * not rethrown and null will be returned. If set to false then if any * objects in the property path evaluate to null then the * IllegalArgumentException throw by PropertyUtils will be logged and * rethrown. * * @return The flag which determines whether null objects in the property path will * genenerate an IllegalArgumentException or not. */ public boolean isIgnoreNull() { return ignoreNull; } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanUtils.java100644 0 0 45666 12262570612 25777 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.InvocationTargetException; import java.util.Map; /** *

      Utility methods for populating JavaBeans properties via reflection.

      * *

      The implementations are provided by {@link BeanUtilsBean}. * These static utility methods use the default instance. * More sophisticated behaviour can be provided by using a BeanUtilsBean instance.

      * * @version $Id: BeanUtils.java 1540186 2013-11-08 21:08:30Z oheger $ * @see BeanUtilsBean */ public class BeanUtils { // ------------------------------------------------------ Private Variables /** * The debugging detail level for this component. * * Note that this static variable will have unexpected side-effects if * this class is deployed in a shared classloader within a container. * However as it is actually completely ignored by this class due to its * deprecated status, it doesn't do any actual harm. * * @deprecated BeanUtils now uses commons-logging for all log messages. * Use your favorite logging tool to configure logging for * this class. */ @Deprecated private static int debug = 0; /** * The debug static property is no longer used * @return debug property * @deprecated BeanUtils now uses commons-logging for all log messages. * Use your favorite logging tool to configure logging for * this class. */ @Deprecated public static int getDebug() { return (debug); } /** * The debug static property is no longer used * @param newDebug debug property * @deprecated BeanUtils now uses commons-logging for all log messages. * Use your favorite logging tool to configure logging for * this class. */ @Deprecated public static void setDebug(int newDebug) { debug = newDebug; } // --------------------------------------------------------- Class Methods /** *

      Clone a bean based on the available property getters and setters, * even if the bean class itself does not implement Cloneable.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean to be cloned * @return the cloned bean * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InstantiationException if a new instance of the bean's * class cannot be instantiated * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found * @see BeanUtilsBean#cloneBean */ public static Object cloneBean(Object bean) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { return BeanUtilsBean.getInstance().cloneBean(bean); } /** *

      Copy property values from the origin bean to the destination bean * for all cases where the property names are the same.

      * *

      For more details see BeanUtilsBean.

      * * @param dest Destination bean whose properties are modified * @param orig Origin bean whose properties are retrieved * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if the dest or * orig argument is null or if the dest * property type is different from the source type and the relevant * converter has not been registered. * @exception InvocationTargetException if the property accessor method * throws an exception * @see BeanUtilsBean#copyProperties */ public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException { BeanUtilsBean.getInstance().copyProperties(dest, orig); } /** *

      Copy the specified property value to the specified destination bean, * performing any type conversion that is required.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value Value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @see BeanUtilsBean#copyProperty */ public static void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { BeanUtilsBean.getInstance().copyProperty(bean, name, value); } /** *

      Return the entire set of properties for which the specified bean * provides a read method.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean whose properties are to be extracted * @return Map of property descriptors * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found * @see BeanUtilsBean#describe */ public static Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return BeanUtilsBean.getInstance().describe(bean); } /** *

      Return the value of the specified array property of the specified * bean, as a String array.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @return The array property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found * @see BeanUtilsBean#getArrayProperty */ public static String[] getArrayProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return BeanUtilsBean.getInstance().getArrayProperty(bean, name); } /** *

      Return the value of the specified indexed property of the specified * bean, as a String.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean whose property is to be extracted * @param name propertyname[index] of the property value * to be extracted * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found * @see BeanUtilsBean#getIndexedProperty(Object, String) */ public static String getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return BeanUtilsBean.getInstance().getIndexedProperty(bean, name); } /** * Return the value of the specified indexed property of the specified * bean, as a String. The index is specified as a method parameter and * must *not* be included in the property name expression * *

      For more details see BeanUtilsBean.

      * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found * @see BeanUtilsBean#getIndexedProperty(Object, String, int) */ public static String getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return BeanUtilsBean.getInstance().getIndexedProperty(bean, name, index); } /** *

      Return the value of the specified indexed property of the specified * bean, as a String.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean whose property is to be extracted * @param name propertyname(index) of the property value * to be extracted * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found * @see BeanUtilsBean#getMappedProperty(Object, String) */ public static String getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return BeanUtilsBean.getInstance().getMappedProperty(bean, name); } /** *

      Return the value of the specified mapped property of the specified * bean, as a String.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param key Lookup key of the property value to be extracted * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found * @see BeanUtilsBean#getMappedProperty(Object, String, String) */ public static String getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return BeanUtilsBean.getInstance().getMappedProperty(bean, name, key); } /** *

      Return the value of the (possibly nested) property of the specified * name, for the specified bean, as a String.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * @return The nested property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found * @see BeanUtilsBean#getNestedProperty */ public static String getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return BeanUtilsBean.getInstance().getNestedProperty(bean, name); } /** *

      Return the value of the specified property of the specified bean, * no matter which property reference format is used, as a String.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found * @see BeanUtilsBean#getProperty */ public static String getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return BeanUtilsBean.getInstance().getProperty(bean, name); } /** *

      Return the value of the specified simple property of the specified * bean, converted to a String.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found * @see BeanUtilsBean#getSimpleProperty */ public static String getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return BeanUtilsBean.getInstance().getSimpleProperty(bean, name); } /** *

      Populate the JavaBeans properties of the specified bean, based on * the specified name/value pairs.

      * *

      For more details see BeanUtilsBean.

      * * @param bean JavaBean whose properties are being populated * @param properties Map keyed by property name, with the * corresponding (String or String[]) value(s) to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @see BeanUtilsBean#populate */ public static void populate(Object bean, Map properties) throws IllegalAccessException, InvocationTargetException { BeanUtilsBean.getInstance().populate(bean, properties); } /** *

      Set the specified property value, performing type conversions as * required to conform to the type of the destination property.

      * *

      For more details see BeanUtilsBean.

      * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value Value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @see BeanUtilsBean#setProperty */ public static void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { BeanUtilsBean.getInstance().setProperty(bean, name, value); } /** * If we're running on JDK 1.4 or later, initialize the cause for the given throwable. * * @param throwable The throwable. * @param cause The cause of the throwable. * @return true if the cause was initialized, otherwise false. * @since 1.8.0 */ public static boolean initCause(Throwable throwable, Throwable cause) { return BeanUtilsBean.getInstance().initCause(throwable, cause); } /** * Create a cache. * @param the key type of the cache * @param the value type of the cache * @return a new cache * @since 1.8.0 */ public static Map createCache() { return new WeakFastHashMap(); } /** * Return whether a Map is fast * @param map The map * @return Whether it is fast or not. * @since 1.8.0 */ public static boolean getCacheFast(Map map) { if (map instanceof WeakFastHashMap) { return ((WeakFastHashMap) map).getFast(); } else { return false; } } /** * Set whether fast on a Map * @param map The map * @param fast Whether it should be fast or not. * @since 1.8.0 */ public static void setCacheFast(Map map, boolean fast) { if (map instanceof WeakFastHashMap) { ((WeakFastHashMap)map).setFast(fast); } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanUtilsBean.java100644 0 0 135362 12262570612 26576 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IndexedPropertyDescriptor; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.expression.Resolver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

      JavaBean property population methods.

      * *

      This class provides implementations for the utility methods in * {@link BeanUtils}. * Different instances can be used to isolate caches between classloaders * and to vary the value converters registered.

      * * @version $Id: BeanUtilsBean.java 1546738 2013-11-30 16:24:19Z oheger $ * @see BeanUtils * @since 1.7 */ public class BeanUtilsBean { // ------------------------------------------------------ Private Class Variables /** * Contains BeanUtilsBean instances indexed by context classloader. */ private static final ContextClassLoaderLocal BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal() { // Creates the default instance used when the context classloader is unavailable @Override protected BeanUtilsBean initialValue() { return new BeanUtilsBean(); } }; /** * Gets the instance which provides the functionality for {@link BeanUtils}. * This is a pseudo-singleton - an single instance is provided per (thread) context classloader. * This mechanism provides isolation for web apps deployed in the same container. * * @return The (pseudo-singleton) BeanUtils bean instance */ public static BeanUtilsBean getInstance() { return BEANS_BY_CLASSLOADER.get(); } /** * Sets the instance which provides the functionality for {@link BeanUtils}. * This is a pseudo-singleton - an single instance is provided per (thread) context classloader. * This mechanism provides isolation for web apps deployed in the same container. * * @param newInstance The (pseudo-singleton) BeanUtils bean instance */ public static void setInstance(BeanUtilsBean newInstance) { BEANS_BY_CLASSLOADER.set(newInstance); } // --------------------------------------------------------- Attributes /** * Logging for this instance */ private final Log log = LogFactory.getLog(BeanUtils.class); /** Used to perform conversions between object types when setting properties */ private final ConvertUtilsBean convertUtilsBean; /** Used to access properties*/ private final PropertyUtilsBean propertyUtilsBean; /** A reference to Throwable's initCause method, or null if it's not there in this JVM */ private static final Method INIT_CAUSE_METHOD = getInitCauseMethod(); // --------------------------------------------------------- Constuctors /** *

      Constructs an instance using new property * and conversion instances.

      */ public BeanUtilsBean() { this(new ConvertUtilsBean(), new PropertyUtilsBean()); } /** *

      Constructs an instance using given conversion instances * and new {@link PropertyUtilsBean} instance.

      * * @param convertUtilsBean use this ConvertUtilsBean * to perform conversions from one object to another * * @since 1.8.0 */ public BeanUtilsBean(ConvertUtilsBean convertUtilsBean) { this(convertUtilsBean, new PropertyUtilsBean()); } /** *

      Constructs an instance using given property and conversion instances.

      * * @param convertUtilsBean use this ConvertUtilsBean * to perform conversions from one object to another * @param propertyUtilsBean use this PropertyUtilsBean * to access properties */ public BeanUtilsBean( ConvertUtilsBean convertUtilsBean, PropertyUtilsBean propertyUtilsBean) { this.convertUtilsBean = convertUtilsBean; this.propertyUtilsBean = propertyUtilsBean; } // --------------------------------------------------------- Public Methods /** *

      Clone a bean based on the available property getters and setters, * even if the bean class itself does not implement Cloneable.

      * *

      * Note: this method creates a shallow clone. * In other words, any objects referred to by the bean are shared with the clone * rather than being cloned in turn. *

      * * @param bean Bean to be cloned * @return the cloned bean * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InstantiationException if a new instance of the bean's * class cannot be instantiated * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public Object cloneBean(Object bean) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { if (log.isDebugEnabled()) { log.debug("Cloning bean: " + bean.getClass().getName()); } Object newBean = null; if (bean instanceof DynaBean) { newBean = ((DynaBean) bean).getDynaClass().newInstance(); } else { newBean = bean.getClass().newInstance(); } getPropertyUtils().copyProperties(newBean, bean); return (newBean); } /** *

      Copy property values from the origin bean to the destination bean * for all cases where the property names are the same. For each * property, a conversion is attempted as necessary. All combinations of * standard JavaBeans and DynaBeans as origin and destination are * supported. Properties that exist in the origin bean, but do not exist * in the destination bean (or are read-only in the destination bean) are * silently ignored.

      * *

      If the origin "bean" is actually a Map, it is assumed * to contain String-valued simple property names as the keys, pointing at * the corresponding property values that will be converted (if necessary) * and set in the destination bean. Note that this method * is intended to perform a "shallow copy" of the properties and so complex * properties (for example, nested ones) will not be copied.

      * *

      This method differs from populate(), which * was primarily designed for populating JavaBeans from the map of request * parameters retrieved on an HTTP request, is that no scalar->indexed * or indexed->scalar manipulations are performed. If the origin property * is indexed, the destination property must be also.

      * *

      If you know that no type conversions are required, the * copyProperties() method in {@link PropertyUtils} will * execute faster than this method.

      * *

      FIXME - Indexed and mapped properties that do not * have getter and setter methods for the underlying array or Map are not * copied by this method.

      * * @param dest Destination bean whose properties are modified * @param orig Origin bean whose properties are retrieved * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if the dest or * orig argument is null or if the dest * property type is different from the source type and the relevant * converter has not been registered. * @exception InvocationTargetException if the property accessor method * throws an exception */ public void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException { // Validate existence of the specified beans if (dest == null) { throw new IllegalArgumentException ("No destination bean specified"); } if (orig == null) { throw new IllegalArgumentException("No origin bean specified"); } if (log.isDebugEnabled()) { log.debug("BeanUtils.copyProperties(" + dest + ", " + orig + ")"); } // Copy the properties, converting as necessary if (orig instanceof DynaBean) { DynaProperty[] origDescriptors = ((DynaBean) orig).getDynaClass().getDynaProperties(); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); // Need to check isReadable() for WrapDynaBean // (see Jira issue# BEANUTILS-61) if (getPropertyUtils().isReadable(orig, name) && getPropertyUtils().isWriteable(dest, name)) { Object value = ((DynaBean) orig).get(name); copyProperty(dest, name, value); } } } else if (orig instanceof Map) { @SuppressWarnings("unchecked") // Map properties are always of type Map propMap = (Map) orig; for (Map.Entry entry : propMap.entrySet()) { String name = entry.getKey(); if (getPropertyUtils().isWriteable(dest, name)) { copyProperty(dest, name, entry.getValue()); } } } else /* if (orig is a standard JavaBean) */ { PropertyDescriptor[] origDescriptors = getPropertyUtils().getPropertyDescriptors(orig); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if ("class".equals(name)) { continue; // No point in trying to set an object's class } if (getPropertyUtils().isReadable(orig, name) && getPropertyUtils().isWriteable(dest, name)) { try { Object value = getPropertyUtils().getSimpleProperty(orig, name); copyProperty(dest, name, value); } catch (NoSuchMethodException e) { // Should not happen } } } } } /** *

      Copy the specified property value to the specified destination bean, * performing any type conversion that is required. If the specified * bean does not have a property of the specified name, or the property * is read only on the destination bean, return without * doing anything. If you have custom destination property types, register * {@link Converter}s for them by calling the register() * method of {@link ConvertUtils}.

      * *

      IMPLEMENTATION RESTRICTIONS:

      *
        *
      • Does not support destination properties that are indexed, * but only an indexed setter (as opposed to an array setter) * is available.
      • *
      • Does not support destination properties that are mapped, * but only a keyed setter (as opposed to a Map setter) * is available.
      • *
      • The desired property type of a mapped setter cannot be * determined (since Maps support any data type), so no conversion * will be performed.
      • *
      * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value Value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ public void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { // Trace logging (if enabled) if (log.isTraceEnabled()) { StringBuilder sb = new StringBuilder(" copyProperty("); sb.append(bean); sb.append(", "); sb.append(name); sb.append(", "); if (value == null) { sb.append(""); } else if (value instanceof String) { sb.append((String) value); } else if (value instanceof String[]) { String[] values = (String[]) value; sb.append('['); for (int i = 0; i < values.length; i++) { if (i > 0) { sb.append(','); } sb.append(values[i]); } sb.append(']'); } else { sb.append(value.toString()); } sb.append(')'); log.trace(sb.toString()); } // Resolve any nested expression to get the actual target bean Object target = bean; Resolver resolver = getPropertyUtils().getResolver(); while (resolver.hasNested(name)) { try { target = getPropertyUtils().getProperty(target, resolver.next(name)); name = resolver.remove(name); } catch (NoSuchMethodException e) { return; // Skip this property setter } } if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + name); } // Declare local variables we will require String propName = resolver.getProperty(name); // Simple name of target property Class type = null; // Java type of target property int index = resolver.getIndex(name); // Indexed subscript value (if any) String key = resolver.getKey(name); // Mapped key value (if any) // Calculate the target property type if (target instanceof DynaBean) { DynaClass dynaClass = ((DynaBean) target).getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return; // Skip this property setter } type = dynaPropertyType(dynaProperty, value); } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, name); if (descriptor == null) { return; // Skip this property setter } } catch (NoSuchMethodException e) { return; // Skip this property setter } type = descriptor.getPropertyType(); if (type == null) { // Most likely an indexed setter on a POJB only if (log.isTraceEnabled()) { log.trace(" target type for property '" + propName + "' is null, so skipping ths setter"); } return; } } if (log.isTraceEnabled()) { log.trace(" target propName=" + propName + ", type=" + type + ", index=" + index + ", key=" + key); } // Convert the specified value to the required type and store it if (index >= 0) { // Destination must be indexed value = convertForCopy(value, type.getComponentType()); try { getPropertyUtils().setIndexedProperty(target, propName, index, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException (e, "Cannot set " + propName); } } else if (key != null) { // Destination must be mapped // Maps do not know what the preferred data type is, // so perform no conversions at all // FIXME - should we create or support a TypedMap? try { getPropertyUtils().setMappedProperty(target, propName, key, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException (e, "Cannot set " + propName); } } else { // Destination must be simple value = convertForCopy(value, type); try { getPropertyUtils().setSimpleProperty(target, propName, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException (e, "Cannot set " + propName); } } } /** *

      Return the entire set of properties for which the specified bean * provides a read method. This map contains the to String * converted property values for all properties for which a read method * is provided (i.e. where the getReadMethod() returns non-null).

      * *

      This map can be fed back to a call to * BeanUtils.populate() to reconsitute the same set of * properties, modulo differences for read-only and write-only * properties, but only if there are no indexed properties.

      * *

      Warning: if any of the bean property implementations * contain (directly or indirectly) a call to this method then * a stack overflow may result. For example: *

           * class MyBean
           * {
           *    public Map getParameterMap()
           *    {
           *         BeanUtils.describe(this);
           *    }
           * }
           * 
      * will result in an infinite regression when getParametersMap * is called. It is recommended that such methods are given alternative * names (for example, parametersMap). *

      * @param bean Bean whose properties are to be extracted * @return Map of property descriptors * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { // return (Collections.EMPTY_MAP); return (new java.util.HashMap()); } if (log.isDebugEnabled()) { log.debug("Describing bean: " + bean.getClass().getName()); } Map description = new HashMap(); if (bean instanceof DynaBean) { DynaProperty[] descriptors = ((DynaBean) bean).getDynaClass().getDynaProperties(); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); description.put(name, getProperty(bean, name)); } } else { PropertyDescriptor[] descriptors = getPropertyUtils().getPropertyDescriptors(bean); Class clazz = bean.getClass(); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); if (getPropertyUtils().getReadMethod(clazz, descriptors[i]) != null) { description.put(name, getProperty(bean, name)); } } } return (description); } /** * Return the value of the specified array property of the specified * bean, as a String array. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @return The array property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String[] getArrayProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getProperty(bean, name); if (value == null) { return (null); } else if (value instanceof Collection) { ArrayList values = new ArrayList(); for (Object item : (Collection) value) { if (item == null) { values.add(null); } else { // convert to string using convert utils values.add(getConvertUtils().convert(item)); } } return (values.toArray(new String[values.size()])); } else if (value.getClass().isArray()) { int n = Array.getLength(value); String[] results = new String[n]; for (int i = 0; i < n; i++) { Object item = Array.get(value, i); if (item == null) { results[i] = null; } else { // convert to string using convert utils results[i] = getConvertUtils().convert(item); } } return (results); } else { String[] results = new String[1]; results[0] = getConvertUtils().convert(value); return (results); } } /** * Return the value of the specified indexed property of the specified * bean, as a String. The zero-relative index of the * required value must be included (in square brackets) as a suffix to * the property name, or IllegalArgumentException will be * thrown. * * @param bean Bean whose property is to be extracted * @param name propertyname[index] of the property value * to be extracted * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getIndexedProperty(bean, name); return (getConvertUtils().convert(value)); } /** * Return the value of the specified indexed property of the specified * bean, as a String. The index is specified as a method parameter and * must *not* be included in the property name expression * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getIndexedProperty(bean, name, index); return (getConvertUtils().convert(value)); } /** * Return the value of the specified indexed property of the specified * bean, as a String. The String-valued key of the required value * must be included (in parentheses) as a suffix to * the property name, or IllegalArgumentException will be * thrown. * * @param bean Bean whose property is to be extracted * @param name propertyname(index) of the property value * to be extracted * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getMappedProperty(bean, name); return (getConvertUtils().convert(value)); } /** * Return the value of the specified mapped property of the specified * bean, as a String. The key is specified as a method parameter and * must *not* be included in the property name expression * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param key Lookup key of the property value to be extracted * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getMappedProperty(bean, name, key); return (getConvertUtils().convert(value)); } /** * Return the value of the (possibly nested) property of the specified * name, for the specified bean, as a String. * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * @return The nested property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getNestedProperty(bean, name); return (getConvertUtils().convert(value)); } /** * Return the value of the specified property of the specified bean, * no matter which property reference format is used, as a String. * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (getNestedProperty(bean, name)); } /** * Return the value of the specified simple property of the specified * bean, converted to a String. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getSimpleProperty(bean, name); return (getConvertUtils().convert(value)); } /** *

      Populate the JavaBeans properties of the specified bean, based on * the specified name/value pairs. This method uses Java reflection APIs * to identify corresponding "property setter" method names, and deals * with setter arguments of type String, boolean, * int, long, float, and * double. In addition, array setters for these types (or the * corresponding primitive types) can also be identified.

      * *

      The particular setter method to be called for each property is * determined using the usual JavaBeans introspection mechanisms. Thus, * you may identify custom setter methods using a BeanInfo class that is * associated with the class of the bean itself. If no such BeanInfo * class is available, the standard method name conversion ("set" plus * the capitalized name of the property in question) is used.

      * *

      NOTE: It is contrary to the JavaBeans Specification * to have more than one setter method (with different argument * signatures) for the same property.

      * *

      WARNING - The logic of this method is customized * for extracting String-based request parameters from an HTTP request. * It is probably not what you want for general property copying with * type conversion. For that purpose, check out the * copyProperties() method instead.

      * * @param bean JavaBean whose properties are being populated * @param properties Map keyed by property name, with the * corresponding (String or String[]) value(s) to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ public void populate(Object bean, Map properties) throws IllegalAccessException, InvocationTargetException { // Do nothing unless both arguments have been specified if ((bean == null) || (properties == null)) { return; } if (log.isDebugEnabled()) { log.debug("BeanUtils.populate(" + bean + ", " + properties + ")"); } // Loop through the property name/value pairs to be set for(Map.Entry entry : properties.entrySet()) { // Identify the property name and value(s) to be assigned String name = entry.getKey(); if (name == null) { continue; } // Perform the assignment for this property setProperty(bean, name, entry.getValue()); } } /** *

      Set the specified property value, performing type conversions as * required to conform to the type of the destination property.

      * *

      If the property is read only then the method returns * without throwing an exception.

      * *

      If null is passed into a property expecting a primitive value, * then this will be converted as if it were a null string.

      * *

      WARNING - The logic of this method is customized * to meet the needs of populate(), and is probably not what * you want for general property copying with type conversion. For that * purpose, check out the copyProperty() method instead.

      * *

      WARNING - PLEASE do not modify the behavior of this * method without consulting with the Struts developer community. There * are some subtleties to its functionality that are not documented in the * Javadoc description above, yet are vital to the way that Struts utilizes * this method.

      * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value Value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ public void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { // Trace logging (if enabled) if (log.isTraceEnabled()) { StringBuilder sb = new StringBuilder(" setProperty("); sb.append(bean); sb.append(", "); sb.append(name); sb.append(", "); if (value == null) { sb.append(""); } else if (value instanceof String) { sb.append((String) value); } else if (value instanceof String[]) { String[] values = (String[]) value; sb.append('['); for (int i = 0; i < values.length; i++) { if (i > 0) { sb.append(','); } sb.append(values[i]); } sb.append(']'); } else { sb.append(value.toString()); } sb.append(')'); log.trace(sb.toString()); } // Resolve any nested expression to get the actual target bean Object target = bean; Resolver resolver = getPropertyUtils().getResolver(); while (resolver.hasNested(name)) { try { target = getPropertyUtils().getProperty(target, resolver.next(name)); if (target == null) { // the value of a nested property is null return; } name = resolver.remove(name); } catch (NoSuchMethodException e) { return; // Skip this property setter } } if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + name); } // Declare local variables we will require String propName = resolver.getProperty(name); // Simple name of target property Class type = null; // Java type of target property int index = resolver.getIndex(name); // Indexed subscript value (if any) String key = resolver.getKey(name); // Mapped key value (if any) // Calculate the property type if (target instanceof DynaBean) { DynaClass dynaClass = ((DynaBean) target).getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return; // Skip this property setter } type = dynaPropertyType(dynaProperty, value); } else if (target instanceof Map) { type = Object.class; } else if (target != null && target.getClass().isArray() && index >= 0) { type = Array.get(target, index).getClass(); } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, name); if (descriptor == null) { return; // Skip this property setter } } catch (NoSuchMethodException e) { return; // Skip this property setter } if (descriptor instanceof MappedPropertyDescriptor) { if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = ((MappedPropertyDescriptor) descriptor). getMappedPropertyType(); } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) { if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = ((IndexedPropertyDescriptor) descriptor). getIndexedPropertyType(); } else if (key != null) { if (descriptor.getReadMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = (value == null) ? Object.class : value.getClass(); } else { if (descriptor.getWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = descriptor.getPropertyType(); } } // Convert the specified value to the required type Object newValue = null; if (type.isArray() && (index < 0)) { // Scalar value into array if (value == null) { String[] values = new String[1]; values[0] = null; newValue = getConvertUtils().convert(values, type); } else if (value instanceof String) { newValue = getConvertUtils().convert(value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert((String[]) value, type); } else { newValue = convert(value, type); } } else if (type.isArray()) { // Indexed value into array if (value instanceof String || value == null) { newValue = getConvertUtils().convert((String) value, type.getComponentType()); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType()); } else { newValue = convert(value, type.getComponentType()); } } else { // Value into scalar if (value instanceof String) { newValue = getConvertUtils().convert((String) value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type); } else { newValue = convert(value, type); } } // Invoke the setter method try { getPropertyUtils().setProperty(target, name, newValue); } catch (NoSuchMethodException e) { throw new InvocationTargetException (e, "Cannot set " + propName); } } /** * Gets the ConvertUtilsBean instance used to perform the conversions. * * @return The ConvertUtils bean instance */ public ConvertUtilsBean getConvertUtils() { return convertUtilsBean; } /** * Gets the PropertyUtilsBean instance used to access properties. * * @return The ConvertUtils bean instance */ public PropertyUtilsBean getPropertyUtils() { return propertyUtilsBean; } /** * If we're running on JDK 1.4 or later, initialize the cause for the given throwable. * * @param throwable The throwable. * @param cause The cause of the throwable. * @return true if the cause was initialized, otherwise false. * @since 1.8.0 */ public boolean initCause(Throwable throwable, Throwable cause) { if (INIT_CAUSE_METHOD != null && cause != null) { try { INIT_CAUSE_METHOD.invoke(throwable, new Object[] { cause }); return true; } catch (Throwable e) { return false; // can't initialize cause } } return false; } /** *

      Convert the value to an object of the specified class (if * possible).

      * * @param value Value to be converted (may be null) * @param type Class of the value to be converted to * @return The converted value * * @exception ConversionException if thrown by an underlying Converter * @since 1.8.0 */ protected Object convert(Object value, Class type) { Converter converter = getConvertUtils().lookup(type); if (converter != null) { log.trace(" USING CONVERTER " + converter); return converter.convert(type, value); } else { return value; } } /** * Performs a type conversion of a property value before it is copied to a target * bean. This method delegates to {@link #convert(Object, Class)}, but null * values are not converted. This causes null values to be copied verbatim. * * @param value the value to be converted and copied * @param type the target type of the conversion * @return the converted value */ private Object convertForCopy(Object value, Class type) { return (value != null) ? convert(value, type) : value; } /** * Returns a Method allowing access to * {@link Throwable#initCause(Throwable)} method of {@link Throwable}, * or null if the method * does not exist. * * @return A Method for Throwable.initCause, or * null if unavailable. */ private static Method getInitCauseMethod() { try { Class[] paramsClasses = new Class[] { Throwable.class }; return Throwable.class.getMethod("initCause", paramsClasses); } catch (NoSuchMethodException e) { Log log = LogFactory.getLog(BeanUtils.class); if (log.isWarnEnabled()) { log.warn("Throwable does not have initCause() method in JDK 1.3"); } return null; } catch (Throwable e) { Log log = LogFactory.getLog(BeanUtils.class); if (log.isWarnEnabled()) { log.warn("Error getting the Throwable initCause() method", e); } return null; } } /** * Determines the type of a {@code DynaProperty}. Here a special treatment * is needed for mapped properties. * * @param dynaProperty the property descriptor * @param value the value object to be set for this property * @return the type of this property */ private static Class dynaPropertyType(DynaProperty dynaProperty, Object value) { if (!dynaProperty.isMapped()) { return dynaProperty.getType(); } return (value == null) ? String.class : value.getClass(); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/BeanUtilsBean2.java100644 0 0 5670 12262570612 26616 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** *

      {@link BeanUtilsBean} implementation that creates a * {@link ConvertUtilsBean2} and delegates conversion to * {@link ConvertUtilsBean#convert(Object, Class)}. *

      * *

      * To configure this implementation for the current context ClassLoader invoke * BeanUtilsBean.setInstance(new BeanUtilsBean2()); *

      * *

      * BeanUtils 1.7.0 delegated all conversion to String to the converter * registered for the String.class. One of the improvements in * BeanUtils 1.8.0 was to upgrade the {@link Converter} implementations so * that they could handle conversion to String for their type (e.g. * IntegerConverter now handles conversion from an Integer to a String as * well as String to Integer). *

      * *

      * In order to take advantage of these improvements BeanUtils needs to change * how it gets the appropriate {@link Converter}. This functionality has been * implemented in the new {@link ConvertUtilsBean#lookup(Class, Class)} and * {@link ConvertUtilsBean#convert(Object, Class)} methods. However changing * {@link BeanUtilsBean} to use these methods could create compatibility * issues for existing users. In order to avoid that, this new * {@link BeanUtilsBean} implementation has been created (and the associated * {@link ConvertUtilsBean2}). *

      * * @see ConvertUtilsBean2 * @version $Id: BeanUtilsBean2.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.8.0 */ public class BeanUtilsBean2 extends BeanUtilsBean { /** *

      Constructs an instance using new property * and conversion instances.

      */ public BeanUtilsBean2() { super(new ConvertUtilsBean2()); } /** *

      Convert the value to an object of the specified class (if * possible).

      * * @param value Value to be converted (may be null) * @param type Class of the value to be converted to * @return The converted value */ @Override protected Object convert(Object value, Class type) { return getConvertUtils().convert(value, type); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/ConstructorUtils.java100644 0 0 44525 12262570612 27450 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; /** *

      Utility reflection methods focussed on constructors, modelled after {@link MethodUtils}.

      * *

      Known Limitations

      *

      Accessing Public Constructors In A Default Access Superclass

      *

      There is an issue when invoking public constructors contained in a default access superclass. * Reflection locates these constructors fine and correctly assigns them as public. * However, an IllegalAccessException is thrown if the constructors is invoked.

      * *

      ConstructorUtils contains a workaround for this situation. * It will attempt to call setAccessible on this constructor. * If this call succeeds, then the method can be invoked as normal. * This call will only succeed when the application has sufficient security privilages. * If this call fails then a warning will be logged and the method may fail.

      * * @version $Id: ConstructorUtils.java 1540518 2013-11-10 19:04:04Z oheger $ */ public class ConstructorUtils { // --------------------------------------------------------- Private Members /** An empty class array */ private static final Class[] EMPTY_CLASS_PARAMETERS = new Class[0]; /** An empty object array */ private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; // --------------------------------------------------------- Public Methods /** *

      Convenience method returning new instance of klazz using a single argument constructor. * The formal parameter type is inferred from the actual values of arg. * See {@link #invokeExactConstructor(Class, Object[], Class[])} for more details.

      * *

      The signatures should be assignment compatible.

      * * @param the type of the object to be constructed * @param klass the class to be constructed. * @param arg the actual argument. May be null (this will result in calling the default constructor). * @return new instance of klazz * * @throws NoSuchMethodException If the constructor cannot be found * @throws IllegalAccessException If an error occurs accessing the constructor * @throws InvocationTargetException If an error occurs invoking the constructor * @throws InstantiationException If an error occurs instantiating the class * * @see #invokeConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) */ public static T invokeConstructor(Class klass, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Object[] args = toArray(arg); return invokeConstructor(klass, args); } /** *

      Returns new instance of klazz created using the actual arguments args. * The formal parameter types are inferred from the actual values of args. * See {@link #invokeExactConstructor(Class, Object[], Class[])} for more details.

      * *

      The signatures should be assignment compatible.

      * * @param the type of the object to be constructed * @param klass the class to be constructed. * @param args actual argument array. May be null (this will result in calling the default constructor). * @return new instance of klazz * * @throws NoSuchMethodException If the constructor cannot be found * @throws IllegalAccessException If an error occurs accessing the constructor * @throws InvocationTargetException If an error occurs invoking the constructor * @throws InstantiationException If an error occurs instantiating the class * * @see #invokeConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) */ public static T invokeConstructor(Class klass, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { if (null == args) { args = EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class parameterTypes[] = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeConstructor(klass, args, parameterTypes); } /** *

      Returns new instance of klazz created using constructor * with signature parameterTypes and actual arguments args.

      * *

      The signatures should be assignment compatible.

      * * @param the type of the object to be constructed * @param klass the class to be constructed. * @param args actual argument array. May be null (this will result in calling the default constructor). * @param parameterTypes parameter types array * @return new instance of klazz * * @throws NoSuchMethodException if matching constructor cannot be found * @throws IllegalAccessException thrown on the constructor's invocation * @throws InvocationTargetException thrown on the constructor's invocation * @throws InstantiationException thrown on the constructor's invocation * @see Constructor#newInstance */ public static T invokeConstructor( Class klass, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { if (parameterTypes == null) { parameterTypes = EMPTY_CLASS_PARAMETERS; } if (args == null) { args = EMPTY_OBJECT_ARRAY; } Constructor ctor = getMatchingAccessibleConstructor(klass, parameterTypes); if (null == ctor) { throw new NoSuchMethodException( "No such accessible constructor on object: " + klass.getName()); } return ctor.newInstance(args); } /** *

      Convenience method returning new instance of klazz using a single argument constructor. * The formal parameter type is inferred from the actual values of arg. * See {@link #invokeExactConstructor(Class, Object[], Class[])} for more details.

      * *

      The signatures should match exactly.

      * * @param the type of the object to be constructed * @param klass the class to be constructed. * @param arg the actual argument. May be null (this will result in calling the default constructor). * @return new instance of klazz * * @throws NoSuchMethodException If the constructor cannot be found * @throws IllegalAccessException If an error occurs accessing the constructor * @throws InvocationTargetException If an error occurs invoking the constructor * @throws InstantiationException If an error occurs instantiating the class * * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) */ public static T invokeExactConstructor(Class klass, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Object[] args = toArray(arg); return invokeExactConstructor(klass, args); } /** *

      Returns new instance of klazz created using the actual arguments args. * The formal parameter types are inferred from the actual values of args. * See {@link #invokeExactConstructor(Class, Object[], Class[])} for more details.

      * *

      The signatures should match exactly.

      * * @param the type of the object to be constructed * @param klass the class to be constructed. * @param args actual argument array. May be null (this will result in calling the default constructor). * @return new instance of klazz * * @throws NoSuchMethodException If the constructor cannot be found * @throws IllegalAccessException If an error occurs accessing the constructor * @throws InvocationTargetException If an error occurs invoking the constructor * @throws InstantiationException If an error occurs instantiating the class * * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) */ public static T invokeExactConstructor(Class klass, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { if (null == args) { args = EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class parameterTypes[] = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeExactConstructor(klass, args, parameterTypes); } /** *

      Returns new instance of klazz created using constructor * with signature parameterTypes and actual arguments * args.

      * *

      The signatures should match exactly.

      * * @param the type of the object to be constructed * @param klass the class to be constructed. * @param args actual argument array. May be null (this will result in calling the default constructor). * @param parameterTypes parameter types array * @return new instance of klazz * * @throws NoSuchMethodException if matching constructor cannot be found * @throws IllegalAccessException thrown on the constructor's invocation * @throws InvocationTargetException thrown on the constructor's invocation * @throws InstantiationException thrown on the constructor's invocation * @see Constructor#newInstance */ public static T invokeExactConstructor( Class klass, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { if (args == null) { args = EMPTY_OBJECT_ARRAY; } if (parameterTypes == null) { parameterTypes = EMPTY_CLASS_PARAMETERS; } Constructor ctor = getAccessibleConstructor(klass, parameterTypes); if (null == ctor) { throw new NoSuchMethodException( "No such accessible constructor on object: " + klass.getName()); } return ctor.newInstance(args); } /** * Returns a constructor with single argument. * @param the type of the constructor * @param klass the class to be constructed * @param parameterType The constructor parameter type * @return null if matching accessible constructor can not be found. * @see Class#getConstructor * @see #getAccessibleConstructor(java.lang.reflect.Constructor) */ public static Constructor getAccessibleConstructor( Class klass, Class parameterType) { Class[] parameterTypes = { parameterType }; return getAccessibleConstructor(klass, parameterTypes); } /** * Returns a constructor given a class and signature. * @param the type to be constructed * @param klass the class to be constructed * @param parameterTypes the parameter array * @return null if matching accessible constructor can not be found * @see Class#getConstructor * @see #getAccessibleConstructor(java.lang.reflect.Constructor) */ public static Constructor getAccessibleConstructor( Class klass, Class[] parameterTypes) { try { return getAccessibleConstructor( klass.getConstructor(parameterTypes)); } catch (NoSuchMethodException e) { return (null); } } /** * Returns accessible version of the given constructor. * @param the type of the constructor * @param ctor prototype constructor object. * @return null if accessible constructor can not be found. * @see java.lang.SecurityManager */ public static Constructor getAccessibleConstructor(Constructor ctor) { // Make sure we have a method to check if (ctor == null) { return (null); } // If the requested method is not public we cannot call it if (!Modifier.isPublic(ctor.getModifiers())) { return (null); } // If the declaring class is public, we are done Class clazz = ctor.getDeclaringClass(); if (Modifier.isPublic(clazz.getModifiers())) { return (ctor); } // what else can we do? return null; } private static Object[] toArray(Object arg) { Object[] args = null; if (arg != null) { args = new Object[] { arg }; } return args; } // -------------------------------------------------------- Private Methods /** *

      Find an accessible constructor with compatible parameters. * Compatible parameters mean that every method parameter is assignable from * the given parameters. In other words, it finds constructor that will take * the parameters given.

      * *

      First it checks if there is constructor matching the exact signature. * If no such, all the constructors of the class are tested if their signatures * are assignment compatible with the parameter types. * The first matching constructor is returned.

      * * @param the type of the class to be inspected * @param clazz find constructor for this class * @param parameterTypes find method with compatible parameters * @return a valid Constructor object. If there's no matching constructor, returns null. */ private static Constructor getMatchingAccessibleConstructor( Class clazz, Class[] parameterTypes) { // see if we can find the method directly // most of the time this works and it's much faster try { Constructor ctor = clazz.getConstructor(parameterTypes); try { // // XXX Default access superclass workaround // // When a public class has a default access superclass // with public methods, these methods are accessible. // Calling them from compiled code works fine. // // Unfortunately, using reflection to invoke these methods // seems to (wrongly) to prevent access even when the method // modifer is public. // // The following workaround solves the problem but will only // work from sufficiently privilages code. // // Better workarounds would be greatfully accepted. // ctor.setAccessible(true); } catch (SecurityException se) { /* SWALLOW, if workaround fails don't fret. */ } return ctor; } catch (NoSuchMethodException e) { /* SWALLOW */ } // search through all methods int paramSize = parameterTypes.length; Constructor[] ctors = clazz.getConstructors(); for (int i = 0, size = ctors.length; i < size; i++) { // compare parameters Class[] ctorParams = ctors[i].getParameterTypes(); int ctorParamSize = ctorParams.length; if (ctorParamSize == paramSize) { boolean match = true; for (int n = 0; n < ctorParamSize; n++) { if (!MethodUtils .isAssignmentCompatible( ctorParams[n], parameterTypes[n])) { match = false; break; } } if (match) { // get accessible version of method Constructor ctor = getAccessibleConstructor(ctors[i]); if (ctor != null) { try { ctor.setAccessible(true); } catch (SecurityException se) { /* Swallow SecurityException * TODO: Why? */ } @SuppressWarnings("unchecked") // Class.getConstructors() actually returns constructors // of type T, so it is safe to cast. Constructor typedCtor = (Constructor) ctor; return typedCtor; } } } } return null; } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/ContextClassLoaderLocal.java100644 0 0 22555 12262570612 30615 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.Map; import java.util.WeakHashMap; /** * An instance of this class represents a value that is provided per (thread) * context classloader. * *

      Occasionally it is necessary to store data in "global" variables * (including uses of the Singleton pattern). In applications which have only * a single classloader such data can simply be stored as "static" members on * some class. When multiple classloaders are involved, however, this approach * can fail; in particular, this doesn't work when the code may be run within a * servlet container or a j2ee container, and the class on which the static * member is defined is loaded via a "shared" classloader that is visible to all * components running within the container. This class provides a mechanism for * associating data with a ClassLoader instance, which ensures that when the * code runs in such a container each component gets its own copy of the * "global" variable rather than unexpectedly sharing a single copy of the * variable with other components that happen to be running in the same * container at the same time (eg servlets or EJBs.)

      * *

      This class is strongly patterned after the java.lang.ThreadLocal * class, which performs a similar task in allowing data to be associated * with a particular thread.

      * *

      When code that uses this class is run as a "normal" application, ie * not within a container, the effect is identical to just using a static * member variable to store the data, because Thread.getContextClassLoader * always returns the same classloader (the system classloader).

      * *

      Expected usage is as follows:
      *

       *  public class SomeClass {
       *    private static final ContextClassLoaderLocal<String> global
       *      = new ContextClassLoaderLocal<String>() {
       *          protected String initialValue() {
       *              return new String("Initial value");
       *          };
       *
       *    public void testGlobal() {
       *      String s = global.get();
       *      System.out.println("global value:" + s);
       *      buf.set("New Value");
       *    }
       * 
      *

      * *

      Note: This class takes some care to ensure that when * a component which uses this class is "undeployed" by a container the * component-specific classloader and all its associated classes (and their * static variables) are garbage-collected. Unfortunately there is one * scenario in which this does not work correctly and there * is unfortunately no known workaround other than ensuring that the * component (or its container) calls the "unset" method on this class for * each instance of this class when the component is undeployed. The problem * occurs if: *

        *
      • the class containing a static instance of this class was loaded via * a shared classloader, and
      • *
      • the value stored in the instance is an object whose class was loaded * via the component-specific classloader (or any of the objects it refers * to were loaded via that classloader).
      • *
      * The result is that the map managed by this object still contains a strong * reference to the stored object, which contains a strong reference to the * classloader that loaded it, meaning that although the container has * "undeployed" the component the component-specific classloader and all the * related classes and static variables cannot be garbage-collected. This is * not expected to be an issue with the commons-beanutils library as the only * classes which use this class are BeanUtilsBean and ConvertUtilsBean and * there is no obvious reason for a user of the beanutils library to subclass * either of those classes.

      * *

      Note: A WeakHashMap bug in several 1.3 JVMs results in * a memory leak for those JVMs.

      * *

      Note: Of course all of this would be unnecessary if * containers required each component to load the full set of classes it * needs, ie avoided providing classes loaded via a "shared" classloader.

      * * @param the type of data stored in an instance * @version $Id: ContextClassLoaderLocal.java 1540186 2013-11-08 21:08:30Z oheger $ * @see java.lang.Thread#getContextClassLoader */ public class ContextClassLoaderLocal { private final Map valueByClassLoader = new WeakHashMap(); private boolean globalValueInitialized = false; private T globalValue; /** * Construct a context classloader instance */ public ContextClassLoaderLocal() { super(); } /** * Returns the initial value for this ContextClassLoaderLocal * variable. This method will be called once per Context ClassLoader for * each ContextClassLoaderLocal, the first time it is accessed * with get or set. If the programmer desires ContextClassLoaderLocal variables * to be initialized to some value other than null, ContextClassLoaderLocal must * be subclassed, and this method overridden. Typically, an anonymous * inner class will be used. Typical implementations of initialValue * will call an appropriate constructor and return the newly constructed * object. * * @return a new Object to be used as an initial value for this ContextClassLoaderLocal */ protected T initialValue() { return null; } /** * Gets the instance which provides the functionality for {@link BeanUtils}. * This is a pseudo-singleton - an single instance is provided per (thread) context classloader. * This mechanism provides isolation for web apps deployed in the same container. * @return the object currently associated with the context-classloader of the current thread. */ public synchronized T get() { // synchronizing the whole method is a bit slower // but guarantees no subtle threading problems, and there's no // need to synchronize valueByClassLoader // make sure that the map is given a change to purge itself valueByClassLoader.isEmpty(); try { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { T value = valueByClassLoader.get(contextClassLoader); if ((value == null) && !valueByClassLoader.containsKey(contextClassLoader)) { value = initialValue(); valueByClassLoader.put(contextClassLoader, value); } return value; } } catch (SecurityException e) { /* SWALLOW - should we log this? */ } // if none or exception, return the globalValue if (!globalValueInitialized) { globalValue = initialValue(); globalValueInitialized = true; }//else already set return globalValue; } /** * Sets the value - a value is provided per (thread) context classloader. * This mechanism provides isolation for web apps deployed in the same container. * * @param value the object to be associated with the entrant thread's context classloader */ public synchronized void set(T value) { // synchronizing the whole method is a bit slower // but guarentees no subtle threading problems // make sure that the map is given a change to purge itself valueByClassLoader.isEmpty(); try { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { valueByClassLoader.put(contextClassLoader, value); return; } } catch (SecurityException e) { /* SWALLOW - should we log this? */ } // if in doubt, set the global value globalValue = value; globalValueInitialized = true; } /** * Unsets the value associated with the current thread's context classloader */ public synchronized void unset() { try { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); unset(contextClassLoader); } catch (SecurityException e) { /* SWALLOW - should we log this? */ } } /** * Unsets the value associated with the given classloader * @param classLoader The classloader to unset for */ public synchronized void unset(ClassLoader classLoader) { valueByClassLoader.remove(classLoader); } }commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/ConversionException.java100644 0 0 5152 12262570613 30060 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** *

      A ConversionException indicates that a call to * Converter.convert() has failed to complete successfully. * * @since 1.3 * @version $Id: ConversionException.java 1454606 2013-03-08 22:30:51Z britter $ */ public class ConversionException extends RuntimeException { // ----------------------------------------------------------- Constructors /** * Construct a new exception with the specified message. * * @param message The message describing this exception */ public ConversionException(String message) { super(message); } /** * Construct a new exception with the specified message and root cause. * * @param message The message describing this exception * @param cause The root cause of this exception */ public ConversionException(String message, Throwable cause) { super(message); this.cause = cause; } /** * Construct a new exception with the specified root cause. * * @param cause The root cause of this exception */ public ConversionException(Throwable cause) { super(cause.getMessage()); this.cause = cause; } // ------------------------------------------------------------- Properties /** * The root cause of this ConversionException, compatible with * JDK 1.4's extensions to java.lang.Throwable. */ protected Throwable cause = null; /** * Return the root cause of this conversion exception. * @return the root cause of this conversion exception */ @Override public Throwable getCause() { return (this.cause); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/Converter.java100644 0 0 4076 12262570610 26024 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** *

      General purpose data type converter that can be registered and used * within the BeanUtils package to manage the conversion of objects from * one type to another.

      * *

      Converter subclasses bundled with the BeanUtils library are required * to be thread-safe, as users of the library may call conversion methods * from more than one thread simultaneously.

      * *

      Custom converter subclasses created by users of the library can be * non-thread-safe if the application using them is single-threaded. However * it is recommended that they be written in a thread-safe manner anyway.

      * * @version $Id: Converter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public interface Converter { /** * Convert the specified input object into an output object of the * specified type. * * @param the desired result type * @param type Data type to which this value should be converted * @param value The input value to be converted * @return The converted value * * @exception ConversionException if conversion cannot be performed * successfully */ public T convert(Class type, Object value); } ././@LongLink100644 0 0 156 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/AbstractArrayConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/AbstractArrayConve100644 0 0 16333 12262570611 31104 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.io.IOException; import java.io.StreamTokenizer; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.Converter; /** *

      Convenience base class for converters that translate the String * representation of an array into a corresponding array of primitives * object. This class encapsulates the functionality required to parse * the String into a list of String elements that can later be * individually converted to the appropriate primitive type.

      * *

      The input syntax accepted by the parseElements() method * is designed to be compatible with the syntax used to initialize arrays * in a Java source program, except that only String literal values are * supported. For maximum flexibility, the surrounding '{' and '}' * characters are optional, and individual elements may be separated by * any combination of whitespace and comma characters.

      * * @version $Id: AbstractArrayConverter.java 1454606 2013-03-08 22:30:51Z britter $ * @since 1.4 * @deprecated Replaced by the new {@link ArrayConverter} implementation */ @Deprecated public abstract class AbstractArrayConverter implements Converter { // ----------------------------------------------------------- Constructors /** * Create a {@link Converter} that will throw a {@link ConversionException} * if a conversion error occurs. */ public AbstractArrayConverter() { this.defaultValue = null; this.useDefault = false; } /** * Create a {@link Converter} that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @since 1.8.0 */ public AbstractArrayConverter(Object defaultValue) { if (defaultValue == NO_DEFAULT) { this.useDefault = false; } else { this.defaultValue = defaultValue; this.useDefault = true; } } // ------------------------------------------------------- Static Variables /** * This is a special reference that can be passed as the "default object" * to the constructor to indicate that no default is desired. Note that * the value 'null' cannot be used for this purpose, as the caller may * want a null to be returned as the default. * @since 1.8.0 */ public static final Object NO_DEFAULT = new Object(); // ----------------------------------------------------- Instance Variables /** *

      Model object for string arrays.

      */ protected static String[] strings = new String[0]; /** * The default value specified to our Constructor, if any. */ protected Object defaultValue = null; /** * Should we return the default value on conversion errors? */ protected boolean useDefault = true; // --------------------------------------------------------- Public Methods /** * Convert the specified input object into an output object of the * specified type. This method must be implemented by a concrete * subclass. * * @param type Data type to which this value should be converted * @param value The input value to be converted * @return The converted value * * @exception ConversionException if conversion cannot be performed * successfully */ public abstract Object convert(Class type, Object value); // ------------------------------------------------------ Protected Methods /** *

      Parse an incoming String of the form similar to an array initializer * in the Java language into a List individual Strings * for each element, according to the following rules.

      *
        *
      • The string is expected to be a comma-separated list of values.
      • *
      • The string may optionally have matching '{' and '}' delimiters * around the list.
      • *
      • Whitespace before and after each element is stripped.
      • *
      • Elements in the list may be delimited by single or double quotes. * Within a quoted elements, the normal Java escape sequences are valid.
      • *
      * * @param svalue String value to be parsed * @return The parsed list of String values * * @exception ConversionException if the syntax of svalue * is not syntactically valid * @exception NullPointerException if svalue * is null */ protected List parseElements(String svalue) { // Validate the passed argument if (svalue == null) { throw new NullPointerException(); } // Trim any matching '{' and '}' delimiters svalue = svalue.trim(); if (svalue.startsWith("{") && svalue.endsWith("}")) { svalue = svalue.substring(1, svalue.length() - 1); } try { // Set up a StreamTokenizer on the characters in this String StreamTokenizer st = new StreamTokenizer(new StringReader(svalue)); st.whitespaceChars(',',','); // Commas are delimiters st.ordinaryChars('0', '9'); // Needed to turn off numeric flag st.ordinaryChars('.', '.'); st.ordinaryChars('-', '-'); st.wordChars('0', '9'); // Needed to make part of tokens st.wordChars('.', '.'); st.wordChars('-', '-'); // Split comma-delimited tokens into a List ArrayList list = new ArrayList(); while (true) { int ttype = st.nextToken(); if ((ttype == StreamTokenizer.TT_WORD) || (ttype > 0)) { list.add(st.sval); } else if (ttype == StreamTokenizer.TT_EOF) { break; } else { throw new ConversionException ("Encountered token of type " + ttype); } } // Return the completed list return (list); } catch (IOException e) { throw new ConversionException(e); } } } ././@LongLink100644 0 0 151 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/AbstractConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/AbstractConverter.100644 0 0 42201 12262570611 31051 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.lang.reflect.Array; import java.util.Collection; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.Converter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Base {@link Converter} implementation that provides the structure * for handling conversion to and from a specified type. *

      * This implementation provides the basic structure for * converting to/from a specified type optionally using a default * value or throwing a {@link ConversionException} if a * conversion error occurs. *

      * Implementations should provide conversion to the specified * type and from the specified type to a String value * by implementing the following methods: *

        *
      • convertToString(value) - convert to a String * (default implementation uses the objects toString() * method).
      • *
      • convertToType(Class, value) - convert * to the specified type
      • *
      *

      * The default value has to be compliant to the default type of this * converter - which is enforced by the generic type parameter. If a * conversion is not possible and a default value is set, the converter * tries to transform the default value to the requested target type. * If this fails, a {@code ConversionException} if thrown. * * @version $Id: AbstractConverter.java 1540518 2013-11-10 19:04:04Z oheger $ * @since 1.8.0 */ public abstract class AbstractConverter implements Converter { /** Debug logging message to indicate default value configuration */ private static final String DEFAULT_CONFIG_MSG = "(N.B. Converters can be configured to use default values to avoid throwing exceptions)"; /** Current package name */ // getPackage() below returns null on some platforms/jvm versions during the unit tests. // private static final String PACKAGE = AbstractConverter.class.getPackage().getName() + "."; private static final String PACKAGE = "org.apache.commons.beanutils.converters."; /** * Logging for this instance. */ private transient Log log; /** * Should we return the default value on conversion errors? */ private boolean useDefault = false; /** * The default value specified to our Constructor, if any. */ private Object defaultValue = null; // ----------------------------------------------------------- Constructors /** * Construct a Converter that throws a * ConversionException if an error occurs. */ public AbstractConverter() { } /** * Construct a Converter that returns a default * value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public AbstractConverter(Object defaultValue) { setDefaultValue(defaultValue); } // --------------------------------------------------------- Public Methods /** * Indicates whether a default value will be returned or exception * thrown in the event of a conversion error. * * @return true if a default value will be returned for * conversion errors or false if a {@link ConversionException} * will be thrown. */ public boolean isUseDefault() { return useDefault; } /** * Convert the input object into an output object of the * specified type. * * @param the target type of the conversion * @param type Data type to which this value should be converted * @param value The input value to be converted * @return The converted value. * @throws ConversionException if conversion cannot be performed * successfully and no default is specified. */ public T convert(Class type, Object value) { if (type == null) { return convertToDefaultType(type, value); } Class sourceType = value == null ? null : value.getClass(); Class targetType = ConvertUtils.primitiveToWrapper(type); if (log().isDebugEnabled()) { log().debug("Converting" + (value == null ? "" : " '" + toString(sourceType) + "'") + " value '" + value + "' to type '" + toString(targetType) + "'"); } value = convertArray(value); // Missing Value if (value == null) { return handleMissing(targetType); } sourceType = value.getClass(); try { // Convert --> String if (targetType.equals(String.class)) { return targetType.cast(convertToString(value)); // No conversion necessary } else if (targetType.equals(sourceType)) { if (log().isDebugEnabled()) { log().debug(" No conversion required, value is already a " + toString(targetType)); } return targetType.cast(value); // Convert --> Type } else { Object result = convertToType(targetType, value); if (log().isDebugEnabled()) { log().debug(" Converted to " + toString(targetType) + " value '" + result + "'"); } return targetType.cast(result); } } catch (Throwable t) { return handleError(targetType, value, t); } } /** * Convert the input object into a String. *

      * N.B.This implementation simply uses the value's * toString() method and should be overriden if a * more sophisticated mechanism for conversion to a String * is required. * * @param value The input value to be converted. * @return the converted String value. * @throws Throwable if an error occurs converting to a String */ protected String convertToString(Object value) throws Throwable { return value.toString(); } /** * Convert the input object into an output object of the * specified type. *

      * Typical implementations will provide a minimum of * String --> type conversion. * * @param Target type of the conversion. * @param type Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Throwable if an error occurs converting to the specified type */ protected abstract T convertToType(Class type, Object value) throws Throwable; /** * Return the first element from an Array (or Collection) * or the value unchanged if not an Array (or Collection). * * N.B. This needs to be overriden for array/Collection converters. * * @param value The value to convert * @return The first element in an Array (or Collection) * or the value unchanged if not an Array (or Collection) */ protected Object convertArray(Object value) { if (value == null) { return null; } if (value.getClass().isArray()) { if (Array.getLength(value) > 0) { return Array.get(value, 0); } else { return null; } } if (value instanceof Collection) { Collection collection = (Collection)value; if (collection.size() > 0) { return collection.iterator().next(); } else { return null; } } return value; } /** * Handle Conversion Errors. *

      * If a default value has been specified then it is returned * otherwise a ConversionException is thrown. * * @param Target type of the conversion. * @param type Data type to which this value should be converted. * @param value The input value to be converted * @param cause The exception thrown by the convert method * @return The default value. * @throws ConversionException if no default value has been * specified for this {@link Converter}. */ protected T handleError(Class type, Object value, Throwable cause) { if (log().isDebugEnabled()) { if (cause instanceof ConversionException) { log().debug(" Conversion threw ConversionException: " + cause.getMessage()); } else { log().debug(" Conversion threw " + cause); } } if (useDefault) { return handleMissing(type); } ConversionException cex = null; if (cause instanceof ConversionException) { cex = (ConversionException)cause; if (log().isDebugEnabled()) { log().debug(" Re-throwing ConversionException: " + cex.getMessage()); log().debug(" " + DEFAULT_CONFIG_MSG); } } else { String msg = "Error converting from '" + toString(value.getClass()) + "' to '" + toString(type) + "' " + cause.getMessage(); cex = new ConversionException(msg, cause); if (log().isDebugEnabled()) { log().debug(" Throwing ConversionException: " + msg); log().debug(" " + DEFAULT_CONFIG_MSG); } BeanUtils.initCause(cex, cause); } throw cex; } /** * Handle missing values. *

      * If a default value has been specified, then it is returned (after a cast * to the desired target class); otherwise a ConversionException is thrown. * * @param the desired target type * @param type Data type to which this value should be converted. * @return The default value. * @throws ConversionException if no default value has been * specified for this {@link Converter}. */ protected T handleMissing(Class type) { if (useDefault || type.equals(String.class)) { Object value = getDefault(type); if (useDefault && value != null && !(type.equals(value.getClass()))) { try { value = convertToType(type, defaultValue); } catch (Throwable t) { throw new ConversionException("Default conversion to " + toString(type) + " failed.", t); } } if (log().isDebugEnabled()) { log().debug(" Using default " + (value == null ? "" : toString(value.getClass()) + " ") + "value '" + defaultValue + "'"); } // value is now either null or of the desired target type return type.cast(value); } ConversionException cex = new ConversionException("No value specified for '" + toString(type) + "'"); if (log().isDebugEnabled()) { log().debug(" Throwing ConversionException: " + cex.getMessage()); log().debug(" " + DEFAULT_CONFIG_MSG); } throw cex; } /** * Set the default value, converting as required. *

      * If the default value is different from the type the * Converter handles, it will be converted * to the handled type. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. * @throws ConversionException if an error occurs converting * the default value */ protected void setDefaultValue(Object defaultValue) { useDefault = false; if (log().isDebugEnabled()) { log().debug("Setting default value: " + defaultValue); } if (defaultValue == null) { this.defaultValue = null; } else { this.defaultValue = convert(getDefaultType(), defaultValue); } useDefault = true; } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. */ protected abstract Class getDefaultType(); /** * Return the default value for conversions to the specified * type. * @param type Data type to which this value should be converted. * @return The default value for the specified type. */ protected Object getDefault(Class type) { if (type.equals(String.class)) { return null; } else { return defaultValue; } } /** * Provide a String representation of this converter. * * @return A String representation of this converter */ @Override public String toString() { return toString(getClass()) + "[UseDefault=" + useDefault + "]"; } // ----------------------------------------------------------- Package Methods /** * Accessor method for Log instance. *

      * The Log instance variable is transient and * accessing it through this method ensures it * is re-initialized when this instance is * de-serialized. * * @return The Log instance. */ Log log() { if (log == null) { log = LogFactory.getLog(getClass()); } return log; } /** * Provide a String representation of a java.lang.Class. * @param type The java.lang.Class. * @return The String representation. */ String toString(Class type) { String typeName = null; if (type == null) { typeName = "null"; } else if (type.isArray()) { Class elementType = type.getComponentType(); int count = 1; while (elementType.isArray()) { elementType = elementType .getComponentType(); count++; } typeName = elementType.getName(); for (int i = 0; i < count; i++) { typeName += "[]"; } } else { typeName = type.getName(); } if (typeName.startsWith("java.lang.") || typeName.startsWith("java.util.") || typeName.startsWith("java.math.")) { typeName = typeName.substring("java.lang.".length()); } else if (typeName.startsWith(PACKAGE)) { typeName = typeName.substring(PACKAGE.length()); } return typeName; } /** * Performs a conversion to the default type. This method is called if we do * not have a target class. In this case, the T parameter is not set. * Therefore, we can cast to it (which is required to fulfill the contract * of the method signature). * * @param the type of the result object * @param targetClass the target class of the conversion * @param value the value to be converted * @return the converted value */ private T convertToDefaultType(Class targetClass, Object value) { @SuppressWarnings("unchecked") T result = (T) convert(getDefaultType(), value); return result; } /** * Generates a standard conversion exception with a message indicating that * the passed in value cannot be converted to the desired target type. * * @param type the target type * @param value the value to be converted * @return a {@code ConversionException} with a standard message * @since 1.9 */ protected ConversionException conversionException(Class type, Object value) { return new ConversionException("Can't convert value '" + value + "' to type " + type); } } ././@LongLink100644 0 0 146 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ArrayConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ArrayConverter.jav100644 0 0 46646 12262570611 31106 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.io.IOException; import java.io.StreamTokenizer; import java.io.StringReader; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.Converter; /** * Generic {@link Converter} implementation that handles conversion * to and from array objects. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. *

      * The main features of this implementation are: *

        *
      • Element Conversion - delegates to a {@link Converter}, * appropriate for the type, to convert individual elements * of the array. This leverages the power of existing converters * without having to replicate their functionality for converting * to the element type and removes the need to create a specifc * array type converters.
      • *
      • Arrays or Collections - can convert from either arrays or * Collections to an array, limited only by the capability * of the delegate {@link Converter}.
      • *
      • Delimited Lists - can Convert to and from a * delimited list in String format.
      • *
      • Conversion to String - converts an array to a * String in one of two ways: as a delimited list * or by converting the first element in the array to a String - this * is controlled by the {@link ArrayConverter#setOnlyFirstToString(boolean)} * parameter.
      • *
      • Multi Dimensional Arrays - it is possible to convert a String * to a multi-dimensional arrays, by embedding {@link ArrayConverter} * within each other - see example below.
      • *
      • Default Value
      • *
          *
        • No Default - use the * {@link ArrayConverter#ArrayConverter(Class, Converter)} * constructor to create a converter which throws a * {@link ConversionException} if the value is missing or * invalid.
        • *
        • Default values - use the * {@link ArrayConverter#ArrayConverter(Class, Converter, int)} * constructor to create a converter which returns a default * value. The defaultSize parameter controls the * default value in the following way:
        • *
            *
          • defaultSize < 0 - default is null
          • *
          • defaultSize = 0 - default is an array of length zero
          • *
          • defaultSize > 0 - default is an array with a * length specified by defaultSize (N.B. elements * in the array will be null)
          • *
          *
        *
      * *

      Parsing Delimited Lists

      * This implementation can convert a delimited list in String format * into an array of the appropriate type. By default, it uses a comma as the delimiter * but the following methods can be used to configure parsing: *
        *
      • setDelimiter(char) - allows the character used as * the delimiter to be configured [default is a comma].
      • *
      • setAllowedChars(char[]) - adds additional characters * (to the default alphabetic/numeric) to those considered to be * valid token characters. *
      * *

      Multi Dimensional Arrays

      * It is possible to convert a String to mulit-dimensional arrays by using * {@link ArrayConverter} as the element {@link Converter} * within another {@link ArrayConverter}. *

      * For example, the following code demonstrates how to construct a {@link Converter} * to convert a delimited String into a two dimensional integer array: *

      *

       *    // Construct an Integer Converter
       *    IntegerConverter integerConverter = new IntegerConverter();
       *
       *    // Construct an array Converter for an integer array (i.e. int[]) using
       *    // an IntegerConverter as the element converter.
       *    // N.B. Uses the default comma (i.e. ",") as the delimiter between individual numbers
       *    ArrayConverter arrayConverter = new ArrayConverter(int[].class, integerConverter);
       *
       *    // Construct a "Matrix" Converter which converts arrays of integer arrays using
       *    // the pre-ceeding ArrayConverter as the element Converter.
       *    // N.B. Uses a semi-colon (i.e. ";") as the delimiter to separate the different sets of numbers.
       *    //      Also the delimiter used by the first ArrayConverter needs to be added to the
       *    //      "allowed characters" for this one.
       *    ArrayConverter matrixConverter = new ArrayConverter(int[][].class, arrayConverter);
       *    matrixConverter.setDelimiter(';');
       *    matrixConverter.setAllowedChars(new char[] {','});
       *
       *    // Do the Conversion
       *    String matrixString = "11,12,13 ; 21,22,23 ; 31,32,33 ; 41,42,43";
       *    int[][] result = (int[][])matrixConverter.convert(int[][].class, matrixString);
       * 
      * * @version $Id: ArrayConverter.java 1540518 2013-11-10 19:04:04Z oheger $ * @since 1.8.0 */ public class ArrayConverter extends AbstractConverter { private final Class defaultType; private final Converter elementConverter; private int defaultSize; private char delimiter = ','; private char[] allowedChars = new char[] {'.', '-'}; private boolean onlyFirstToString = true; // ----------------------------------------------------------- Constructors /** * Construct an array Converter with the specified * component Converter that throws a * ConversionException if an error occurs. * * @param defaultType The default array type this * Converter handles * @param elementConverter Converter used to convert * individual array elements. */ public ArrayConverter(Class defaultType, Converter elementConverter) { super(); if (defaultType == null) { throw new IllegalArgumentException("Default type is missing"); } if (!defaultType.isArray()) { throw new IllegalArgumentException("Default type must be an array."); } if (elementConverter == null) { throw new IllegalArgumentException("Component Converter is missing."); } this.defaultType = defaultType; this.elementConverter = elementConverter; } /** * Construct an array Converter with the specified * component Converter that returns a default * array of the specified size (or null) if an error occurs. * * @param defaultType The default array type this * Converter handles * @param elementConverter Converter used to convert * individual array elements. * @param defaultSize Specifies the size of the default array value or if less * than zero indicates that a null default value should be used. */ public ArrayConverter(Class defaultType, Converter elementConverter, int defaultSize) { this(defaultType, elementConverter); this.defaultSize = defaultSize; Object defaultValue = null; if (defaultSize >= 0) { defaultValue = Array.newInstance(defaultType.getComponentType(), defaultSize); } setDefaultValue(defaultValue); } /** * Set the delimiter to be used for parsing a delimited String. * * @param delimiter The delimiter [default ','] */ public void setDelimiter(char delimiter) { this.delimiter = delimiter; } /** * Set the allowed characters to be used for parsing a delimited String. * * @param allowedChars Characters which are to be considered as part of * the tokens when parsing a delimited String [default is '.' and '-'] */ public void setAllowedChars(char[] allowedChars) { this.allowedChars = allowedChars; } /** * Indicates whether converting to a String should create * a delimited list or just convert the first value. * * @param onlyFirstToString true converts only * the first value in the array to a String, false * converts all values in the array into a delimited list (default * is true */ public void setOnlyFirstToString(boolean onlyFirstToString) { this.onlyFirstToString = onlyFirstToString; } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. */ @Override protected Class getDefaultType() { return defaultType; } /** * Handles conversion to a String. * * @param value The value to be converted. * @return the converted String value. * @throws Throwable if an error occurs converting to a String */ @Override protected String convertToString(Object value) throws Throwable { int size = 0; Iterator iterator = null; Class type = value.getClass(); if (type.isArray()) { size = Array.getLength(value); } else { Collection collection = convertToCollection(type, value); size = collection.size(); iterator = collection.iterator(); } if (size == 0) { return (String)getDefault(String.class); } if (onlyFirstToString) { size = 1; } // Create a StringBuffer containing a delimited list of the values StringBuilder buffer = new StringBuilder(); for (int i = 0; i < size; i++) { if (i > 0) { buffer.append(delimiter); } Object element = iterator == null ? Array.get(value, i) : iterator.next(); element = elementConverter.convert(String.class, element); if (element != null) { buffer.append(element); } } return buffer.toString(); } /** * Handles conversion to an array of the specified type. * * @param Target type of the conversion. * @param type The type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Throwable if an error occurs converting to the specified type */ @Override protected T convertToType(Class type, Object value) throws Throwable { if (!type.isArray()) { throw new ConversionException(toString(getClass()) + " cannot handle conversion to '" + toString(type) + "' (not an array)."); } // Handle the source int size = 0; Iterator iterator = null; if (value.getClass().isArray()) { size = Array.getLength(value); } else { Collection collection = convertToCollection(type, value); size = collection.size(); iterator = collection.iterator(); } // Allocate a new Array Class componentType = type.getComponentType(); Object newArray = Array.newInstance(componentType, size); // Convert and set each element in the new Array for (int i = 0; i < size; i++) { Object element = iterator == null ? Array.get(value, i) : iterator.next(); // TODO - probably should catch conversion errors and throw // new exception providing better info back to the user element = elementConverter.convert(componentType, element); Array.set(newArray, i, element); } @SuppressWarnings("unchecked") // This is safe because T is an array type and newArray is an array of // T's component type T result = (T) newArray; return result; } /** * Returns the value unchanged. * * @param value The value to convert * @return The value unchanged */ @Override protected Object convertArray(Object value) { return value; } /** * Converts non-array values to a Collection prior * to being converted either to an array or a String. *

      *
        *
      • {@link Collection} values are returned unchanged
      • *
      • {@link Number}, {@link Boolean} and {@link java.util.Date} * values returned as a the only element in a List.
      • *
      • All other types are converted to a String and parsed * as a delimited list.
      • *
      * * N.B. The method is called by both the * {@link ArrayConverter#convertToType(Class, Object)} and * {@link ArrayConverter#convertToString(Object)} methods for * non-array types. * * @param type The type to convert the value to * @param value value to be converted * @return Collection elements. */ protected Collection convertToCollection(Class type, Object value) { if (value instanceof Collection) { return (Collection)value; } if (value instanceof Number || value instanceof Boolean || value instanceof java.util.Date) { List list = new ArrayList(1); list.add(value); return list; } return parseElements(type, value.toString()); } /** * Return the default value for conversions to the specified * type. * @param type Data type to which this value should be converted. * @return The default value for the specified type. */ @Override protected Object getDefault(Class type) { if (type.equals(String.class)) { return null; } Object defaultValue = super.getDefault(type); if (defaultValue == null) { return null; } if (defaultValue.getClass().equals(type)) { return defaultValue; } else { return Array.newInstance(type.getComponentType(), defaultSize); } } /** * Provide a String representation of this array converter. * * @return A String representation of this array converter */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(toString(getClass())); buffer.append("[UseDefault="); buffer.append(isUseDefault()); buffer.append(", "); buffer.append(elementConverter.toString()); buffer.append(']'); return buffer.toString(); } /** *

      Parse an incoming String of the form similar to an array initializer * in the Java language into a List individual Strings * for each element, according to the following rules.

      *
        *
      • The string is expected to be a comma-separated list of values.
      • *
      • The string may optionally have matching '{' and '}' delimiters * around the list.
      • *
      • Whitespace before and after each element is stripped.
      • *
      • Elements in the list may be delimited by single or double quotes. * Within a quoted elements, the normal Java escape sequences are valid.
      • *
      * * @param type The type to convert the value to * @param value String value to be parsed * @return List of parsed elements. * * @throws ConversionException if the syntax of svalue * is not syntactically valid * @throws NullPointerException if svalue * is null */ private List parseElements(Class type, String value) { if (log().isDebugEnabled()) { log().debug("Parsing elements, delimiter=[" + delimiter + "], value=[" + value + "]"); } // Trim any matching '{' and '}' delimiters value = value.trim(); if (value.startsWith("{") && value.endsWith("}")) { value = value.substring(1, value.length() - 1); } try { // Set up a StreamTokenizer on the characters in this String StreamTokenizer st = new StreamTokenizer(new StringReader(value)); st.whitespaceChars(delimiter , delimiter); // Set the delimiters st.ordinaryChars('0', '9'); // Needed to turn off numeric flag st.wordChars('0', '9'); // Needed to make part of tokens for (int i = 0; i < allowedChars.length; i++) { st.ordinaryChars(allowedChars[i], allowedChars[i]); st.wordChars(allowedChars[i], allowedChars[i]); } // Split comma-delimited tokens into a List List list = null; while (true) { int ttype = st.nextToken(); if ((ttype == StreamTokenizer.TT_WORD) || (ttype > 0)) { if (st.sval != null) { if (list == null) { list = new ArrayList(); } list.add(st.sval); } } else if (ttype == StreamTokenizer.TT_EOF) { break; } else { throw new ConversionException("Encountered token of type " + ttype + " parsing elements to '" + toString(type) + "."); } } if (list == null) { list = Collections.emptyList(); } if (log().isDebugEnabled()) { log().debug(list.size() + " elements parsed"); } // Return the completed list return (list); } catch (IOException e) { throw new ConversionException("Error converting from String to '" + toString(type) + "': " + e.getMessage(), e); } } } ././@LongLink100644 0 0 153 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/BigDecimalConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/BigDecimalConverte100644 0 0 4767 12262570611 31025 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.math.BigDecimal; /** * {@link NumberConverter} implementation that handles conversion to * and from java.math.BigDecimal objects. *

      * This implementation can be configured to handle conversion either * by using BigDecimal's default String conversion, or by using a Locale's pattern * or by specifying a format pattern. See the {@link NumberConverter} * documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: BigDecimalConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class BigDecimalConverter extends NumberConverter { /** * Construct a java.math.BigDecimal Converter that throws * a ConversionException if an error occurs. */ public BigDecimalConverter() { super(true); } /** * Construct a java.math.BigDecimal Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public BigDecimalConverter(Object defaultValue) { super(true, defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return BigDecimal.class; } } ././@LongLink100644 0 0 153 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/BigIntegerConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/BigIntegerConverte100644 0 0 4771 12262570611 31057 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.math.BigInteger; /** * {@link NumberConverter} implementation that handles conversion to * and from java.math.BigInteger objects. *

      * This implementation can be configured to handle conversion either * by using BigInteger's default String conversion, or by using a Locale's pattern * or by specifying a format pattern. See the {@link NumberConverter} * documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: BigIntegerConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class BigIntegerConverter extends NumberConverter { /** * Construct a java.math.BigInteger Converter that throws * a ConversionException if an error occurs. */ public BigIntegerConverter() { super(false); } /** * Construct a java.math.BigInteger Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public BigIntegerConverter(Object defaultValue) { super(false, defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return BigInteger.class; } } ././@LongLink100644 0 0 155 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/BooleanArrayConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/BooleanArrayConver100644 0 0 22777 12262570611 31113 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.List; import org.apache.commons.beanutils.ConversionException; /** *

      Standard {@link org.apache.commons.beanutils.Converter} implementation that converts an incoming * String into a primitive array of boolean. On a conversion failure, returns * a specified default value or throws a {@link ConversionException} depending * on how this instance is constructed.

      * *

      By default, the values to be converted are expected to be those * recognised by a default instance of BooleanConverter. A customised * BooleanConverter can be provided in order to recognise alternative values * as true/false.

      * * @version $Id: BooleanArrayConverter.java 1454606 2013-03-08 22:30:51Z britter $ * @since 1.4 * @deprecated Replaced by the new {@link ArrayConverter} implementation */ @Deprecated public final class BooleanArrayConverter extends AbstractArrayConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.Converter} that will throw * a {@link ConversionException} if a conversion error occurs. * *

      Conversion of strings to boolean values will be done via a default * instance of class BooleanConverter.

      */ public BooleanArrayConverter() { super(); this.booleanConverter = DEFAULT_CONVERTER; } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. * *

      Conversion of strings to boolean values will be done via a default * instance of class BooleanConverter.

      * * @param defaultValue The default value to be returned */ public BooleanArrayConverter(Object defaultValue) { super(defaultValue); this.booleanConverter = DEFAULT_CONVERTER; } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. * *

      Conversion of strings to boolean values will be done via the * specified converter.

      * * @param converter is the converter object that will be used to * convert each input string-value into a boolean. * * @param defaultValue is the default value to be returned by method * convert if conversion fails; null is a valid default value. See the * documentation for method "convert" for more information. * The value BooleanArrayConverter.NO_DEFAULT may be passed here to * specify that an exception should be thrown on conversion failure. * */ public BooleanArrayConverter(BooleanConverter converter, Object defaultValue) { super(defaultValue); this.booleanConverter = converter; } // ------------------------------------------------------- Static Variables /** * Type which this class converts its input to. This value can be * used as a parameter to the ConvertUtils.register method. * @since 1.8.0 */ public static final Class MODEL = new boolean[0].getClass(); /** * The converter that all instances of this class will use to * do individual string->boolean conversions, unless overridden * in the constructor. */ private static final BooleanConverter DEFAULT_CONVERTER = new BooleanConverter(); // ---------------------------------------------------- Instance Variables /** * This object is used to perform the conversion of individual strings * into Boolean/boolean values. */ protected final BooleanConverter booleanConverter; // --------------------------------------------------------- Public Methods /** * Convert the specified input object into an output object of type * array-of-boolean. * *

      If the input value is null, then the default value specified in the * constructor is returned. If no such value was provided, then a * ConversionException is thrown instead.

      * *

      If the input value is of type String[] then the returned array shall * be of the same size as this array, with a true or false value in each * array element depending on the result of applying method * BooleanConverter.convert to each string.

      * *

      For all other types of value, the object's toString method is * expected to return a string containing a comma-separated list of * values, eg "true, false, true". See the documentation for * {@link AbstractArrayConverter#parseElements} for more information on * the exact formats supported.

      * *

      If the result of value.toString() cannot be split into separate * words, then the default value is also returned (or an exception thrown). *

      * *

      If any of the elements in the value array (or the elements resulting * from splitting up value.toString) are not recognised by the * BooleanConverter associated with this object, then what happens depends * on whether that BooleanConverter has a default value or not: if it does, * then that unrecognised element is converted into the BooleanConverter's * default value. If the BooleanConverter does not have a default * value, then the default value for this object is returned as the * complete conversion result (not just for the element), or an * exception is thrown if this object has no default value defined.

      * * @param type is the type to which this value should be converted. In the * case of this BooleanArrayConverter class, this value is ignored. * * @param value is the input value to be converted. * * @return an object of type boolean[], or the default value if there was * any sort of error during conversion and the constructor * was provided with a default value. * * @exception ConversionException if conversion cannot be performed * successfully and the constructor was not provided with a default * value to return on conversion failure. * * @exception NullPointerException if value is an array, and any of the * array elements are null. */ @Override public Object convert(Class type, Object value) { // Deal with a null value if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } // Deal with the no-conversion-needed case if (MODEL == value.getClass()) { return (value); } // Deal with input value as a String array // // TODO: use if (value.getClass().isArray() instead... // this requires casting to Object[], then using values[i].toString() if (strings.getClass() == value.getClass()) { try { String[] values = (String[]) value; boolean[] results = new boolean[values.length]; for (int i = 0; i < values.length; i++) { String stringValue = values[i]; Object result = booleanConverter.convert(Boolean.class, stringValue); results[i] = ((Boolean) result).booleanValue(); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } // We only get here if the input value is not of type String[]. // In this case, we assume value.toString() returns a comma-separated // sequence of values; see method AbstractArrayConverter.parseElements // for more information. try { List list = parseElements(value.toString()); boolean[] results = new boolean[list.size()]; for (int i = 0; i < results.length; i++) { String stringValue = (String) list.get(i); Object result = booleanConverter.convert(Boolean.class, stringValue); results[i] = ((Boolean) result).booleanValue(); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } } ././@LongLink100644 0 0 150 12262571655 10262 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/BooleanConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/BooleanConverter.j100644 0 0 23750 12262570611 31047 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; /** * {@link org.apache.commons.beanutils.Converter} implementation that handles conversion * to and from Boolean objects. * {@link org.apache.commons.beanutils.Converter} implementation that * handles conversion to and from java.lang.Boolean objects. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. *

      * By default any object whose string representation is one of the values * {"yes", "y", "true", "on", "1"} is converted to Boolean.TRUE, and * string representations {"no", "n", "false", "off", "0"} are converted * to Boolean.FALSE. The recognised true/false strings can be changed by: *

       *  String[] trueStrings = {"oui", "o", "1"};
       *  String[] falseStrings = {"non", "n", "0"};
       *  Converter bc = new BooleanConverter(trueStrings, falseStrings);
       *  ConvertUtils.register(bc, Boolean.class);
       *  ConvertUtils.register(bc, Boolean.TYPE);
       * 
      * In addition, it is recommended that the BooleanArrayConverter also be * modified to recognise the same set of values: *
       *   Converter bac = new BooleanArrayConverter(bc, BooleanArrayConverter.NO_DEFAULT);
       *   ConvertUtils.register(bac, bac.MODEL);
       * 
      *

      * *

      Case is ignored when converting values to true or false.

      * * @version $Id: BooleanConverter.java 1540518 2013-11-10 19:04:04Z oheger $ * @since 1.3 */ public final class BooleanConverter extends AbstractConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.Converter} that will throw a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs, ie the string value being converted is * not one of the known true strings, nor one of the known false strings. */ public BooleanConverter() { super(); } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return the specified default value * if a conversion error occurs, ie the string value being converted is * not one of the known true strings, nor one of the known false strings. * * @param defaultValue The default value to be returned if the value * being converted is not recognised. This value may be null, in which * case null will be returned on conversion failure. When non-null, it is * expected that this value will be either Boolean.TRUE or Boolean.FALSE. * The special value BooleanConverter.NO_DEFAULT can also be passed here, * in which case this constructor acts like the no-argument one. */ public BooleanConverter(Object defaultValue) { super(); if (defaultValue != NO_DEFAULT) { setDefaultValue(defaultValue); } } /** * Create a {@link org.apache.commons.beanutils.Converter} that will throw a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs, ie the string value being converted is * not one of the known true strings, nor one of the known false strings. *

      * The provided string arrays are copied, so that changes to the elements * of the array after this call is made do not affect this object. * * @param trueStrings is the set of strings which should convert to the * value Boolean.TRUE. The value null must not be present. Case is * ignored. * * @param falseStrings is the set of strings which should convert to the * value Boolean.TRUE. The value null must not be present. Case is * ignored. * @since 1.8.0 */ public BooleanConverter(String[] trueStrings, String[] falseStrings) { super(); this.trueStrings = copyStrings(trueStrings); this.falseStrings = copyStrings(falseStrings); } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. *

      * The provided string arrays are copied, so that changes to the elements * of the array after this call is made do not affect this object. * * @param trueStrings is the set of strings which should convert to the * value Boolean.TRUE. The value null must not be present. Case is * ignored. * * @param falseStrings is the set of strings which should convert to the * value Boolean.TRUE. The value null must not be present. Case is * ignored. * * @param defaultValue The default value to be returned if the value * being converted is not recognised. This value may be null, in which * case null will be returned on conversion failure. When non-null, it is * expected that this value will be either Boolean.TRUE or Boolean.FALSE. * The special value BooleanConverter.NO_DEFAULT can also be passed here, * in which case an exception will be thrown on conversion failure. * @since 1.8.0 */ public BooleanConverter(String[] trueStrings, String[] falseStrings, Object defaultValue) { super(); this.trueStrings = copyStrings(trueStrings); this.falseStrings = copyStrings(falseStrings); if (defaultValue != NO_DEFAULT) { setDefaultValue(defaultValue); } } // ----------------------------------------------------- Static Variables /** * This is a special reference that can be passed as the "default object" * to the constructor to indicate that no default is desired. Note that * the value 'null' cannot be used for this purpose, as the caller may * want a null to be returned as the default. * @deprecated Use constructors without default value. */ @Deprecated public static final Object NO_DEFAULT = new Object(); // ----------------------------------------------------- Instance Variables /** * The set of strings that are known to map to Boolean.TRUE. */ private String[] trueStrings = {"true", "yes", "y", "on", "1"}; /** * The set of strings that are known to map to Boolean.FALSE. */ private String[] falseStrings = {"false", "no", "n", "off", "0"}; // --------------------------------------------------------- Protected Methods /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Boolean.class; } /** * Convert the specified input object into an output object of the * specified type. * * @param Target type of the conversion. * @param type is the type to which this value should be converted. In the * case of this BooleanConverter class, this value is ignored. * * @param value is the input value to be converted. The toString method * shall be invoked on this object, and the result compared (ignoring * case) against the known "true" and "false" string values. * * @return Boolean.TRUE if the value was a recognised "true" value, * Boolean.FALSE if the value was a recognised "false" value, or * the default value if the value was not recognised and the constructor * was provided with a default value. * * @throws Throwable if an error occurs converting to the specified type * @since 1.8.0 */ @Override protected T convertToType(Class type, Object value) throws Throwable { if (Boolean.class.equals(type) || Boolean.TYPE.equals(type)) { // All the values in the trueStrings and falseStrings arrays are // guaranteed to be lower-case. By converting the input value // to lowercase too, we can use the efficient String.equals method // instead of the less-efficient String.equalsIgnoreCase method. String stringValue = value.toString().toLowerCase(); for (int i = 0; i < trueStrings.length; ++i) { if (trueStrings[i].equals(stringValue)) { return type.cast(Boolean.TRUE); } } for (int i = 0; i < falseStrings.length; ++i) { if (falseStrings[i].equals(stringValue)) { return type.cast(Boolean.FALSE); } } } throw conversionException(type, value); } /** * This method creates a copy of the provided array, and ensures that * all the strings in the newly created array contain only lower-case * letters. *

      * Using this method to copy string arrays means that changes to the * src array do not modify the dst array. */ private static String[] copyStrings(String[] src) { String[] dst = new String[src.length]; for(int i=0; iStandard {@link org.apache.commons.beanutils.Converter} implementation that converts an incoming * String into a primitive array of byte. On a conversion failure, returns * a specified default value or throws a {@link ConversionException} depending * on how this instance is constructed.

      * * @version $Id: ByteArrayConverter.java 1454606 2013-03-08 22:30:51Z britter $ * @since 1.4 * @deprecated Replaced by the new {@link ArrayConverter} implementation */ @Deprecated public final class ByteArrayConverter extends AbstractArrayConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.Converter} that will * throw a {@link ConversionException} if a conversion error occurs. */ public ByteArrayConverter() { this.defaultValue = null; this.useDefault = false; } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. * * @param defaultValue The default value to be returned */ public ByteArrayConverter(Object defaultValue) { this.defaultValue = defaultValue; this.useDefault = true; } // ------------------------------------------------------- Static Variables /** *

      Model object for type comparisons.

      */ private static final byte[] MODEL = new byte[0]; // --------------------------------------------------------- Public Methods /** * Convert the specified input object into an output object of the * specified type. * * @param type Data type to which this value should be converted * @param value The input value to be converted * @return the converted value * @exception ConversionException if conversion cannot be performed * successfully */ @Override public Object convert(Class type, Object value) { // Deal with a null value if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } // Deal with the no-conversion-needed case if (MODEL.getClass() == value.getClass()) { return (value); } // Deal with input value as a String array if (strings.getClass() == value.getClass()) { try { String[] values = (String[]) value; byte[] results = new byte[values.length]; for (int i = 0; i < values.length; i++) { results[i] = Byte.parseByte(values[i]); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } // Parse the input value as a String into elements // and convert to the appropriate type try { List list = parseElements(value.toString()); byte[] results = new byte[list.size()]; for (int i = 0; i < results.length; i++) { results[i] = Byte.parseByte((String) list.get(i)); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } } ././@LongLink100644 0 0 145 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ByteConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ByteConverter.java100644 0 0 4635 12262570611 31044 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; /** * {@link NumberConverter} implementation that handles conversion to * and from java.lang.Byte objects. *

      * This implementation can be configured to handle conversion either * by using Byte's default String conversion, or by using a Locale's pattern * or by specifying a format pattern. See the {@link NumberConverter} * documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: ByteConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class ByteConverter extends NumberConverter { /** * Construct a java.lang.Byte Converter that throws * a ConversionException if an error occurs. */ public ByteConverter() { super(false); } /** * Construct a java.lang.Byte Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public ByteConverter(Object defaultValue) { super(false, defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Byte.class; } } ././@LongLink100644 0 0 151 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/CalendarConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/CalendarConverter.100644 0 0 4733 12262570611 31007 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.Calendar; /** * {@link DateTimeConverter} implementation that handles conversion to * and from java.util.Calendar objects. *

      * This implementation can be configured to handle conversion either * by using a Locale's default format or by specifying a set of format * patterns (note, there is no default String conversion for Calendar). * See the {@link DateTimeConverter} documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: CalendarConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.8.0 */ public final class CalendarConverter extends DateTimeConverter { /** * Construct a java.util.Calendar Converter that throws * a ConversionException if an error occurs. */ public CalendarConverter() { super(); } /** * Construct a java.util.Calendar Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public CalendarConverter(Object defaultValue) { super(defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. */ @Override protected Class getDefaultType() { return Calendar.class; } } ././@LongLink100644 0 0 157 12262571655 10271 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/CharacterArrayConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/CharacterArrayConv100644 0 0 11245 12262570611 31065 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.List; import org.apache.commons.beanutils.ConversionException; /** *

      Standard {@link org.apache.commons.beanutils.Converter} implementation that converts an incoming * String into a primitive array of char. On a conversion failure, returns * a specified default value or throws a {@link ConversionException} depending * on how this instance is constructed.

      * * @version $Id: CharacterArrayConverter.java 1454606 2013-03-08 22:30:51Z britter $ * @since 1.4 * @deprecated Replaced by the new {@link ArrayConverter} implementation */ @Deprecated public final class CharacterArrayConverter extends AbstractArrayConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.Converter} that will throw * a {@link ConversionException} if a conversion error occurs. */ public CharacterArrayConverter() { this.defaultValue = null; this.useDefault = false; } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. * * @param defaultValue The default value to be returned */ public CharacterArrayConverter(Object defaultValue) { this.defaultValue = defaultValue; this.useDefault = true; } // ------------------------------------------------------- Static Variables /** *

      Model object for type comparisons.

      */ private static final char[] MODEL = new char[0]; // --------------------------------------------------------- Public Methods /** * Convert the specified input object into an output object of the * specified type. * * @param type Data type to which this value should be converted * @param value The input value to be converted * @return the converted value * * @exception ConversionException if conversion cannot be performed * successfully */ @Override public Object convert(Class type, Object value) { // Deal with a null value if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } // Deal with the no-conversion-needed case if (MODEL.getClass() == value.getClass()) { return (value); } // Deal with input value as a String array if (strings.getClass() == value.getClass()) { try { String[] values = (String[]) value; char[] results = new char[values.length]; for (int i = 0; i < values.length; i++) { results[i] = values[i].charAt(0); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } // Parse the input value as a String into elements // and convert to the appropriate type try { List list = parseElements(value.toString()); char[] results = new char[list.size()]; for (int i = 0; i < results.length; i++) { results[i] = ((String) list.get(i)).charAt(0); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } } ././@LongLink100644 0 0 152 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/CharacterConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/CharacterConverter100644 0 0 6452 12262570611 31114 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; /** * {@link org.apache.commons.beanutils.Converter} implementaion that handles conversion * to and from java.lang.Character objects. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: CharacterConverter.java 1540518 2013-11-10 19:04:04Z oheger $ * @since 1.3 */ public final class CharacterConverter extends AbstractConverter { /** * Construct a java.lang.Character Converter that throws * a ConversionException if an error occurs. */ public CharacterConverter() { super(); } /** * Construct a java.lang.Character Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public CharacterConverter(Object defaultValue) { super(defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Character.class; } /** *

      Convert a java.lang.Class or object into a String.

      * * @param value The input value to be converted * @return the converted String value. * @since 1.8.0 */ @Override protected String convertToString(Object value) { String strValue = value.toString(); return strValue.length() == 0 ? "" : strValue.substring(0, 1); } /** *

      Convert the input object into a java.lang.Character.

      * * @param Target type of the conversion. * @param type Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Exception if conversion cannot be performed successfully * @since 1.8.0 */ @Override protected T convertToType(Class type, Object value) throws Exception { if (Character.class.equals(type) || Character.TYPE.equals(type)) { return type.cast(new Character(value.toString().charAt(0))); } throw conversionException(type, value); } } ././@LongLink100644 0 0 146 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ClassConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ClassConverter.jav100644 0 0 7665 12262570611 31053 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; /** * {@link org.apache.commons.beanutils.Converter} implementaion that handles conversion * to and from java.lang.Class objects. *

      * The class will be loaded from the thread context class * loader (if it exists); otherwise the class loader that loaded this class * will be used. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: ClassConverter.java 1540518 2013-11-10 19:04:04Z oheger $ * @since 1.4 */ public final class ClassConverter extends AbstractConverter { /** * Construct a java.lang.Class Converter that throws * a ConversionException if an error occurs. */ public ClassConverter() { super(); } /** * Construct a java.lang.Class Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public ClassConverter(Object defaultValue) { super(defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Class.class; } /** *

      Convert a java.lang.Class or object into a String.

      * * @param value The input value to be converted * @return the converted String value. * @since 1.8.0 */ @Override protected String convertToString(Object value) { return (value instanceof Class) ? ((Class)value).getName() : value.toString(); } /** *

      Convert the input object into a java.lang.Class.

      * * @param Target type of the conversion. * @param type Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Throwable if an error occurs converting to the specified type * @since 1.8.0 */ @Override protected T convertToType(Class type, Object value) throws Throwable { if (Class.class.equals(type)) { ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); if (classLoader != null) { try { return type.cast(classLoader.loadClass(value.toString())); } catch (ClassNotFoundException ex) { // Don't fail, carry on and try this class's class loader // (see issue# BEANUTILS-263) } } // Try this class's class loader classLoader = ClassConverter.class.getClassLoader(); return type.cast(classLoader.loadClass(value.toString())); } throw conversionException(type, value); } } ././@LongLink100644 0 0 147 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ConverterFacade.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ConverterFacade.ja100644 0 0 5376 12262570611 30760 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import org.apache.commons.beanutils.Converter; /** * Provides a facade for {@link Converter} implementations * preventing access to any public API in the implementation, * other than that specified by {@link Converter}. *

      * This implementation can be used to prevent registered {@link Converter} * implementations that provide configuration options from being * retrieved and modified. * * @version $Id: ConverterFacade.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.8.0 */ public final class ConverterFacade implements Converter { private final Converter converter; /** * Construct a converter which delegates to the specified * {@link Converter} implementation. * * @param converter The converter to delegate to */ public ConverterFacade(Converter converter) { if (converter == null) { throw new IllegalArgumentException("Converter is missing"); } this.converter = converter; } /** * Convert the input object into an output object of the * specified type by delegating to the underlying {@link Converter} * implementation. * * @param The result type of the conversion * @param type Data type to which this value should be converted * @param value The input value to be converted * @return The converted value. */ public T convert(Class type, Object value) { return converter.convert(type, value); } /** * Provide a String representation of this facade implementation * sand the underlying {@link Converter} it delegates to. * * @return A String representation of this facade implementation * sand the underlying {@link Converter} it delegates to */ @Override public String toString() { return "ConverterFacade[" + converter.toString() + "]"; } } ././@LongLink100644 0 0 145 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/DateConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/DateConverter.java100644 0 0 4663 12262570611 31017 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.Date; /** * {@link DateTimeConverter} implementation that handles conversion to * and from java.util.Date objects. *

      * This implementation can be configured to handle conversion either * by using a Locale's default format or by specifying a set of format * patterns (note, there is no default String conversion for Date). * See the {@link DateTimeConverter} documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: DateConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.8.0 */ public final class DateConverter extends DateTimeConverter { /** * Construct a java.util.Date Converter that throws * a ConversionException if an error occurs. */ public DateConverter() { super(); } /** * Construct a java.util.Date Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public DateConverter(Object defaultValue) { super(defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. */ @Override protected Class getDefaultType() { return Date.class; } } ././@LongLink100644 0 0 151 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/DateTimeConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/DateTimeConverter.100644 0 0 54527 12262570611 31020 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.text.DateFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.apache.commons.beanutils.ConversionException; /** * {@link org.apache.commons.beanutils.Converter} implementaion * that handles conversion to and from date/time objects. *

      * This implementation handles conversion for the following * date/time types. *

        *
      • java.util.Date
      • *
      • java.util.Calendar
      • *
      • java.sql.Date
      • *
      • java.sql.Time
      • *
      • java.sql.Timestamp
      • *
      * *

      String Conversions (to and from)

      * This class provides a number of ways in which date/time * conversions to/from Strings can be achieved: *
        *
      • Using the SHORT date format for the default Locale, configure using:
      • *
          *
        • setUseLocaleFormat(true)
        • *
        *
      • Using the SHORT date format for a specified Locale, configure using:
      • *
          *
        • setLocale(Locale)
        • *
        *
      • Using the specified date pattern(s) for the default Locale, configure using:
      • *
          *
        • Either setPattern(String) or * setPatterns(String[])
        • *
        *
      • Using the specified date pattern(s) for a specified Locale, configure using:
      • *
          *
        • setPattern(String) or * setPatterns(String[]) and...
        • *
        • setLocale(Locale)
        • *
        *
      • If none of the above are configured the * toDate(String) method is used to convert * from String to Date and the Dates's * toString() method used to convert from * Date to String.
      • *
      * *

      * The Time Zone to use with the date format can be specified * using the setTimeZone() method. * * @version $Id: DateTimeConverter.java 1546738 2013-11-30 16:24:19Z oheger $ * @since 1.8.0 */ public abstract class DateTimeConverter extends AbstractConverter { private String[] patterns; private String displayPatterns; private Locale locale; private TimeZone timeZone; private boolean useLocaleFormat; // ----------------------------------------------------------- Constructors /** * Construct a Date/Time Converter that throws a * ConversionException if an error occurs. */ public DateTimeConverter() { super(); } /** * Construct a Date/Time Converter that returns a default * value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public DateTimeConverter(Object defaultValue) { super(defaultValue); } // --------------------------------------------------------- Public Methods /** * Indicate whether conversion should use a format/pattern or not. * * @param useLocaleFormat true if the format * for the locale should be used, otherwise false */ public void setUseLocaleFormat(boolean useLocaleFormat) { this.useLocaleFormat = useLocaleFormat; } /** * Return the Time Zone to use when converting dates * (or null if none specified. * * @return The Time Zone. */ public TimeZone getTimeZone() { return timeZone; } /** * Set the Time Zone to use when converting dates. * * @param timeZone The Time Zone. */ public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; } /** * Return the Locale for the Converter * (or null if none specified). * * @return The locale to use for conversion */ public Locale getLocale() { return locale; } /** * Set the Locale for the Converter. * * @param locale The Locale. */ public void setLocale(Locale locale) { this.locale = locale; setUseLocaleFormat(true); } /** * Set a date format pattern to use to convert * dates to/from a java.lang.String. * * @see SimpleDateFormat * @param pattern The format pattern. */ public void setPattern(String pattern) { setPatterns(new String[] {pattern}); } /** * Return the date format patterns used to convert * dates to/from a java.lang.String * (or null if none specified). * * @see SimpleDateFormat * @return Array of format patterns. */ public String[] getPatterns() { return patterns; } /** * Set the date format patterns to use to convert * dates to/from a java.lang.String. * * @see SimpleDateFormat * @param patterns Array of format patterns. */ public void setPatterns(String[] patterns) { this.patterns = patterns; if (patterns != null && patterns.length > 1) { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < patterns.length; i++) { if (i > 0) { buffer.append(", "); } buffer.append(patterns[i]); } displayPatterns = buffer.toString(); } setUseLocaleFormat(true); } // ------------------------------------------------------ Protected Methods /** * Convert an input Date/Calendar object into a String. *

      * N.B.If the converter has been configured to with * one or more patterns (using setPatterns()), then * the first pattern will be used to format the date into a String. * Otherwise the default DateFormat for the default locale * (and style if configured) will be used. * * @param value The input value to be converted * @return the converted String value. * @throws Throwable if an error occurs converting to a String */ @Override protected String convertToString(Object value) throws Throwable { Date date = null; if (value instanceof Date) { date = (Date)value; } else if (value instanceof Calendar) { date = ((Calendar)value).getTime(); } else if (value instanceof Long) { date = new Date(((Long)value).longValue()); } String result = null; if (useLocaleFormat && date != null) { DateFormat format = null; if (patterns != null && patterns.length > 0) { format = getFormat(patterns[0]); } else { format = getFormat(locale, timeZone); } logFormat("Formatting", format); result = format.format(date); if (log().isDebugEnabled()) { log().debug(" Converted to String using format '" + result + "'"); } } else { result = value.toString(); if (log().isDebugEnabled()) { log().debug(" Converted to String using toString() '" + result + "'"); } } return result; } /** * Convert the input object into a Date object of the * specified type. *

      * This method handles conversions between the following * types: *

        *
      • java.util.Date
      • *
      • java.util.Calendar
      • *
      • java.sql.Date
      • *
      • java.sql.Time
      • *
      • java.sql.Timestamp
      • *
      * * It also handles conversion from a String to * any of the above types. *

      * * For String conversion, if the converter has been configured * with one or more patterns (using setPatterns()), then * the conversion is attempted with each of the specified patterns. * Otherwise the default DateFormat for the default locale * (and style if configured) will be used. * * @param The desired target type of the conversion. * @param targetType Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Exception if conversion cannot be performed successfully */ @Override protected T convertToType(Class targetType, Object value) throws Exception { Class sourceType = value.getClass(); // Handle java.sql.Timestamp if (value instanceof java.sql.Timestamp) { // ---------------------- JDK 1.3 Fix ---------------------- // N.B. Prior to JDK 1.4 the Timestamp's getTime() method // didn't include the milliseconds. The following code // ensures it works consistently accross JDK versions java.sql.Timestamp timestamp = (java.sql.Timestamp)value; long timeInMillis = ((timestamp.getTime() / 1000) * 1000); timeInMillis += timestamp.getNanos() / 1000000; // ---------------------- JDK 1.3 Fix ---------------------- return toDate(targetType, timeInMillis); } // Handle Date (includes java.sql.Date & java.sql.Time) if (value instanceof Date) { Date date = (Date)value; return toDate(targetType, date.getTime()); } // Handle Calendar if (value instanceof Calendar) { Calendar calendar = (Calendar)value; return toDate(targetType, calendar.getTime().getTime()); } // Handle Long if (value instanceof Long) { Long longObj = (Long)value; return toDate(targetType, longObj.longValue()); } // Convert all other types to String & handle String stringValue = value.toString().trim(); if (stringValue.length() == 0) { return handleMissing(targetType); } // Parse the Date/Time if (useLocaleFormat) { Calendar calendar = null; if (patterns != null && patterns.length > 0) { calendar = parse(sourceType, targetType, stringValue); } else { DateFormat format = getFormat(locale, timeZone); calendar = parse(sourceType, targetType, stringValue, format); } if (Calendar.class.isAssignableFrom(targetType)) { return targetType.cast(calendar); } else { return toDate(targetType, calendar.getTime().getTime()); } } // Default String conversion return toDate(targetType, stringValue); } /** * Convert a long value to the specified Date type for this * Converter. *

      * * This method handles conversion to the following types: *

        *
      • java.util.Date
      • *
      • java.util.Calendar
      • *
      • java.sql.Date
      • *
      • java.sql.Time
      • *
      • java.sql.Timestamp
      • *
      * * @param The target type * @param type The Date type to convert to * @param value The long value to convert. * @return The converted date value. */ private T toDate(Class type, long value) { // java.util.Date if (type.equals(Date.class)) { return type.cast(new Date(value)); } // java.sql.Date if (type.equals(java.sql.Date.class)) { return type.cast(new java.sql.Date(value)); } // java.sql.Time if (type.equals(java.sql.Time.class)) { return type.cast(new java.sql.Time(value)); } // java.sql.Timestamp if (type.equals(java.sql.Timestamp.class)) { return type.cast(new java.sql.Timestamp(value)); } // java.util.Calendar if (type.equals(Calendar.class)) { Calendar calendar = null; if (locale == null && timeZone == null) { calendar = Calendar.getInstance(); } else if (locale == null) { calendar = Calendar.getInstance(timeZone); } else if (timeZone == null) { calendar = Calendar.getInstance(locale); } else { calendar = Calendar.getInstance(timeZone, locale); } calendar.setTime(new Date(value)); calendar.setLenient(false); return type.cast(calendar); } String msg = toString(getClass()) + " cannot handle conversion to '" + toString(type) + "'"; if (log().isWarnEnabled()) { log().warn(" " + msg); } throw new ConversionException(msg); } /** * Default String to Date conversion. *

      * This method handles conversion from a String to the following types: *

        *
      • java.sql.Date
      • *
      • java.sql.Time
      • *
      • java.sql.Timestamp
      • *
      *

      * N.B. No default String conversion * mechanism is provided for java.util.Date * and java.util.Calendar type. * * @param The target type * @param type The date type to convert to * @param value The String value to convert. * @return The converted Number value. */ private T toDate(Class type, String value) { // java.sql.Date if (type.equals(java.sql.Date.class)) { try { return type.cast(java.sql.Date.valueOf(value)); } catch (IllegalArgumentException e) { throw new ConversionException( "String must be in JDBC format [yyyy-MM-dd] to create a java.sql.Date"); } } // java.sql.Time if (type.equals(java.sql.Time.class)) { try { return type.cast(java.sql.Time.valueOf(value)); } catch (IllegalArgumentException e) { throw new ConversionException( "String must be in JDBC format [HH:mm:ss] to create a java.sql.Time"); } } // java.sql.Timestamp if (type.equals(java.sql.Timestamp.class)) { try { return type.cast(java.sql.Timestamp.valueOf(value)); } catch (IllegalArgumentException e) { throw new ConversionException( "String must be in JDBC format [yyyy-MM-dd HH:mm:ss.fffffffff] " + "to create a java.sql.Timestamp"); } } String msg = toString(getClass()) + " does not support default String to '" + toString(type) + "' conversion."; if (log().isWarnEnabled()) { log().warn(" " + msg); log().warn(" (N.B. Re-configure Converter or use alternative implementation)"); } throw new ConversionException(msg); } /** * Return a DateFormat for the Locale. * @param locale The Locale to create the Format with (may be null) * @param timeZone The Time Zone create the Format with (may be null) * * @return A Date Format. */ protected DateFormat getFormat(Locale locale, TimeZone timeZone) { DateFormat format = null; if (locale == null) { format = DateFormat.getDateInstance(DateFormat.SHORT); } else { format = DateFormat.getDateInstance(DateFormat.SHORT, locale); } if (timeZone != null) { format.setTimeZone(timeZone); } return format; } /** * Create a date format for the specified pattern. * * @param pattern The date pattern * @return The DateFormat */ private DateFormat getFormat(String pattern) { DateFormat format = new SimpleDateFormat(pattern); if (timeZone != null) { format.setTimeZone(timeZone); } return format; } /** * Parse a String date value using the set of patterns. * * @param sourceType The type of the value being converted * @param targetType The type to convert the value to. * @param value The String date value. * * @return The converted Date object. * @throws Exception if an error occurs parsing the date. */ private Calendar parse(Class sourceType, Class targetType, String value) throws Exception { Exception firstEx = null; for (int i = 0; i < patterns.length; i++) { try { DateFormat format = getFormat(patterns[i]); Calendar calendar = parse(sourceType, targetType, value, format); return calendar; } catch (Exception ex) { if (firstEx == null) { firstEx = ex; } } } if (patterns.length > 1) { throw new ConversionException("Error converting '" + toString(sourceType) + "' to '" + toString(targetType) + "' using patterns '" + displayPatterns + "'"); } else { throw firstEx; } } /** * Parse a String into a Calendar object * using the specified DateFormat. * * @param sourceType The type of the value being converted * @param targetType The type to convert the value to * @param value The String date value. * @param format The DateFormat to parse the String value. * * @return The converted Calendar object. * @throws ConversionException if the String cannot be converted. */ private Calendar parse(Class sourceType, Class targetType, String value, DateFormat format) { logFormat("Parsing", format); format.setLenient(false); ParsePosition pos = new ParsePosition(0); Date parsedDate = format.parse(value, pos); // ignore the result (use the Calendar) if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedDate == null) { String msg = "Error converting '" + toString(sourceType) + "' to '" + toString(targetType) + "'"; if (format instanceof SimpleDateFormat) { msg += " using pattern '" + ((SimpleDateFormat)format).toPattern() + "'"; } if (log().isDebugEnabled()) { log().debug(" " + msg); } throw new ConversionException(msg); } Calendar calendar = format.getCalendar(); return calendar; } /** * Provide a String representation of this date/time converter. * * @return A String representation of this date/time converter */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(toString(getClass())); buffer.append("[UseDefault="); buffer.append(isUseDefault()); buffer.append(", UseLocaleFormat="); buffer.append(useLocaleFormat); if (displayPatterns != null) { buffer.append(", Patterns={"); buffer.append(displayPatterns); buffer.append('}'); } if (locale != null) { buffer.append(", Locale="); buffer.append(locale); } if (timeZone != null) { buffer.append(", TimeZone="); buffer.append(timeZone); } buffer.append(']'); return buffer.toString(); } /** * Log the DateFormat creation. * @param action The action the format is being used for * @param format The Date format */ private void logFormat(String action, DateFormat format) { if (log().isDebugEnabled()) { StringBuilder buffer = new StringBuilder(45); buffer.append(" "); buffer.append(action); buffer.append(" with Format"); if (format instanceof SimpleDateFormat) { buffer.append("["); buffer.append(((SimpleDateFormat)format).toPattern()); buffer.append("]"); } buffer.append(" for "); if (locale == null) { buffer.append("default locale"); } else { buffer.append("locale["); buffer.append(locale); buffer.append("]"); } if (timeZone != null) { buffer.append(", TimeZone["); buffer.append(timeZone); buffer.append("]"); } log().debug(buffer.toString()); } } } ././@LongLink100644 0 0 154 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/DoubleArrayConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/DoubleArrayConvert100644 0 0 11261 12262570611 31114 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.List; import org.apache.commons.beanutils.ConversionException; /** *

      Standard {@link org.apache.commons.beanutils.Converter} implementation that converts an incoming * String into a primitive array of double. On a conversion failure, returns * a specified default value or throws a {@link ConversionException} depending * on how this instance is constructed.

      * * @version $Id: DoubleArrayConverter.java 1454606 2013-03-08 22:30:51Z britter $ * @since 1.4 * @deprecated Replaced by the new {@link ArrayConverter} implementation */ @Deprecated public final class DoubleArrayConverter extends AbstractArrayConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.Converter} that will throw * a {@link ConversionException} if a conversion error occurs. */ public DoubleArrayConverter() { this.defaultValue = null; this.useDefault = false; } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. * * @param defaultValue The default value to be returned */ public DoubleArrayConverter(Object defaultValue) { this.defaultValue = defaultValue; this.useDefault = true; } // ------------------------------------------------------- Static Variables /** *

      Model object for type comparisons.

      */ private static final double[] MODEL = new double[0]; // --------------------------------------------------------- Public Methods /** * Convert the specified input object into an output object of the * specified type. * * @param type Data type to which this value should be converted * @param value The input value to be converted * @return the converted value * @exception ConversionException if conversion cannot be performed * successfully */ @Override public Object convert(Class type, Object value) { // Deal with a null value if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } // Deal with the no-conversion-needed case if (MODEL.getClass() == value.getClass()) { return (value); } // Deal with input value as a String array if (strings.getClass() == value.getClass()) { try { String[] values = (String[]) value; double[] results = new double[values.length]; for (int i = 0; i < values.length; i++) { results[i] = Double.parseDouble(values[i]); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } // Parse the input value as a String into elements // and convert to the appropriate type try { List list = parseElements(value.toString()); double[] results = new double[list.size()]; for (int i = 0; i < results.length; i++) { results[i] = Double.parseDouble((String) list.get(i)); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } } ././@LongLink100644 0 0 147 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/DoubleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/DoubleConverter.ja100644 0 0 4657 12262570611 31030 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; /** * {@link NumberConverter} implementation that handles conversion to * and from java.lang.Double objects. *

      * This implementation can be configured to handle conversion either * by using Double's default String conversion, or by using a Locale's pattern * or by specifying a format pattern. See the {@link NumberConverter} * documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: DoubleConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class DoubleConverter extends NumberConverter { /** * Construct a java.lang.Double Converter that throws * a ConversionException if an error occurs. */ public DoubleConverter() { super(true); } /** * Construct a java.lang.Double Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public DoubleConverter(Object defaultValue) { super(true, defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Double.class; } } ././@LongLink100644 0 0 145 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/FileConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/FileConverter.java100644 0 0 5512 12262570611 31013 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.io.File; /** * {@link org.apache.commons.beanutils.Converter} implementaion that handles conversion * to and from java.io.File objects. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: FileConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.6 */ public final class FileConverter extends AbstractConverter { /** * Construct a java.io.File Converter that throws * a ConversionException if an error occurs. */ public FileConverter() { super(); } /** * Construct a java.io.File Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public FileConverter(Object defaultValue) { super(defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return File.class; } /** *

      Convert the input object into a java.io.File.

      * * @param The target type of the conversion. * @param type Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Throwable if an error occurs converting to the specified type * @since 1.8.0 */ @Override protected T convertToType(Class type, Object value) throws Throwable { if (File.class.equals(type)) { return type.cast(new File(value.toString())); } throw conversionException(type, value); } } ././@LongLink100644 0 0 153 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/FloatArrayConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/FloatArrayConverte100644 0 0 11252 12262570611 31114 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.List; import org.apache.commons.beanutils.ConversionException; /** *

      Standard {@link org.apache.commons.beanutils.Converter} implementation that converts an incoming * String into a primitive array of float. On a conversion failure, returns * a specified default value or throws a {@link ConversionException} depending * on how this instance is constructed.

      * * @version $Id: FloatArrayConverter.java 1454606 2013-03-08 22:30:51Z britter $ * @since 1.4 * @deprecated Replaced by the new {@link ArrayConverter} implementation */ @Deprecated public final class FloatArrayConverter extends AbstractArrayConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.Converter} that will throw * a {@link ConversionException} if a conversion error occurs. */ public FloatArrayConverter() { this.defaultValue = null; this.useDefault = false; } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. * * @param defaultValue The default value to be returned */ public FloatArrayConverter(Object defaultValue) { this.defaultValue = defaultValue; this.useDefault = true; } // ------------------------------------------------------- Static Variables /** *

      Model object for type comparisons.

      */ private static final float[] MODEL = new float[0]; // --------------------------------------------------------- Public Methods /** * Convert the specified input object into an output object of the * specified type. * * @param type Data type to which this value should be converted * @param value The input value to be converted * @return the converted value * * @exception ConversionException if conversion cannot be performed * successfully */ @Override public Object convert(Class type, Object value) { // Deal with a null value if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } // Deal with the no-conversion-needed case if (MODEL.getClass() == value.getClass()) { return (value); } // Deal with input value as a String array if (strings.getClass() == value.getClass()) { try { String[] values = (String[]) value; float[] results = new float[values.length]; for (int i = 0; i < values.length; i++) { results[i] = Float.parseFloat(values[i]); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } // Parse the input value as a String into elements // and convert to the appropriate type try { List list = parseElements(value.toString()); float[] results = new float[list.size()]; for (int i = 0; i < results.length; i++) { results[i] = Float.parseFloat((String) list.get(i)); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } } ././@LongLink100644 0 0 146 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/FloatConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/FloatConverter.jav100644 0 0 4645 12262570611 31046 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; /** * {@link NumberConverter} implementation that handles conversion to * and from java.lang.Float objects. *

      * This implementation can be configured to handle conversion either * by using Float's default String conversion, or by using a Locale's pattern * or by specifying a format pattern. See the {@link NumberConverter} * documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: FloatConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class FloatConverter extends NumberConverter { /** * Construct a java.lang.Float Converter that throws * a ConversionException if an error occurs. */ public FloatConverter() { super(true); } /** * Construct a java.lang.Float Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public FloatConverter(Object defaultValue) { super(true, defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Float.class; } } ././@LongLink100644 0 0 155 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/IntegerArrayConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/IntegerArrayConver100644 0 0 11244 12262570611 31114 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.List; import org.apache.commons.beanutils.ConversionException; /** *

      Standard {@link org.apache.commons.beanutils.Converter} implementation that converts an incoming * String into a primitive array of int. On a conversion failure, returns * a specified default value or throws a {@link ConversionException} depending * on how this instance is constructed.

      * * @version $Id: IntegerArrayConverter.java 1454606 2013-03-08 22:30:51Z britter $ * @since 1.4 * @deprecated Replaced by the new {@link ArrayConverter} implementation */ @Deprecated public final class IntegerArrayConverter extends AbstractArrayConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.Converter} that will throw * a {@link ConversionException} if a conversion error occurs. */ public IntegerArrayConverter() { this.defaultValue = null; this.useDefault = false; } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. * * @param defaultValue The default value to be returned */ public IntegerArrayConverter(Object defaultValue) { this.defaultValue = defaultValue; this.useDefault = true; } // ------------------------------------------------------- Static Variables /** *

      Model object for type comparisons.

      */ private static final int[] MODEL = new int[0]; // --------------------------------------------------------- Public Methods /** * Convert the specified input object into an output object of the * specified type. * * @param type Data type to which this value should be converted * @param value The input value to be converted * @return the converted value * * @exception ConversionException if conversion cannot be performed * successfully */ @Override public Object convert(Class type, Object value) { // Deal with a null value if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } // Deal with the no-conversion-needed case if (MODEL.getClass() == value.getClass()) { return (value); } // Deal with input value as a String array if (strings.getClass() == value.getClass()) { try { String[] values = (String[]) value; int[] results = new int[values.length]; for (int i = 0; i < values.length; i++) { results[i] = Integer.parseInt(values[i]); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } // Parse the input value as a String into elements // and convert to the appropriate type try { List list = parseElements(value.toString()); int[] results = new int[list.size()]; for (int i = 0; i < results.length; i++) { results[i] = Integer.parseInt((String) list.get(i)); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } } ././@LongLink100644 0 0 150 12262571655 10262 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/IntegerConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/IntegerConverter.j100644 0 0 4673 12262570611 31050 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; /** * {@link NumberConverter} implementation that handles conversion to * and from java.lang.Integer objects. *

      * This implementation can be configured to handle conversion either * by using Integer's default String conversion, or by using a Locale's pattern * or by specifying a format pattern. See the {@link NumberConverter} * documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: IntegerConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class IntegerConverter extends NumberConverter { /** * Construct a java.lang.Integer Converter that throws * a ConversionException if an error occurs. */ public IntegerConverter() { super(false); } /** * Construct a java.lang.Integer Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public IntegerConverter(Object defaultValue) { super(false, defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Integer.class; } } ././@LongLink100644 0 0 152 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/LongArrayConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/LongArrayConverter100644 0 0 11233 12262570611 31127 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.List; import org.apache.commons.beanutils.ConversionException; /** *

      Standard {@link org.apache.commons.beanutils.Converter} implementation that converts an incoming * String into a primitive array of long. On a conversion failure, returns * a specified default value or throws a {@link ConversionException} depending * on how this instance is constructed.

      * * @version $Id: LongArrayConverter.java 1454606 2013-03-08 22:30:51Z britter $ * @since 1.4 * @deprecated Replaced by the new {@link ArrayConverter} implementation */ @Deprecated public final class LongArrayConverter extends AbstractArrayConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.Converter} that will throw * a {@link ConversionException} if a conversion error occurs. */ public LongArrayConverter() { this.defaultValue = null; this.useDefault = false; } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. * * @param defaultValue The default value to be returned */ public LongArrayConverter(Object defaultValue) { this.defaultValue = defaultValue; this.useDefault = true; } // ------------------------------------------------------- Static Variables /** *

      Model object for type comparisons.

      */ private static final long[] MODEL = new long[0]; // --------------------------------------------------------- Public Methods /** * Convert the specified input object into an output object of the * specified type. * * @param type Data type to which this value should be converted * @param value The input value to be converted * @return the converted value * * @exception ConversionException if conversion cannot be performed * successfully */ @Override public Object convert(Class type, Object value) { // Deal with a null value if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } // Deal with the no-conversion-needed case if (MODEL.getClass() == value.getClass()) { return (value); } // Deal with input value as a String array if (strings.getClass() == value.getClass()) { try { String[] values = (String[]) value; long[] results = new long[values.length]; for (int i = 0; i < values.length; i++) { results[i] = Long.parseLong(values[i]); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } // Parse the input value as a String into elements // and convert to the appropriate type try { List list = parseElements(value.toString()); long[] results = new long[list.size()]; for (int i = 0; i < results.length; i++) { results[i] = Long.parseLong((String) list.get(i)); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } } ././@LongLink100644 0 0 145 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/LongConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/LongConverter.java100644 0 0 4635 12262570611 31040 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; /** * {@link NumberConverter} implementation that handles conversion to * and from java.lang.Long objects. *

      * This implementation can be configured to handle conversion either * by using Long's default String conversion, or by using a Locale's pattern * or by specifying a format pattern. See the {@link NumberConverter} * documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: LongConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class LongConverter extends NumberConverter { /** * Construct a java.lang.Long Converter that throws * a ConversionException if an error occurs. */ public LongConverter() { super(false); } /** * Construct a java.lang.Long Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public LongConverter(Object defaultValue) { super(false, defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Long.class; } } ././@LongLink100644 0 0 147 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/NumberConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/NumberConverter.ja100644 0 0 47521 12262570611 31063 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.apache.commons.beanutils.ConversionException; /** * {@link org.apache.commons.beanutils.Converter} implementaion that handles conversion * to and from java.lang.Number objects. *

      * This implementation handles conversion for the following * java.lang.Number types. *

        *
      • java.lang.Byte
      • *
      • java.lang.Short
      • *
      • java.lang.Integer
      • *
      • java.lang.Long
      • *
      • java.lang.Float
      • *
      • java.lang.Double
      • *
      • java.math.BigDecimal
      • *
      • java.math.BigInteger
      • *
      * *

      String Conversions (to and from)

      * This class provides a number of ways in which number * conversions to/from Strings can be achieved: *
        *
      • Using the default format for the default Locale, configure using:
      • *
          *
        • setUseLocaleFormat(true)
        • *
        *
      • Using the default format for a specified Locale, configure using:
      • *
          *
        • setLocale(Locale)
        • *
        *
      • Using a specified pattern for the default Locale, configure using:
      • *
          *
        • setPattern(String)
        • *
        *
      • Using a specified pattern for a specified Locale, configure using:
      • *
          *
        • setPattern(String)
        • *
        • setLocale(Locale)
        • *
        *
      • If none of the above are configured the * toNumber(String) method is used to convert * from String to Number and the Number's * toString() method used to convert from * Number to String.
      • *
      * *

      * N.B.Patterns can only be specified using the standard * pattern characters and NOT in localized form (see java.text.DecimalFormat). * For example to cater for number styles used in Germany such as 0.000,00 the pattern * is specified in the normal form 0,000.00 and the locale set to Locale.GERMANY. * * @version $Id: NumberConverter.java 1546738 2013-11-30 16:24:19Z oheger $ * @since 1.8.0 */ public abstract class NumberConverter extends AbstractConverter { private static final Integer ZERO = new Integer(0); private static final Integer ONE = new Integer(1); private String pattern; private final boolean allowDecimals; private boolean useLocaleFormat; private Locale locale; // ----------------------------------------------------------- Constructors /** * Construct a java.lang.Number Converter * that throws a ConversionException if a error occurs. * * @param allowDecimals Indicates whether decimals are allowed */ public NumberConverter(boolean allowDecimals) { super(); this.allowDecimals = allowDecimals; } /** * Construct a java.lang.Number Converter that returns * a default value if an error occurs. * * @param allowDecimals Indicates whether decimals are allowed * @param defaultValue The default value to be returned */ public NumberConverter(boolean allowDecimals, Object defaultValue) { super(); this.allowDecimals = allowDecimals; setDefaultValue(defaultValue); } // --------------------------------------------------------- Public Methods /** * Return whether decimals are allowed in the number. * * @return Whether decimals are allowed in the number */ public boolean isAllowDecimals() { return allowDecimals; } /** * Set whether a format should be used to convert * the Number. * * @param useLocaleFormat true if a number format * should be used. */ public void setUseLocaleFormat(boolean useLocaleFormat) { this.useLocaleFormat = useLocaleFormat; } /** * Return the number format pattern used to convert * Numbers to/from a java.lang.String * (or null if none specified). *

      * See java.text.DecimalFormat for details * of how to specify the pattern. * * @return The format pattern. */ public String getPattern() { return pattern; } /** * Set a number format pattern to use to convert * Numbers to/from a java.lang.String. *

      * See java.text.DecimalFormat for details * of how to specify the pattern. * * @param pattern The format pattern. */ public void setPattern(String pattern) { this.pattern = pattern; setUseLocaleFormat(true); } /** * Return the Locale for the Converter * (or null if none specified). * * @return The locale to use for conversion */ public Locale getLocale() { return locale; } /** * Set the Locale for the Converter. * * @param locale The locale to use for conversion */ public void setLocale(Locale locale) { this.locale = locale; setUseLocaleFormat(true); } // ------------------------------------------------------ Protected Methods /** * Convert an input Number object into a String. * * @param value The input value to be converted * @return the converted String value. * @throws Throwable if an error occurs converting to a String */ @Override protected String convertToString(Object value) throws Throwable { String result = null; if (useLocaleFormat && value instanceof Number) { NumberFormat format = getFormat(); format.setGroupingUsed(false); result = format.format(value); if (log().isDebugEnabled()) { log().debug(" Converted to String using format '" + result + "'"); } } else { result = value.toString(); if (log().isDebugEnabled()) { log().debug(" Converted to String using toString() '" + result + "'"); } } return result; } /** * Convert the input object into a Number object of the * specified type. * * @param Target type of the conversion. * @param targetType Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Throwable if an error occurs converting to the specified type */ @Override protected T convertToType(Class targetType, Object value) throws Throwable { Class sourceType = value.getClass(); // Handle Number if (value instanceof Number) { return toNumber(sourceType, targetType, (Number)value); } // Handle Boolean if (value instanceof Boolean) { return toNumber(sourceType, targetType, ((Boolean)value).booleanValue() ? ONE : ZERO); } // Handle Date --> Long if (value instanceof Date && Long.class.equals(targetType)) { return targetType.cast(new Long(((Date)value).getTime())); } // Handle Calendar --> Long if (value instanceof Calendar && Long.class.equals(targetType)) { return targetType.cast(new Long(((Calendar)value).getTime().getTime())); } // Convert all other types to String & handle String stringValue = value.toString().trim(); if (stringValue.length() == 0) { return handleMissing(targetType); } // Convert/Parse a String Number number = null; if (useLocaleFormat) { NumberFormat format = getFormat(); number = parse(sourceType, targetType, stringValue, format); } else { if (log().isDebugEnabled()) { log().debug(" No NumberFormat, using default conversion"); } number = toNumber(sourceType, targetType, stringValue); } // Ensure the correct number type is returned return toNumber(sourceType, targetType, number); } /** * Convert any Number object to the specified type for this * Converter. *

      * This method handles conversion to the following types: *

        *
      • java.lang.Byte
      • *
      • java.lang.Short
      • *
      • java.lang.Integer
      • *
      • java.lang.Long
      • *
      • java.lang.Float
      • *
      • java.lang.Double
      • *
      • java.math.BigDecimal
      • *
      • java.math.BigInteger
      • *
      * @param sourceType The type being converted from * @param targetType The Number type to convert to * @param value The Number to convert. * * @return The converted value. */ private T toNumber(Class sourceType, Class targetType, Number value) { // Correct Number type already if (targetType.equals(value.getClass())) { return targetType.cast(value); } // Byte if (targetType.equals(Byte.class)) { long longValue = value.longValue(); if (longValue > Byte.MAX_VALUE) { throw new ConversionException(toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Byte.MIN_VALUE) { throw new ConversionException(toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return targetType.cast(new Byte(value.byteValue())); } // Short if (targetType.equals(Short.class)) { long longValue = value.longValue(); if (longValue > Short.MAX_VALUE) { throw new ConversionException(toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Short.MIN_VALUE) { throw new ConversionException(toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return targetType.cast(new Short(value.shortValue())); } // Integer if (targetType.equals(Integer.class)) { long longValue = value.longValue(); if (longValue > Integer.MAX_VALUE) { throw new ConversionException(toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Integer.MIN_VALUE) { throw new ConversionException(toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return targetType.cast(new Integer(value.intValue())); } // Long if (targetType.equals(Long.class)) { return targetType.cast(new Long(value.longValue())); } // Float if (targetType.equals(Float.class)) { if (value.doubleValue() > Float.MAX_VALUE) { throw new ConversionException(toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } return targetType.cast(new Float(value.floatValue())); } // Double if (targetType.equals(Double.class)) { return targetType.cast(new Double(value.doubleValue())); } // BigDecimal if (targetType.equals(BigDecimal.class)) { if (value instanceof Float || value instanceof Double) { return targetType.cast(new BigDecimal(value.toString())); } else if (value instanceof BigInteger) { return targetType.cast(new BigDecimal((BigInteger)value)); } else { return targetType.cast(BigDecimal.valueOf(value.longValue())); } } // BigInteger if (targetType.equals(BigInteger.class)) { if (value instanceof BigDecimal) { return targetType.cast(((BigDecimal)value).toBigInteger()); } else { return targetType.cast(BigInteger.valueOf(value.longValue())); } } String msg = toString(getClass()) + " cannot handle conversion to '" + toString(targetType) + "'"; if (log().isWarnEnabled()) { log().warn(" " + msg); } throw new ConversionException(msg); } /** * Default String to Number conversion. *

      * This method handles conversion from a String to the following types: *

        *
      • java.lang.Byte
      • *
      • java.lang.Short
      • *
      • java.lang.Integer
      • *
      • java.lang.Long
      • *
      • java.lang.Float
      • *
      • java.lang.Double
      • *
      • java.math.BigDecimal
      • *
      • java.math.BigInteger
      • *
      * @param sourceType The type being converted from * @param targetType The Number type to convert to * @param value The String value to convert. * * @return The converted Number value. */ private Number toNumber(Class sourceType, Class targetType, String value) { // Byte if (targetType.equals(Byte.class)) { return new Byte(value); } // Short if (targetType.equals(Short.class)) { return new Short(value); } // Integer if (targetType.equals(Integer.class)) { return new Integer(value); } // Long if (targetType.equals(Long.class)) { return new Long(value); } // Float if (targetType.equals(Float.class)) { return new Float(value); } // Double if (targetType.equals(Double.class)) { return new Double(value); } // BigDecimal if (targetType.equals(BigDecimal.class)) { return new BigDecimal(value); } // BigInteger if (targetType.equals(BigInteger.class)) { return new BigInteger(value); } String msg = toString(getClass()) + " cannot handle conversion from '" + toString(sourceType) + "' to '" + toString(targetType) + "'"; if (log().isWarnEnabled()) { log().warn(" " + msg); } throw new ConversionException(msg); } /** * Provide a String representation of this number converter. * * @return A String representation of this number converter */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(toString(getClass())); buffer.append("[UseDefault="); buffer.append(isUseDefault()); buffer.append(", UseLocaleFormat="); buffer.append(useLocaleFormat); if (pattern != null) { buffer.append(", Pattern="); buffer.append(pattern); } if (locale != null) { buffer.append(", Locale="); buffer.append(locale); } buffer.append(']'); return buffer.toString(); } /** * Return a NumberFormat to use for Conversion. * * @return The NumberFormat. */ private NumberFormat getFormat() { NumberFormat format = null; if (pattern != null) { if (locale == null) { if (log().isDebugEnabled()) { log().debug(" Using pattern '" + pattern + "'"); } format = new DecimalFormat(pattern); } else { if (log().isDebugEnabled()) { log().debug(" Using pattern '" + pattern + "'" + " with Locale[" + locale + "]"); } DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale); format = new DecimalFormat(pattern, symbols); } } else { if (locale == null) { if (log().isDebugEnabled()) { log().debug(" Using default Locale format"); } format = NumberFormat.getInstance(); } else { if (log().isDebugEnabled()) { log().debug(" Using Locale[" + locale + "] format"); } format = NumberFormat.getInstance(locale); } } if (!allowDecimals) { format.setParseIntegerOnly(true); } return format; } /** * Convert a String into a Number object. * @param sourceType the source type of the conversion * @param targetType The type to convert the value to * @param value The String date value. * @param format The NumberFormat to parse the String value. * * @return The converted Number object. * @throws ConversionException if the String cannot be converted. */ private Number parse(Class sourceType, Class targetType, String value, NumberFormat format) { ParsePosition pos = new ParsePosition(0); Number parsedNumber = format.parse(value, pos); if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedNumber == null) { String msg = "Error converting from '" + toString(sourceType) + "' to '" + toString(targetType) + "'"; if (format instanceof DecimalFormat) { msg += " using pattern '" + ((DecimalFormat)format).toPattern() + "'"; } if (locale != null) { msg += " for locale=[" + locale + "]"; } if (log().isDebugEnabled()) { log().debug(" " + msg); } throw new ConversionException(msg); } return parsedNumber; } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/package-info.java100644 0 0 1770 12262570611 30572 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Standard implementations of the {@link Converter} interface that * are pre-registered with {@link ConvertUtils} at startup time. */ package org.apache.commons.beanutils.converters; ././@LongLink100644 0 0 153 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ShortArrayConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ShortArrayConverte100644 0 0 11252 12262570611 31146 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.List; import org.apache.commons.beanutils.ConversionException; /** *

      Standard {@link org.apache.commons.beanutils.Converter} implementation that converts an incoming * String into a primitive array of short. On a conversion failure, returns * a specified default value or throws a {@link ConversionException} depending * on how this instance is constructed.

      * * @version $Id: ShortArrayConverter.java 1454606 2013-03-08 22:30:51Z britter $ * @since 1.4 * @deprecated Replaced by the new {@link ArrayConverter} implementation */ @Deprecated public final class ShortArrayConverter extends AbstractArrayConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.Converter} that will throw * a {@link ConversionException} if a conversion error occurs. */ public ShortArrayConverter() { this.defaultValue = null; this.useDefault = false; } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. * * @param defaultValue The default value to be returned */ public ShortArrayConverter(Object defaultValue) { this.defaultValue = defaultValue; this.useDefault = true; } // ------------------------------------------------------- Static Variables /** *

      Model object for type comparisons.

      */ private static final short[] MODEL = new short[0]; // --------------------------------------------------------- Public Methods /** * Convert the specified input object into an output object of the * specified type. * * @param type Data type to which this value should be converted * @param value The input value to be converted * @return the converted value * * @exception ConversionException if conversion cannot be performed * successfully */ @Override public Object convert(Class type, Object value) { // Deal with a null value if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } // Deal with the no-conversion-needed case if (MODEL.getClass() == value.getClass()) { return (value); } // Deal with input value as a String array if (strings.getClass() == value.getClass()) { try { String[] values = (String[]) value; short[] results = new short[values.length]; for (int i = 0; i < values.length; i++) { results[i] = Short.parseShort(values[i]); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } // Parse the input value as a String into elements // and convert to the appropriate type try { List list = parseElements(value.toString()); short[] results = new short[list.size()]; for (int i = 0; i < results.length; i++) { results[i] = Short.parseShort((String) list.get(i)); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } } ././@LongLink100644 0 0 146 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ShortConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/ShortConverter.jav100644 0 0 4647 12262570611 31102 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; /** * {@link NumberConverter} implementation that handles conversion to * and from java.lang.Short objects. *

      * This implementation can be configured to handle conversion either * by using Short's default String conversion, or by using a Locale's pattern * or by specifying a format pattern. See the {@link NumberConverter} * documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: ShortConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class ShortConverter extends NumberConverter { /** * Construct a java.lang.Short Converter that throws * a ConversionException if an error occurs. */ public ShortConverter() { super(false); } /** * Construct a java.lang.Short Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public ShortConverter(Object defaultValue) { super(false, defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Short.class; } } ././@LongLink100644 0 0 150 12262571655 10262 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/SqlDateConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/SqlDateConverter.j100644 0 0 4716 12262570611 31006 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.sql.Date; /** * {@link DateTimeConverter} implementation that handles conversion to * and from java.sql.Date objects. *

      * This implementation can be configured to handle conversion either * by using java.sql.Date's default String conversion, or by using a * Locale's default format or by specifying a set of format patterns. * See the {@link DateTimeConverter} documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: SqlDateConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class SqlDateConverter extends DateTimeConverter { /** * Construct a java.sql.Date Converter that throws * a ConversionException if an error occurs. */ public SqlDateConverter() { super(); } /** * Construct a java.sql.Date Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public SqlDateConverter(Object defaultValue) { super(defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Date.class; } } ././@LongLink100644 0 0 150 12262571655 10262 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/SqlTimeConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/SqlTimeConverter.j100644 0 0 6237 12262570611 31027 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.sql.Time; import java.text.DateFormat; import java.util.Locale; import java.util.TimeZone; /** * {@link DateTimeConverter} implementation that handles conversion to * and from java.sql.Time objects. *

      * This implementation can be configured to handle conversion either * by using java.sql.Time's default String conversion, or by using a * Locale's default format or by specifying a set of format patterns. * See the {@link DateTimeConverter} documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: SqlTimeConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class SqlTimeConverter extends DateTimeConverter { /** * Construct a java.sql.Time Converter that throws * a ConversionException if an error occurs. */ public SqlTimeConverter() { super(); } /** * Construct a java.sql.Time Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public SqlTimeConverter(Object defaultValue) { super(defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Time.class; } /** * Return a DateFormat for the Locale. * @param locale TODO * @param timeZone TODO * * @return The DateFormat. * @since 1.8.0 */ @Override protected DateFormat getFormat(Locale locale, TimeZone timeZone) { DateFormat format = null; if (locale == null) { format = DateFormat.getTimeInstance(DateFormat.SHORT); } else { format = DateFormat.getTimeInstance(DateFormat.SHORT, locale); } if (timeZone != null) { format.setTimeZone(timeZone); } return format; } } ././@LongLink100644 0 0 155 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/SqlTimestampConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/SqlTimestampConver100644 0 0 6373 12262570611 31132 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.sql.Timestamp; import java.text.DateFormat; import java.util.Locale; import java.util.TimeZone; /** * {@link DateTimeConverter} implementation that handles conversion to * and from java.sql.Timestamp objects. *

      * This implementation can be configured to handle conversion either * by using java.sql.Timestamp's default String conversion, or by using a * Locale's default format or by specifying a set of format patterns. * See the {@link DateTimeConverter} documentation for further details. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: SqlTimestampConverter.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.3 */ public final class SqlTimestampConverter extends DateTimeConverter { /** * Construct a java.sql.Timestamp Converter that throws * a ConversionException if an error occurs. */ public SqlTimestampConverter() { super(); } /** * Construct a java.sql.Timestamp Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public SqlTimestampConverter(Object defaultValue) { super(defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return Timestamp.class; } /** * Return a DateFormat for the Locale. * @param locale TODO * @param timeZone TODO * * @return The DateFormat. * @since 1.8.0 */ @Override protected DateFormat getFormat(Locale locale, TimeZone timeZone) { DateFormat format = null; if (locale == null) { format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); } else { format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); } if (timeZone != null) { format.setTimeZone(timeZone); } return format; } } ././@LongLink100644 0 0 154 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/StringArrayConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/StringArrayConvert100644 0 0 13412 12262570611 31150 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.List; import org.apache.commons.beanutils.ConversionException; /** * Standard {@link org.apache.commons.beanutils.Converter} implementation that converts an incoming * String into an array of String objects. On a conversion failure, returns * a specified default value or throws a {@link ConversionException} depending * on how this instance is constructed. *

      * There is also some special handling where the input is of type int[]. * See method convert for more details. * * @version $Id: StringArrayConverter.java 1454606 2013-03-08 22:30:51Z britter $ * @since 1.4 * @deprecated Replaced by the new {@link ArrayConverter} implementation */ @Deprecated public final class StringArrayConverter extends AbstractArrayConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.Converter} that will throw * a {@link ConversionException} if a conversion error occurs. */ public StringArrayConverter() { this.defaultValue = null; this.useDefault = false; } /** * Create a {@link org.apache.commons.beanutils.Converter} that will return * the specified default value if a conversion error occurs. * * @param defaultValue The default value to be returned */ public StringArrayConverter(Object defaultValue) { this.defaultValue = defaultValue; this.useDefault = true; } // ------------------------------------------------------- Static Variables /** *

      Model object for type comparisons.

      */ private static final String[] MODEL = new String[0]; /** *

      Model object for int arrays.

      */ private static final int[] INT_MODEL = new int[0]; // --------------------------------------------------------- Public Methods /** * Convert the specified input object into an output object of the * specified type. *

      * If the value is already of type String[] then it is simply returned * unaltered. *

      * If the value is of type int[], then a String[] is returned where each * element in the string array is the result of calling Integer.toString * on the corresponding element of the int array. This was added as a * result of bugzilla request #18297 though there is not complete * agreement that this feature should have been added. *

      * In all other cases, this method calls toString on the input object, then * assumes the result is a comma-separated list of values. The values are * split apart into the individual items and returned as the elements of an * array. See class AbstractArrayConverter for the exact input formats * supported. * * @param type is the data type to which this value should be converted. * It is expected to be the class for type String[] (though this parameter * is actually ignored by this method). * * @param value is the input value to be converted. If null then the * default value is returned or an exception thrown if no default value * exists. * @return the converted value * * @exception ConversionException if conversion cannot be performed * successfully, or the input is null and there is no default value set * for this object. */ @Override public Object convert(Class type, Object value) { // Deal with a null value if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } // Deal with the no-conversion-needed case if (MODEL.getClass() == value.getClass()) { return (value); } // Deal with the input value as an int array if (INT_MODEL.getClass() == value.getClass()) { int[] values = (int[]) value; String[] results = new String[values.length]; for (int i = 0; i < values.length; i++) { results[i] = Integer.toString(values[i]); } return (results); } // Parse the input value as a String into elements // and convert to the appropriate type try { List list = parseElements(value.toString()); String[] results = new String[list.size()]; for (int i = 0; i < results.length; i++) { results[i] = (String) list.get(i); } return (results); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(value.toString(), e); } } } } ././@LongLink100644 0 0 147 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/StringConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/StringConverter.ja100644 0 0 7420 12262570611 31053 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; /** * {@link org.apache.commons.beanutils.Converter} * implementation that converts an incoming * object into a java.lang.String object. *

      * Note that ConvertUtils really is designed to do string->object conversions, * and offers very little support for object->string conversions. The * ConvertUtils/ConvertUtilsBean methods only select a converter to apply * based upon the target type being converted to, and generally assume that * the input is a string (by calling its toString method if needed). *

      * This class is therefore just a dummy converter that converts its input * into a string by calling the input object's toString method and returning * that value. *

      * It is possible to replace this converter with something that has a big * if/else statement that selects behaviour based on the real type of the * object being converted (or possibly has a map of converters, and looks * them up based on the class of the input object). However this is not part * of the existing ConvertUtils framework. * * * @version $Id: StringConverter.java 1540518 2013-11-10 19:04:04Z oheger $ * @since 1.3 */ public final class StringConverter extends AbstractConverter { /** * Construct a java.lang.String Converter that throws * a ConversionException if an error occurs. */ public StringConverter() { super(); } /** * Construct a java.lang.String Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public StringConverter(Object defaultValue) { super(defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return String.class; } /** * Convert the specified input object into an output object of the * specified type. * * @param Target type of the conversion. * @param type Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Throwable if an error occurs converting to the specified type * @since 1.8.0 */ @Override protected T convertToType(Class type, Object value) throws Throwable { // We have to support Object, too, because this class is sometimes // used for a standard to Object conversion if (String.class.equals(type) || Object.class.equals(type)) { return type.cast(value.toString()); } throw conversionException(type, value); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/converters/URLConverter.java100644 0 0 5503 12262570611 30576 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.net.URL; /** * {@link org.apache.commons.beanutils.Converter} implementaion that handles conversion * to and from java.net.URL objects. *

      * Can be configured to either return a default value or throw a * ConversionException if a conversion error occurs. * * @version $Id: URLConverter.java 1540518 2013-11-10 19:04:04Z oheger $ * @since 1.3 */ public final class URLConverter extends AbstractConverter { /** * Construct a java.net.URL Converter that throws * a ConversionException if an error occurs. */ public URLConverter() { super(); } /** * Construct a java.net.URL Converter that returns * a default value if an error occurs. * * @param defaultValue The default value to be returned * if the value to be converted is missing or an error * occurs converting the value. */ public URLConverter(Object defaultValue) { super(defaultValue); } /** * Return the default type this Converter handles. * * @return The default type this Converter handles. * @since 1.8.0 */ @Override protected Class getDefaultType() { return URL.class; } /** *

      Convert a java.net.URL or object into a String.

      * * @param Target type of the conversion. * @param type Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Throwable if an error occurs converting to the specified type * @since 1.8.0 */ @Override protected T convertToType(Class type, Object value) throws Throwable { if (URL.class.equals(type)) { return type.cast(new URL(value.toString())); } throw conversionException(type, value); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/ConvertingWrapDynaBean.java100644 0 0 6077 12262570611 30433 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.InvocationTargetException; /** *

      Implementation of DynaBean that wraps a standard JavaBean * instance, so that DynaBean APIs can be used to access its properties, * though this implementation allows type conversion to occur when properties are set. * This means that (say) Strings can be passed in as values in setter methods and * this DynaBean will convert them to the correct primitive data types.

      * *

      IMPLEMENTATION NOTE - This implementation does not * support the contains() and remove() methods.

      * * @version $Id: ConvertingWrapDynaBean.java 1454606 2013-03-08 22:30:51Z britter $ */ public class ConvertingWrapDynaBean extends WrapDynaBean { /** * Construct a new DynaBean associated with the specified * JavaBean instance. * * @param instance JavaBean instance to be wrapped */ public ConvertingWrapDynaBean(Object instance) { super(instance); } /** * Set the value of the property with the specified name * performing any type conversions if necessary. So this method * can accept String values for primitive numeric data types for example. * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set * * @exception IllegalArgumentException if there are any problems * copying the property. */ @Override public void set(String name, Object value) { try { BeanUtils.copyProperty(instance, name, value); } catch (InvocationTargetException ite) { Throwable cause = ite.getTargetException(); throw new IllegalArgumentException ("Error setting property '" + name + "' nested exception - " + cause); } catch (Throwable t) { IllegalArgumentException iae = new IllegalArgumentException ("Error setting property '" + name + "', exception - " + t); BeanUtils.initCause(iae, t); throw iae; } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/ConvertUtils.java100644 0 0 32755 12262570612 26545 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** *

      Utility methods for converting String scalar values to objects of the * specified Class, String arrays to arrays of the specified Class.

      * *

      For more details, see ConvertUtilsBean which provides the * implementations for these methods.

      * * @version $Id: ConvertUtils.java 1540518 2013-11-10 19:04:04Z oheger $ * @see ConvertUtilsBean */ public class ConvertUtils { // ------------------------------------------------------ Static Properties /** * Gets the default value for Boolean conversions. * @return The default Boolean value * @deprecated Register replacement converters for Boolean.TYPE and * Boolean.class instead */ @Deprecated public static boolean getDefaultBoolean() { return (ConvertUtilsBean.getInstance().getDefaultBoolean()); } /** * Sets the default value for Boolean conversions. * @param newDefaultBoolean The default Boolean value * @deprecated Register replacement converters for Boolean.TYPE and * Boolean.class instead */ @Deprecated public static void setDefaultBoolean(boolean newDefaultBoolean) { ConvertUtilsBean.getInstance().setDefaultBoolean(newDefaultBoolean); } /** * Gets the default value for Byte conversions. * @return The default Byte value * @deprecated Register replacement converters for Byte.TYPE and * Byte.class instead */ @Deprecated public static byte getDefaultByte() { return ConvertUtilsBean.getInstance().getDefaultByte(); } /** * Sets the default value for Byte conversions. * @param newDefaultByte The default Byte value * @deprecated Register replacement converters for Byte.TYPE and * Byte.class instead */ @Deprecated public static void setDefaultByte(byte newDefaultByte) { ConvertUtilsBean.getInstance().setDefaultByte(newDefaultByte); } /** * Gets the default value for Character conversions. * @return The default Character value * @deprecated Register replacement converters for Character.TYPE and * Character.class instead */ @Deprecated public static char getDefaultCharacter() { return ConvertUtilsBean.getInstance().getDefaultCharacter(); } /** * Sets the default value for Character conversions. * @param newDefaultCharacter The default Character value * @deprecated Register replacement converters for Character.TYPE and * Character.class instead */ @Deprecated public static void setDefaultCharacter(char newDefaultCharacter) { ConvertUtilsBean.getInstance().setDefaultCharacter(newDefaultCharacter); } /** * Gets the default value for Double conversions. * @return The default Double value * @deprecated Register replacement converters for Double.TYPE and * Double.class instead */ @Deprecated public static double getDefaultDouble() { return ConvertUtilsBean.getInstance().getDefaultDouble(); } /** * Sets the default value for Double conversions. * @param newDefaultDouble The default Double value * @deprecated Register replacement converters for Double.TYPE and * Double.class instead */ @Deprecated public static void setDefaultDouble(double newDefaultDouble) { ConvertUtilsBean.getInstance().setDefaultDouble(newDefaultDouble); } /** * Get the default value for Float conversions. * @return The default Float value * @deprecated Register replacement converters for Float.TYPE and * Float.class instead */ @Deprecated public static float getDefaultFloat() { return ConvertUtilsBean.getInstance().getDefaultFloat(); } /** * Sets the default value for Float conversions. * @param newDefaultFloat The default Float value * @deprecated Register replacement converters for Float.TYPE and * Float.class instead */ @Deprecated public static void setDefaultFloat(float newDefaultFloat) { ConvertUtilsBean.getInstance().setDefaultFloat(newDefaultFloat); } /** * Gets the default value for Integer conversions. * @return The default Integer value * @deprecated Register replacement converters for Integer.TYPE and * Integer.class instead */ @Deprecated public static int getDefaultInteger() { return ConvertUtilsBean.getInstance().getDefaultInteger(); } /** * Sets the default value for Integer conversions. * @param newDefaultInteger The default Integer value * @deprecated Register replacement converters for Integer.TYPE and * Integer.class instead */ @Deprecated public static void setDefaultInteger(int newDefaultInteger) { ConvertUtilsBean.getInstance().setDefaultInteger(newDefaultInteger); } /** * Gets the default value for Long conversions. * @return The default Long value * @deprecated Register replacement converters for Long.TYPE and * Long.class instead */ @Deprecated public static long getDefaultLong() { return (ConvertUtilsBean.getInstance().getDefaultLong()); } /** * Sets the default value for Long conversions. * @param newDefaultLong The default Long value * @deprecated Register replacement converters for Long.TYPE and * Long.class instead */ @Deprecated public static void setDefaultLong(long newDefaultLong) { ConvertUtilsBean.getInstance().setDefaultLong(newDefaultLong); } /** * Gets the default value for Short conversions. * @return The default Short value * @deprecated Register replacement converters for Short.TYPE and * Short.class instead */ @Deprecated public static short getDefaultShort() { return ConvertUtilsBean.getInstance().getDefaultShort(); } /** * Sets the default value for Short conversions. * @param newDefaultShort The default Short value * @deprecated Register replacement converters for Short.TYPE and * Short.class instead */ @Deprecated public static void setDefaultShort(short newDefaultShort) { ConvertUtilsBean.getInstance().setDefaultShort(newDefaultShort); } // --------------------------------------------------------- Public Classes /** *

      Convert the specified value into a String.

      * *

      For more details see ConvertUtilsBean.

      * * @param value Value to be converted (may be null) * @return The converted String value or null if value is null * * @see ConvertUtilsBean#convert(Object) */ public static String convert(Object value) { return ConvertUtilsBean.getInstance().convert(value); } /** *

      Convert the specified value to an object of the specified class (if * possible). Otherwise, return a String representation of the value.

      * *

      For more details see ConvertUtilsBean.

      * * @param value Value to be converted (may be null) * @param clazz Java class to be converted to (must not be null) * @return The converted value * * @see ConvertUtilsBean#convert(String, Class) */ public static Object convert(String value, Class clazz) { return ConvertUtilsBean.getInstance().convert(value, clazz); } /** *

      Convert an array of specified values to an array of objects of the * specified class (if possible).

      * *

      For more details see ConvertUtilsBean.

      * * @param values Array of values to be converted * @param clazz Java array or element class to be converted to (must not be null) * @return The converted value * * @see ConvertUtilsBean#convert(String[], Class) */ public static Object convert(String[] values, Class clazz) { return ConvertUtilsBean.getInstance().convert(values, clazz); } /** *

      Convert the value to an object of the specified class (if * possible).

      * * @param value Value to be converted (may be null) * @param targetType Class of the value to be converted to (must not be null) * @return The converted value * * @exception ConversionException if thrown by an underlying Converter */ public static Object convert(Object value, Class targetType) { return ConvertUtilsBean.getInstance().convert(value, targetType); } /** *

      Remove all registered {@link Converter}s, and re-establish the * standard Converters.

      * *

      For more details see ConvertUtilsBean.

      * * @see ConvertUtilsBean#deregister() */ public static void deregister() { ConvertUtilsBean.getInstance().deregister(); } /** *

      Remove any registered {@link Converter} for the specified destination * Class.

      * *

      For more details see ConvertUtilsBean.

      * * @param clazz Class for which to remove a registered Converter * @see ConvertUtilsBean#deregister(Class) */ public static void deregister(Class clazz) { ConvertUtilsBean.getInstance().deregister(clazz); } /** *

      Look up and return any registered {@link Converter} for the specified * destination class; if there is no registered Converter, return * null.

      * *

      For more details see ConvertUtilsBean.

      * * @param clazz Class for which to return a registered Converter * @return The registered {@link Converter} or null if not found * @see ConvertUtilsBean#lookup(Class) */ public static Converter lookup(Class clazz) { return ConvertUtilsBean.getInstance().lookup(clazz); } /** * Look up and return any registered {@link Converter} for the specified * source and destination class; if there is no registered Converter, * return null. * * @param sourceType Class of the value being converted * @param targetType Class of the value to be converted to * @return The registered {@link Converter} or null if not found */ public static Converter lookup(Class sourceType, Class targetType) { return ConvertUtilsBean.getInstance().lookup(sourceType, targetType); } /** *

      Register a custom {@link Converter} for the specified destination * Class, replacing any previously registered Converter.

      * *

      For more details see ConvertUtilsBean.

      * * @param converter Converter to be registered * @param clazz Destination class for conversions performed by this * Converter * @see ConvertUtilsBean#register(Converter, Class) */ public static void register(Converter converter, Class clazz) { ConvertUtilsBean.getInstance().register(converter, clazz); } /** * Change primitive Class types to the associated wrapper class. This is * useful for concrete converter implementations which typically treat * primitive types like their corresponding wrapper types. * * @param The type to be checked. * @param type The class type to check. * @return The converted type. * @since 1.9 */ // All type casts are safe because the TYPE members of the wrapper types // return their own class. @SuppressWarnings("unchecked") public static Class primitiveToWrapper(Class type) { if (type == null || !type.isPrimitive()) { return type; } if (type == Integer.TYPE) { return (Class) Integer.class; } else if (type == Double.TYPE) { return (Class) Double.class; } else if (type == Long.TYPE) { return (Class) Long.class; } else if (type == Boolean.TYPE) { return (Class) Boolean.class; } else if (type == Float.TYPE) { return (Class) Float.class; } else if (type == Short.TYPE) { return (Class) Short.class; } else if (type == Byte.TYPE) { return (Class) Byte.class; } else if (type == Character.TYPE) { return (Class) Character.class; } else { return type; } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/ConvertUtilsBean.java100644 0 0 113614 12262570612 27345 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.File; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URL; import java.sql.Timestamp; import java.util.Calendar; import java.util.Collection; import org.apache.commons.beanutils.converters.ArrayConverter; import org.apache.commons.beanutils.converters.BigDecimalConverter; import org.apache.commons.beanutils.converters.BigIntegerConverter; import org.apache.commons.beanutils.converters.BooleanConverter; import org.apache.commons.beanutils.converters.ByteConverter; import org.apache.commons.beanutils.converters.CalendarConverter; import org.apache.commons.beanutils.converters.CharacterConverter; import org.apache.commons.beanutils.converters.ClassConverter; import org.apache.commons.beanutils.converters.ConverterFacade; import org.apache.commons.beanutils.converters.DateConverter; import org.apache.commons.beanutils.converters.DoubleConverter; import org.apache.commons.beanutils.converters.FileConverter; import org.apache.commons.beanutils.converters.FloatConverter; import org.apache.commons.beanutils.converters.IntegerConverter; import org.apache.commons.beanutils.converters.LongConverter; import org.apache.commons.beanutils.converters.ShortConverter; import org.apache.commons.beanutils.converters.SqlDateConverter; import org.apache.commons.beanutils.converters.SqlTimeConverter; import org.apache.commons.beanutils.converters.SqlTimestampConverter; import org.apache.commons.beanutils.converters.StringConverter; import org.apache.commons.beanutils.converters.URLConverter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

      Utility methods for converting String scalar values to objects of the * specified Class, String arrays to arrays of the specified Class. The * actual {@link Converter} instance to be used can be registered for each * possible destination Class. Unless you override them, standard * {@link Converter} instances are provided for all of the following * destination Classes:

      *
        *
      • java.lang.BigDecimal (no default value)
      • *
      • java.lang.BigInteger (no default value)
      • *
      • boolean and java.lang.Boolean (default to false)
      • *
      • byte and java.lang.Byte (default to zero)
      • *
      • char and java.lang.Character (default to a space)
      • *
      • java.lang.Class (no default value)
      • *
      • double and java.lang.Double (default to zero)
      • *
      • float and java.lang.Float (default to zero)
      • *
      • int and java.lang.Integer (default to zero)
      • *
      • long and java.lang.Long (default to zero)
      • *
      • short and java.lang.Short (default to zero)
      • *
      • java.lang.String (default to null)
      • *
      • java.io.File (no default value)
      • *
      • java.net.URL (no default value)
      • *
      • java.sql.Date (no default value)
      • *
      • java.sql.Time (no default value)
      • *
      • java.sql.Timestamp (no default value)
      • *
      * *

      For backwards compatibility, the standard Converters for primitive * types (and the corresponding wrapper classes) return a defined * default value when a conversion error occurs. If you prefer to have a * {@link ConversionException} thrown instead, replace the standard Converter * instances with instances created with the zero-arguments constructor. For * example, to cause the Converters for integers to throw an exception on * conversion errors, you could do this:

      *
       *   // No-args constructor gets the version that throws exceptions
       *   Converter myConverter =
       *    new org.apache.commons.beanutils.converter.IntegerConverter();
       *   ConvertUtils.register(myConverter, Integer.TYPE);    // Native type
       *   ConvertUtils.register(myConverter, Integer.class);   // Wrapper class
       * 
      * *

      * Converters generally treat null input as if it were invalid * input, ie they return their default value if one was specified when the * converter was constructed, and throw an exception otherwise. If you prefer * nulls to be preserved for converters that are converting to objects (not * primitives) then register a converter as above, passing a default value of * null to the converter constructor (and of course registering that converter * only for the .class target). *

      * *

      * When a converter is listed above as having no default value, then that * converter will throw an exception when passed null or an invalid value * as its input. In particular, by default the BigInteger and BigDecimal * converters have no default (and are therefore somewhat inconsistent * with the other numerical converters which all have zero as their default). *

      * *

      * Converters that generate arrays of each of the primitive types are * also automatically configured (including String[]). When passed null * or invalid input, these return an empty array (not null). See class * AbstractArrayConverter for the supported input formats for these converters. *

      * * @version $Id: ConvertUtilsBean.java 1540518 2013-11-10 19:04:04Z oheger $ * @since 1.7 */ public class ConvertUtilsBean { private static final Integer ZERO = new Integer(0); private static final Character SPACE = new Character(' '); // ------------------------------------------------------- Class Methods /** * Get singleton instance * @return The singleton instance */ protected static ConvertUtilsBean getInstance() { return BeanUtilsBean.getInstance().getConvertUtils(); } // ------------------------------------------------------- Variables /** * The set of {@link Converter}s that can be used to convert Strings * into objects of a specified Class, keyed by the destination Class. */ private final WeakFastHashMap, Converter> converters = new WeakFastHashMap, Converter>(); /** * The Log instance for this class. */ private final Log log = LogFactory.getLog(ConvertUtils.class); // ------------------------------------------------------- Constructors /** Construct a bean with standard converters registered */ public ConvertUtilsBean() { converters.setFast(false); deregister(); converters.setFast(true); } // --------------------------------------------------------- Public Methods /** * The default value for Boolean conversions. * @deprecated Register replacement converters for Boolean.TYPE and * Boolean.class instead */ @Deprecated private Boolean defaultBoolean = Boolean.FALSE; /** * Gets the default value for Boolean conversions. * @return The default Boolean value * @deprecated Register replacement converters for Boolean.TYPE and * Boolean.class instead */ @Deprecated public boolean getDefaultBoolean() { return (defaultBoolean.booleanValue()); } /** * Sets the default value for Boolean conversions. * @param newDefaultBoolean The default Boolean value * @deprecated Register replacement converters for Boolean.TYPE and * Boolean.class instead */ @Deprecated public void setDefaultBoolean(boolean newDefaultBoolean) { defaultBoolean = (newDefaultBoolean ? Boolean.TRUE : Boolean.FALSE); register(new BooleanConverter(defaultBoolean), Boolean.TYPE); register(new BooleanConverter(defaultBoolean), Boolean.class); } /** * The default value for Byte conversions. * @deprecated Register replacement converters for Byte.TYPE and * Byte.class instead */ @Deprecated private Byte defaultByte = new Byte((byte) 0); /** * Gets the default value for Byte conversions. * @return The default Byte value * @deprecated Register replacement converters for Byte.TYPE and * Byte.class instead */ @Deprecated public byte getDefaultByte() { return (defaultByte.byteValue()); } /** * Sets the default value for Byte conversions. * @param newDefaultByte The default Byte value * @deprecated Register replacement converters for Byte.TYPE and * Byte.class instead */ @Deprecated public void setDefaultByte(byte newDefaultByte) { defaultByte = new Byte(newDefaultByte); register(new ByteConverter(defaultByte), Byte.TYPE); register(new ByteConverter(defaultByte), Byte.class); } /** * The default value for Character conversions. * @deprecated Register replacement converters for Character.TYPE and * Character.class instead */ @Deprecated private Character defaultCharacter = new Character(' '); /** * Gets the default value for Character conversions. * @return The default Character value * @deprecated Register replacement converters for Character.TYPE and * Character.class instead */ @Deprecated public char getDefaultCharacter() { return (defaultCharacter.charValue()); } /** * Sets the default value for Character conversions. * @param newDefaultCharacter The default Character value * @deprecated Register replacement converters for Character.TYPE and * Character.class instead */ @Deprecated public void setDefaultCharacter(char newDefaultCharacter) { defaultCharacter = new Character(newDefaultCharacter); register(new CharacterConverter(defaultCharacter), Character.TYPE); register(new CharacterConverter(defaultCharacter), Character.class); } /** * The default value for Double conversions. * @deprecated Register replacement converters for Double.TYPE and * Double.class instead */ @Deprecated private Double defaultDouble = new Double(0.0); /** * Gets the default value for Double conversions. * @return The default Double value * @deprecated Register replacement converters for Double.TYPE and * Double.class instead */ @Deprecated public double getDefaultDouble() { return (defaultDouble.doubleValue()); } /** * Sets the default value for Double conversions. * @param newDefaultDouble The default Double value * @deprecated Register replacement converters for Double.TYPE and * Double.class instead */ @Deprecated public void setDefaultDouble(double newDefaultDouble) { defaultDouble = new Double(newDefaultDouble); register(new DoubleConverter(defaultDouble), Double.TYPE); register(new DoubleConverter(defaultDouble), Double.class); } /** * The default value for Float conversions. * @deprecated Register replacement converters for Float.TYPE and * Float.class instead */ @Deprecated private Float defaultFloat = new Float((float) 0.0); /** * Gets the default value for Float conversions. * @return The default Float value * @deprecated Register replacement converters for Float.TYPE and * Float.class instead */ @Deprecated public float getDefaultFloat() { return (defaultFloat.floatValue()); } /** * Sets the default value for Float conversions. * @param newDefaultFloat The default Float value * @deprecated Register replacement converters for Float.TYPE and * Float.class instead */ @Deprecated public void setDefaultFloat(float newDefaultFloat) { defaultFloat = new Float(newDefaultFloat); register(new FloatConverter(defaultFloat), Float.TYPE); register(new FloatConverter(defaultFloat), Float.class); } /** * The default value for Integer conversions. * @deprecated Register replacement converters for Integer.TYPE and * Integer.class instead */ @Deprecated private Integer defaultInteger = new Integer(0); /** * Gets the default value for Integer conversions. * @return The default Integer value * @deprecated Register replacement converters for Integer.TYPE and * Integer.class instead */ @Deprecated public int getDefaultInteger() { return (defaultInteger.intValue()); } /** * Sets the default value for Integer conversions. * @param newDefaultInteger The default Integer value * @deprecated Register replacement converters for Integer.TYPE and * Integer.class instead */ @Deprecated public void setDefaultInteger(int newDefaultInteger) { defaultInteger = new Integer(newDefaultInteger); register(new IntegerConverter(defaultInteger), Integer.TYPE); register(new IntegerConverter(defaultInteger), Integer.class); } /** * The default value for Long conversions. * @deprecated Register replacement converters for Long.TYPE and * Long.class instead */ @Deprecated private Long defaultLong = new Long(0); /** * Gets the default value for Long conversions. * @return The default Long value * @deprecated Register replacement converters for Long.TYPE and * Long.class instead */ @Deprecated public long getDefaultLong() { return (defaultLong.longValue()); } /** * Sets the default value for Long conversions. * @param newDefaultLong The default Long value * @deprecated Register replacement converters for Long.TYPE and * Long.class instead */ @Deprecated public void setDefaultLong(long newDefaultLong) { defaultLong = new Long(newDefaultLong); register(new LongConverter(defaultLong), Long.TYPE); register(new LongConverter(defaultLong), Long.class); } /** * The default value for Short conversions. * @deprecated Register replacement converters for Short.TYPE and * Short.class instead */ @Deprecated private static Short defaultShort = new Short((short) 0); /** * Gets the default value for Short conversions. * @return The default Short value * @deprecated Register replacement converters for Short.TYPE and * Short.class instead */ @Deprecated public short getDefaultShort() { return (defaultShort.shortValue()); } /** * Sets the default value for Short conversions. * @param newDefaultShort The default Short value * @deprecated Register replacement converters for Short.TYPE and * Short.class instead */ @Deprecated public void setDefaultShort(short newDefaultShort) { defaultShort = new Short(newDefaultShort); register(new ShortConverter(defaultShort), Short.TYPE); register(new ShortConverter(defaultShort), Short.class); } /** * Convert the specified value into a String. If the specified value * is an array, the first element (converted to a String) will be * returned. The registered {@link Converter} for the * java.lang.String class will be used, which allows * applications to customize Object->String conversions (the default * implementation simply uses toString()). * * @param value Value to be converted (may be null) * @return The converted String value or null if value is null */ public String convert(Object value) { if (value == null) { return null; } else if (value.getClass().isArray()) { if (Array.getLength(value) < 1) { return (null); } value = Array.get(value, 0); if (value == null) { return null; } else { Converter converter = lookup(String.class); return (converter.convert(String.class, value)); } } else { Converter converter = lookup(String.class); return (converter.convert(String.class, value)); } } /** * Convert the specified value to an object of the specified class (if * possible). Otherwise, return a String representation of the value. * * @param value Value to be converted (may be null) * @param clazz Java class to be converted to (must not be null) * @return The converted value * * @exception ConversionException if thrown by an underlying Converter */ public Object convert(String value, Class clazz) { if (log.isDebugEnabled()) { log.debug("Convert string '" + value + "' to class '" + clazz.getName() + "'"); } Converter converter = lookup(clazz); if (converter == null) { converter = lookup(String.class); } if (log.isTraceEnabled()) { log.trace(" Using converter " + converter); } return (converter.convert(clazz, value)); } /** * Convert an array of specified values to an array of objects of the * specified class (if possible). If the specified Java class is itself * an array class, this class will be the type of the returned value. * Otherwise, an array will be constructed whose component type is the * specified class. * * @param values Array of values to be converted * @param clazz Java array or element class to be converted to (must not be null) * @return The converted value * * @exception ConversionException if thrown by an underlying Converter */ public Object convert(String[] values, Class clazz) { Class type = clazz; if (clazz.isArray()) { type = clazz.getComponentType(); } if (log.isDebugEnabled()) { log.debug("Convert String[" + values.length + "] to class '" + type.getName() + "[]'"); } Converter converter = lookup(type); if (converter == null) { converter = lookup(String.class); } if (log.isTraceEnabled()) { log.trace(" Using converter " + converter); } Object array = Array.newInstance(type, values.length); for (int i = 0; i < values.length; i++) { Array.set(array, i, converter.convert(type, values[i])); } return (array); } /** * Convert the value to an object of the specified class (if * possible). If no converter for the desired target type is registered, * the passed in object is returned unchanged. * * @param value Value to be converted (may be null) * @param targetType Class of the value to be converted to (must not be null) * @return The converted value * * @exception ConversionException if thrown by an underlying Converter */ public Object convert(Object value, Class targetType) { Class sourceType = value == null ? null : value.getClass(); if (log.isDebugEnabled()) { if (value == null) { log.debug("Convert null value to type '" + targetType.getName() + "'"); } else { log.debug("Convert type '" + sourceType.getName() + "' value '" + value + "' to type '" + targetType.getName() + "'"); } } Object converted = value; Converter converter = lookup(sourceType, targetType); if (converter != null) { if (log.isTraceEnabled()) { log.trace(" Using converter " + converter); } converted = converter.convert(targetType, value); } if (String.class.equals(targetType) && converted != null && !(converted instanceof String)) { // NOTE: For backwards compatibility, if the Converter // doesn't handle conversion-->String then // use the registered String Converter converter = lookup(String.class); if (converter != null) { if (log.isTraceEnabled()) { log.trace(" Using converter " + converter); } converted = converter.convert(String.class, converted); } // If the object still isn't a String, use toString() method if (converted != null && !(converted instanceof String)) { converted = converted.toString(); } } return converted; } /** * Remove all registered {@link Converter}s, and re-establish the * standard Converters. */ public void deregister() { converters.clear(); registerPrimitives(false); registerStandard(false, false); registerOther(true); registerArrays(false, 0); register(BigDecimal.class, new BigDecimalConverter()); register(BigInteger.class, new BigIntegerConverter()); } /** * Register the provided converters with the specified defaults. * * @param throwException true if the converters should * throw an exception when a conversion error occurs, otherwise * false if a default value should be used. * @param defaultNull trueif the standard converters * (see {@link ConvertUtilsBean#registerStandard(boolean, boolean)}) * should use a default value of null, otherwise false. * N.B. This values is ignored if throwException is true * @param defaultArraySize The size of the default array value for array converters * (N.B. This values is ignored if throwException is true). * Specifying a value less than zero causes a null value to be used for * the default. */ public void register(boolean throwException, boolean defaultNull, int defaultArraySize) { registerPrimitives(throwException); registerStandard(throwException, defaultNull); registerOther(throwException); registerArrays(throwException, defaultArraySize); } /** * Register the converters for primitive types. *

      * This method registers the following converters: *
        *
      • Boolean.TYPE - {@link BooleanConverter}
      • *
      • Byte.TYPE - {@link ByteConverter}
      • *
      • Character.TYPE - {@link CharacterConverter}
      • *
      • Double.TYPE - {@link DoubleConverter}
      • *
      • Float.TYPE - {@link FloatConverter}
      • *
      • Integer.TYPE - {@link IntegerConverter}
      • *
      • Long.TYPE - {@link LongConverter}
      • *
      • Short.TYPE - {@link ShortConverter}
      • *
      * @param throwException true if the converters should * throw an exception when a conversion error occurs, otherwise * false if a default value should be used. */ private void registerPrimitives(boolean throwException) { register(Boolean.TYPE, throwException ? new BooleanConverter() : new BooleanConverter(Boolean.FALSE)); register(Byte.TYPE, throwException ? new ByteConverter() : new ByteConverter(ZERO)); register(Character.TYPE, throwException ? new CharacterConverter() : new CharacterConverter(SPACE)); register(Double.TYPE, throwException ? new DoubleConverter() : new DoubleConverter(ZERO)); register(Float.TYPE, throwException ? new FloatConverter() : new FloatConverter(ZERO)); register(Integer.TYPE, throwException ? new IntegerConverter() : new IntegerConverter(ZERO)); register(Long.TYPE, throwException ? new LongConverter() : new LongConverter(ZERO)); register(Short.TYPE, throwException ? new ShortConverter() : new ShortConverter(ZERO)); } /** * Register the converters for standard types. *

      * This method registers the following converters: *
        *
      • BigDecimal.class - {@link BigDecimalConverter}
      • *
      • BigInteger.class - {@link BigIntegerConverter}
      • *
      • Boolean.class - {@link BooleanConverter}
      • *
      • Byte.class - {@link ByteConverter}
      • *
      • Character.class - {@link CharacterConverter}
      • *
      • Double.class - {@link DoubleConverter}
      • *
      • Float.class - {@link FloatConverter}
      • *
      • Integer.class - {@link IntegerConverter}
      • *
      • Long.class - {@link LongConverter}
      • *
      • Short.class - {@link ShortConverter}
      • *
      • String.class - {@link StringConverter}
      • *
      * @param throwException true if the converters should * throw an exception when a conversion error occurs, otherwise * false if a default value should be used. * @param defaultNull trueif the standard converters * (see {@link ConvertUtilsBean#registerStandard(boolean, boolean)}) * should use a default value of null, otherwise false. * N.B. This values is ignored if throwException is true */ private void registerStandard(boolean throwException, boolean defaultNull) { Number defaultNumber = defaultNull ? null : ZERO; BigDecimal bigDecDeflt = defaultNull ? null : new BigDecimal("0.0"); BigInteger bigIntDeflt = defaultNull ? null : new BigInteger("0"); Boolean booleanDefault = defaultNull ? null : Boolean.FALSE; Character charDefault = defaultNull ? null : SPACE; String stringDefault = defaultNull ? null : ""; register(BigDecimal.class, throwException ? new BigDecimalConverter() : new BigDecimalConverter(bigDecDeflt)); register(BigInteger.class, throwException ? new BigIntegerConverter() : new BigIntegerConverter(bigIntDeflt)); register(Boolean.class, throwException ? new BooleanConverter() : new BooleanConverter(booleanDefault)); register(Byte.class, throwException ? new ByteConverter() : new ByteConverter(defaultNumber)); register(Character.class, throwException ? new CharacterConverter() : new CharacterConverter(charDefault)); register(Double.class, throwException ? new DoubleConverter() : new DoubleConverter(defaultNumber)); register(Float.class, throwException ? new FloatConverter() : new FloatConverter(defaultNumber)); register(Integer.class, throwException ? new IntegerConverter() : new IntegerConverter(defaultNumber)); register(Long.class, throwException ? new LongConverter() : new LongConverter(defaultNumber)); register(Short.class, throwException ? new ShortConverter() : new ShortConverter(defaultNumber)); register(String.class, throwException ? new StringConverter() : new StringConverter(stringDefault)); } /** * Register the converters for other types. *

      * This method registers the following converters: *
        *
      • Class.class - {@link ClassConverter}
      • *
      • java.util.Date.class - {@link DateConverter}
      • *
      • java.util.Calendar.class - {@link CalendarConverter}
      • *
      • File.class - {@link FileConverter}
      • *
      • java.sql.Date.class - {@link SqlDateConverter}
      • *
      • java.sql.Time.class - {@link SqlTimeConverter}
      • *
      • java.sql.Timestamp.class - {@link SqlTimestampConverter}
      • *
      • URL.class - {@link URLConverter}
      • *
      * @param throwException true if the converters should * throw an exception when a conversion error occurs, otherwise * false if a default value should be used. */ private void registerOther(boolean throwException) { register(Class.class, throwException ? new ClassConverter() : new ClassConverter(null)); register(java.util.Date.class, throwException ? new DateConverter() : new DateConverter(null)); register(Calendar.class, throwException ? new CalendarConverter() : new CalendarConverter(null)); register(File.class, throwException ? new FileConverter() : new FileConverter(null)); register(java.sql.Date.class, throwException ? new SqlDateConverter() : new SqlDateConverter(null)); register(java.sql.Time.class, throwException ? new SqlTimeConverter() : new SqlTimeConverter(null)); register(Timestamp.class, throwException ? new SqlTimestampConverter() : new SqlTimestampConverter(null)); register(URL.class, throwException ? new URLConverter() : new URLConverter(null)); } /** * Register array converters. * * @param throwException true if the converters should * throw an exception when a conversion error occurs, otherwise * false if a default value should be used. * @param defaultArraySize The size of the default array value for array converters * (N.B. This values is ignored if throwException is true). * Specifying a value less than zero causes a null value to be used for * the default. */ private void registerArrays(boolean throwException, int defaultArraySize) { // Primitives registerArrayConverter(Boolean.TYPE, new BooleanConverter(), throwException, defaultArraySize); registerArrayConverter(Byte.TYPE, new ByteConverter(), throwException, defaultArraySize); registerArrayConverter(Character.TYPE, new CharacterConverter(), throwException, defaultArraySize); registerArrayConverter(Double.TYPE, new DoubleConverter(), throwException, defaultArraySize); registerArrayConverter(Float.TYPE, new FloatConverter(), throwException, defaultArraySize); registerArrayConverter(Integer.TYPE, new IntegerConverter(), throwException, defaultArraySize); registerArrayConverter(Long.TYPE, new LongConverter(), throwException, defaultArraySize); registerArrayConverter(Short.TYPE, new ShortConverter(), throwException, defaultArraySize); // Standard registerArrayConverter(BigDecimal.class, new BigDecimalConverter(), throwException, defaultArraySize); registerArrayConverter(BigInteger.class, new BigIntegerConverter(), throwException, defaultArraySize); registerArrayConverter(Boolean.class, new BooleanConverter(), throwException, defaultArraySize); registerArrayConverter(Byte.class, new ByteConverter(), throwException, defaultArraySize); registerArrayConverter(Character.class, new CharacterConverter(), throwException, defaultArraySize); registerArrayConverter(Double.class, new DoubleConverter(), throwException, defaultArraySize); registerArrayConverter(Float.class, new FloatConverter(), throwException, defaultArraySize); registerArrayConverter(Integer.class, new IntegerConverter(), throwException, defaultArraySize); registerArrayConverter(Long.class, new LongConverter(), throwException, defaultArraySize); registerArrayConverter(Short.class, new ShortConverter(), throwException, defaultArraySize); registerArrayConverter(String.class, new StringConverter(), throwException, defaultArraySize); // Other registerArrayConverter(Class.class, new ClassConverter(), throwException, defaultArraySize); registerArrayConverter(java.util.Date.class, new DateConverter(), throwException, defaultArraySize); registerArrayConverter(Calendar.class, new DateConverter(), throwException, defaultArraySize); registerArrayConverter(File.class, new FileConverter(), throwException, defaultArraySize); registerArrayConverter(java.sql.Date.class, new SqlDateConverter(), throwException, defaultArraySize); registerArrayConverter(java.sql.Time.class, new SqlTimeConverter(), throwException, defaultArraySize); registerArrayConverter(Timestamp.class, new SqlTimestampConverter(), throwException, defaultArraySize); registerArrayConverter(URL.class, new URLConverter(), throwException, defaultArraySize); } /** * Register a new ArrayConverter with the specified element delegate converter * that returns a default array of the specified size in the event of conversion errors. * * @param componentType The component type of the array * @param componentConverter The converter to delegate to for the array elements * @param throwException Whether a conversion exception should be thrown or a default * value used in the event of a conversion error * @param defaultArraySize The size of the default array */ private void registerArrayConverter(Class componentType, Converter componentConverter, boolean throwException, int defaultArraySize) { Class arrayType = Array.newInstance(componentType, 0).getClass(); Converter arrayConverter = null; if (throwException) { arrayConverter = new ArrayConverter(arrayType, componentConverter); } else { arrayConverter = new ArrayConverter(arrayType, componentConverter, defaultArraySize); } register(arrayType, arrayConverter); } /** strictly for convenience since it has same parameter order as Map.put */ private void register(Class clazz, Converter converter) { register(new ConverterFacade(converter), clazz); } /** * Remove any registered {@link Converter} for the specified destination * Class. * * @param clazz Class for which to remove a registered Converter */ public void deregister(Class clazz) { converters.remove(clazz); } /** * Look up and return any registered {@link Converter} for the specified * destination class; if there is no registered Converter, return * null. * * @param clazz Class for which to return a registered Converter * @return The registered {@link Converter} or null if not found */ public Converter lookup(Class clazz) { return (converters.get(clazz)); } /** * Look up and return any registered {@link Converter} for the specified * source and destination class; if there is no registered Converter, * return null. * * @param sourceType Class of the value being converted * @param targetType Class of the value to be converted to * @return The registered {@link Converter} or null if not found */ public Converter lookup(Class sourceType, Class targetType) { if (targetType == null) { throw new IllegalArgumentException("Target type is missing"); } if (sourceType == null) { return lookup(targetType); } Converter converter = null; // Convert --> String if (targetType == String.class) { converter = lookup(sourceType); if (converter == null && (sourceType.isArray() || Collection.class.isAssignableFrom(sourceType))) { converter = lookup(String[].class); } if (converter == null) { converter = lookup(String.class); } return converter; } // Convert --> String array if (targetType == String[].class) { if (sourceType.isArray() || Collection.class.isAssignableFrom(sourceType)) { converter = lookup(sourceType); } if (converter == null) { converter = lookup(String[].class); } return converter; } return lookup(targetType); } /** * Register a custom {@link Converter} for the specified destination * Class, replacing any previously registered Converter. * * @param converter Converter to be registered * @param clazz Destination class for conversions performed by this * Converter */ public void register(Converter converter, Class clazz) { converters.put(clazz, converter); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/ConvertUtilsBean2.java100644 0 0 5364 12262570611 27370 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * {@link ConvertUtilsBean} implementation that delegates convert() * methods to the new {@link ConvertUtilsBean#convert(Object, Class)} method. * *

      * To configure this implementation for the current context ClassLoader invoke * BeanUtilsBean.setInstance(new BeanUtilsBean2()); *

      * * @see BeanUtilsBean2 * @version $Id: ConvertUtilsBean2.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.8.0 */ public class ConvertUtilsBean2 extends ConvertUtilsBean { /** * Delegates to the new {@link ConvertUtilsBean#convert(Object, Class)} * method. * * @param value Value to be converted (may be null) * @return The converted String value or null if value is null * * @see ConvertUtilsBean#convert(String[], Class) */ @Override public String convert(Object value) { return (String)convert(value, String.class); } /** * Delegates to the new {@link ConvertUtilsBean#convert(Object, Class)} * method. * * @param value Value to be converted (may be null) * @param clazz Java class to be converted to (must not be null) * @return The converted value or null if value is null * * @see ConvertUtilsBean#convert(String[], Class) */ @Override public Object convert(String value, Class clazz) { return convert((Object)value, clazz); } /** * Delegates to the new {@link ConvertUtilsBean#convert(Object, Class)} * method. * * @param value Array of values to be converted * @param clazz Java array or element class to be converted to (must not be null) * @return The converted value * * @see ConvertUtilsBean#convert(String[], Class) */ @Override public Object convert(String[] value, Class clazz) { return convert((Object)value, clazz); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/DefaultBeanIntrospector.java100644 0 0 17201 12262570612 30657 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.BeanInfo; import java.beans.IndexedPropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

      * The default {@link BeanIntrospector} implementation. *

      *

      * This class implements a default bean introspection algorithm based on the JDK * classes in the java.beans package. It discovers properties * conforming to the Java Beans specification. *

      *

      * This class is a singleton. The single instance can be obtained using the * {@code INSTANCE} field. It does not define any state and thus can be * shared by arbitrary clients. {@link PropertyUtils} per default uses this * instance as its only {@code BeanIntrospector} object. *

      * * @version $Id: DefaultBeanIntrospector.java 1540359 2013-11-09 18:10:52Z oheger $ * @since 1.9 */ public class DefaultBeanIntrospector implements BeanIntrospector { /** The singleton instance of this class. */ public static final BeanIntrospector INSTANCE = new DefaultBeanIntrospector(); /** Constant for argument types of a method that expects no arguments. */ private static final Class[] EMPTY_CLASS_PARAMETERS = new Class[0]; /** Constant for arguments types of a method that expects a list argument. */ private static final Class[] LIST_CLASS_PARAMETER = new Class[] { java.util.List.class }; /** Log instance */ private final Log log = LogFactory.getLog(getClass()); /** * Private constructor so that no instances can be created. */ private DefaultBeanIntrospector() { } /** * Performs introspection of a specific Java class. This implementation uses * the {@code java.beans.Introspector.getBeanInfo()} method to obtain * all property descriptors for the current class and adds them to the * passed in introspection context. * * @param icontext the introspection context */ public void introspect(IntrospectionContext icontext) { BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(icontext.getTargetClass()); } catch (IntrospectionException e) { // no descriptors are added to the context log.error( "Error when inspecting class " + icontext.getTargetClass(), e); return; } PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); if (descriptors == null) { descriptors = new PropertyDescriptor[0]; } handleIndexedPropertyDescriptors(icontext.getTargetClass(), descriptors); icontext.addPropertyDescriptors(descriptors); } /** * This method fixes an issue where IndexedPropertyDescriptor behaves * differently in different versions of the JDK for 'indexed' properties * which use java.util.List (rather than an array). It implements a * workaround for Bug 28358. If you have a Bean with the following * getters/setters for an indexed property: * *
           * public List getFoo()
           * public Object getFoo(int index)
           * public void setFoo(List foo)
           * public void setFoo(int index, Object foo)
           * 
      * * then the IndexedPropertyDescriptor's getReadMethod() and getWriteMethod() * behave as follows: *
        *
      • JDK 1.3.1_04: returns valid Method objects from these methods.
      • *
      • JDK 1.4.2_05: returns null from these methods.
      • *
      * * @param beanClass the current class to be inspected * @param descriptors the array with property descriptors */ private void handleIndexedPropertyDescriptors(Class beanClass, PropertyDescriptor[] descriptors) { for (PropertyDescriptor pd : descriptors) { if (pd instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor) pd; String propName = descriptor.getName().substring(0, 1) .toUpperCase() + descriptor.getName().substring(1); if (descriptor.getReadMethod() == null) { String methodName = descriptor.getIndexedReadMethod() != null ? descriptor .getIndexedReadMethod().getName() : "get" + propName; Method readMethod = MethodUtils .getMatchingAccessibleMethod(beanClass, methodName, EMPTY_CLASS_PARAMETERS); if (readMethod != null) { try { descriptor.setReadMethod(readMethod); } catch (Exception e) { log.error( "Error setting indexed property read method", e); } } } if (descriptor.getWriteMethod() == null) { String methodName = descriptor.getIndexedWriteMethod() != null ? descriptor .getIndexedWriteMethod().getName() : "set" + propName; Method writeMethod = MethodUtils .getMatchingAccessibleMethod(beanClass, methodName, LIST_CLASS_PARAMETER); if (writeMethod == null) { for (Method m : beanClass.getMethods()) { if (m.getName().equals(methodName)) { Class[] parameterTypes = m.getParameterTypes(); if (parameterTypes.length == 1 && List.class .isAssignableFrom(parameterTypes[0])) { writeMethod = m; break; } } } } if (writeMethod != null) { try { descriptor.setWriteMethod(writeMethod); } catch (Exception e) { log.error( "Error setting indexed property write method", e); } } } } } } } ././@LongLink100644 0 0 150 12262571655 10262 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/DefaultIntrospectionContext.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/DefaultIntrospectionContext.j100644 0 0 7254 12262570612 31102 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map; import java.util.Set; /** *

      * An implementation of the {@code IntrospectionContext} interface used by * {@link PropertyUtilsBean} when doing introspection of a bean class. *

      *

      * This class implements the methods required by the * {@code IntrospectionContext} interface in a straight-forward manner * based on a map. It is used internally only. It is not thread-safe. *

      * * @version $Id: DefaultIntrospectionContext.java 1540359 2013-11-09 18:10:52Z oheger $ * @since 1.9 */ class DefaultIntrospectionContext implements IntrospectionContext { /** Constant for an empty array of property descriptors. */ private static final PropertyDescriptor[] EMPTY_DESCRIPTORS = new PropertyDescriptor[0]; /** The current class for introspection. */ private final Class currentClass; /** A map for storing the already added property descriptors. */ private final Map descriptors; /** * * Creates a new instance of DefaultIntrospectionContext and sets * the current class for introspection. * * @param cls the current class */ public DefaultIntrospectionContext(Class cls) { currentClass = cls; descriptors = new HashMap(); } public Class getTargetClass() { return currentClass; } public void addPropertyDescriptor(PropertyDescriptor desc) { if (desc == null) { throw new IllegalArgumentException( "Property descriptor must not be null!"); } descriptors.put(desc.getName(), desc); } public void addPropertyDescriptors(PropertyDescriptor[] descs) { if (descs == null) { throw new IllegalArgumentException( "Array with descriptors must not be null!"); } for (int i = 0; i < descs.length; i++) { addPropertyDescriptor(descs[i]); } } public boolean hasProperty(String name) { return descriptors.containsKey(name); } public PropertyDescriptor getPropertyDescriptor(String name) { return descriptors.get(name); } public void removePropertyDescriptor(String name) { descriptors.remove(name); } public Set propertyNames() { return descriptors.keySet(); } /** * Returns an array with all descriptors added to this context. This method * is used to obtain the results of introspection. * * @return an array with all known property descriptors */ public PropertyDescriptor[] getPropertyDescriptors() { return descriptors.values().toArray(EMPTY_DESCRIPTORS); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/DynaBean.java100644 0 0 14333 12262570612 25555 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** *

      A DynaBean is a Java object that supports properties * whose names and data types, as well as values, may be dynamically modified. * To the maximum degree feasible, other components of the BeanUtils package * will recognize such beans and treat them as standard JavaBeans for the * purpose of retrieving and setting property values.

      * * @version $Id: DynaBean.java 1454597 2013-03-08 21:58:12Z britter $ */ public interface DynaBean { /** * Does the specified mapped property contain a value for the specified * key value? * * @param name Name of the property to check * @param key Name of the key to check * @return true if the mapped property contains a value for * the specified key, otherwise false * * @exception IllegalArgumentException if there is no property * of the specified name */ public boolean contains(String name, String key); /** * Return the value of a simple property with the specified name. * * @param name Name of the property whose value is to be retrieved * @return The property's value * * @exception IllegalArgumentException if there is no property * of the specified name */ public Object get(String name); /** * Return the value of an indexed property with the specified name. * * @param name Name of the property whose value is to be retrieved * @param index Index of the value to be retrieved * @return The indexed property's value * * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property * @exception NullPointerException if no array or List has been * initialized for this property */ public Object get(String name, int index); /** * Return the value of a mapped property with the specified name, * or null if there is no value for the specified key. * * @param name Name of the property whose value is to be retrieved * @param key Key of the value to be retrieved * @return The mapped property's value * * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public Object get(String name, String key); /** * Return the DynaClass instance that describes the set of * properties available for this DynaBean. * * @return The associated DynaClass */ public DynaClass getDynaClass(); /** * Remove any existing value for the specified key on the * specified mapped property. * * @param name Name of the property for which a value is to * be removed * @param key Key of the value to be removed * * @exception IllegalArgumentException if there is no property * of the specified name */ public void remove(String name, String key); /** * Set the value of a simple property with the specified name. * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception NullPointerException if an attempt is made to set a * primitive property to null */ public void set(String name, Object value); /** * Set the value of an indexed property with the specified name. * * @param name Name of the property whose value is to be set * @param index Index of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property */ public void set(String name, int index, Object value); /** * Set the value of a mapped property with the specified name. * * @param name Name of the property whose value is to be set * @param key Key of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public void set(String name, String key, Object value); } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/DynaBeanMapDecorator.java100644 0 0 10261 12262570612 30052 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** *

      Decorates a {@link DynaBean} to provide Map behaviour.

      * *

      The motivation for this implementation is to provide access to {@link DynaBean} * properties in technologies that are unaware of BeanUtils and {@link DynaBean}s - * such as the expression languages of JSTL and JSF.

      * *

      This can be achieved either by wrapping the {@link DynaBean} prior to * providing it to the technolody to process or by providing a Map * accessor method on the DynaBean implementation: *

      
       *         public Map getMap() {
       *             return new DynaBeanMapDecorator(this);
       *         }
      * *

      * *

      This, for example, could be used in JSTL in the following way to access * a DynaBean's fooProperty: *

      • ${myDynaBean.map.fooProperty}
      *

      * *

      Usage

      * *

      To decorate a {@link DynaBean} simply instantiate this class with the * target {@link DynaBean}:

      * *
      • Map fooMap = new DynaBeanMapDecorator(fooDynaBean);
      * *

      The above example creates a read only Map. * To create a Map which can be modified, construct a * DynaBeanMapDecorator with the read only * attribute set to false:

      * *
      • Map fooMap = new DynaBeanMapDecorator(fooDynaBean, false);
      * *

      Limitations

      *

      In this implementation the entrySet(), keySet() * and values() methods create an unmodifiable * Set and it does not support the Map's clear() * and remove() operations.

      *

      For reasons of backwards compatibility, the generic types of this * {@code Map} implementation are {@code }. However, the * keys of the map are typically strings.

      * * @since BeanUtils 1.8.0 * @version $Id: DynaBeanMapDecorator.java 1540186 2013-11-08 21:08:30Z oheger $ * @deprecated Use {@link DynaBeanPropertyMapDecorator} instead. When adding * generics it turned out that it was not possible to use the correct type * parameters without breaking backwards compatibility. Therefore, class * {@code DynaBeanPropertyMapDecorator} was introduced as a replacement. */ @Deprecated public class DynaBeanMapDecorator extends BaseDynaBeanMapDecorator { /** * Construct a Map for the specified {@link DynaBean}. * * @param dynaBean The dyna bean being decorated * @param readOnly true if the Map is read only * otherwise false * @throws IllegalArgumentException if the {@link DynaBean} is null. */ public DynaBeanMapDecorator(DynaBean dynaBean, boolean readOnly) { super(dynaBean, readOnly); } /** * Constructs a read only Map for the specified * {@link DynaBean}. * * @param dynaBean The dyna bean being decorated * @throws IllegalArgumentException if the {@link DynaBean} is null. */ public DynaBeanMapDecorator(DynaBean dynaBean) { super(dynaBean); } @Override protected Object convertKey(String propertyName) { return propertyName; } } ././@LongLink100644 0 0 151 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/DynaBeanPropertyMapDecorator.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/DynaBeanPropertyMapDecorator.100644 0 0 7463 12262570612 30747 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** *

      Decorates a {@link DynaBean} to provide Map behavior.

      * *

      The motivation for this implementation is to provide access to {@link DynaBean} * properties in technologies that are unaware of BeanUtils and {@link DynaBean}s - * such as the expression languages of JSTL and JSF.

      * *

      This can be achieved either by wrapping the {@link DynaBean} prior to * providing it to the technology to process or by providing a Map * accessor method on the DynaBean implementation: *

      
       *         public Map<String, Object> getMap() {
       *             return new DynaBeanPropertyMapDecorator(this);
       *         }
      * *

      * *

      This, for example, could be used in JSTL in the following way to access * a DynaBean's fooProperty: *

      • ${myDynaBean.map.fooProperty}
      *

      * *

      Usage

      * *

      To decorate a {@link DynaBean} simply instantiate this class with the * target {@link DynaBean}:

      * *
      • Map<String, Object> fooMap = new DynaBeanPropertyMapDecorator(fooDynaBean);
      * *

      The above example creates a read only Map. * To create a Map which can be modified, construct a * DynaBeanPropertyMapDecorator with the read only * attribute set to false:

      * *
      • Map<String, Object> fooMap = * new DynaBeanPropertyMapDecorator(fooDynaBean, false);
      * *

      Limitations

      *

      In this implementation the entrySet(), keySet() * and values() methods create an unmodifiable * Set and it does not support the Map's clear() * and remove() operations.

      * * @since BeanUtils 1.9.0 * @version $Id: DynaBeanPropertyMapDecorator.java 1540518 2013-11-10 19:04:04Z oheger $ */ public class DynaBeanPropertyMapDecorator extends BaseDynaBeanMapDecorator { /** * Construct a Map for the specified {@link DynaBean}. * * @param dynaBean The dyna bean being decorated * @param readOnly true if the Map is read only * otherwise false * @throws IllegalArgumentException if the {@link DynaBean} is null. */ public DynaBeanPropertyMapDecorator(DynaBean dynaBean, boolean readOnly) { super(dynaBean, readOnly); } /** * Constructs a read only Map for the specified * {@link DynaBean}. * * @param dynaBean The dyna bean being decorated * @throws IllegalArgumentException if the {@link DynaBean} is null. */ public DynaBeanPropertyMapDecorator(DynaBean dynaBean) { super(dynaBean); } @Override protected String convertKey(String propertyName) { return propertyName; } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/DynaClass.java100644 0 0 6366 12262570612 25744 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** *

      A DynaClass is a simulation of the functionality of * java.lang.Class for classes implementing the * DynaBean interface. DynaBean instances that share the same * DynaClass all have the same set of available properties, along with any * associated data types, read-only states, and write-only states.

      * * @version $Id: DynaClass.java 1454597 2013-03-08 21:58:12Z britter $ */ public interface DynaClass { /** * Return the name of this DynaClass (analogous to the * getName() method of java.lang.ClassDynaClass implementation class to support * different dynamic classes, with different sets of properties. * * @return the name of the DynaClass */ public String getName(); /** * Return a property descriptor for the specified property, if it exists; * otherwise, return null. * * @param name Name of the dynamic property for which a descriptor * is requested * @return The descriptor for the specified property * * @exception IllegalArgumentException if no property name is specified */ public DynaProperty getDynaProperty(String name); /** *

      Return an array of ProperyDescriptors for the properties * currently defined in this DynaClass. If no properties are defined, a * zero-length array will be returned.

      * *

      FIXME - Should we really be implementing * getBeanInfo() instead, which returns property descriptors * and a bunch of other stuff?

      * * @return the set of properties for this DynaClass */ public DynaProperty[] getDynaProperties(); /** * Instantiate and return a new DynaBean instance, associated * with this DynaClass. * * @return A new DynaBean instance * * @exception IllegalAccessException if the Class or the appropriate * constructor is not accessible * @exception InstantiationException if this Class represents an abstract * class, an array class, a primitive type, or void; or if instantiation * fails for some other reason */ public DynaBean newInstance() throws IllegalAccessException, InstantiationException; } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/DynaProperty.java100644 0 0 30376 12262570612 26541 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.io.StreamCorruptedException; import java.util.List; import java.util.Map; /** *

      The metadata describing an individual property of a DynaBean.

      * *

      The meta contains an optional content type property ({@link #getContentType}) * for use by mapped and iterated properties. * A mapped or iterated property may choose to indicate the type it expects. * The DynaBean implementation may choose to enforce this type on its entries. * Alternatively, an implementatin may choose to ignore this property. * All keys for maps must be of type String so no meta data is needed for map keys.

      * * @version $Id: DynaProperty.java 1546738 2013-11-30 16:24:19Z oheger $ */ public class DynaProperty implements Serializable { // ----------------------------------------------------------- Constants /* * There are issues with serializing primitive class types on certain JVM versions * (including java 1.3). * This class uses a custom serialization implementation that writes an integer * for these primitive class. * This list of constants are the ones used in serialization. * If these values are changed, then older versions will no longer be read correctly */ private static final int BOOLEAN_TYPE = 1; private static final int BYTE_TYPE = 2; private static final int CHAR_TYPE = 3; private static final int DOUBLE_TYPE = 4; private static final int FLOAT_TYPE = 5; private static final int INT_TYPE = 6; private static final int LONG_TYPE = 7; private static final int SHORT_TYPE = 8; // ----------------------------------------------------------- Constructors /** * Construct a property that accepts any data type. * * @param name Name of the property being described */ public DynaProperty(String name) { this(name, Object.class); } /** * Construct a property of the specified data type. * * @param name Name of the property being described * @param type Java class representing the property data type */ public DynaProperty(String name, Class type) { super(); this.name = name; this.type = type; if (type != null && type.isArray()) { this.contentType = type.getComponentType(); } } /** * Construct an indexed or mapped DynaProperty that supports (pseudo)-introspection * of the content type. * * @param name Name of the property being described * @param type Java class representing the property data type * @param contentType Class that all indexed or mapped elements are instances of */ public DynaProperty(String name, Class type, Class contentType) { super(); this.name = name; this.type = type; this.contentType = contentType; } // ------------------------------------------------------------- Properties /** Property name */ protected String name = null; /** * Get the name of this property. * @return the name of the property */ public String getName() { return (this.name); } /** Property type */ protected transient Class type = null; /** *

      Gets the Java class representing the data type of the underlying property * values.

      * *

      There are issues with serializing primitive class types on certain JVM versions * (including java 1.3). * Therefore, this field must not be serialized using the standard methods.

      * *

      Please leave this field as transient

      * * @return the property type */ public Class getType() { return (this.type); } /** The (optional) type of content elements for indexed DynaProperty */ protected transient Class contentType; /** * Gets the (optional) type of the indexed content for DynaProperty's * that support this feature. * *

      There are issues with serializing primitive class types on certain JVM versions * (including java 1.3). * Therefore, this field must not be serialized using the standard methods.

      * * @return the Class for the content type if this is an indexed DynaProperty * and this feature is supported. Otherwise null. */ public Class getContentType() { return contentType; } // --------------------------------------------------------- Public Methods /** * Does this property represent an indexed value (ie an array or List)? * * @return true if the property is indexed (i.e. is a List or * array), otherwise false */ public boolean isIndexed() { if (type == null) { return (false); } else if (type.isArray()) { return (true); } else if (List.class.isAssignableFrom(type)) { return (true); } else { return (false); } } /** * Does this property represent a mapped value (ie a Map)? * * @return true if the property is a Map * otherwise false */ public boolean isMapped() { if (type == null) { return (false); } else { return (Map.class.isAssignableFrom(type)); } } /** * Checks this instance against the specified Object for equality. Overrides the * default refererence test for equality provided by {@link java.lang.Object#equals(Object)} * @param obj The object to compare to * @return true if object is a dyna property with the same name * type and content type, otherwise false * @since 1.8.0 */ @Override public boolean equals(final Object obj) { boolean result = false; result = (obj == this); if ((!result) && obj instanceof DynaProperty) { final DynaProperty that = (DynaProperty) obj; result = ((this.name == null) ? (that.name == null) : (this.name.equals(that.name))) && ((this.type == null) ? (that.type == null) : (this.type.equals(that.type))) && ((this.contentType == null) ? (that.contentType == null) : (this.contentType.equals(that.contentType))); } return result; } /** * @return the hashcode for this dyna property * @see java.lang.Object#hashCode * @since 1.8.0 */ @Override public int hashCode() { int result = 1; result = result * 31 + ((name == null) ? 0 : name.hashCode()); result = result * 31 + ((type == null) ? 0 : type.hashCode()); result = result * 31 + ((contentType == null) ? 0 : contentType.hashCode()); return result; } /** * Return a String representation of this Object. * @return a String representation of the dyna property */ @Override public String toString() { StringBuilder sb = new StringBuilder("DynaProperty[name="); sb.append(this.name); sb.append(",type="); sb.append(this.type); if (isMapped() || isIndexed()) { sb.append(" <").append(this.contentType).append(">"); } sb.append("]"); return (sb.toString()); } // --------------------------------------------------------- Serialization helper methods /** * Writes this object safely. * There are issues with serializing primitive class types on certain JVM versions * (including java 1.3). * This method provides a workaround. */ private void writeObject(ObjectOutputStream out) throws IOException { writeAnyClass(this.type,out); if (isMapped() || isIndexed()) { writeAnyClass(this.contentType,out); } // write out other values out.defaultWriteObject(); } /** * Write a class using safe encoding to workaround java 1.3 serialization bug. */ private void writeAnyClass(Class clazz, ObjectOutputStream out) throws IOException { // safely write out any class int primitiveType = 0; if (Boolean.TYPE.equals(clazz)) { primitiveType = BOOLEAN_TYPE; } else if (Byte.TYPE.equals(clazz)) { primitiveType = BYTE_TYPE; } else if (Character.TYPE.equals(clazz)) { primitiveType = CHAR_TYPE; } else if (Double.TYPE.equals(clazz)) { primitiveType = DOUBLE_TYPE; } else if (Float.TYPE.equals(clazz)) { primitiveType = FLOAT_TYPE; } else if (Integer.TYPE.equals(clazz)) { primitiveType = INT_TYPE; } else if (Long.TYPE.equals(clazz)) { primitiveType = LONG_TYPE; } else if (Short.TYPE.equals(clazz)) { primitiveType = SHORT_TYPE; } if (primitiveType == 0) { // then it's not a primitive type out.writeBoolean(false); out.writeObject(clazz); } else { // we'll write out a constant instead out.writeBoolean(true); out.writeInt(primitiveType); } } /** * Reads field values for this object safely. * There are issues with serializing primitive class types on certain JVM versions * (including java 1.3). * This method provides a workaround. * * @throws StreamCorruptedException when the stream data values are outside expected range */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { this.type = readAnyClass(in); if (isMapped() || isIndexed()) { this.contentType = readAnyClass(in); } // read other values in.defaultReadObject(); } /** * Reads a class using safe encoding to workaround java 1.3 serialization bug. */ private Class readAnyClass(ObjectInputStream in) throws IOException, ClassNotFoundException { // read back type class safely if (in.readBoolean()) { // it's a type constant switch (in.readInt()) { case BOOLEAN_TYPE: return Boolean.TYPE; case BYTE_TYPE: return Byte.TYPE; case CHAR_TYPE: return Character.TYPE; case DOUBLE_TYPE: return Double.TYPE; case FLOAT_TYPE: return Float.TYPE; case INT_TYPE: return Integer.TYPE; case LONG_TYPE: return Long.TYPE; case SHORT_TYPE: return Short.TYPE; default: // something's gone wrong throw new StreamCorruptedException( "Invalid primitive type. " + "Check version of beanutils used to serialize is compatible."); } } else { // it's another class return ((Class) in.readObject()); } } }././@LongLink100644 0 0 147 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/expression/DefaultResolver.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/expression/DefaultResolver.ja100644 0 0 24362 12262570611 31054 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.expression; /** * Default Property Name Expression {@link Resolver} Implementation. *

      * This class assists in resolving property names in the following five formats, * with the layout of an identifying String in parentheses: *

        *
      • Simple (name) - The specified * name identifies an individual property of a particular * JavaBean. The name of the actual getter or setter method to be used * is determined using standard JavaBeans instrospection, so that (unless * overridden by a BeanInfo class, a property named "xyz" * will have a getter method named getXyz() or (for boolean * properties only) isXyz(), and a setter method named * setXyz().
      • *
      • Nested (name1.name2.name3) The first * name element is used to select a property getter, as for simple * references above. The object returned for this property is then * consulted, using the same approach, for a property getter for a * property named name2, and so on. The property value that * is ultimately retrieved or modified is the one identified by the * last name element.
      • *
      • Indexed (name[index]) - The underlying * property value is assumed to be an array, or this JavaBean is assumed * to have indexed property getter and setter methods. The appropriate * (zero-relative) entry in the array is selected. List * objects are now also supported for read/write. You simply need to define * a getter that returns the List
      • *
      • Mapped (name(key)) - The JavaBean * is assumed to have an property getter and setter methods with an * additional attribute of type java.lang.String.
      • *
      • Combined (name1.name2[index].name3(key)) - * Combining mapped, nested, and indexed references is also * supported.
      • *
      * * @version $Id: DefaultResolver.java 1454597 2013-03-08 21:58:12Z britter $ * @since 1.8.0 */ public class DefaultResolver implements Resolver { private static final char NESTED = '.'; private static final char MAPPED_START = '('; private static final char MAPPED_END = ')'; private static final char INDEXED_START = '['; private static final char INDEXED_END = ']'; /** * Default Constructor. */ public DefaultResolver() { } /** * Return the index value from the property expression or -1. * * @param expression The property expression * @return The index value or -1 if the property is not indexed * @throws IllegalArgumentException If the indexed property is illegally * formed or has an invalid (non-numeric) value. */ public int getIndex(String expression) { if (expression == null || expression.length() == 0) { return -1; } for (int i = 0; i < expression.length(); i++) { char c = expression.charAt(i); if (c == NESTED || c == MAPPED_START) { return -1; } else if (c == INDEXED_START) { int end = expression.indexOf(INDEXED_END, i); if (end < 0) { throw new IllegalArgumentException("Missing End Delimiter"); } String value = expression.substring(i + 1, end); if (value.length() == 0) { throw new IllegalArgumentException("No Index Value"); } int index = 0; try { index = Integer.parseInt(value, 10); } catch (Exception e) { throw new IllegalArgumentException("Invalid index value '" + value + "'"); } return index; } } return -1; } /** * Return the map key from the property expression or null. * * @param expression The property expression * @return The index value * @throws IllegalArgumentException If the mapped property is illegally formed. */ public String getKey(String expression) { if (expression == null || expression.length() == 0) { return null; } for (int i = 0; i < expression.length(); i++) { char c = expression.charAt(i); if (c == NESTED || c == INDEXED_START) { return null; } else if (c == MAPPED_START) { int end = expression.indexOf(MAPPED_END, i); if (end < 0) { throw new IllegalArgumentException("Missing End Delimiter"); } return expression.substring(i + 1, end); } } return null; } /** * Return the property name from the property expression. * * @param expression The property expression * @return The property name */ public String getProperty(String expression) { if (expression == null || expression.length() == 0) { return expression; } for (int i = 0; i < expression.length(); i++) { char c = expression.charAt(i); if (c == NESTED) { return expression.substring(0, i); } else if (c == MAPPED_START || c == INDEXED_START) { return expression.substring(0, i); } } return expression; } /** * Indicates whether or not the expression * contains nested property expressions or not. * * @param expression The property expression * @return The next property expression */ public boolean hasNested(String expression) { if (expression == null || expression.length() == 0) { return false; } else { return (remove(expression) != null); } } /** * Indicate whether the expression is for an indexed property or not. * * @param expression The property expression * @return true if the expresion is indexed, * otherwise false */ public boolean isIndexed(String expression) { if (expression == null || expression.length() == 0) { return false; } for (int i = 0; i < expression.length(); i++) { char c = expression.charAt(i); if (c == NESTED || c == MAPPED_START) { return false; } else if (c == INDEXED_START) { return true; } } return false; } /** * Indicate whether the expression is for a mapped property or not. * * @param expression The property expression * @return true if the expresion is mapped, * otherwise false */ public boolean isMapped(String expression) { if (expression == null || expression.length() == 0) { return false; } for (int i = 0; i < expression.length(); i++) { char c = expression.charAt(i); if (c == NESTED || c == INDEXED_START) { return false; } else if (c == MAPPED_START) { return true; } } return false; } /** * Extract the next property expression from the * current expression. * * @param expression The property expression * @return The next property expression */ public String next(String expression) { if (expression == null || expression.length() == 0) { return null; } boolean indexed = false; boolean mapped = false; for (int i = 0; i < expression.length(); i++) { char c = expression.charAt(i); if (indexed) { if (c == INDEXED_END) { return expression.substring(0, i + 1); } } else if (mapped) { if (c == MAPPED_END) { return expression.substring(0, i + 1); } } else { if (c == NESTED) { return expression.substring(0, i); } else if (c == MAPPED_START) { mapped = true; } else if (c == INDEXED_START) { indexed = true; } } } return expression; } /** * Remove the last property expresson from the * current expression. * * @param expression The property expression * @return The new expression value, with first property * expression removed - null if there are no more expressions */ public String remove(String expression) { if (expression == null || expression.length() == 0) { return null; } String property = next(expression); if (expression.length() == property.length()) { return null; } int start = property.length(); if (expression.charAt(start) == NESTED) { start++; } return expression.substring(start); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/expression/package-info.java100644 0 0 1662 12262570611 30577 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Contains the {@link Resolver} interface and implementations. */ package org.apache.commons.beanutils.expression; commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/expression/Resolver.java100644 0 0 14641 12262570611 30075 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.expression; /** * Property Name Expression Resolver. *

      * Methods such as PropertyUtilsBean's setNestedProperty() method * use a Resolver to process a property name * expression and resolve nested, indexed and mapped * property names. The following code provides an example usage * demonstrating all the methods: * *

       *      // Iterate through a nested property expression
       *      while (resolver.hasNested(name)) {
       *
       *          // isolate a single property from a nested expresion
       *          String next = resolver.next(name);
       *
       *          // Process...
       *          String property = resolver.getProperty(next);
       *          if (resolver.isIndexed(next)) {
       *
       *              int index = resolver.getIndex(next);
       *              bean = getIndexedProperty(bean, property, index);
       *
       *          } else if (resolver.isMapped(next)) {
       *
       *              String key = resolver.getKey(next);
       *              bean = getMappedProperty(bean, property, key);
       *
       *          } else {
       *
       *              bean = getSimpleProperty(bean, property);
       *
       *          }
       *
       *          // remove the processed property from the expression
       *          name = resolver.remove(name);
       *      }
       * 
      * * In order to create an implementation, it is important to understand how * BeanUtils/PropertyUtils uses the resolver. The following are * the main methods that use it: *
        *
      • {@link org.apache.commons.beanutils.PropertyUtilsBean}
      • *
          *
        • {@link org.apache.commons.beanutils.PropertyUtilsBean#getIndexedProperty(Object, String)}
        • *
        • {@link org.apache.commons.beanutils.PropertyUtilsBean#getMappedProperty(Object, String)}
        • *
        • {@link org.apache.commons.beanutils.PropertyUtilsBean#getNestedProperty(Object, String)}
        • *
        • {@link org.apache.commons.beanutils.PropertyUtilsBean#getPropertyDescriptor(Object, String)}
        • *
        • {@link org.apache.commons.beanutils.PropertyUtilsBean#getSimpleProperty(Object, String)}
        • *
        • {@link org.apache.commons.beanutils.PropertyUtilsBean#setIndexedProperty(Object, String, Object)}
        • *
        • {@link org.apache.commons.beanutils.PropertyUtilsBean#setMappedProperty(Object, String, Object)}
        • *
        • {@link org.apache.commons.beanutils.PropertyUtilsBean#setNestedProperty(Object, String, Object)}
        • *
        • {@link org.apache.commons.beanutils.PropertyUtilsBean#setSimpleProperty(Object, String, Object)}
        • *
        *
      • {@link org.apache.commons.beanutils.BeanUtilsBean}
      • *
          *
        • {@link org.apache.commons.beanutils.BeanUtilsBean#copyProperty(Object, String, Object)}
        • *
        • {@link org.apache.commons.beanutils.BeanUtilsBean#setProperty(Object, String, Object)}
        • *
        *
      • {@link org.apache.commons.beanutils.locale.LocaleBeanUtilsBean}
      • *
          *
        • {@link org.apache.commons.beanutils.locale.LocaleBeanUtilsBean#setProperty(Object, * String, Object, String)}
        • *
        *
      * * @version $Id: Resolver.java 1454597 2013-03-08 21:58:12Z britter $ * @see org.apache.commons.beanutils.PropertyUtilsBean#setResolver(Resolver) * @since 1.8.0 */ public interface Resolver { /** * Extract the index value from the property expression or -1. * * @param expression The property expression * @return The index value or -1 if the property is not indexed * @throws IllegalArgumentException If the indexed property is illegally * formed or has an invalid (non-numeric) value */ int getIndex(String expression); /** * Extract the map key from the property expression or null. * * @param expression The property expression * @return The index value * @throws IllegalArgumentException If the mapped property is illegally formed */ String getKey(String expression); /** * Return the property name from the property expression. * * @param expression The property expression * @return The property name */ String getProperty(String expression); /** * Indicates whether or not the expression * contains nested property expressions or not. * * @param expression The property expression * @return The next property expression */ boolean hasNested(String expression); /** * Indicate whether the expression is for an indexed property or not. * * @param expression The property expression * @return true if the expresion is indexed, * otherwise false */ boolean isIndexed(String expression); /** * Indicate whether the expression is for a mapped property or not. * * @param expression The property expression * @return true if the expresion is mapped, * otherwise false */ boolean isMapped(String expression); /** * Extract the next property expression from the * current expression. * * @param expression The property expression * @return The next property expression */ String next(String expression); /** * Remove the last property expresson from the * current expression. * * @param expression The property expression * @return The new expression value, with first property * expression removed - null if there are no more expressions */ String remove(String expression); } ././@LongLink100644 0 0 153 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/FluentPropertyBeanIntrospector.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/FluentPropertyBeanIntrospecto100644 0 0 15507 12262570612 31202 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

      * An implementation of the BeanIntrospector interface which can * detect write methods for properties used in fluent API scenario. *

      *

      * A fluent API allows setting multiple properties using a single * statement by supporting so-called method chaining: Methods for * setting a property value do not return void, but an object which can * be called for setting another property. An example of such a fluent API could * look as follows: * *

       * public class FooBuilder {
       *     public FooBuilder setFooProperty1(String value) {
       *        ...
       *        return this;
       *    }
       *
       *     public FooBuilder setFooProperty2(int value) {
       *        ...
       *        return this;
       *    }
       * }
       * 
      * * Per default, PropertyUtils does not detect methods like this * because, having a non-void return type, they violate the Java Beans * specification. *

      *

      * This class is more tolerant with regards to the return type of a set method. * It basically iterates over all methods of a class and filters them for a * configurable prefix (the default prefix is set). It then * generates corresponding PropertyDescriptor objects for the * methods found which use these methods as write methods. *

      *

      * An instance of this class is intended to collaborate with a * {@link DefaultBeanIntrospector} object. So best results are achieved by * adding this instance as custom {@code BeanIntrospector} after the * DefaultBeanIntrospector object. Then default introspection finds * read-only properties because it does not detect the write methods with a * non-void return type. {@code FluentPropertyBeanIntrospector} * completes the descriptors for these properties by setting the correct write * method. *

      * * @version $Id: FluentPropertyBeanIntrospector.java 1540359 2013-11-09 18:10:52Z oheger $ * @since 1.9 */ public class FluentPropertyBeanIntrospector implements BeanIntrospector { /** The default prefix for write methods. */ public static final String DEFAULT_WRITE_METHOD_PREFIX = "set"; /** The logger. */ private final Log log = LogFactory.getLog(getClass()); /** The prefix of write methods to search for. */ private final String writeMethodPrefix; /** * * Creates a new instance of FluentPropertyBeanIntrospector and * initializes it with the prefix for write methods used by the classes to * be inspected. * * @param writePrefix the prefix for write methods (must not be null) * @throws IllegalArgumentException if the prefix is null */ public FluentPropertyBeanIntrospector(String writePrefix) { if (writePrefix == null) { throw new IllegalArgumentException( "Prefix for write methods must not be null!"); } writeMethodPrefix = writePrefix; } /** * * Creates a new instance of FluentPropertyBeanIntrospector and * sets the default prefix for write methods. */ public FluentPropertyBeanIntrospector() { this(DEFAULT_WRITE_METHOD_PREFIX); } /** * Returns the prefix for write methods this instance scans for. * * @return the prefix for write methods */ public String getWriteMethodPrefix() { return writeMethodPrefix; } /** * Performs introspection. This method scans the current class's methods for * property write methods which have not been discovered by default * introspection. * * @param icontext the introspection context * @throws IntrospectionException if an error occurs */ public void introspect(IntrospectionContext icontext) throws IntrospectionException { for (Method m : icontext.getTargetClass().getMethods()) { if (m.getName().startsWith(getWriteMethodPrefix())) { String propertyName = propertyName(m); PropertyDescriptor pd = icontext .getPropertyDescriptor(propertyName); try { if (pd == null) { icontext.addPropertyDescriptor(createFluentPropertyDescritor( m, propertyName)); } else if (pd.getWriteMethod() == null) { pd.setWriteMethod(m); } } catch (IntrospectionException e) { log.warn("Error when creating PropertyDescriptor for " + m + "! Ignoring this property.", e); } } } } /** * Derives the name of a property from the given set method. * * @param m the method * @return the corresponding property name */ private String propertyName(Method m) { String methodName = m.getName().substring( getWriteMethodPrefix().length()); return (methodName.length() > 1) ? Character.toLowerCase(methodName .charAt(0)) + methodName.substring(1) : methodName .toLowerCase(Locale.ENGLISH); } /** * Creates a property descriptor for a fluent API property. * * @param m the set method for the fluent API property * @param propertyName the name of the corresponding property * @return the descriptor * @throws IntrospectionException if an error occurs */ private PropertyDescriptor createFluentPropertyDescritor(Method m, String propertyName) throws IntrospectionException { return new PropertyDescriptor(propertyName(m), null, m); } }commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/IntrospectionContext.java100644 0 0 7221 12262570610 30255 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.PropertyDescriptor; import java.util.Set; /** *

      * A context interface used during introspection for querying and setting * property descriptors. *

      *

      * An implementation of this interface is passed to {@link BeanIntrospector} * objects during processing of a bean class. It allows the * {@code BeanIntrospector} to deliver descriptors for properties it has * detected. It is also possible to find out which properties have already been * found by another {@code BeanIntrospector}; this allows multiple * {@code BeanIntrospector} instances to collaborate. *

      * * @version $Id: IntrospectionContext.java 1540359 2013-11-09 18:10:52Z oheger $ * @since 1.9 */ public interface IntrospectionContext { /** * Returns the class that is subject of introspection. * * @return the current class */ Class getTargetClass(); /** * Adds the given property descriptor to this context. This method is called * by a {@code BeanIntrospector} during introspection for each detected * property. If this context already contains a descriptor for the affected * property, it is overridden. * * @param desc the property descriptor */ void addPropertyDescriptor(PropertyDescriptor desc); /** * Adds an array of property descriptors to this context. Using this method * multiple descriptors can be added at once. * * @param descriptors the array of descriptors to be added */ void addPropertyDescriptors(PropertyDescriptor[] descriptors); /** * Tests whether a descriptor for the property with the given name is * already contained in this context. This method can be used for instance * to prevent that an already existing property descriptor is overridden. * * @param name the name of the property in question * @return true if a descriptor for this property has already been * added, false otherwise */ boolean hasProperty(String name); /** * Returns the descriptor for the property with the given name or * null if this property is unknown. * * @param name the name of the property in question * @return the descriptor for this property or null if this property * is unknown */ PropertyDescriptor getPropertyDescriptor(String name); /** * Removes the descriptor for the property with the given name. * * @param name the name of the affected property */ void removePropertyDescriptor(String name); /** * Returns a set with the names of all properties known to this context. * * @return a set with the known property names */ Set propertyNames(); } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/JDBCDynaClass.java100644 0 0 25322 12262570612 26400 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.Serializable; import java.sql.Date; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** *

      Provides common logic for JDBC implementations of {@link DynaClass}.

      * * @version $Id: JDBCDynaClass.java 1540186 2013-11-08 21:08:30Z oheger $ */ abstract class JDBCDynaClass implements DynaClass, Serializable { // ----------------------------------------------------- Instance Variables /** *

      Flag defining whether column names should be lower cased when * converted to property names.

      */ protected boolean lowerCase = true; /** *

      Flag defining whether column names or labels should be used. */ private boolean useColumnLabel; /** *

      The set of dynamic properties that are part of this * {@link DynaClass}.

      */ protected DynaProperty[] properties = null; /** *

      The set of dynamic properties that are part of this * {@link DynaClass}, keyed by the property name. Individual descriptor * instances will be the same instances as those in the * properties list.

      */ protected Map propertiesMap = new HashMap(); /** * Cross Reference for column name --> dyna property name * (needed when lowerCase option is true) */ private Map columnNameXref; // ------------------------------------------------------ DynaClass Methods /** *

      Return the name of this DynaClass (analogous to the * getName() method of java.lang.ClassDynaClass implementation class to support * different dynamic classes, with different sets of properties.

      */ public String getName() { return (this.getClass().getName()); } /** *

      Return a property descriptor for the specified property, if it * exists; otherwise, return null.

      * * @param name Name of the dynamic property for which a descriptor * is requested * * @exception IllegalArgumentException if no property name is specified */ public DynaProperty getDynaProperty(String name) { if (name == null) { throw new IllegalArgumentException("No property name specified"); } return (propertiesMap.get(name)); } /** *

      Return an array of ProperyDescriptors for the properties * currently defined in this DynaClass. If no properties are defined, a * zero-length array will be returned.

      */ public DynaProperty[] getDynaProperties() { return (properties); } /** *

      Instantiate and return a new DynaBean instance, associated * with this DynaClass. NOTE - This operation is not * supported, and throws an exception.

      * * @exception IllegalAccessException if the Class or the appropriate * constructor is not accessible * @exception InstantiationException if this Class represents an abstract * class, an array class, a primitive type, or void; or if instantiation * fails for some other reason */ public DynaBean newInstance() throws IllegalAccessException, InstantiationException { throw new UnsupportedOperationException("newInstance() not supported"); } /** * Set whether the column label or name should be used for the property name. * * @param useColumnLabel true if the column label should be used, otherwise false */ public void setUseColumnLabel(boolean useColumnLabel) { this.useColumnLabel = useColumnLabel; } /** *

      Loads and returns the Class of the given name. * By default, a load from the thread context class loader is attempted. * If there is no such class loader, the class loader used to load this * class will be utilized.

      * * @param className The name of the class to load * @return The loaded class * @exception SQLException if an exception was thrown trying to load * the specified class */ protected Class loadClass(String className) throws SQLException { try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = this.getClass().getClassLoader(); } // use Class.forName() - see BEANUTILS-327 return Class.forName(className, false, cl); } catch (Exception e) { throw new SQLException( "Cannot load column class '" + className + "': " + e); } } /** *

      Factory method to create a new DynaProperty for the given index * into the result set metadata.

      * * @param metadata is the result set metadata * @param i is the column index in the metadata * @return the newly created DynaProperty instance * @throws SQLException If an error occurs accessing the SQL metadata */ protected DynaProperty createDynaProperty( ResultSetMetaData metadata, int i) throws SQLException { String columnName = null; if (useColumnLabel) { columnName = metadata.getColumnLabel(i); } if (columnName == null || columnName.trim().length() == 0) { columnName = metadata.getColumnName(i); } String name = lowerCase ? columnName.toLowerCase() : columnName; if (!name.equals(columnName)) { if (columnNameXref == null) { columnNameXref = new HashMap(); } columnNameXref.put(name, columnName); } String className = null; try { int sqlType = metadata.getColumnType(i); switch (sqlType) { case java.sql.Types.DATE: return new DynaProperty(name, java.sql.Date.class); case java.sql.Types.TIMESTAMP: return new DynaProperty(name, java.sql.Timestamp.class); case java.sql.Types.TIME: return new DynaProperty(name, java.sql.Time.class); default: className = metadata.getColumnClassName(i); } } catch (SQLException e) { // this is a patch for HsqlDb to ignore exceptions // thrown by its metadata implementation } // Default to Object type if no class name could be retrieved // from the metadata Class clazz = Object.class; if (className != null) { clazz = loadClass(className); } return new DynaProperty(name, clazz); } /** *

      Introspect the metadata associated with our result set, and populate * the properties and propertiesMap instance * variables.

      * * @param resultSet The resultSet whose metadata is to * be introspected * * @exception SQLException if an error is encountered processing the * result set metadata */ protected void introspect(ResultSet resultSet) throws SQLException { // Accumulate an ordered list of DynaProperties ArrayList list = new ArrayList(); ResultSetMetaData metadata = resultSet.getMetaData(); int n = metadata.getColumnCount(); for (int i = 1; i <= n; i++) { // JDBC is one-relative! DynaProperty dynaProperty = createDynaProperty(metadata, i); if (dynaProperty != null) { list.add(dynaProperty); } } // Convert this list into the internal data structures we need properties = list.toArray(new DynaProperty[list.size()]); for (int i = 0; i < properties.length; i++) { propertiesMap.put(properties[i].getName(), properties[i]); } } /** * Get a column value from a {@link ResultSet} for the specified name. * * @param resultSet The result set * @param name The property name * @return The value * @throws SQLException if an error occurs */ protected Object getObject(ResultSet resultSet, String name) throws SQLException { DynaProperty property = getDynaProperty(name); if (property == null) { throw new IllegalArgumentException("Invalid name '" + name + "'"); } String columnName = getColumnName(name); Class type = property.getType(); // java.sql.Date if (type.equals(Date.class)) { return resultSet.getDate(columnName); } // java.sql.Timestamp if (type.equals(Timestamp.class)) { return resultSet.getTimestamp(columnName); } // java.sql.Time if (type.equals(Time.class)) { return resultSet.getTime(columnName); } return resultSet.getObject(columnName); } /** * Get the table column name for the specified property name. * * @param name The property name * @return The column name (which can be different if the lowerCase * option is used). */ protected String getColumnName(String name) { if (columnNameXref != null && columnNameXref.containsKey(name)) { return columnNameXref.get(name); } else { return name; } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/LazyDynaBean.java100644 0 0 103242 12262570612 26433 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.Serializable; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

      DynaBean which automatically adds properties to the DynaClass * and provides Lazy List and Lazy Map features.

      * *

      DynaBeans deal with three types of properties - simple, indexed and mapped and * have the following get() and set() methods for * each of these types:

      *
        *
      • Simple property methods - get(name) and * set(name, value)
      • *
      • Indexed property methods - get(name, index) and * set(name, index, value)
      • *
      • Mapped property methods - get(name, key) and * set(name, key, value)
      • *
      * *

      Getting Property Values

      *

      Calling any of the get() methods, for a property which * doesn't exist, returns null in this implementation.

      * *

      Setting Simple Properties

      *

      The LazyDynaBean will automatically add a property to the DynaClass * if it doesn't exist when the set(name, value) method is called.

      * * DynaBean myBean = new LazyDynaBean();
      * myBean.set("myProperty", "myValue");
      * *

      Setting Indexed Properties

      *

      If the property doesn't exist, the LazyDynaBean will automatically add * a property with an ArrayList type to the DynaClass when * the set(name, index, value) method is called. * It will also instantiate a new ArrayList and automatically grow * the List so that it is big enough to accomodate the index being set. * ArrayList is the default indexed property that LazyDynaBean uses but * this can be easily changed by overriding the defaultIndexedProperty(name) * method.

      * * DynaBean myBean = new LazyDynaBean();
      * myBean.set("myIndexedProperty", 0, "myValue1");
      * myBean.set("myIndexedProperty", 1, "myValue2");
      * *

      If the indexed property does exist in the DynaClass but is set to * null in the LazyDynaBean, then it will instantiate a * new List or Array as specified by the property's type * in the DynaClass and automatically grow the List * or Array so that it is big enough to accomodate the index being set.

      * * DynaBean myBean = new LazyDynaBean();
      * MutableDynaClass myClass = (MutableDynaClass)myBean.getDynaClass();
      * myClass.add("myIndexedProperty", int[].class);
      * myBean.set("myIndexedProperty", 0, new Integer(10));
      * myBean.set("myIndexedProperty", 1, new Integer(20));
      * *

      Setting Mapped Properties

      *

      If the property doesn't exist, the LazyDynaBean will automatically add * a property with a HashMap type to the DynaClass and * instantiate a new HashMap in the DynaBean when the * set(name, key, value) method is called. HashMap is the default * mapped property that LazyDynaBean uses but this can be easily changed by overriding * the defaultMappedProperty(name) method.

      * * DynaBean myBean = new LazyDynaBean();
      * myBean.set("myMappedProperty", "myKey", "myValue");
      * *

      If the mapped property does exist in the DynaClass but is set to * null in the LazyDynaBean, then it will instantiate a * new Map as specified by the property's type in the DynaClass.

      * * DynaBean myBean = new LazyDynaBean();
      * MutableDynaClass myClass = (MutableDynaClass)myBean.getDynaClass();
      * myClass.add("myMappedProperty", TreeMap.class);
      * myBean.set("myMappedProperty", "myKey", "myValue");
      * *

      Restricted DynaClass

      *

      MutableDynaClass have a facility to restrict the DynaClass * so that its properties cannot be modified. If the MutableDynaClass is * restricted then calling any of the set() methods for a property which * doesn't exist will result in a IllegalArgumentException being thrown.

      * * @version $Id: LazyDynaBean.java 1540504 2013-11-10 18:22:57Z niallp $ * @see LazyDynaClass */ public class LazyDynaBean implements DynaBean, Serializable { /** * Commons Logging */ private transient Log logger = LogFactory.getLog(LazyDynaBean.class); /** BigInteger Zero */ protected static final BigInteger BigInteger_ZERO = new BigInteger("0"); /** BigDecimal Zero */ protected static final BigDecimal BigDecimal_ZERO = new BigDecimal("0"); /** Character Space */ protected static final Character Character_SPACE = new Character(' '); /** Byte Zero */ protected static final Byte Byte_ZERO = new Byte((byte)0); /** Short Zero */ protected static final Short Short_ZERO = new Short((short)0); /** Integer Zero */ protected static final Integer Integer_ZERO = new Integer(0); /** Long Zero */ protected static final Long Long_ZERO = new Long(0); /** Float Zero */ protected static final Float Float_ZERO = new Float((byte)0); /** Double Zero */ protected static final Double Double_ZERO = new Double((byte)0); /** * The MutableDynaClass "base class" that this DynaBean * is associated with. */ protected Map values; /** Map decorator for this DynaBean */ private transient Map mapDecorator; /** * The MutableDynaClass "base class" that this DynaBean * is associated with. */ protected MutableDynaClass dynaClass; // ------------------- Constructors ---------------------------------- /** * Construct a new LazyDynaBean with a LazyDynaClass instance. */ public LazyDynaBean() { this(new LazyDynaClass()); } /** * Construct a new LazyDynaBean with a LazyDynaClass instance. * * @param name Name of this DynaBean class */ public LazyDynaBean(String name) { this(new LazyDynaClass(name)); } /** * Construct a new DynaBean associated with the specified * DynaClass instance - if its not a MutableDynaClass * then a new LazyDynaClass is created and the properties copied. * * @param dynaClass The DynaClass we are associated with */ public LazyDynaBean(DynaClass dynaClass) { values = newMap(); if (dynaClass instanceof MutableDynaClass) { this.dynaClass = (MutableDynaClass)dynaClass; } else { this.dynaClass = new LazyDynaClass(dynaClass.getName(), dynaClass.getDynaProperties()); } } // ------------------- Public Methods ---------------------------------- /** * Return a Map representation of this DynaBean. *

      * This, for example, could be used in JSTL in the following way to access * a DynaBean's fooProperty: *
      • ${myDynaBean.map.fooProperty}
      * * @return a Map representation of this DynaBean */ public Map getMap() { // cache the Map if (mapDecorator == null) { mapDecorator = new DynaBeanPropertyMapDecorator(this); } return mapDecorator; } /** *

      Return the size of an indexed or mapped property.

      * * @param name Name of the property * @return The indexed or mapped property size * @exception IllegalArgumentException if no property name is specified */ public int size(String name) { if (name == null) { throw new IllegalArgumentException("No property name specified"); } Object value = values.get(name); if (value == null) { return 0; } if (value instanceof Map) { return ((Map)value).size(); } if (value instanceof List) { return ((List)value).size(); } if ((value.getClass().isArray())) { return Array.getLength(value); } return 0; } // ------------------- DynaBean Methods ---------------------------------- /** * Does the specified mapped property contain a value for the specified * key value? * * @param name Name of the property to check * @param key Name of the key to check * @return true if the mapped property contains a value for * the specified key, otherwise false * * @exception IllegalArgumentException if no property name is specified */ public boolean contains(String name, String key) { if (name == null) { throw new IllegalArgumentException("No property name specified"); } Object value = values.get(name); if (value == null) { return false; } if (value instanceof Map) { return (((Map) value).containsKey(key)); } return false; } /** *

      Return the value of a simple property with the specified name.

      * *

      N.B. Returns null if there is no property * of the specified name.

      * * @param name Name of the property whose value is to be retrieved. * @return The property's value * @exception IllegalArgumentException if no property name is specified */ public Object get(String name) { if (name == null) { throw new IllegalArgumentException("No property name specified"); } // Value found Object value = values.get(name); if (value != null) { return value; } // Property doesn't exist if (!isDynaProperty(name)) { return null; } // Property doesn't exist value = createProperty(name, dynaClass.getDynaProperty(name).getType()); if (value != null) { set(name, value); } return value; } /** *

      Return the value of an indexed property with the specified name.

      * *

      N.B. Returns null if there is no 'indexed' * property of the specified name.

      * * @param name Name of the property whose value is to be retrieved * @param index Index of the value to be retrieved * @return The indexed property's value * * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property */ public Object get(String name, int index) { // If its not a property, then create default indexed property if (!isDynaProperty(name)) { set(name, defaultIndexedProperty(name)); } // Get the indexed property Object indexedProperty = get(name); // Check that the property is indexed if (!dynaClass.getDynaProperty(name).isIndexed()) { throw new IllegalArgumentException ("Non-indexed property for '" + name + "[" + index + "]' " + dynaClass.getDynaProperty(name).getName()); } // Grow indexed property to appropriate size indexedProperty = growIndexedProperty(name, indexedProperty, index); // Return the indexed value if (indexedProperty.getClass().isArray()) { return Array.get(indexedProperty, index); } else if (indexedProperty instanceof List) { return ((List)indexedProperty).get(index); } else { throw new IllegalArgumentException ("Non-indexed property for '" + name + "[" + index + "]' " + indexedProperty.getClass().getName()); } } /** *

      Return the value of a mapped property with the specified name.

      * *

      N.B. Returns null if there is no 'mapped' * property of the specified name.

      * * @param name Name of the property whose value is to be retrieved * @param key Key of the value to be retrieved * @return The mapped property's value * * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public Object get(String name, String key) { // If its not a property, then create default mapped property if (!isDynaProperty(name)) { set(name, defaultMappedProperty(name)); } // Get the mapped property Object mappedProperty = get(name); // Check that the property is mapped if (!dynaClass.getDynaProperty(name).isMapped()) { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")' " + dynaClass.getDynaProperty(name).getType().getName()); } // Get the value from the Map if (mappedProperty instanceof Map) { return (((Map) mappedProperty).get(key)); } else { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'" + mappedProperty.getClass().getName()); } } /** * Return the DynaClass instance that describes the set of * properties available for this DynaBean. * * @return The associated DynaClass */ public DynaClass getDynaClass() { return dynaClass; } /** * Remove any existing value for the specified key on the * specified mapped property. * * @param name Name of the property for which a value is to * be removed * @param key Key of the value to be removed * * @exception IllegalArgumentException if there is no property * of the specified name */ public void remove(String name, String key) { if (name == null) { throw new IllegalArgumentException("No property name specified"); } Object value = values.get(name); if (value == null) { return; } if (value instanceof Map) { ((Map) value).remove(key); } else { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'" + value.getClass().getName()); } } /** * Set the value of a simple property with the specified name. * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set * * @exception IllegalArgumentException if this is not an existing property * name for our DynaClass and the MutableDynaClass is restricted * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception NullPointerException if an attempt is made to set a * primitive property to null */ public void set(String name, Object value) { // If the property doesn't exist, then add it if (!isDynaProperty(name)) { if (dynaClass.isRestricted()) { throw new IllegalArgumentException ("Invalid property name '" + name + "' (DynaClass is restricted)"); } if (value == null) { dynaClass.add(name); } else { dynaClass.add(name, value.getClass()); } } DynaProperty descriptor = dynaClass.getDynaProperty(name); if (value == null) { if (descriptor.getType().isPrimitive()) { throw new NullPointerException ("Primitive value for '" + name + "'"); } } else if (!isAssignable(descriptor.getType(), value.getClass())) { throw new ConversionException ("Cannot assign value of type '" + value.getClass().getName() + "' to property '" + name + "' of type '" + descriptor.getType().getName() + "'"); } // Set the property's value values.put(name, value); } /** * Set the value of an indexed property with the specified name. * * @param name Name of the property whose value is to be set * @param index Index of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property */ public void set(String name, int index, Object value) { // If its not a property, then create default indexed property if (!isDynaProperty(name)) { set(name, defaultIndexedProperty(name)); } // Get the indexed property Object indexedProperty = get(name); // Check that the property is indexed if (!dynaClass.getDynaProperty(name).isIndexed()) { throw new IllegalArgumentException ("Non-indexed property for '" + name + "[" + index + "]'" + dynaClass.getDynaProperty(name).getType().getName()); } // Grow indexed property to appropriate size indexedProperty = growIndexedProperty(name, indexedProperty, index); // Set the value in an array if (indexedProperty.getClass().isArray()) { Array.set(indexedProperty, index, value); } else if (indexedProperty instanceof List) { @SuppressWarnings("unchecked") // Indexed properties are stored in a List List values = (List) indexedProperty; values.set(index, value); } else { throw new IllegalArgumentException ("Non-indexed property for '" + name + "[" + index + "]' " + indexedProperty.getClass().getName()); } } /** * Set the value of a mapped property with the specified name. * * @param name Name of the property whose value is to be set * @param key Key of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public void set(String name, String key, Object value) { // If the 'mapped' property doesn't exist, then add it if (!isDynaProperty(name)) { set(name, defaultMappedProperty(name)); } // Get the mapped property Object mappedProperty = get(name); // Check that the property is mapped if (!dynaClass.getDynaProperty(name).isMapped()) { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'" + dynaClass.getDynaProperty(name).getType().getName()); } // Set the value in the Map @SuppressWarnings("unchecked") // mapped properties are stored in a Map Map valuesMap = (Map) mappedProperty; valuesMap.put(key, value); } // ------------------- protected Methods ---------------------------------- /** * Grow the size of an indexed property * @param name The name of the property * @param indexedProperty The current property value * @param index The indexed value to grow the property to (i.e. one less than * the required size) * @return The new property value (grown to the appropriate size) */ protected Object growIndexedProperty(String name, Object indexedProperty, int index) { // Grow a List to the appropriate size if (indexedProperty instanceof List) { @SuppressWarnings("unchecked") // Indexed properties are stored as List List list = (List)indexedProperty; while (index >= list.size()) { Class contentType = getDynaClass().getDynaProperty(name).getContentType(); Object value = null; if (contentType != null) { value = createProperty(name+"["+list.size()+"]", contentType); } list.add(value); } } // Grow an Array to the appropriate size if ((indexedProperty.getClass().isArray())) { int length = Array.getLength(indexedProperty); if (index >= length) { Class componentType = indexedProperty.getClass().getComponentType(); Object newArray = Array.newInstance(componentType, (index + 1)); System.arraycopy(indexedProperty, 0, newArray, 0, length); indexedProperty = newArray; set(name, indexedProperty); int newLength = Array.getLength(indexedProperty); for (int i = length; i < newLength; i++) { Array.set(indexedProperty, i, createProperty(name+"["+i+"]", componentType)); } } } return indexedProperty; } /** * Create a new Instance of a Property * @param name The name of the property * @param type The class of the property * @return The new value */ protected Object createProperty(String name, Class type) { if (type == null) { return null; } // Create Lists, arrays or DynaBeans if (type.isArray() || List.class.isAssignableFrom(type)) { return createIndexedProperty(name, type); } if (Map.class.isAssignableFrom(type)) { return createMappedProperty(name, type); } if (DynaBean.class.isAssignableFrom(type)) { return createDynaBeanProperty(name, type); } if (type.isPrimitive()) { return createPrimitiveProperty(name, type); } if (Number.class.isAssignableFrom(type)) { return createNumberProperty(name, type); } return createOtherProperty(name, type); } /** * Create a new Instance of an 'Indexed' Property * @param name The name of the property * @param type The class of the property * @return The new value */ protected Object createIndexedProperty(String name, Class type) { // Create the indexed object Object indexedProperty = null; if (type == null) { indexedProperty = defaultIndexedProperty(name); } else if (type.isArray()) { indexedProperty = Array.newInstance(type.getComponentType(), 0); } else if (List.class.isAssignableFrom(type)) { if (type.isInterface()) { indexedProperty = defaultIndexedProperty(name); } else { try { indexedProperty = type.newInstance(); } catch (Exception ex) { throw new IllegalArgumentException ("Error instantiating indexed property of type '" + type.getName() + "' for '" + name + "' " + ex); } } } else { throw new IllegalArgumentException ("Non-indexed property of type '" + type.getName() + "' for '" + name + "'"); } return indexedProperty; } /** * Create a new Instance of a 'Mapped' Property * @param name The name of the property * @param type The class of the property * @return The new value */ protected Object createMappedProperty(String name, Class type) { // Create the mapped object Object mappedProperty = null; if (type == null) { mappedProperty = defaultMappedProperty(name); } else if (type.isInterface()) { mappedProperty = defaultMappedProperty(name); } else if (Map.class.isAssignableFrom(type)) { try { mappedProperty = type.newInstance(); } catch (Exception ex) { throw new IllegalArgumentException ("Error instantiating mapped property of type '" + type.getName() + "' for '" + name + "' " + ex); } } else { throw new IllegalArgumentException ("Non-mapped property of type '" + type.getName() + "' for '" + name + "'"); } return mappedProperty; } /** * Create a new Instance of a 'DynaBean' Property. * @param name The name of the property * @param type The class of the property * @return The new value */ protected Object createDynaBeanProperty(String name, Class type) { try { return type.newInstance(); } catch (Exception ex) { if (logger().isWarnEnabled()) { logger().warn("Error instantiating DynaBean property of type '" + type.getName() + "' for '" + name + "' " + ex); } return null; } } /** * Create a new Instance of a 'Primitive' Property. * @param name The name of the property * @param type The class of the property * @return The new value */ protected Object createPrimitiveProperty(String name, Class type) { if (type == Boolean.TYPE) { return Boolean.FALSE; } else if (type == Integer.TYPE) { return Integer_ZERO; } else if (type == Long.TYPE) { return Long_ZERO; } else if (type == Double.TYPE) { return Double_ZERO; } else if (type == Float.TYPE) { return Float_ZERO; } else if (type == Byte.TYPE) { return Byte_ZERO; } else if (type == Short.TYPE) { return Short_ZERO; } else if (type == Character.TYPE) { return Character_SPACE; } else { return null; } } /** * Create a new Instance of a java.lang.Number Property. * @param name The name of the property * @param type The class of the property * @return The new value */ protected Object createNumberProperty(String name, Class type) { return null; } /** * Create a new Instance of other Property types * @param name The name of the property * @param type The class of the property * @return The new value */ protected Object createOtherProperty(String name, Class type) { if (type == Object.class || type == String.class || type == Boolean.class || type == Character.class || Date.class.isAssignableFrom(type)) { return null; } try { return type.newInstance(); } catch (Exception ex) { if (logger().isWarnEnabled()) { logger().warn("Error instantiating property of type '" + type.getName() + "' for '" + name + "' " + ex); } return null; } } /** *

      Creates a new ArrayList for an 'indexed' property * which doesn't exist.

      * *

      This method should be overridden if an alternative List * or Array implementation is required for 'indexed' properties.

      * * @param name Name of the 'indexed property. * @return The default value for an indexed property (java.util.ArrayList) */ protected Object defaultIndexedProperty(String name) { return new ArrayList(); } /** *

      Creates a new HashMap for a 'mapped' property * which doesn't exist.

      * *

      This method can be overridden if an alternative Map * implementation is required for 'mapped' properties.

      * * @param name Name of the 'mapped property. * @return The default value for a mapped property (java.util.HashMap) */ protected Map defaultMappedProperty(String name) { return new HashMap(); } /** * Indicates if there is a property with the specified name. * @param name The name of the property to check * @return true if there is a property of the * specified name, otherwise false */ protected boolean isDynaProperty(String name) { if (name == null) { throw new IllegalArgumentException("No property name specified"); } // Handle LazyDynaClasses if (dynaClass instanceof LazyDynaClass) { return ((LazyDynaClass)dynaClass).isDynaProperty(name); } // Handle other MutableDynaClass return dynaClass.getDynaProperty(name) == null ? false : true; } /** * Is an object of the source class assignable to the destination class? * * @param dest Destination class * @param source Source class * @return true if the source class is assignable to the * destination class, otherwise false */ protected boolean isAssignable(Class dest, Class source) { if (dest.isAssignableFrom(source) || ((dest == Boolean.TYPE) && (source == Boolean.class)) || ((dest == Byte.TYPE) && (source == Byte.class)) || ((dest == Character.TYPE) && (source == Character.class)) || ((dest == Double.TYPE) && (source == Double.class)) || ((dest == Float.TYPE) && (source == Float.class)) || ((dest == Integer.TYPE) && (source == Integer.class)) || ((dest == Long.TYPE) && (source == Long.class)) || ((dest == Short.TYPE) && (source == Short.class))) { return (true); } else { return (false); } } /** *

      Creates a new instance of the Map.

      * @return a new Map instance */ protected Map newMap() { return new HashMap(); } /** *

      Returns the Log. */ private Log logger() { if (logger == null) { logger = LogFactory.getLog(LazyDynaBean.class); } return logger; } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/LazyDynaClass.java100644 0 0 33615 12262570612 26621 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** *

      DynaClass which implements the MutableDynaClass interface.

      * *

      A MutableDynaClass is a specialized extension to DynaClass * that allows properties to be added or removed dynamically.

      * *

      This implementation has one slightly unusual default behaviour - calling * the getDynaProperty(name) method for a property which doesn't * exist returns a DynaProperty rather than null. The * reason for this is that BeanUtils calls this method to check if * a property exists before trying to set the value. This would defeat the object * of the LazyDynaBean which automatically adds missing properties * when any of its set() methods are called. For this reason the * isDynaProperty(name) method has been added to this implementation * in order to determine if a property actually exists. If the more normal * behaviour of returning null is required, then this can be achieved * by calling the setReturnNull(true).

      * *

      The add(name, type, readable, writable) method is not implemented * and always throws an UnsupportedOperationException. I believe * this attributes need to be added to the DynaProperty class * in order to control read/write facilities.

      * * @version $Id: LazyDynaClass.java 1540504 2013-11-10 18:22:57Z niallp $ * @see LazyDynaBean */ public class LazyDynaClass extends BasicDynaClass implements MutableDynaClass { /** * Controls whether changes to this DynaClass's properties are allowed. */ protected boolean restricted; /** *

      Controls whether the getDynaProperty() method returns * null if a property doesn't exist - or creates a new one.

      * *

      Default is false. */ protected boolean returnNull = false; /** * Construct a new LazyDynaClass with default parameters. */ public LazyDynaClass() { this(null, (DynaProperty[])null); } /** * Construct a new LazyDynaClass with the specified name. * * @param name Name of this DynaBean class */ public LazyDynaClass(String name) { this(name, (DynaProperty[])null); } /** * Construct a new LazyDynaClass with the specified name and DynaBean class. * * @param name Name of this DynaBean class * @param dynaBeanClass The implementation class for new instances */ public LazyDynaClass(String name, Class dynaBeanClass) { this(name, dynaBeanClass, null); } /** * Construct a new LazyDynaClass with the specified name and properties. * * @param name Name of this DynaBean class * @param properties Property descriptors for the supported properties */ public LazyDynaClass(String name, DynaProperty[] properties) { this(name, LazyDynaBean.class, properties); } /** * Construct a new LazyDynaClass with the specified name, DynaBean class and properties. * * @param name Name of this DynaBean class * @param dynaBeanClass The implementation class for new instances * @param properties Property descriptors for the supported properties */ public LazyDynaClass(String name, Class dynaBeanClass, DynaProperty properties[]) { super(name, dynaBeanClass, properties); } /** *

      Is this DynaClass currently restricted.

      *

      If restricted, no changes to the existing registration of * property names, data types, readability, or writeability are allowed.

      * @return true if this {@link MutableDynaClass} cannot be changed * otherwise false */ public boolean isRestricted() { return restricted; } /** *

      Set whether this DynaClass is currently restricted.

      *

      If restricted, no changes to the existing registration of * property names, data types, readability, or writeability are allowed.

      * @param restricted true if this {@link MutableDynaClass} cannot * be changed otherwise false */ public void setRestricted(boolean restricted) { this.restricted = restricted; } /** * Should this DynaClass return a null from * the getDynaProperty(name) method if the property * doesn't exist. * * @return true if a null {@link DynaProperty} * should be returned if the property doesn't exist, otherwise * false if a new {@link DynaProperty} should be created. */ public boolean isReturnNull() { return returnNull; } /** * Set whether this DynaClass should return a null from * the getDynaProperty(name) method if the property * doesn't exist. * @param returnNull true if a null {@link DynaProperty} * should be returned if the property doesn't exist, otherwise * false if a new {@link DynaProperty} should be created. */ public void setReturnNull(boolean returnNull) { this.returnNull = returnNull; } /** * Add a new dynamic property with no restrictions on data type, * readability, or writeability. * * @param name Name of the new dynamic property * * @exception IllegalArgumentException if name is null * @exception IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ public void add(String name) { add(new DynaProperty(name)); } /** * Add a new dynamic property with the specified data type, but with * no restrictions on readability or writeability. * * @param name Name of the new dynamic property * @param type Data type of the new dynamic property (null for no * restrictions) * * @exception IllegalArgumentException if name is null * @exception IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ public void add(String name, Class type) { if (type == null) { add(name); } else { add(new DynaProperty(name, type)); } } /** *

      Add a new dynamic property with the specified data type, readability, * and writeability.

      * *

      N.B.Support for readable/writeable properties has not been implemented * and this method always throws a UnsupportedOperationException.

      * *

      I'm not sure the intention of the original authors for this method, but it seems to * me that readable/writable should be attributes of the DynaProperty class * (which they are not) and is the reason this method has not been implemented.

      * * @param name Name of the new dynamic property * @param type Data type of the new dynamic property (null for no * restrictions) * @param readable Set to true if this property value * should be readable * @param writeable Set to true if this property value * should be writeable * * @exception UnsupportedOperationException anytime this method is called */ public void add(String name, Class type, boolean readable, boolean writeable) { throw new java.lang.UnsupportedOperationException("readable/writable properties not supported"); } /** * Add a new dynamic property. * * @param property Property the new dynamic property to add. * * @exception IllegalArgumentException if name is null * @exception IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ protected void add(DynaProperty property) { if (property.getName() == null) { throw new IllegalArgumentException("Property name is missing."); } if (isRestricted()) { throw new IllegalStateException("DynaClass is currently restricted. No new properties can be added."); } // Check if property already exists if (propertiesMap.get(property.getName()) != null) { return; } // Create a new property array with the specified property DynaProperty[] oldProperties = getDynaProperties(); DynaProperty[] newProperties = new DynaProperty[oldProperties.length+1]; System.arraycopy(oldProperties, 0, newProperties, 0, oldProperties.length); newProperties[oldProperties.length] = property; // Update the properties setProperties(newProperties); } /** * Remove the specified dynamic property, and any associated data type, * readability, and writeability, from this dynamic class. * NOTE - This does NOT cause any * corresponding property values to be removed from DynaBean instances * associated with this DynaClass. * * @param name Name of the dynamic property to remove * * @exception IllegalArgumentException if name is null * @exception IllegalStateException if this DynaClass is currently * restricted, so no properties can be removed */ public void remove(String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } if (isRestricted()) { throw new IllegalStateException("DynaClass is currently restricted. No properties can be removed."); } // Ignore if property doesn't exist if (propertiesMap.get(name) == null) { return; } // Create a new property array of without the specified property DynaProperty[] oldProperties = getDynaProperties(); DynaProperty[] newProperties = new DynaProperty[oldProperties.length-1]; int j = 0; for (int i = 0; i < oldProperties.length; i++) { if (!(name.equals(oldProperties[i].getName()))) { newProperties[j] = oldProperties[i]; j++; } } // Update the properties setProperties(newProperties); } /** *

      Return a property descriptor for the specified property.

      * *

      If the property is not found and the returnNull indicator is * true, this method always returns null.

      * *

      If the property is not found and the returnNull indicator is * false a new property descriptor is created and returned (although * its not actually added to the DynaClass's properties). This is the default * beahviour.

      * *

      The reason for not returning a null property descriptor is that * BeanUtils uses this method to check if a property exists * before trying to set it - since these Lazy implementations automatically * add any new properties when they are set, returning null from * this method would defeat their purpose.

      * * @param name Name of the dynamic property for which a descriptor * is requested * @return The dyna property for the specified name * * @exception IllegalArgumentException if no property name is specified */ @Override public DynaProperty getDynaProperty(String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } DynaProperty dynaProperty = propertiesMap.get(name); // If it doesn't exist and returnNull is false // create a new DynaProperty if (dynaProperty == null && !isReturnNull() && !isRestricted()) { dynaProperty = new DynaProperty(name); } return dynaProperty; } /** *

      Indicate whether a property actually exists.

      * *

      N.B. Using getDynaProperty(name) == null * doesn't work in this implementation because that method might * return a DynaProperty if it doesn't exist (depending on the * returnNull indicator).

      * * @param name The name of the property to check * @return true if there is a property of the * specified name, otherwise false * @exception IllegalArgumentException if no property name is specified */ public boolean isDynaProperty(String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } return propertiesMap.get(name) == null ? false : true; } }commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/LazyDynaList.java100644 0 0 56142 12262570612 26467 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Map; /** *

      Lazy DynaBean List.

      * *

      There are two main purposes for this class:

      *
        *
      • To provide Lazy List behaviour - automatically * growing and populating the List * with either DynaBean, java.util.Map * or POJO Beans.
      • *
      • To provide a straight forward way of putting a Collection * or Array into the lazy list and a straight forward * way to get it out again at the end.
      • *
      * *

      All elements added to the List are stored as DynaBean's:

      *
        *
      • java.util.Map elements are "wrapped" in a LazyDynaMap. *
      • POJO Bean elements are "wrapped" in a WrapDynaBean. *
      • DynaBean's are stored un-changed. *
      * *

      toArray()

      *

      The toArray() method returns an array of the * elements of the appropriate type. If the LazyDynaList * is populated with java.util.Map objects a * Map[] array is returned. * If the list is populated with POJO Beans an appropriate * array of the POJO Beans is returned. Otherwise a DynaBean[] * array is returned. *

      * *

      toDynaBeanArray()

      *

      The toDynaBeanArray() method returns a * DynaBean[] array of the elements in the List. *

      * *

      N.B.All the elements in the List must be the * same type. If the DynaClass or Class * of the LazyDynaList's elements is * not specified, then it will be automatically set to the type * of the first element populated. *

      * *

      Example 1

      *

      If you have an array of java.util.Map[] - you can put that into * a LazyDynaList.

      * *
      
       *    TreeMap[] myArray = .... // your Map[]
       *    List lazyList = new LazyDynaList(myArray);
       * 
      * *

      New elements of the appropriate Map type are * automatically populated:

      * *
      
       *    // get(index) automatically grows the list
       *    DynaBean newElement = (DynaBean)lazyList.get(lazyList.size());
       *    newElement.put("someProperty", "someValue");
       * 
      * *

      Once you've finished you can get back an Array of the * elements of the appropriate type:

      * *
      
       *    // Retrieve the array from the list
       *    TreeMap[] myArray = (TreeMap[])lazyList.toArray());
       * 
      * * *

      Example 2

      *

      Alternatively you can create an empty List and * specify the Class for List's elements. The LazyDynaList * uses the Class to automatically populate elements:

      * *
      
       *    // e.g. For Maps
       *    List lazyList = new LazyDynaList(TreeMap.class);
       *
       *    // e.g. For POJO Beans
       *    List lazyList = new LazyDynaList(MyPojo.class);
       *
       *    // e.g. For DynaBeans
       *    List lazyList = new LazyDynaList(MyDynaBean.class);
       * 
      * *

      Example 3

      *

      Alternatively you can create an empty List and specify the * DynaClass for List's elements. The LazyDynaList uses * the DynaClass to automatically populate elements:

      * *
      
       *    // e.g. For Maps
       *    DynaClass dynaClass = new LazyDynaMap(new HashMap());
       *    List lazyList = new LazyDynaList(dynaClass);
       *
       *    // e.g. For POJO Beans
       *    DynaClass dynaClass = (new WrapDynaBean(myPojo)).getDynaClass();
       *    List lazyList = new LazyDynaList(dynaClass);
       *
       *    // e.g. For DynaBeans
       *    DynaClass dynaClass = new BasicDynaClass(properties);
       *    List lazyList = new LazyDynaList(dynaClass);
       * 
      * *

      N.B. You may wonder why control the type * using a DynaClass rather than the Class * as in the previous example - the reason is that some DynaBean * implementations don't have a default empty constructor and * therefore need to be instantiated using the DynaClass.newInstance() * method.

      * *

      Example 4

      *

      A slight variation - set the element type using either * the setElementType(Class) method or the * setElementDynaClass(DynaClass) method - then populate * with the normal java.util.List methods(i.e. * add(), addAll() or set()).

      * *
      
       *    // Create a new LazyDynaList (100 element capacity)
       *    LazyDynaList lazyList = new LazyDynaList(100);
       *
       *    // Either Set the element type...
       *    lazyList.setElementType(TreeMap.class);
       *
       *    // ...or the element DynaClass...
       *    lazyList.setElementDynaClass(new MyCustomDynaClass());
       *
       *    // Populate from a collection
       *    lazyList.addAll(myCollection);
       *
       * 
      * * @version $Id: LazyDynaList.java 1540186 2013-11-08 21:08:30Z oheger $ * @since 1.8.0 */ public class LazyDynaList extends ArrayList { /** * The DynaClass of the List's elements. */ private DynaClass elementDynaClass; /** * The WrapDynaClass if the List's contains * POJO Bean elements. * * N.B. WrapDynaClass isn't serlializable, which * is why its stored separately in a * transient instance variable. */ private transient WrapDynaClass wrapDynaClass; /** * The type of the List's elements. */ private Class elementType; /** * The DynaBean type of the List's elements. */ private Class elementDynaBeanType; // ------------------- Constructors ------------------------------ /** * Default Constructor. */ public LazyDynaList() { super(); } /** * Construct a LazyDynaList with the * specified capacity. * * @param capacity The initial capacity of the list. */ public LazyDynaList(int capacity) { super(capacity); } /** * Construct a LazyDynaList with a * specified DynaClass for its elements. * * @param elementDynaClass The DynaClass of the List's elements. */ public LazyDynaList(DynaClass elementDynaClass) { super(); setElementDynaClass(elementDynaClass); } /** * Construct a LazyDynaList with a * specified type for its elements. * * @param elementType The Type of the List's elements. */ public LazyDynaList(Class elementType) { super(); setElementType(elementType); } /** * Construct a LazyDynaList populated with the * elements of a Collection. * * @param collection The Collection to populate the List from. */ public LazyDynaList(Collection collection) { super(collection.size()); addAll(collection); } /** * Construct a LazyDynaList populated with the * elements of an Array. * * @param array The Array to populate the List from. */ public LazyDynaList(Object[] array) { super(array.length); for (int i = 0; i < array.length; i++) { add(array[i]); } } // ------------------- java.util.List Methods -------------------- /** *

      Insert an element at the specified index position.

      * *

      If the index position is greater than the current * size of the List, then the List is automatically * grown to the appropriate size.

      * * @param index The index position to insert the new element. * @param element The new element to add. */ @Override public void add(int index, Object element) { DynaBean dynaBean = transform(element); growList(index); super.add(index, dynaBean); } /** *

      Add an element to the List.

      * * @param element The new element to add. * @return true. */ @Override public boolean add(Object element) { DynaBean dynaBean = transform(element); return super.add(dynaBean); } /** *

      Add all the elements from a Collection to the list. * * @param collection The Collection of new elements. * @return true if elements were added. */ @Override public boolean addAll(Collection collection) { if (collection == null || collection.size() == 0) { return false; } ensureCapacity(size() + collection.size()); for (Object e : collection) { add(e); } return true; } /** *

      Insert all the elements from a Collection into the * list at a specified position. * *

      If the index position is greater than the current * size of the List, then the List is automatically * grown to the appropriate size.

      * * @param collection The Collection of new elements. * @param index The index position to insert the new elements at. * @return true if elements were added. */ @Override public boolean addAll(int index, Collection collection) { if (collection == null || collection.size() == 0) { return false; } ensureCapacity((index > size() ? index : size()) + collection.size()); // Call "transform" with first element, before // List is "grown" to ensure the correct DynaClass // is set. if (size() == 0) { transform(collection.iterator().next()); } growList(index); int currentIndex = index; for (Object e : collection) { add(currentIndex++, e); } return true; } /** *

      Return the element at the specified position.

      * *

      If the position requested is greater than the current * size of the List, then the List is automatically * grown (and populated) to the appropriate size.

      * * @param index The index position to insert the new elements at. * @return The element at the specified position. */ @Override public Object get(int index) { growList(index + 1); return super.get(index); } /** *

      Set the element at the specified position.

      * *

      If the position requested is greater than the current * size of the List, then the List is automatically * grown (and populated) to the appropriate size.

      * * @param index The index position to insert the new element at. * @param element The new element. * @return The new element. */ @Override public Object set(int index, Object element) { DynaBean dynaBean = transform(element); growList(index + 1); return super.set(index, dynaBean); } /** *

      Converts the List to an Array.

      * *

      The type of Array created depends on the contents * of the List:

      *
        *
      • If the List contains only LazyDynaMap type elements * then a java.util.Map[] array will be created.
      • *
      • If the List contains only elements which are * "wrapped" DynaBeans then an Object[] of the most * suitable type will be created.
      • *
      • ...otherwise a DynaBean[] will be created.
      • * * @return An Array of the elements in this List. */ @Override public Object[] toArray() { if (size() == 0 && elementType == null) { return new LazyDynaBean[0]; } Object[] array = (Object[])Array.newInstance(elementType, size()); for (int i = 0; i < size(); i++) { if (Map.class.isAssignableFrom(elementType)) { array[i] = ((LazyDynaMap)get(i)).getMap(); } else if (DynaBean.class.isAssignableFrom(elementType)) { array[i] = get(i); } else { array[i] = ((WrapDynaBean)get(i)).getInstance(); } } return array; } /** *

        Converts the List to an Array of the specified type.

        * * @param The type of the array elements * @param model The model for the type of array to return * @return An Array of the elements in this List. */ @Override public T[] toArray(T[] model) { Class arrayType = model.getClass().getComponentType(); if ((DynaBean.class.isAssignableFrom(arrayType)) || (size() == 0 && elementType == null)) { return super.toArray(model); } if ((arrayType.isAssignableFrom(elementType))) { T[] array; if (model.length >= size()) { array = model; } else { @SuppressWarnings("unchecked") // This is safe because we know the element type T[] tempArray = (T[]) Array.newInstance(arrayType, size()); array = tempArray; } for (int i = 0; i < size(); i++) { Object elem; if (Map.class.isAssignableFrom(elementType)) { elem = ((LazyDynaMap) get(i)).getMap(); } else if (DynaBean.class.isAssignableFrom(elementType)) { elem = get(i); } else { elem = ((WrapDynaBean) get(i)).getInstance(); } Array.set(array, i, elem); } return array; } throw new IllegalArgumentException("Invalid array type: " + arrayType.getName() + " - not compatible with '" + elementType.getName()); } // ------------------- Public Methods ---------------------------- /** *

        Converts the List to an DynaBean Array.

        * * @return A DynaBean[] of the elements in this List. */ public DynaBean[] toDynaBeanArray() { if (size() == 0 && elementDynaBeanType == null) { return new LazyDynaBean[0]; } DynaBean[] array = (DynaBean[])Array.newInstance(elementDynaBeanType, size()); for (int i = 0; i < size(); i++) { array[i] = (DynaBean)get(i); } return array; } /** *

        Set the element Type and DynaClass.

        * * @param elementType The type of the elements. * @exception IllegalArgumentException if the List already * contains elements or the DynaClass is null. */ public void setElementType(Class elementType) { if (elementType == null) { throw new IllegalArgumentException("Element Type is missing"); } boolean changeType = (this.elementType != null && !this.elementType.equals(elementType)); if (changeType && size() > 0) { throw new IllegalStateException("Element Type cannot be reset"); } this.elementType = elementType; // Create a new object of the specified type Object object = null; try { object = elementType.newInstance(); } catch (Exception e) { throw new IllegalArgumentException("Error creating type: " + elementType.getName() + " - " + e); } // Create a DynaBean DynaBean dynaBean = null; if (Map.class.isAssignableFrom(elementType)) { dynaBean = createDynaBeanForMapProperty(object); this.elementDynaClass = dynaBean.getDynaClass(); } else if (DynaBean.class.isAssignableFrom(elementType)) { dynaBean = (DynaBean)object; this.elementDynaClass = dynaBean.getDynaClass(); } else { dynaBean = new WrapDynaBean(object); this.wrapDynaClass = (WrapDynaClass)dynaBean.getDynaClass(); } this.elementDynaBeanType = dynaBean.getClass(); // Re-calculate the type if (WrapDynaBean.class.isAssignableFrom(elementDynaBeanType )) { this.elementType = ((WrapDynaBean)dynaBean).getInstance().getClass(); } else if (LazyDynaMap.class.isAssignableFrom(elementDynaBeanType )) { this.elementType = ((LazyDynaMap)dynaBean).getMap().getClass(); } } /** *

        Set the element Type and DynaClass.

        * * @param elementDynaClass The DynaClass of the elements. * @exception IllegalArgumentException if the List already * contains elements or the DynaClass is null. */ public void setElementDynaClass(DynaClass elementDynaClass) { if (elementDynaClass == null) { throw new IllegalArgumentException("Element DynaClass is missing"); } if (size() > 0) { throw new IllegalStateException("Element DynaClass cannot be reset"); } // Try to create a new instance of the DynaBean try { DynaBean dynaBean = elementDynaClass.newInstance(); this.elementDynaBeanType = dynaBean.getClass(); if (WrapDynaBean.class.isAssignableFrom(elementDynaBeanType)) { this.elementType = ((WrapDynaBean)dynaBean).getInstance().getClass(); this.wrapDynaClass = (WrapDynaClass)elementDynaClass; } else if (LazyDynaMap.class.isAssignableFrom(elementDynaBeanType)) { this.elementType = ((LazyDynaMap)dynaBean).getMap().getClass(); this.elementDynaClass = elementDynaClass; } else { this.elementType = dynaBean.getClass(); this.elementDynaClass = elementDynaClass; } } catch (Exception e) { throw new IllegalArgumentException( "Error creating DynaBean from " + elementDynaClass.getClass().getName() + " - " + e); } } // ------------------- Private Methods --------------------------- /** *

        Automatically grown the List * to the appropriate size, populating with * DynaBeans.

        * * @param requiredSize the required size of the List. */ private void growList(int requiredSize) { if (requiredSize < size()) { return; } ensureCapacity(requiredSize + 1); for (int i = size(); i < requiredSize; i++) { DynaBean dynaBean = transform(null); super.add(dynaBean); } } /** *

        Transform the element into a DynaBean:

        * *
          *
        • Map elements are turned into LazyDynaMap's.
        • *
        • POJO Beans are "wrapped" in a WrapDynaBean.
        • *
        • DynaBeans are unchanged.
        • * * * @param element The element to transformed. * @param The DynaBean to store in the List. */ private DynaBean transform(Object element) { DynaBean dynaBean = null; Class newDynaBeanType = null; Class newElementType = null; // Create a new element if (element == null) { // Default Types to LazyDynaBean // if not specified if (elementType == null) { setElementDynaClass(new LazyDynaClass()); } // Get DynaClass (restore WrapDynaClass lost in serialization) if (getDynaClass() == null) { setElementType(elementType); } // Create a new DynaBean try { dynaBean = getDynaClass().newInstance(); newDynaBeanType = dynaBean.getClass(); } catch (Exception e) { throw new IllegalArgumentException("Error creating DynaBean: " + getDynaClass().getClass().getName() + " - " + e); } } else { // Transform Object to a DynaBean newElementType = element.getClass(); if (Map.class.isAssignableFrom(element.getClass())) { dynaBean = createDynaBeanForMapProperty(element); } else if (DynaBean.class.isAssignableFrom(element.getClass())) { dynaBean = (DynaBean)element; } else { dynaBean = new WrapDynaBean(element); } newDynaBeanType = dynaBean.getClass(); } // Re-calculate the element type newElementType = dynaBean.getClass(); if (WrapDynaBean.class.isAssignableFrom(newDynaBeanType)) { newElementType = ((WrapDynaBean)dynaBean).getInstance().getClass(); } else if (LazyDynaMap.class.isAssignableFrom(newDynaBeanType)) { newElementType = ((LazyDynaMap)dynaBean).getMap().getClass(); } // Check the new element type, matches all the // other elements in the List if (elementType != null && !newElementType.equals(elementType)) { throw new IllegalArgumentException("Element Type " + newElementType + " doesn't match other elements " + elementType); } return dynaBean; } /** * Creates a new {@code LazyDynaMap} object for the given property value. * * @param value the property value * @return the newly created {@code LazyDynaMap} */ private LazyDynaMap createDynaBeanForMapProperty(Object value) { @SuppressWarnings("unchecked") // map properties are always stored as Map Map valueMap = (Map) value; return new LazyDynaMap(valueMap); } /** * Return the DynaClass. */ private DynaClass getDynaClass() { return (elementDynaClass == null ? wrapDynaClass : elementDynaClass); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/LazyDynaMap.java100644 0 0 42403 12262570612 26264 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.Map; /** *

          Provides a light weight DynaBean facade to a Map * with lazy map/list processing.

          * *

          Its a light weight DynaBean implementation because there is no * actual DynaClass associated with this DynaBean - in fact * it implements the DynaClass interface itself providing pseudo DynaClass * behaviour from the actual values stored in the Map.

          * *

          As well providing rhe standard DynaBean access to the Map's properties * this class also provides the usual Lazy behaviour:

          *
            *
          • Properties don't need to be pre-defined in a DynaClass
          • *
          • Indexed properties (Lists or Arrays) are automatically instantiated * and grown so that they are large enough to cater for the index being set.
          • *
          • Mapped properties are automatically instantiated.
          • *
          * *

          Restricted DynaClass

          *

          This class implements the MutableDynaClass interface. * MutableDynaClass have a facility to restrict the DynaClass * so that its properties cannot be modified. If the MutableDynaClass is * restricted then calling any of the set() methods for a property which * doesn't exist will result in a IllegalArgumentException being thrown.

          * * @version $Id: LazyDynaMap.java 1540509 2013-11-10 18:39:11Z oheger $ */ public class LazyDynaMap extends LazyDynaBean implements MutableDynaClass { /** * The name of this DynaClass (analogous to the * getName() method of java.lang.Class). */ protected String name; /** * Controls whether changes to this DynaClass's properties are allowed. */ protected boolean restricted; /** *

          Controls whether the getDynaProperty() method returns * null if a property doesn't exist - or creates a new one.

          * *

          Default is false. */ protected boolean returnNull = false; // ------------------- Constructors ---------------------------------- /** * Default Constructor. */ public LazyDynaMap() { this(null, (Map)null); } /** * Construct a new LazyDynaMap with the specified name. * * @param name Name of this DynaBean class */ public LazyDynaMap(String name) { this(name, (Map)null); } /** * Construct a new LazyDynaMap with the specified Map. * * @param values The Map backing this LazyDynaMap */ public LazyDynaMap(Map values) { this(null, values); } /** * Construct a new LazyDynaMap with the specified name and Map. * * @param name Name of this DynaBean class * @param values The Map backing this LazyDynaMap */ public LazyDynaMap(String name, Map values) { this.name = name == null ? "LazyDynaMap" : name; this.values = values == null ? newMap() : values; this.dynaClass = this; } /** * Construct a new LazyDynaMap with the specified properties. * * @param properties Property descriptors for the supported properties */ public LazyDynaMap(DynaProperty[] properties) { this(null, properties); } /** * Construct a new LazyDynaMap with the specified name and properties. * * @param name Name of this DynaBean class * @param properties Property descriptors for the supported properties */ public LazyDynaMap(String name, DynaProperty[] properties) { this(name, (Map)null); if (properties != null) { for (int i = 0; i < properties.length; i++) { add(properties[i]); } } } /** * Construct a new LazyDynaMap based on an exisiting DynaClass * * @param dynaClass DynaClass to copy the name and properties from */ public LazyDynaMap(DynaClass dynaClass) { this(dynaClass.getName(), dynaClass.getDynaProperties()); } // ------------------- Public Methods ---------------------------------- /** * Set the Map backing this DynaBean * * @param values The new Map of values */ public void setMap(Map values) { this.values = values; } /** * Return the underlying Map backing this DynaBean * @return the underlying Map * @since 1.8.0 */ @Override public Map getMap() { return values; } // ------------------- DynaBean Methods ---------------------------------- /** * Set the value of a simple property with the specified name. * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set */ @Override public void set(String name, Object value) { if (isRestricted() && !values.containsKey(name)) { throw new IllegalArgumentException ("Invalid property name '" + name + "' (DynaClass is restricted)"); } values.put(name, value); } // ------------------- DynaClass Methods ---------------------------------- /** * Return the name of this DynaClass (analogous to the * getName() method of java.lang.Class) * * @return the name of the DynaClass */ public String getName() { return this.name; } /** *

          Return a property descriptor for the specified property.

          * *

          If the property is not found and the returnNull indicator is * true, this method always returns null.

          * *

          If the property is not found and the returnNull indicator is * false a new property descriptor is created and returned (although * its not actually added to the DynaClass's properties). This is the default * beahviour.

          * *

          The reason for not returning a null property descriptor is that * BeanUtils uses this method to check if a property exists * before trying to set it - since these Map implementations automatically * add any new properties when they are set, returning null from * this method would defeat their purpose.

          * * @param name Name of the dynamic property for which a descriptor * is requested * @return The descriptor for the specified property * * @exception IllegalArgumentException if no property name is specified */ public DynaProperty getDynaProperty(String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } // If it doesn't exist and returnNull is false // create a new DynaProperty if (!values.containsKey(name) && isReturnNull()) { return null; } Object value = values.get(name); if (value == null) { return new DynaProperty(name); } else { return new DynaProperty(name, value.getClass()); } } /** *

          Return an array of ProperyDescriptors for the properties * currently defined in this DynaClass. If no properties are defined, a * zero-length array will be returned.

          * *

          FIXME - Should we really be implementing * getBeanInfo() instead, which returns property descriptors * and a bunch of other stuff?

          * @return the set of properties for this DynaClass */ public DynaProperty[] getDynaProperties() { int i = 0; DynaProperty[] properties = new DynaProperty[values.size()]; for (Map.Entry e : values.entrySet()) { String name = e.getKey(); Object value = values.get(name); properties[i++] = new DynaProperty(name, value == null ? null : value.getClass()); } return properties; } /** * Instantiate and return a new DynaBean instance, associated * with this DynaClass. * @return A new DynaBean instance */ public DynaBean newInstance() { // Create a new instance of the Map Map newMap = null; try { @SuppressWarnings("unchecked") // The new map is used as properties map Map temp = getMap().getClass().newInstance(); newMap = temp; } catch(Exception ex) { newMap = newMap(); } // Crate new LazyDynaMap and initialize properties LazyDynaMap lazyMap = new LazyDynaMap(newMap); DynaProperty[] properties = this.getDynaProperties(); if (properties != null) { for (int i = 0; i < properties.length; i++) { lazyMap.add(properties[i]); } } return lazyMap; } // ------------------- MutableDynaClass Methods ---------------------------------- /** *

          Is this DynaClass currently restricted.

          *

          If restricted, no changes to the existing registration of * property names, data types, readability, or writeability are allowed.

          * * @return true if this Mutable {@link DynaClass} is restricted, * otherwise false */ public boolean isRestricted() { return restricted; } /** *

          Set whether this DynaClass is currently restricted.

          *

          If restricted, no changes to the existing registration of * property names, data types, readability, or writeability are allowed.

          * * @param restricted The new restricted state */ public void setRestricted(boolean restricted) { this.restricted = restricted; } /** * Add a new dynamic property with no restrictions on data type, * readability, or writeability. * * @param name Name of the new dynamic property * * @exception IllegalArgumentException if name is null */ public void add(String name) { add(name, null); } /** * Add a new dynamic property with the specified data type, but with * no restrictions on readability or writeability. * * @param name Name of the new dynamic property * @param type Data type of the new dynamic property (null for no * restrictions) * * @exception IllegalArgumentException if name is null * @exception IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ public void add(String name, Class type) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } if (isRestricted()) { throw new IllegalStateException("DynaClass is currently restricted. No new properties can be added."); } Object value = values.get(name); // Check if the property already exists if (value == null) { values.put(name, type == null ? null : createProperty(name, type)); } } /** *

          Add a new dynamic property with the specified data type, readability, * and writeability.

          * *

          N.B.Support for readable/writeable properties has not been implemented * and this method always throws a UnsupportedOperationException.

          * *

          I'm not sure the intention of the original authors for this method, but it seems to * me that readable/writable should be attributes of the DynaProperty class * (which they are not) and is the reason this method has not been implemented.

          * * @param name Name of the new dynamic property * @param type Data type of the new dynamic property (null for no * restrictions) * @param readable Set to true if this property value * should be readable * @param writeable Set to true if this property value * should be writeable * * @exception UnsupportedOperationException anytime this method is called */ public void add(String name, Class type, boolean readable, boolean writeable) { throw new java.lang.UnsupportedOperationException("readable/writable properties not supported"); } /** * Add a new dynamic property. * * @param property Property the new dynamic property to add. * * @exception IllegalArgumentException if name is null */ protected void add(DynaProperty property) { add(property.getName(), property.getType()); } /** * Remove the specified dynamic property, and any associated data type, * readability, and writeability, from this dynamic class. * NOTE - This does NOT cause any * corresponding property values to be removed from DynaBean instances * associated with this DynaClass. * * @param name Name of the dynamic property to remove * * @exception IllegalArgumentException if name is null * @exception IllegalStateException if this DynaClass is currently * restricted, so no properties can be removed */ public void remove(String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } if (isRestricted()) { throw new IllegalStateException("DynaClass is currently restricted. No properties can be removed."); } // Remove, if property doesn't exist if (values.containsKey(name)) { values.remove(name); } } // ------------------- Additional Public Methods ---------------------------------- /** * Should this DynaClass return a null from * the getDynaProperty(name) method if the property * doesn't exist. * * @return true if a null {@link DynaProperty} * should be returned if the property doesn't exist, otherwise * false if a new {@link DynaProperty} should be created. */ public boolean isReturnNull() { return returnNull; } /** * Set whether this DynaClass should return a null from * the getDynaProperty(name) method if the property * doesn't exist. * * @param returnNull true if a null {@link DynaProperty} * should be returned if the property doesn't exist, otherwise * false if a new {@link DynaProperty} should be created. */ public void setReturnNull(boolean returnNull) { this.returnNull = returnNull; } // ------------------- Protected Methods ---------------------------------- /** *

          Indicate whether a property actually exists.

          * *

          N.B. Using getDynaProperty(name) == null * doesn't work in this implementation because that method might * return a DynaProperty if it doesn't exist (depending on the * returnNull indicator).

          * * @param name Name of the dynamic property * @return true if the property exists, * otherwise false * @exception IllegalArgumentException if no property name is specified */ @Override protected boolean isDynaProperty(String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } return values.containsKey(name); } }././@LongLink100644 0 0 147 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/BaseLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/BaseLocaleConverter.ja100644 0 0 25513 12262570611 30667 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale; import java.text.ParseException; import java.util.Locale; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

          The base class for all standart type locale-sensitive converters. * It has {@link LocaleConverter} and {@link org.apache.commons.beanutils.Converter} implementations, * that convert an incoming locale-sensitive Object into an object of correspond type, * optionally using a default value or throwing a {@link ConversionException} * if a conversion error occurs.

          * * @version $Id: BaseLocaleConverter.java 1540186 2013-11-08 21:08:30Z oheger $ */ public abstract class BaseLocaleConverter implements LocaleConverter { // ----------------------------------------------------- Instance Variables /** All logging goes through this logger */ private final Log log = LogFactory.getLog(BaseLocaleConverter.class); /** The default value specified to our Constructor, if any. */ private Object defaultValue = null; /** Should we return the default value on conversion errors? */ protected boolean useDefault = false; /** The locale specified to our Constructor, by default - system locale. */ protected Locale locale = Locale.getDefault(); /** The default pattern specified to our Constructor, if any. */ protected String pattern = null; /** The flag indicating whether the given pattern string is localized or not. */ protected boolean locPattern = false; // ----------------------------------------------------------- Constructors /** * Create a {@link LocaleConverter} that will throw a {@link ConversionException} * if a conversion error occurs. * An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ protected BaseLocaleConverter(Locale locale, String pattern) { this(null, locale, pattern, false, false); } /** * Create a {@link LocaleConverter} that will throw a {@link ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ protected BaseLocaleConverter(Locale locale, String pattern, boolean locPattern) { this(null, locale, pattern, false, locPattern); } /** * Create a {@link LocaleConverter} that will return the specified default value * if a conversion error occurs. * An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ protected BaseLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link LocaleConverter} that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ protected BaseLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { this(defaultValue, locale, pattern, true, locPattern); } /** * Create a {@link LocaleConverter} that will return the specified default value * or throw a {@link ConversionException} if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param useDefault Indicate whether the default value is used or not * @param locPattern Indicate whether the pattern is localized or not */ private BaseLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean useDefault, boolean locPattern) { if (useDefault) { this.defaultValue = defaultValue; this.useDefault = true; } if (locale != null) { this.locale = locale; } this.pattern = pattern; this.locPattern = locPattern; } // --------------------------------------------------------- Methods /** * Convert the specified locale-sensitive input object into an output object of the * specified type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception ParseException if conversion cannot be performed * successfully */ abstract protected Object parse(Object value, String pattern) throws ParseException; /** * Convert the specified locale-sensitive input object into an output object. * The default pattern is used for the conversion. * * @param value The input object to be converted * @return The converted value * * @exception ConversionException if conversion cannot be performed * successfully */ public Object convert(Object value) { return convert(value, null); } /** * Convert the specified locale-sensitive input object into an output object. * * @param value The input object to be converted * @param pattern The pattern is used for the conversion * @return The converted value * * @exception ConversionException if conversion cannot be performed * successfully */ public Object convert(Object value, String pattern) { return convert(null, value, pattern); } /** * Convert the specified locale-sensitive input object into an output object of the * specified type. The default pattern is used for the convertion. * * @param The desired target type of the conversion * @param type Data type to which this value should be converted * @param value The input object to be converted * @return The converted value * * @exception ConversionException if conversion cannot be performed * successfully */ public T convert(Class type, Object value) { return convert(type, value, null); } /** * Convert the specified locale-sensitive input object into an output object of the * specified type. * * @param The desired target type of the conversion * @param type Data is type to which this value should be converted * @param value is the input object to be converted * @param pattern is the pattern is used for the conversion; if null is * passed then the default pattern associated with the converter object * will be used. * @return The converted value * * @exception ConversionException if conversion cannot be performed * successfully */ public T convert(Class type, Object value, String pattern) { Class targetType = ConvertUtils.primitiveToWrapper(type); if (value == null) { if (useDefault) { return getDefaultAs(targetType); } else { // symmetric beanutils function allows null // so do not: throw new ConversionException("No value specified"); log.debug("Null value specified for conversion, returing null"); return null; } } try { if (pattern != null) { return checkConversionResult(targetType, parse(value, pattern)); } else { return checkConversionResult(targetType, parse(value, this.pattern)); } } catch (Exception e) { if (useDefault) { return getDefaultAs(targetType); } else { if (e instanceof ConversionException) { throw (ConversionException)e; } throw new ConversionException(e); } } } /** * Returns the default object specified for this converter cast for the * given target type. If the default value is not conform to the given type, * an exception is thrown. * * @param the desired target type * @param type the target class of the conversion * @return the default value in the given target type * @throws ConversionException if the default object is not compatible with * the target type */ private T getDefaultAs(Class type) { return checkConversionResult(type, defaultValue); } /** * Checks whether the result of a conversion is conform to the specified * target type. If this is the case, the passed in result object is cast to * the correct target type. Otherwise, an exception is thrown. * * @param the desired result type * @param type the target class of the conversion * @param result the conversion result object * @return the result cast to the target class * @throws ConversionException if the result object is not compatible with * the target type */ private static T checkConversionResult(Class type, Object result) { if (type == null) { // in this case we cannot do much; the result object is returned @SuppressWarnings("unchecked") T temp = (T) result; return temp; } if (type.isInstance(result)) { return type.cast(result); } throw new ConversionException("Unsupported target type: " + type); } } ././@LongLink100644 0 0 170 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/BigDecimalLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/BigDecimalL100644 0 0 21116 12262570611 30675 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.util.Locale; import java.math.BigDecimal; import java.text.ParseException; import org.apache.commons.beanutils.ConversionException; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.math.BigDecimal object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: BigDecimalLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class BigDecimalLocaleConverter extends DecimalLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public BigDecimalLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public BigDecimalLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public BigDecimalLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public BigDecimalLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public BigDecimalLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public BigDecimalLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public BigDecimalLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public BigDecimalLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public BigDecimalLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public BigDecimalLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public BigDecimalLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public BigDecimalLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } /** * Convert the specified locale-sensitive input object into an output object of * BigDecimal type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number * @since 1.8.0 */ @Override protected Object parse(Object value, String pattern) throws ParseException { Object result = super.parse(value, pattern); if (result == null || result instanceof BigDecimal) { return result; } try { return new BigDecimal(result.toString()); } catch (NumberFormatException ex) { throw new ConversionException("Suplied number is not of type BigDecimal: " + result); } } } ././@LongLink100644 0 0 170 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/BigIntegerLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/BigIntegerL100644 0 0 21314 12262570612 30735 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.util.Locale; import java.math.BigInteger; import java.text.ParseException; import org.apache.commons.beanutils.ConversionException; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.math.BigInteger object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: BigIntegerLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class BigIntegerLocaleConverter extends DecimalLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public BigIntegerLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public BigIntegerLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public BigIntegerLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public BigIntegerLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public BigIntegerLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public BigIntegerLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public BigIntegerLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public BigIntegerLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public BigIntegerLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public BigIntegerLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public BigIntegerLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public BigIntegerLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } /** * Convert the specified locale-sensitive input object into an output object of * BigInteger type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number * @since 1.8.0 */ @Override protected Object parse(Object value, String pattern) throws ParseException { Object result = super.parse(value, pattern); if (result == null || result instanceof BigInteger) { return result; } if (result instanceof Number) { return BigInteger.valueOf(((Number)result).longValue()); } try { return new BigInteger(result.toString()); } catch (NumberFormatException ex) { throw new ConversionException("Suplied number is not of type BigInteger: " + result); } } } ././@LongLink100644 0 0 162 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/ByteLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/ByteLocaleC100644 0 0 20711 12262570612 30730 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import org.apache.commons.beanutils.ConversionException; import java.util.Locale; import java.text.ParseException; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.lang.Byte object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: ByteLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class ByteLocaleConverter extends DecimalLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public ByteLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public ByteLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public ByteLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public ByteLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public ByteLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public ByteLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public ByteLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public ByteLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public ByteLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public ByteLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public ByteLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public ByteLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } /** * Convert the specified locale-sensitive input object into an output object of the * specified type. This method will return values of type Byte. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception org.apache.commons.beanutils.ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number */ @Override protected Object parse(Object value, String pattern) throws ParseException { final Number parsed = (Number) super.parse(value, pattern); if (parsed.longValue() != parsed.byteValue()) { throw new ConversionException("Supplied number is not of type Byte: " + parsed.longValue()); } // now returns property Byte return new Byte(parsed.byteValue()); } } ././@LongLink100644 0 0 162 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/DateLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/DateLocaleC100644 0 0 33543 12262570612 30711 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Locale; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.locale.BaseLocaleConverter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.util.Date object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: DateLocaleConverter.java 1546738 2013-11-30 16:24:19Z oheger $ */ public class DateLocaleConverter extends BaseLocaleConverter { // ----------------------------------------------------- Instance Variables /** All logging goes through this logger */ private final Log log = LogFactory.getLog(DateLocaleConverter.class); /** Should the date conversion be lenient? */ boolean isLenient = false; /** * Default Pattern Characters * */ private static final String DEFAULT_PATTERN_CHARS = DateLocaleConverter.initDefaultChars(); // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public DateLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public DateLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public DateLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public DateLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public DateLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public DateLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public DateLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public DateLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public DateLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public DateLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public DateLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public DateLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } // --------------------------------------------------------- Methods /** * Returns whether date formatting is lenient. * * @return true if the DateFormat used for formatting is lenient * @see java.text.DateFormat#isLenient */ public boolean isLenient() { return isLenient; } /** * Specify whether or not date-time parsing should be lenient. * * @param lenient true if the DateFormat used for formatting should be lenient * @see java.text.DateFormat#setLenient */ public void setLenient(boolean lenient) { isLenient = lenient; } // --------------------------------------------------------- Methods /** * Convert the specified locale-sensitive input object into an output object of the * specified type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return the converted Date value * * @exception org.apache.commons.beanutils.ConversionException * if conversion cannot be performed successfully * @throws ParseException if an error occurs parsing */ @Override protected Object parse(Object value, String pattern) throws ParseException { // Handle Date if (value instanceof java.util.Date) { return value; } // Handle Calendar if (value instanceof java.util.Calendar) { return ((java.util.Calendar)value).getTime(); } if (locPattern) { pattern = convertLocalizedPattern(pattern, locale); } // Create Formatter - use default if pattern is null DateFormat formatter = pattern == null ? DateFormat.getDateInstance(DateFormat.SHORT, locale) : new SimpleDateFormat(pattern, locale); formatter.setLenient(isLenient); // Parse the Date ParsePosition pos = new ParsePosition(0); String strValue = value.toString(); Object parsedValue = formatter.parseObject(strValue, pos); if (pos.getErrorIndex() > -1) { throw new ConversionException("Error parsing date '" + value + "' at position="+ pos.getErrorIndex()); } if (pos.getIndex() < strValue.length()) { throw new ConversionException("Date '" + value + "' contains unparsed characters from position=" + pos.getIndex()); } return parsedValue; } /** * Convert a pattern from a localized format to the default format. * * @param locale The locale * @param localizedPattern The pattern in 'local' symbol format * @return pattern in 'default' symbol format */ private String convertLocalizedPattern(String localizedPattern, Locale locale) { if (localizedPattern == null) { return null; } // Note that this is a little obtuse. // However, it is the best way that anyone can come up with // that works with some 1.4 series JVM. // Get the symbols for the localized pattern DateFormatSymbols localizedSymbols = new DateFormatSymbols(locale); String localChars = localizedSymbols.getLocalPatternChars(); if (DEFAULT_PATTERN_CHARS.equals(localChars)) { return localizedPattern; } // Convert the localized pattern to default String convertedPattern = null; try { convertedPattern = convertPattern(localizedPattern, localChars, DEFAULT_PATTERN_CHARS); } catch (Exception ex) { log.debug("Converting pattern '" + localizedPattern + "' for " + locale, ex); } return convertedPattern; } /** *

          Converts a Pattern from one character set to another.

          */ private String convertPattern(String pattern, String fromChars, String toChars) { StringBuilder converted = new StringBuilder(); boolean quoted = false; for (int i = 0; i < pattern.length(); ++i) { char thisChar = pattern.charAt(i); if (quoted) { if (thisChar == '\'') { quoted = false; } } else { if (thisChar == '\'') { quoted = true; } else if ((thisChar >= 'a' && thisChar <= 'z') || (thisChar >= 'A' && thisChar <= 'Z')) { int index = fromChars.indexOf(thisChar ); if (index == -1) { throw new IllegalArgumentException( "Illegal pattern character '" + thisChar + "'"); } thisChar = toChars.charAt(index); } } converted.append(thisChar); } if (quoted) { throw new IllegalArgumentException("Unfinished quote in pattern"); } return converted.toString(); } /** * This method is called at class initialization time to define the * value for constant member DEFAULT_PATTERN_CHARS. All other methods needing * this data should just read that constant. */ private static String initDefaultChars() { DateFormatSymbols defaultSymbols = new DateFormatSymbols(Locale.US); return defaultSymbols.getLocalPatternChars(); } } ././@LongLink100644 0 0 165 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/DecimalLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/DecimalLoca100644 0 0 22663 12262570612 30747 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import org.apache.commons.beanutils.locale.BaseLocaleConverter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.text.DecimalFormat; import java.text.ParseException; import java.util.Locale; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.lang.Number object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @since 1.7 * @version $Id: DecimalLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class DecimalLocaleConverter extends BaseLocaleConverter { // ----------------------------------------------------- Instance Variables /** All logging goes through this logger */ private final Log log = LogFactory.getLog(DecimalLocaleConverter.class); // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public DecimalLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public DecimalLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public DecimalLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public DecimalLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public DecimalLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public DecimalLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public DecimalLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public DecimalLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public DecimalLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public DecimalLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public DecimalLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public DecimalLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } // --------------------------------------------------------- Methods /** * Convert the specified locale-sensitive input object into an output * object of the specified type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception org.apache.commons.beanutils.ConversionException if conversion * cannot be performed successfully * @throws ParseException if an error occurs parsing a String to a Number */ @Override protected Object parse(Object value, String pattern) throws ParseException { if (value instanceof Number) { return value; } // Note that despite the ambiguous "getInstance" name, and despite the // fact that objects returned from this method have the same toString // representation, each call to getInstance actually returns a new // object. DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(locale); // if some constructors default pattern to null, it makes only sense // to handle null pattern gracefully if (pattern != null) { if (locPattern) { formatter.applyLocalizedPattern(pattern); } else { formatter.applyPattern(pattern); } } else { log.debug("No pattern provided, using default."); } return formatter.parse((String) value); } } ././@LongLink100644 0 0 164 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/DoubleLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/DoubleLocal100644 0 0 20473 12262570612 30774 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.text.ParseException; import java.util.Locale; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.lang.Double object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: DoubleLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class DoubleLocaleConverter extends DecimalLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public DoubleLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public DoubleLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public DoubleLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public DoubleLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public DoubleLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public DoubleLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public DoubleLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public DoubleLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public DoubleLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public DoubleLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public DoubleLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public DoubleLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } /** * Convert the specified locale-sensitive input object into an output object of the * specified type. This method will return Double type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @throws org.apache.commons.beanutils.ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number */ @Override protected Object parse(Object value, String pattern) throws ParseException { Number result = (Number) super.parse(value, pattern); if (result instanceof Long) { return new Double(result.doubleValue()); } else { return (result); } } } ././@LongLink100644 0 0 163 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/FloatLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/FloatLocale100644 0 0 21203 12262570612 30764 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import org.apache.commons.beanutils.ConversionException; import java.util.Locale; import java.text.ParseException; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.math.BigDecimal object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: FloatLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class FloatLocaleConverter extends DecimalLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public FloatLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public FloatLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public FloatLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public FloatLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public FloatLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public FloatLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } /** * Convert the specified locale-sensitive input object into an output object of the * specified type. This method will return Float value or throw exception if value * can not be stored in the Float. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number */ @Override protected Object parse(Object value, String pattern) throws ParseException { final Number parsed = (Number) super.parse(value, pattern); double doubleValue = parsed.doubleValue(); double posDouble = (doubleValue >= 0) ? doubleValue : (doubleValue * -1); if (posDouble != 0 && (posDouble < Float.MIN_VALUE || posDouble > Float.MAX_VALUE)) { throw new ConversionException("Supplied number is not of type Float: "+parsed); } return new Float(parsed.floatValue()); // unlike superclass it returns Float type } } ././@LongLink100644 0 0 165 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/IntegerLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/IntegerLoca100644 0 0 20745 12262570611 31004 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import org.apache.commons.beanutils.ConversionException; import java.util.Locale; import java.text.ParseException; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.lang.Integer object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: IntegerLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class IntegerLocaleConverter extends DecimalLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public IntegerLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public IntegerLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public IntegerLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public IntegerLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public IntegerLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public IntegerLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public IntegerLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public IntegerLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public IntegerLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public IntegerLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public IntegerLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public IntegerLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } /** * Convert the specified locale-sensitive input object into an output object of the * specified type. This method will return Integer type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number */ @Override protected Object parse(Object value, String pattern) throws ParseException { final Number parsed = (Number) super.parse(value, pattern); if (parsed.longValue() != parsed.intValue()) { throw new ConversionException("Suplied number is not of type Integer: " + parsed.longValue()); } return new Integer(parsed.intValue()); // unlike superclass it will return proper Integer } } ././@LongLink100644 0 0 162 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/LongLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/LongLocaleC100644 0 0 20451 12262570612 30725 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.util.Locale; import java.text.ParseException; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.lang.Long object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: LongLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class LongLocaleConverter extends DecimalLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public LongLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public LongLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public LongLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public LongLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public LongLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public LongLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public LongLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public LongLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public LongLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public LongLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public LongLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public LongLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } /** * Convert the specified locale-sensitive input object into an output object of the * specified type. This method will return a Long type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception org.apache.commons.beanutils.ConversionException if conversion * cannot be performed successfully * @throws ParseException if an error occurs parsing a String to a Number * @since 1.8.0 */ @Override protected Object parse(Object value, String pattern) throws ParseException { Object result = super.parse(value, pattern); if (result == null || result instanceof Long) { return result; } return new Long(((Number)result).longValue()); } } ././@LongLink100644 0 0 153 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/package-info.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/package-inf100644 0 0 2051 12262570612 30724 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Standard implementations of the locale-aware {@link LocaleConverter} * interface that are pre-registered with locale-aware {@link LocaleConvertUtils} * at startup time. */ package org.apache.commons.beanutils.locale.converters; ././@LongLink100644 0 0 163 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/ShortLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/ShortLocale100644 0 0 21167 12262570612 31027 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.util.Locale; import java.text.ParseException; import org.apache.commons.beanutils.ConversionException; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.lang.Short object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: ShortLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class ShortLocaleConverter extends DecimalLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public ShortLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public ShortLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public ShortLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public ShortLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public ShortLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public ShortLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public ShortLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public ShortLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public ShortLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public ShortLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public ShortLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public ShortLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } /** * Convert the specified locale-sensitive input object into an output object of the * specified type. This method will return values of type Short. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception org.apache.commons.beanutils.ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number * @since 1.8.0 */ @Override protected Object parse(Object value, String pattern) throws ParseException { Object result = super.parse(value, pattern); if (result == null || result instanceof Short) { return result; } Number parsed = (Number)result; if (parsed.longValue() != parsed.shortValue()) { throw new ConversionException("Supplied number is not of type Short: " + parsed.longValue()); } // now returns property Short return new Short(parsed.shortValue()); } } ././@LongLink100644 0 0 165 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/SqlDateLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/SqlDateLoca100644 0 0 20370 12262570612 30737 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.sql.Date; import java.text.ParseException; import java.util.Locale; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.sql.Date object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: SqlDateLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class SqlDateLocaleConverter extends DateLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public SqlDateLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public SqlDateLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public SqlDateLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public SqlDateLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public SqlDateLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public SqlDateLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public SqlDateLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public SqlDateLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public SqlDateLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public SqlDateLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public SqlDateLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public SqlDateLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } // --------------------------------------------------------- Methods /** * Convert the specified locale-sensitive input object into an output object of the * specified type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception org.apache.commons.beanutils.ConversionException if conversion * cannot be performed successfully * @throws ParseException if an error occurs parsing a String to a Number */ @Override protected Object parse(Object value, String pattern) throws ParseException { return new Date(((java.util.Date) super.parse(value, pattern)).getTime()); } } ././@LongLink100644 0 0 165 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/SqlTimeLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/SqlTimeLoca100644 0 0 20361 12262570612 30760 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.sql.Time; import java.text.ParseException; import java.util.Locale; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.sql.Time object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: SqlTimeLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class SqlTimeLocaleConverter extends DateLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public SqlTimeLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimeLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public SqlTimeLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimeLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public SqlTimeLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimeLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public SqlTimeLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimeLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public SqlTimeLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimeLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public SqlTimeLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimeLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } // --------------------------------------------------------- Methods /** * Convert the specified locale-sensitive input object into an output object of the * specified type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception org.apache.commons.beanutils.ConversionException if conversion * cannot be performed successfully * @throws ParseException if an error occurs parsing a String to a Number */ @Override protected Object parse(Object value, String pattern) throws ParseException { return new Time(((java.util.Date) super.parse(value, pattern)).getTime()); } } ././@LongLink100644 0 0 172 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/SqlTimestampLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/SqlTimestam100644 0 0 20505 12262570612 31046 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.sql.Timestamp; import java.text.ParseException; import java.util.Locale; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a java.sql.Timestamp object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: SqlTimestampLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class SqlTimestampLocaleConverter extends DateLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public SqlTimestampLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimestampLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public SqlTimestampLocaleConverter(Locale locale) { this(locale, (String) null); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimestampLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public SqlTimestampLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimestampLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public SqlTimestampLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimestampLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public SqlTimestampLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimestampLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public SqlTimestampLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public SqlTimestampLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } // --------------------------------------------------------- Methods /** * Convert the specified locale-sensitive input object into an output object of the * specified type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception org.apache.commons.beanutils.ConversionException if conversion * cannot be performed successfully * @throws ParseException if an error occurs parsing a String to a Number */ @Override protected Object parse(Object value, String pattern) throws ParseException { return new Timestamp(((java.util.Date) super.parse(value, pattern)).getTime()); } } ././@LongLink100644 0 0 164 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/StringLocaleConverter.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/converters/StringLocal100644 0 0 25171 12262570611 31027 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import org.apache.commons.beanutils.locale.BaseLocaleConverter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** *

          Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive object into a java.lang.String object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.

          * * @version $Id: StringLocaleConverter.java 1454606 2013-03-08 22:30:51Z britter $ */ public class StringLocaleConverter extends BaseLocaleConverter { // ----------------------------------------------------- Instance Variables /** All logging goes through this logger */ private final Log log = LogFactory.getLog(StringLocaleConverter.class); //msz fix // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public StringLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public StringLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public StringLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public StringLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public StringLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public StringLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public StringLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public StringLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public StringLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public StringLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public StringLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public StringLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } // --------------------------------------------------------- Methods /** * Convert the specified locale-sensitive input object into an output object of the * specified type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @exception org.apache.commons.beanutils.ConversionException if conversion * cannot be performed successfully * @throws ParseException if an error occurs */ @Override protected Object parse(Object value, String pattern) throws ParseException { String result = null; if ((value instanceof Integer) || (value instanceof Long) || (value instanceof BigInteger) || (value instanceof Byte) || (value instanceof Short)) { result = getDecimalFormat(locale, pattern).format(((Number) value).longValue()); } else if ((value instanceof Double) || (value instanceof BigDecimal) || (value instanceof Float)) { result = getDecimalFormat(locale, pattern).format(((Number) value).doubleValue()); } else if (value instanceof Date) { // java.util.Date, java.sql.Date, java.sql.Time, java.sql.Timestamp SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, locale); result = dateFormat.format(value); } else { result = value.toString(); } return result; } /** * Make an instance of DecimalFormat. * * @param locale The locale * @param pattern The pattern is used for the convertion * @return The format for the locale and pattern * * @exception ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number */ private DecimalFormat getDecimalFormat(Locale locale, String pattern) { DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(locale); // if some constructors default pattern to null, it makes only sense to handle null pattern gracefully if (pattern != null) { if (locPattern) { numberFormat.applyLocalizedPattern(pattern); } else { numberFormat.applyPattern(pattern); } } else { log.debug("No pattern provided, using default."); } return numberFormat; } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtils.java100644 0 0 74153 12262570612 30347 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale; import java.lang.reflect.InvocationTargetException; import java.util.Locale; import org.apache.commons.beanutils.BeanUtils; /** *

          Utility methods for populating JavaBeans properties * via reflection in a locale-dependent manner.

          * *

          The implementations for these methods are provided by LocaleBeanUtilsBean. * For more details see {@link LocaleBeanUtilsBean}.

          * * @version $Id: LocaleBeanUtils.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class LocaleBeanUtils extends BeanUtils { // ----------------------------------------------------- Instance Variables /** *

          Gets the locale used when no locale is passed.

          * *

          For more details see LocaleBeanUtilsBean

          * * @return the default locale * @see LocaleBeanUtilsBean#getDefaultLocale() */ public static Locale getDefaultLocale() { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getDefaultLocale(); } /** *

          Sets the locale used when no locale is passed.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param locale the default locale * @see LocaleBeanUtilsBean#setDefaultLocale(Locale) */ public static void setDefaultLocale(Locale locale) { LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().setDefaultLocale(locale); } /** *

          Gets whether the pattern is localized or not.

          * *

          For more details see LocaleBeanUtilsBean

          * * @return true if pattern is localized, * otherwise false * @see LocaleBeanUtilsBean#getApplyLocalized() */ public static boolean getApplyLocalized() { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getApplyLocalized(); } /** *

          Sets whether the pattern is localized or not.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param newApplyLocalized true if pattern is localized, * otherwise false * @see LocaleBeanUtilsBean#setApplyLocalized(boolean) */ public static void setApplyLocalized(boolean newApplyLocalized) { LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().setApplyLocalized(newApplyLocalized); } // --------------------------------------------------------- Public Methods /** *

          Return the value of the specified locale-sensitive indexed property * of the specified bean, as a String.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name propertyname[index] of the property value * to be extracted * @param pattern The conversion pattern * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getIndexedProperty(Object, String, String) */ public static String getIndexedProperty(Object bean, String name, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getIndexedProperty(bean, name, pattern); } /** * Return the value of the specified locale-sensitive indexed property * of the specified bean, as a String using the default conversion pattern of * the corresponding {@link LocaleConverter}. * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name propertyname[index] of the property value * to be extracted * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getIndexedProperty(Object, String) */ public static String getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getIndexedProperty(bean, name); } /** *

          Return the value of the specified locale-sensetive indexed property * of the specified bean, as a String using the specified conversion pattern.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * @param pattern The conversion pattern * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getIndexedProperty(Object, String, int, String) */ public static String getIndexedProperty(Object bean, String name, int index, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getIndexedProperty(bean, name, index, pattern); } /** *

          Return the value of the specified locale-sensetive indexed property * of the specified bean, as a String using the default conversion pattern of * the corresponding {@link LocaleConverter}.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getIndexedProperty(Object, String, int) */ public static String getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getIndexedProperty(bean, name, index); } /** *

          Return the value of the specified simple locale-sensitive property * of the specified bean, converted to a String using the specified * conversion pattern.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @param pattern The conversion pattern * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getSimpleProperty(Object, String, String) */ public static String getSimpleProperty(Object bean, String name, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getSimpleProperty(bean, name, pattern); } /** *

          Return the value of the specified simple locale-sensitive property * of the specified bean, converted to a String using the default * conversion pattern of the corresponding {@link LocaleConverter}.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getSimpleProperty(Object, String) */ public static String getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getSimpleProperty(bean, name); } /** *

          Return the value of the specified mapped locale-sensitive property * of the specified bean, as a String using the specified conversion pattern.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param key Lookup key of the property value to be extracted * @param pattern The conversion pattern * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getMappedProperty(Object, String, String, String) */ public static String getMappedProperty(Object bean, String name, String key, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getMappedProperty(bean, name, key, pattern); } /** *

          Return the value of the specified mapped locale-sensitive property * of the specified bean, as a String * The key is specified as a method parameter and must *not* be included * in the property name expression.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param key Lookup key of the property value to be extracted * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getMappedProperty(Object, String, String) */ public static String getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getMappedProperty(bean, name, key); } /** *

          Return the value of the specified locale-sensitive mapped property * of the specified bean, as a String using the specified pattern.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name propertyname(index) of the property value * to be extracted * @param pattern The conversion pattern * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getMappedPropertyLocale(Object, String, String) */ public static String getMappedPropertyLocale(Object bean, String name, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getMappedPropertyLocale(bean, name, pattern); } /** *

          Return the value of the specified locale-sensitive mapped property * of the specified bean, as a String using the default * conversion pattern of the corresponding {@link LocaleConverter}.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name propertyname(index) of the property value * to be extracted * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getMappedProperty(Object, String) */ public static String getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getMappedProperty(bean, name); } /** *

          Return the value of the (possibly nested) locale-sensitive property * of the specified name, for the specified bean, * as a String using the specified pattern.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * @param pattern The conversion pattern * @return The nested property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getNestedProperty(Object, String, String) */ public static String getNestedProperty(Object bean, String name, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getNestedProperty(bean, name, pattern); } /** *

          Return the value of the (possibly nested) locale-sensitive property * of the specified name.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * @return The nested property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getNestedProperty(Object, String) */ public static String getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getNestedProperty(bean, name); } /** *

          Return the value of the specified locale-sensitive property * of the specified bean.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * @param pattern The conversion pattern * @return The nested property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getProperty(Object, String, String) */ public static String getProperty(Object bean, String name, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getProperty(bean, name, pattern); } /** *

          Return the value of the specified locale-sensitive property * of the specified bean.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * * @see LocaleBeanUtilsBean#getProperty(Object, String) */ public static String getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getProperty(bean, name); } /** *

          Set the specified locale-sensitive property value, performing type * conversions as required to conform to the type of the destination property * using the default conversion pattern of the corresponding {@link LocaleConverter}.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value Value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * * @see LocaleBeanUtilsBean#setProperty(Object, String, Object) */ public static void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().setProperty(bean, name, value); } /** *

          Set the specified locale-sensitive property value, performing type * conversions as required to conform to the type of the destination * property using the specified conversion pattern.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value Value to be set * @param pattern The conversion pattern * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * * @see LocaleBeanUtilsBean#setProperty(Object, String, Object, String) */ public static void setProperty(Object bean, String name, Object value, String pattern) throws IllegalAccessException, InvocationTargetException { LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().setProperty(bean, name, value, pattern); } /** *

          Calculate the property type.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param target The bean * @param name The property name * @param propName The Simple name of target property * @return The property's type * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * * @see LocaleBeanUtilsBean#definePropertyType(Object, String, String) */ protected static Class definePropertyType(Object target, String name, String propName) throws IllegalAccessException, InvocationTargetException { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().definePropertyType(target, name, propName); } /** *

          Convert the specified value to the required type using the * specified conversion pattern.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param type The Java type of target property * @param index The indexed subscript value (if any) * @param value The value to be converted * @param pattern The conversion pattern * @return The converted value * @see LocaleBeanUtilsBean#convert(Class, int, Object, String) */ protected static Object convert(Class type, int index, Object value, String pattern) { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().convert(type, index, value, pattern); } /** *

          Convert the specified value to the required type.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param type The Java type of target property * @param index The indexed subscript value (if any) * @param value The value to be converted * @return The converted value * @see LocaleBeanUtilsBean#convert(Class, int, Object) */ protected static Object convert(Class type, int index, Object value) { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().convert(type, index, value); } /** *

          Invoke the setter method.

          * *

          For more details see LocaleBeanUtilsBean

          * * @param target The bean * @param propName The Simple name of target property * @param key The Mapped key value (if any) * @param index The indexed subscript value (if any) * @param newValue The value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * * @see LocaleBeanUtilsBean#invokeSetter(Object, String, String, int, Object) */ protected static void invokeSetter(Object target, String propName, String key, int index, Object newValue) throws IllegalAccessException, InvocationTargetException { LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().invokeSetter(target, propName, key, index, newValue); } /** * Resolve any nested expression to get the actual target bean. * * @deprecated moved into LocaleBeanUtilsBean * @param bean The bean * @param name The property name * @return The property's descriptor * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ @Deprecated protected static Descriptor calculate(Object bean, String name) throws IllegalAccessException, InvocationTargetException { org.apache.commons.beanutils.locale.LocaleBeanUtilsBean.Descriptor descriptor = LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().calculate(bean, name); return new Descriptor( descriptor.getTarget(), descriptor.getName(), descriptor.getPropName(), descriptor.getKey(), descriptor.getIndex()); } /** @deprecated moved into LocaleBeanUtils */ @Deprecated protected static class Descriptor { private int index = -1; // Indexed subscript value (if any) private String name; private String propName; // Simple name of target property private String key; // Mapped key value (if any) private Object target; /** * Construct a descriptor instance for the target bean and property. * * @param target The target bean * @param name The property name (includes indexed/mapped expr) * @param propName The property name * @param key The mapped property key (if any) * @param index The indexed property index (if any) */ public Descriptor(Object target, String name, String propName, String key, int index) { setTarget(target); setName(name); setPropName(propName); setKey(key); setIndex(index); } /** * Return the target bean. * * @return The descriptors target bean */ public Object getTarget() { return target; } /** * Set the target bean. * * @param target The target bean */ public void setTarget(Object target) { this.target = target; } /** * Return the mapped property key. * * @return the mapped property key (if any) */ public String getKey() { return key; } /** * Set the mapped property key. * * @param key The mapped property key (if any) */ public void setKey(String key) { this.key = key; } /** * Return indexed property index. * * @return indexed property index (if any) */ public int getIndex() { return index; } /** * Set the indexed property index. * * @param index The indexed property index (if any) */ public void setIndex(int index) { this.index = index; } /** * Return property name (includes indexed/mapped expr). * * @return The property name (includes indexed/mapped expr) */ public String getName() { return name; } /** * Set the property name (includes indexed/mapped expr). * * @param name The property name (includes indexed/mapped expr) */ public void setName(String name) { this.name = name; } /** * Return the property name. * * @return The property name */ public String getPropName() { return propName; } /** * Set the property name. * * @param propName The property name */ public void setPropName(String propName) { this.propName = propName; } } } ././@LongLink100644 0 0 147 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtilsBean.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/LocaleBeanUtilsBean.ja100644 0 0 122360 12262570612 30620 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale; import java.beans.IndexedPropertyDescriptor; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.util.Locale; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.ContextClassLoaderLocal; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.beanutils.DynaBean; import org.apache.commons.beanutils.DynaClass; import org.apache.commons.beanutils.DynaProperty; import org.apache.commons.beanutils.MappedPropertyDescriptor; import org.apache.commons.beanutils.PropertyUtilsBean; import org.apache.commons.beanutils.expression.Resolver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

          Utility methods for populating JavaBeans properties * via reflection in a locale-dependent manner.

          * * @since 1.7 * @version $Id: LocaleBeanUtilsBean.java 1546738 2013-11-30 16:24:19Z oheger $ */ public class LocaleBeanUtilsBean extends BeanUtilsBean { /** * Contains LocaleBeanUtilsBean instances indexed by context classloader. */ private static final ContextClassLoaderLocal LOCALE_BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal() { // Creates the default instance used when the context classloader is unavailable @Override protected LocaleBeanUtilsBean initialValue() { return new LocaleBeanUtilsBean(); } }; /** * Gets singleton instance * * @return the singleton instance */ public static LocaleBeanUtilsBean getLocaleBeanUtilsInstance() { return LOCALE_BEANS_BY_CLASSLOADER.get(); } /** * Sets the instance which provides the functionality for {@link LocaleBeanUtils}. * This is a pseudo-singleton - an single instance is provided per (thread) context classloader. * This mechanism provides isolation for web apps deployed in the same container. * * @param newInstance a new singleton instance */ public static void setInstance(LocaleBeanUtilsBean newInstance) { LOCALE_BEANS_BY_CLASSLOADER.set(newInstance); } /** All logging goes through this logger */ private final Log log = LogFactory.getLog(LocaleBeanUtilsBean.class); // ----------------------------------------------------- Instance Variables /** Convertor used by this class */ private final LocaleConvertUtilsBean localeConvertUtils; // --------------------------------------------------------- Constructors /** Construct instance with standard conversion bean */ public LocaleBeanUtilsBean() { this.localeConvertUtils = new LocaleConvertUtilsBean(); } /** * Construct instance that uses given locale conversion * * @param localeConvertUtils use this localeConvertUtils to perform * conversions * @param convertUtilsBean use this for standard conversions * @param propertyUtilsBean use this for property conversions */ public LocaleBeanUtilsBean( LocaleConvertUtilsBean localeConvertUtils, ConvertUtilsBean convertUtilsBean, PropertyUtilsBean propertyUtilsBean) { super(convertUtilsBean, propertyUtilsBean); this.localeConvertUtils = localeConvertUtils; } /** * Construct instance that uses given locale conversion * * @param localeConvertUtils use this localeConvertUtils to perform * conversions */ public LocaleBeanUtilsBean(LocaleConvertUtilsBean localeConvertUtils) { this.localeConvertUtils = localeConvertUtils; } // --------------------------------------------------------- Public Methods /** * Gets the bean instance used for conversions * * @return the locale converter bean instance */ public LocaleConvertUtilsBean getLocaleConvertUtils() { return localeConvertUtils; } /** * Gets the default Locale * @return the default locale */ public Locale getDefaultLocale() { return getLocaleConvertUtils().getDefaultLocale(); } /** * Sets the default Locale. * * @param locale the default locale */ public void setDefaultLocale(Locale locale) { getLocaleConvertUtils().setDefaultLocale(locale); } /** * Is the pattern to be applied localized * (Indicate whether the pattern is localized or not) * * @return true if pattern is localized, * otherwise false */ public boolean getApplyLocalized() { return getLocaleConvertUtils().getApplyLocalized(); } /** * Sets whether the pattern is applied localized * (Indicate whether the pattern is localized or not) * * @param newApplyLocalized true if pattern is localized, * otherwise false */ public void setApplyLocalized(boolean newApplyLocalized) { getLocaleConvertUtils().setApplyLocalized(newApplyLocalized); } // --------------------------------------------------------- Public Methods /** * Return the value of the specified locale-sensitive indexed property * of the specified bean, as a String. The zero-relative index of the * required value must be included (in square brackets) as a suffix to * the property name, or IllegalArgumentException will be * thrown. * * @param bean Bean whose property is to be extracted * @param name propertyname[index] of the property value * to be extracted * @param pattern The conversion pattern * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public String getIndexedProperty( Object bean, String name, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getIndexedProperty(bean, name); return getLocaleConvertUtils().convert(value, pattern); } /** * Return the value of the specified locale-sensitive indexed property * of the specified bean, as a String using the default conversion pattern of * the corresponding {@link LocaleConverter}. The zero-relative index * of the required value must be included (in square brackets) as a suffix * to the property name, or IllegalArgumentException will be thrown. * * @param bean Bean whose property is to be extracted * @param name propertyname[index] of the property value * to be extracted * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ @Override public String getIndexedProperty( Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return getIndexedProperty(bean, name, null); } /** * Return the value of the specified locale-sensetive indexed property * of the specified bean, as a String using the specified conversion pattern. * The index is specified as a method parameter and * must *not* be included in the property name expression * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * @param pattern The conversion pattern * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public String getIndexedProperty(Object bean, String name, int index, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getIndexedProperty(bean, name, index); return getLocaleConvertUtils().convert(value, pattern); } /** * Return the value of the specified locale-sensetive indexed property * of the specified bean, as a String using the default conversion pattern of * the corresponding {@link LocaleConverter}. * The index is specified as a method parameter and * must *not* be included in the property name expression * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ @Override public String getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return getIndexedProperty(bean, name, index, null); } /** * Return the value of the specified simple locale-sensitive property * of the specified bean, converted to a String using the specified * conversion pattern. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @param pattern The conversion pattern * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getSimpleProperty(Object bean, String name, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getSimpleProperty(bean, name); return getLocaleConvertUtils().convert(value, pattern); } /** * Return the value of the specified simple locale-sensitive property * of the specified bean, converted to a String using the default * conversion pattern of the corresponding {@link LocaleConverter}. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ @Override public String getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return getSimpleProperty(bean, name, null); } /** * Return the value of the specified mapped locale-sensitive property * of the specified bean, as a String using the specified conversion pattern. * The key is specified as a method parameter and must *not* be included in * the property name expression. * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param key Lookup key of the property value to be extracted * @param pattern The conversion pattern * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getMappedProperty( Object bean, String name, String key, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getMappedProperty(bean, name, key); return getLocaleConvertUtils().convert(value, pattern); } /** * Return the value of the specified mapped locale-sensitive property * of the specified bean, as a String * The key is specified as a method parameter and must *not* be included * in the property name expression * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param key Lookup key of the property value to be extracted * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ @Override public String getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return getMappedProperty(bean, name, key, null); } /** * Return the value of the specified locale-sensitive mapped property * of the specified bean, as a String using the specified pattern. * The String-valued key of the required value * must be included (in parentheses) as a suffix to * the property name, or IllegalArgumentException will be * thrown. * * @param bean Bean whose property is to be extracted * @param name propertyname(index) of the property value * to be extracted * @param pattern The conversion pattern * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getMappedPropertyLocale( Object bean, String name, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getMappedProperty(bean, name); return getLocaleConvertUtils().convert(value, pattern); } /** * Return the value of the specified locale-sensitive mapped property * of the specified bean, as a String using the default * conversion pattern of the corresponding {@link LocaleConverter}. * The String-valued key of the required value * must be included (in parentheses) as a suffix to * the property name, or IllegalArgumentException will be * thrown. * * @param bean Bean whose property is to be extracted * @param name propertyname(index) of the property value * to be extracted * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ @Override public String getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return getMappedPropertyLocale(bean, name, null); } /** * Return the value of the (possibly nested) locale-sensitive property * of the specified name, for the specified bean, * as a String using the specified pattern. * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * @param pattern The conversion pattern * @return The nested property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getNestedProperty( Object bean, String name, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getNestedProperty(bean, name); return getLocaleConvertUtils().convert(value, pattern); } /** * Return the value of the (possibly nested) locale-sensitive property * of the specified name, for the specified bean, as a String using the default * conversion pattern of the corresponding {@link LocaleConverter}. * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * @return The nested property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ @Override public String getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return getNestedProperty(bean, name, null); } /** * Return the value of the specified locale-sensitive property * of the specified bean, no matter which property reference * format is used, as a String using the specified conversion pattern. * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * @param pattern The conversion pattern * @return The nested property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getProperty(Object bean, String name, String pattern) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return getNestedProperty(bean, name, pattern); } /** * Return the value of the specified locale-sensitive property * of the specified bean, no matter which property reference * format is used, as a String using the default * conversion pattern of the corresponding {@link LocaleConverter}. * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ @Override public String getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return getNestedProperty(bean, name); } /** * Set the specified locale-sensitive property value, performing type * conversions as required to conform to the type of the destination property * using the default conversion pattern of the corresponding {@link LocaleConverter}. * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value Value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ @Override public void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { setProperty(bean, name, value, null); } /** * Set the specified locale-sensitive property value, performing type * conversions as required to conform to the type of the destination * property using the specified conversion pattern. * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value Value to be set * @param pattern The conversion pattern * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ public void setProperty( Object bean, String name, Object value, String pattern) throws IllegalAccessException, InvocationTargetException { // Trace logging (if enabled) if (log.isTraceEnabled()) { StringBuilder sb = new StringBuilder(" setProperty("); sb.append(bean); sb.append(", "); sb.append(name); sb.append(", "); if (value == null) { sb.append(""); } else if (value instanceof String) { sb.append((String) value); } else if (value instanceof String[]) { String[] values = (String[]) value; sb.append('['); for (int i = 0; i < values.length; i++) { if (i > 0) { sb.append(','); } sb.append(values[i]); } sb.append(']'); } else { sb.append(value.toString()); } sb.append(')'); log.trace(sb.toString()); } // Resolve any nested expression to get the actual target bean Object target = bean; Resolver resolver = getPropertyUtils().getResolver(); while (resolver.hasNested(name)) { try { target = getPropertyUtils().getProperty(target, resolver.next(name)); name = resolver.remove(name); } catch (NoSuchMethodException e) { return; // Skip this property setter } } if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + name); } // Declare local variables we will require String propName = resolver.getProperty(name); // Simple name of target property int index = resolver.getIndex(name); // Indexed subscript value (if any) String key = resolver.getKey(name); // Mapped key value (if any) Class type = definePropertyType(target, name, propName); if (type != null) { Object newValue = convert(type, index, value, pattern); invokeSetter(target, propName, key, index, newValue); } } /** * Calculate the property type. * * @param target The bean * @param name The property name * @param propName The Simple name of target property * @return The property's type * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ protected Class definePropertyType(Object target, String name, String propName) throws IllegalAccessException, InvocationTargetException { Class type = null; // Java type of target property if (target instanceof DynaBean) { DynaClass dynaClass = ((DynaBean) target).getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return null; // Skip this property setter } type = dynaProperty.getType(); } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, name); if (descriptor == null) { return null; // Skip this property setter } } catch (NoSuchMethodException e) { return null; // Skip this property setter } if (descriptor instanceof MappedPropertyDescriptor) { type = ((MappedPropertyDescriptor) descriptor). getMappedPropertyType(); } else if (descriptor instanceof IndexedPropertyDescriptor) { type = ((IndexedPropertyDescriptor) descriptor). getIndexedPropertyType(); } else { type = descriptor.getPropertyType(); } } return type; } /** * Convert the specified value to the required type using the * specified conversion pattern. * * @param type The Java type of target property * @param index The indexed subscript value (if any) * @param value The value to be converted * @param pattern The conversion pattern * @return The converted value */ protected Object convert(Class type, int index, Object value, String pattern) { if (log.isTraceEnabled()) { log.trace("Converting value '" + value + "' to type:" + type); } Object newValue = null; if (type.isArray() && (index < 0)) { // Scalar value into array if (value instanceof String) { String[] values = new String[1]; values[0] = (String) value; newValue = getLocaleConvertUtils().convert(values, type, pattern); } else if (value instanceof String[]) { newValue = getLocaleConvertUtils().convert((String[]) value, type, pattern); } else { newValue = value; } } else if (type.isArray()) { // Indexed value into array if (value instanceof String) { newValue = getLocaleConvertUtils().convert((String) value, type.getComponentType(), pattern); } else if (value instanceof String[]) { newValue = getLocaleConvertUtils().convert(((String[]) value)[0], type.getComponentType(), pattern); } else { newValue = value; } } else { // Value into scalar if (value instanceof String) { newValue = getLocaleConvertUtils().convert((String) value, type, pattern); } else if (value instanceof String[]) { newValue = getLocaleConvertUtils().convert(((String[]) value)[0], type, pattern); } else { newValue = value; } } return newValue; } /** * Convert the specified value to the required type. * * @param type The Java type of target property * @param index The indexed subscript value (if any) * @param value The value to be converted * @return The converted value */ protected Object convert(Class type, int index, Object value) { Object newValue = null; if (type.isArray() && (index < 0)) { // Scalar value into array if (value instanceof String) { String[] values = new String[1]; values[0] = (String) value; newValue = ConvertUtils.convert(values, type); } else if (value instanceof String[]) { newValue = ConvertUtils.convert((String[]) value, type); } else { newValue = value; } } else if (type.isArray()) { // Indexed value into array if (value instanceof String) { newValue = ConvertUtils.convert((String) value, type.getComponentType()); } else if (value instanceof String[]) { newValue = ConvertUtils.convert(((String[]) value)[0], type.getComponentType()); } else { newValue = value; } } else { // Value into scalar if (value instanceof String) { newValue = ConvertUtils.convert((String) value, type); } else if (value instanceof String[]) { newValue = ConvertUtils.convert(((String[]) value)[0], type); } else { newValue = value; } } return newValue; } /** * Invoke the setter method. * * @param target The bean * @param propName The Simple name of target property * @param key The Mapped key value (if any) * @param index The indexed subscript value (if any) * @param newValue The value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ protected void invokeSetter(Object target, String propName, String key, int index, Object newValue) throws IllegalAccessException, InvocationTargetException { try { if (index >= 0) { getPropertyUtils().setIndexedProperty(target, propName, index, newValue); } else if (key != null) { getPropertyUtils().setMappedProperty(target, propName, key, newValue); } else { getPropertyUtils().setProperty(target, propName, newValue); } } catch (NoSuchMethodException e) { throw new InvocationTargetException (e, "Cannot set " + propName); } } /** * Resolve any nested expression to get the actual target property. * * @param bean The bean * @param name The property name * @return The property's descriptor * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @deprecated Property name expressions are now processed by * the configured {@link Resolver} implementation and this method * is no longer used by BeanUtils. */ @Deprecated protected Descriptor calculate(Object bean, String name) throws IllegalAccessException, InvocationTargetException { // Resolve any nested expression to get the actual target bean Object target = bean; Resolver resolver = getPropertyUtils().getResolver(); while (resolver.hasNested(name)) { try { target = getPropertyUtils().getProperty(target, resolver.next(name)); name = resolver.remove(name); } catch (NoSuchMethodException e) { return null; // Skip this property setter } } if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + name); } // Declare local variables we will require String propName = resolver.getProperty(name); // Simple name of target property int index = resolver.getIndex(name); // Indexed subscript value (if any) String key = resolver.getKey(name); // Mapped key value (if any) return new Descriptor(target, name, propName, key, index); } /** * @deprecated Property name expressions are now processed by * the configured {@link Resolver} implementation and this class * is no longer used by BeanUtils. */ @Deprecated protected class Descriptor { private int index = -1; // Indexed subscript value (if any) private String name; private String propName; // Simple name of target property private String key; // Mapped key value (if any) private Object target; /** * Construct a descriptor instance for the target bean and property. * * @param target The target bean * @param name The property name (includes indexed/mapped expr) * @param propName The property name * @param key The mapped property key (if any) * @param index The indexed property index (if any) */ public Descriptor(Object target, String name, String propName, String key, int index) { setTarget(target); setName(name); setPropName(propName); setKey(key); setIndex(index); } /** * Return the target bean. * * @return The descriptors target bean */ public Object getTarget() { return target; } /** * Set the target bean. * * @param target The target bean */ public void setTarget(Object target) { this.target = target; } /** * Return the mapped property key. * * @return the mapped property key (if any) */ public String getKey() { return key; } /** * Set the mapped property key. * * @param key The mapped property key (if any) */ public void setKey(String key) { this.key = key; } /** * Return indexed property index. * * @return indexed property index (if any) */ public int getIndex() { return index; } /** * Set the indexed property index. * * @param index The indexed property index (if any) */ public void setIndex(int index) { this.index = index; } /** * Return property name (includes indexed/mapped expr). * * @return The property name (includes indexed/mapped expr) */ public String getName() { return name; } /** * Set the property name (includes indexed/mapped expr). * * @param name The property name (includes indexed/mapped expr) */ public void setName(String name) { this.name = name; } /** * Return the property name. * * @return The property name */ public String getPropName() { return propName; } /** * Set the property name. * * @param propName The property name */ public void setPropName(String propName) { this.propName = propName; } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/LocaleConverter.java100644 0 0 3644 12262570612 30405 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale; import org.apache.commons.beanutils.Converter; /** *

          General purpose locale-sensitive data type converter that can be registered and used * within the BeanUtils package to manage the conversion of objects from * one type to another. * * @version $Id: LocaleConverter.java 1540186 2013-11-08 21:08:30Z oheger $ */ public interface LocaleConverter extends Converter { /** * Convert the specified locale-sensitive input object into an output object of the * specified type. * * @param The desired target type of the conversion * @param type Data type to which this value should be converted * @param value The input value to be converted * @param pattern The user-defined pattern is used for the input object formatting. * @return The converted value * * @exception org.apache.commons.beanutils.ConversionException if conversion * cannot be performed successfully or if the target type is not supported */ public T convert(Class type, Object value, String pattern); } ././@LongLink100644 0 0 146 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtils.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtils.jav100644 0 0 32226 12262570611 30753 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale; import java.util.Locale; import org.apache.commons.collections.FastHashMap; /** *

          Utility methods for converting locale-sensitive String scalar values to objects of the * specified Class, String arrays to arrays of the specified Class and * object to locale-sensitive String scalar value.

          * *

          The implementations for these method are provided by {@link LocaleConvertUtilsBean}. * These static utility method use the default instance. More sophisticated can be provided * by using a LocaleConvertUtilsBean instance.

          * * @version $Id: LocaleConvertUtils.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class LocaleConvertUtils { // ----------------------------------------------------- Instance Variables /** *

          Gets the Locale which will be used when * no Locale is passed to a method.

          * *

          For more details see LocaleConvertUtilsBean

          * @return the default locale * @see LocaleConvertUtilsBean#getDefaultLocale() */ public static Locale getDefaultLocale() { return LocaleConvertUtilsBean.getInstance().getDefaultLocale(); } /** *

          Sets the Locale which will be used when * no Locale is passed to a method.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param locale the default locale * @see LocaleConvertUtilsBean#setDefaultLocale(Locale) */ public static void setDefaultLocale(Locale locale) { LocaleConvertUtilsBean.getInstance().setDefaultLocale(locale); } /** *

          Gets applyLocalized.

          * *

          For more details see LocaleConvertUtilsBean

          * * @return true if pattern is localized, * otherwise false * @see LocaleConvertUtilsBean#getApplyLocalized() */ public static boolean getApplyLocalized() { return LocaleConvertUtilsBean.getInstance().getApplyLocalized(); } /** *

          Sets applyLocalized.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param newApplyLocalized true if pattern is localized, * otherwise false * @see LocaleConvertUtilsBean#setApplyLocalized(boolean) */ public static void setApplyLocalized(boolean newApplyLocalized) { LocaleConvertUtilsBean.getInstance().setApplyLocalized(newApplyLocalized); } // --------------------------------------------------------- Methods /** *

          Convert the specified locale-sensitive value into a String.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param value The Value to be converted * @return the converted value * @see LocaleConvertUtilsBean#convert(Object) */ public static String convert(Object value) { return LocaleConvertUtilsBean.getInstance().convert(value); } /** *

          Convert the specified locale-sensitive value into a String * using the conversion pattern.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param value The Value to be converted * @param pattern The convertion pattern * @return the converted value * @see LocaleConvertUtilsBean#convert(Object, String) */ public static String convert(Object value, String pattern) { return LocaleConvertUtilsBean.getInstance().convert(value, pattern); } /** *

          Convert the specified locale-sensitive value into a String * using the paticular convertion pattern.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param value The Value to be converted * @param locale The locale * @param pattern The convertion pattern * @return the converted value * @see LocaleConvertUtilsBean#convert(Object, Locale, String) */ public static String convert(Object value, Locale locale, String pattern) { return LocaleConvertUtilsBean.getInstance().convert(value, locale, pattern); } /** *

          Convert the specified value to an object of the specified class (if * possible). Otherwise, return a String representation of the value.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param value The String scalar value to be converted * @param clazz The Data type to which this value should be converted. * @return the converted value * @see LocaleConvertUtilsBean#convert(String, Class) */ public static Object convert(String value, Class clazz) { return LocaleConvertUtilsBean.getInstance().convert(value, clazz); } /** *

          Convert the specified value to an object of the specified class (if * possible) using the convertion pattern. Otherwise, return a String * representation of the value.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param value The String scalar value to be converted * @param clazz The Data type to which this value should be converted. * @param pattern The convertion pattern * @return the converted value * @see LocaleConvertUtilsBean#convert(String, Class, String) */ public static Object convert(String value, Class clazz, String pattern) { return LocaleConvertUtilsBean.getInstance().convert(value, clazz, pattern); } /** *

          Convert the specified value to an object of the specified class (if * possible) using the convertion pattern. Otherwise, return a String * representation of the value.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param value The String scalar value to be converted * @param clazz The Data type to which this value should be converted. * @param locale The locale * @param pattern The convertion pattern * @return the converted value * @see LocaleConvertUtilsBean#convert(String, Class, Locale, String) */ public static Object convert(String value, Class clazz, Locale locale, String pattern) { return LocaleConvertUtilsBean.getInstance().convert(value, clazz, locale, pattern); } /** *

          Convert an array of specified values to an array of objects of the * specified class (if possible) using the convertion pattern.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param values Value to be converted (may be null) * @param clazz Java array or element class to be converted to * @param pattern The convertion pattern * @return the converted value * @see LocaleConvertUtilsBean#convert(String[], Class, String) */ public static Object convert(String[] values, Class clazz, String pattern) { return LocaleConvertUtilsBean.getInstance().convert(values, clazz, pattern); } /** *

          Convert an array of specified values to an array of objects of the * specified class (if possible).

          * *

          For more details see LocaleConvertUtilsBean

          * * @param values Value to be converted (may be null) * @param clazz Java array or element class to be converted to * @return the converted value * @see LocaleConvertUtilsBean#convert(String[], Class) */ public static Object convert(String[] values, Class clazz) { return LocaleConvertUtilsBean.getInstance().convert(values, clazz); } /** *

          Convert an array of specified values to an array of objects of the * specified class (if possible) using the convertion pattern.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param values Value to be converted (may be null) * @param clazz Java array or element class to be converted to * @param locale The locale * @param pattern The convertion pattern * @return the converted value * @see LocaleConvertUtilsBean#convert(String[], Class, Locale, String) */ public static Object convert(String[] values, Class clazz, Locale locale, String pattern) { return LocaleConvertUtilsBean.getInstance().convert(values, clazz, locale, pattern); } /** *

          Register a custom {@link LocaleConverter} for the specified destination * Class, replacing any previously registered converter.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param converter The LocaleConverter to be registered * @param clazz The Destination class for conversions performed by this * Converter * @param locale The locale * @see LocaleConvertUtilsBean#register(LocaleConverter, Class, Locale) */ public static void register(LocaleConverter converter, Class clazz, Locale locale) { LocaleConvertUtilsBean.getInstance().register(converter, clazz, locale); } /** *

          Remove any registered {@link LocaleConverter}.

          * *

          For more details see LocaleConvertUtilsBean

          * * @see LocaleConvertUtilsBean#deregister() */ public static void deregister() { LocaleConvertUtilsBean.getInstance().deregister(); } /** *

          Remove any registered {@link LocaleConverter} for the specified locale.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param locale The locale * @see LocaleConvertUtilsBean#deregister(Locale) */ public static void deregister(Locale locale) { LocaleConvertUtilsBean.getInstance().deregister(locale); } /** *

          Remove any registered {@link LocaleConverter} for the specified locale and Class.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param clazz Class for which to remove a registered Converter * @param locale The locale * @see LocaleConvertUtilsBean#deregister(Class, Locale) */ public static void deregister(Class clazz, Locale locale) { LocaleConvertUtilsBean.getInstance().deregister(clazz, locale); } /** *

          Look up and return any registered {@link LocaleConverter} for the specified * destination class and locale; if there is no registered Converter, return * null.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param clazz Class for which to return a registered Converter * @param locale The Locale * @return The registered locale Converter, if any * @see LocaleConvertUtilsBean#lookup(Class, Locale) */ public static LocaleConverter lookup(Class clazz, Locale locale) { return LocaleConvertUtilsBean.getInstance().lookup(clazz, locale); } /** *

          Look up and return any registered FastHashMap instance for the specified locale.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param locale The Locale * @return The FastHashMap instance contains the all {@link LocaleConverter} types for * the specified locale. * @see LocaleConvertUtilsBean#lookup(Locale) * @deprecated This method will be modified to return a Map in the next release. */ @Deprecated protected static FastHashMap lookup(Locale locale) { return LocaleConvertUtilsBean.getInstance().lookup(locale); } /** *

          Create all {@link LocaleConverter} types for specified locale.

          * *

          For more details see LocaleConvertUtilsBean

          * * @param locale The Locale * @return The FastHashMap instance contains the all {@link LocaleConverter} types * for the specified locale. * @see LocaleConvertUtilsBean#create(Locale) * @deprecated This method will be modified to return a Map in the next release. */ @Deprecated protected static FastHashMap create(Locale locale) { return LocaleConvertUtilsBean.getInstance().create(locale); } } ././@LongLink100644 0 0 152 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsBean.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsBean100644 0 0 51124 12262570612 30761 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.locale.converters.BigDecimalLocaleConverter; import org.apache.commons.beanutils.locale.converters.BigIntegerLocaleConverter; import org.apache.commons.beanutils.locale.converters.ByteLocaleConverter; import org.apache.commons.beanutils.locale.converters.DoubleLocaleConverter; import org.apache.commons.beanutils.locale.converters.FloatLocaleConverter; import org.apache.commons.beanutils.locale.converters.IntegerLocaleConverter; import org.apache.commons.beanutils.locale.converters.LongLocaleConverter; import org.apache.commons.beanutils.locale.converters.ShortLocaleConverter; import org.apache.commons.beanutils.locale.converters.SqlDateLocaleConverter; import org.apache.commons.beanutils.locale.converters.SqlTimeLocaleConverter; import org.apache.commons.beanutils.locale.converters.SqlTimestampLocaleConverter; import org.apache.commons.beanutils.locale.converters.StringLocaleConverter; import org.apache.commons.collections.FastHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

          Utility methods for converting locale-sensitive String scalar values to objects of the * specified Class, String arrays to arrays of the specified Class and * object to locale-sensitive String scalar value.

          * *

          This class provides the implementations used by the static utility methods in * {@link LocaleConvertUtils}.

          * *

          The actual {@link LocaleConverter} instance to be used * can be registered for each possible destination Class. Unless you override them, standard * {@link LocaleConverter} instances are provided for all of the following * destination Classes:

          *
            *
          • java.lang.BigDecimal
          • *
          • java.lang.BigInteger
          • *
          • byte and java.lang.Byte
          • *
          • double and java.lang.Double
          • *
          • float and java.lang.Float
          • *
          • int and java.lang.Integer
          • *
          • long and java.lang.Long
          • *
          • short and java.lang.Short
          • *
          • java.lang.String
          • *
          • java.sql.Date
          • *
          • java.sql.Time
          • *
          • java.sql.Timestamp
          • *
          * *

          For backwards compatibility, the standard locale converters * for primitive types (and the corresponding wrapper classes). * * If you prefer to have another {@link LocaleConverter} * thrown instead, replace the standard {@link LocaleConverter} instances * with ones created with the one of the appropriate constructors. * * It's important that {@link LocaleConverter} should be registered for * the specified locale and Class (or primitive type). * * @since 1.7 * @version $Id: LocaleConvertUtilsBean.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class LocaleConvertUtilsBean { /** * Gets singleton instance. * This is the same as the instance used by the default {@link LocaleBeanUtilsBean} singleton. * @return the singleton instance */ public static LocaleConvertUtilsBean getInstance() { return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getLocaleConvertUtils(); } // ----------------------------------------------------- Instance Variables /** The locale - default for convertion. */ private Locale defaultLocale = Locale.getDefault(); /** Indicate whether the pattern is localized or not */ private boolean applyLocalized = false; /** The Log instance for this class. */ private final Log log = LogFactory.getLog(LocaleConvertUtils.class); /** Every entry of the mapConverters is: * key = locale * value = FastHashMap of converters for the certain locale. */ private final FastHashMap mapConverters = new DelegateFastHashMap(BeanUtils.createCache()); // --------------------------------------------------------- Constructors /** * Makes the state by default (deregisters all converters for all locales) * and then registers default locale converters. */ public LocaleConvertUtilsBean() { mapConverters.setFast(false); deregister(); mapConverters.setFast(true); } // --------------------------------------------------------- Properties /** * getter for defaultLocale. * @return the default locale */ public Locale getDefaultLocale() { return defaultLocale; } /** * setter for defaultLocale. * @param locale the default locale */ public void setDefaultLocale(Locale locale) { if (locale == null) { defaultLocale = Locale.getDefault(); } else { defaultLocale = locale; } } /** * getter for applyLocalized * * @return true if pattern is localized, * otherwise false */ public boolean getApplyLocalized() { return applyLocalized; } /** * setter for applyLocalized * * @param newApplyLocalized true if pattern is localized, * otherwise false */ public void setApplyLocalized(boolean newApplyLocalized) { applyLocalized = newApplyLocalized; } // --------------------------------------------------------- Methods /** * Convert the specified locale-sensitive value into a String. * * @param value The Value to be converted * @return the converted value * * @throws org.apache.commons.beanutils.ConversionException if thrown by an * underlying Converter */ public String convert(Object value) { return convert(value, defaultLocale, null); } /** * Convert the specified locale-sensitive value into a String * using the conversion pattern. * * @param value The Value to be converted * @param pattern The convertion pattern * @return the converted value * * @throws org.apache.commons.beanutils.ConversionException if thrown by an * underlying Converter */ public String convert(Object value, String pattern) { return convert(value, defaultLocale, pattern); } /** * Convert the specified locale-sensitive value into a String * using the paticular convertion pattern. * * @param value The Value to be converted * @param locale The locale * @param pattern The convertion pattern * @return the converted value * * @throws org.apache.commons.beanutils.ConversionException if thrown by an * underlying Converter */ public String convert(Object value, Locale locale, String pattern) { LocaleConverter converter = lookup(String.class, locale); return converter.convert(String.class, value, pattern); } /** * Convert the specified value to an object of the specified class (if * possible). Otherwise, return a String representation of the value. * * @param value The String scalar value to be converted * @param clazz The Data type to which this value should be converted. * @return the converted value * * @throws org.apache.commons.beanutils.ConversionException if thrown by an * underlying Converter */ public Object convert(String value, Class clazz) { return convert(value, clazz, defaultLocale, null); } /** * Convert the specified value to an object of the specified class (if * possible) using the convertion pattern. Otherwise, return a String * representation of the value. * * @param value The String scalar value to be converted * @param clazz The Data type to which this value should be converted. * @param pattern The convertion pattern * @return the converted value * * @throws org.apache.commons.beanutils.ConversionException if thrown by an * underlying Converter */ public Object convert(String value, Class clazz, String pattern) { return convert(value, clazz, defaultLocale, pattern); } /** * Convert the specified value to an object of the specified class (if * possible) using the convertion pattern. Otherwise, return a String * representation of the value. * * @param value The String scalar value to be converted * @param clazz The Data type to which this value should be converted. * @param locale The locale * @param pattern The convertion pattern * @return the converted value * * @throws org.apache.commons.beanutils.ConversionException if thrown by an * underlying Converter */ public Object convert(String value, Class clazz, Locale locale, String pattern) { if (log.isDebugEnabled()) { log.debug("Convert string " + value + " to class " + clazz.getName() + " using " + locale + " locale and " + pattern + " pattern"); } Class targetClass = clazz; LocaleConverter converter = lookup(clazz, locale); if (converter == null) { converter = lookup(String.class, locale); targetClass = String.class; } if (log.isTraceEnabled()) { log.trace(" Using converter " + converter); } return (converter.convert(targetClass, value, pattern)); } /** * Convert an array of specified values to an array of objects of the * specified class (if possible) using the convertion pattern. * * @param values Value to be converted (may be null) * @param clazz Java array or element class to be converted to * @param pattern The convertion pattern * @return the converted value * * @throws org.apache.commons.beanutils.ConversionException if thrown by an * underlying Converter */ public Object convert(String[] values, Class clazz, String pattern) { return convert(values, clazz, getDefaultLocale(), pattern); } /** * Convert an array of specified values to an array of objects of the * specified class (if possible) . * * @param values Value to be converted (may be null) * @param clazz Java array or element class to be converted to * @return the converted value * * @throws org.apache.commons.beanutils.ConversionException if thrown by an * underlying Converter */ public Object convert(String[] values, Class clazz) { return convert(values, clazz, getDefaultLocale(), null); } /** * Convert an array of specified values to an array of objects of the * specified class (if possible) using the convertion pattern. * * @param values Value to be converted (may be null) * @param clazz Java array or element class to be converted to * @param locale The locale * @param pattern The convertion pattern * @return the converted value * * @throws org.apache.commons.beanutils.ConversionException if thrown by an * underlying Converter */ public Object convert(String[] values, Class clazz, Locale locale, String pattern) { Class type = clazz; if (clazz.isArray()) { type = clazz.getComponentType(); } if (log.isDebugEnabled()) { log.debug("Convert String[" + values.length + "] to class " + type.getName() + "[] using " + locale + " locale and " + pattern + " pattern"); } Object array = Array.newInstance(type, values.length); for (int i = 0; i < values.length; i++) { Array.set(array, i, convert(values[i], type, locale, pattern)); } return (array); } /** * Register a custom {@link LocaleConverter} for the specified destination * Class, replacing any previously registered converter. * * @param converter The LocaleConverter to be registered * @param clazz The Destination class for conversions performed by this * Converter * @param locale The locale */ public void register(LocaleConverter converter, Class clazz, Locale locale) { lookup(locale).put(clazz, converter); } /** * Remove any registered {@link LocaleConverter}. */ public void deregister() { FastHashMap defaultConverter = lookup(defaultLocale); mapConverters.setFast(false); mapConverters.clear(); mapConverters.put(defaultLocale, defaultConverter); mapConverters.setFast(true); } /** * Remove any registered {@link LocaleConverter} for the specified locale * * @param locale The locale */ public void deregister(Locale locale) { mapConverters.remove(locale); } /** * Remove any registered {@link LocaleConverter} for the specified locale and Class. * * @param clazz Class for which to remove a registered Converter * @param locale The locale */ public void deregister(Class clazz, Locale locale) { lookup(locale).remove(clazz); } /** * Look up and return any registered {@link LocaleConverter} for the specified * destination class and locale; if there is no registered Converter, return * null. * * @param clazz Class for which to return a registered Converter * @param locale The Locale * @return The registered locale Converter, if any */ public LocaleConverter lookup(Class clazz, Locale locale) { LocaleConverter converter = (LocaleConverter) lookup(locale).get(clazz); if (log.isTraceEnabled()) { log.trace("LocaleConverter:" + converter); } return converter; } /** * Look up and return any registered FastHashMap instance for the specified locale; * if there is no registered one, return null. * * @param locale The Locale * @return The FastHashMap instance contains the all {@link LocaleConverter} types for * the specified locale. * @deprecated This method will be modified to return a Map in the next release. */ @Deprecated protected FastHashMap lookup(Locale locale) { FastHashMap localeConverters; if (locale == null) { localeConverters = (FastHashMap) mapConverters.get(defaultLocale); } else { localeConverters = (FastHashMap) mapConverters.get(locale); if (localeConverters == null) { localeConverters = create(locale); mapConverters.put(locale, localeConverters); } } return localeConverters; } /** * Create all {@link LocaleConverter} types for specified locale. * * @param locale The Locale * @return The FastHashMap instance contains the all {@link LocaleConverter} types * for the specified locale. * @deprecated This method will be modified to return a Map in the next release. */ @Deprecated protected FastHashMap create(Locale locale) { FastHashMap converter = new DelegateFastHashMap(BeanUtils.createCache()); converter.setFast(false); converter.put(BigDecimal.class, new BigDecimalLocaleConverter(locale, applyLocalized)); converter.put(BigInteger.class, new BigIntegerLocaleConverter(locale, applyLocalized)); converter.put(Byte.class, new ByteLocaleConverter(locale, applyLocalized)); converter.put(Byte.TYPE, new ByteLocaleConverter(locale, applyLocalized)); converter.put(Double.class, new DoubleLocaleConverter(locale, applyLocalized)); converter.put(Double.TYPE, new DoubleLocaleConverter(locale, applyLocalized)); converter.put(Float.class, new FloatLocaleConverter(locale, applyLocalized)); converter.put(Float.TYPE, new FloatLocaleConverter(locale, applyLocalized)); converter.put(Integer.class, new IntegerLocaleConverter(locale, applyLocalized)); converter.put(Integer.TYPE, new IntegerLocaleConverter(locale, applyLocalized)); converter.put(Long.class, new LongLocaleConverter(locale, applyLocalized)); converter.put(Long.TYPE, new LongLocaleConverter(locale, applyLocalized)); converter.put(Short.class, new ShortLocaleConverter(locale, applyLocalized)); converter.put(Short.TYPE, new ShortLocaleConverter(locale, applyLocalized)); converter.put(String.class, new StringLocaleConverter(locale, applyLocalized)); // conversion format patterns of java.sql.* types should correspond to default // behaviour of toString and valueOf methods of these classes converter.put(java.sql.Date.class, new SqlDateLocaleConverter(locale, "yyyy-MM-dd")); converter.put(java.sql.Time.class, new SqlTimeLocaleConverter(locale, "HH:mm:ss")); converter.put( java.sql.Timestamp.class, new SqlTimestampLocaleConverter(locale, "yyyy-MM-dd HH:mm:ss.S") ); converter.setFast(true); return converter; } /** * FastHashMap implementation that uses WeakReferences to overcome * memory leak problems. * * This is a hack to retain binary compatibility with previous * releases (where FastHashMap is exposed in the API), but * use WeakHashMap to resolve memory leaks. */ private static class DelegateFastHashMap extends FastHashMap { private final Map map; private DelegateFastHashMap(Map map) { this.map = map; } @Override public void clear() { map.clear(); } @Override public boolean containsKey(Object key) { return map.containsKey(key); } @Override public boolean containsValue(Object value) { return map.containsValue(value); } @Override public Set> entrySet() { return map.entrySet(); } @Override public boolean equals(Object o) { return map.equals(o); } @Override public Object get(Object key) { return map.get(key); } @Override public int hashCode() { return map.hashCode(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public Set keySet() { return map.keySet(); } @Override public Object put(Object key, Object value) { return map.put(key, value); } @SuppressWarnings({ "rawtypes", "unchecked" }) // we operate on very generic types (), so there is // no need for doing type checks @Override public void putAll(Map m) { map.putAll(m); } @Override public Object remove(Object key) { return map.remove(key); } @Override public int size() { return map.size(); } @Override public Collection values() { return map.values(); } @Override public boolean getFast() { return BeanUtils.getCacheFast(map); } @Override public void setFast(boolean fast) { BeanUtils.setCacheFast(map, fast); } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/locale/package-info.java100644 0 0 1756 12262570611 27643 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Locale-aware extensions of the standard beanutils classes. * This package allows locale-dependent population of JavaBeans. */ package org.apache.commons.beanutils.locale; ././@LongLink100644 0 0 145 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/MappedPropertyDescriptor.javacommons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/MappedPropertyDescriptor.java100644 0 0 51450 12262570611 31106 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * A MappedPropertyDescriptor describes one mapped property. * Mapped properties are multivalued properties like indexed properties * but that are accessed with a String key instead of an index. * Such property values are typically stored in a Map collection. * For this class to work properly, a mapped value must have * getter and setter methods of the form *

          getProperty(String key) and *

          setProperty(String key, Object value), *

          where Property must be replaced * by the name of the property. * @see java.beans.PropertyDescriptor * * @version $Id: MappedPropertyDescriptor.java 1540504 2013-11-10 18:22:57Z niallp $ */ public class MappedPropertyDescriptor extends PropertyDescriptor { // ----------------------------------------------------- Instance Variables /** * The underlying data type of the property we are describing. */ private Reference> mappedPropertyTypeRef; /** * The reader method for this property (if any). */ private MappedMethodReference mappedReadMethodRef; /** * The writer method for this property (if any). */ private MappedMethodReference mappedWriteMethodRef; /** * The parameter types array for the reader method signature. */ private static final Class[] STRING_CLASS_PARAMETER = new Class[]{String.class}; // ----------------------------------------------------------- Constructors /** * Constructs a MappedPropertyDescriptor for a property that follows * the standard Java convention by having getFoo and setFoo * accessor methods, with the addition of a String parameter (the key). * Thus if the argument name is "fred", it will * assume that the writer method is "setFred" and the reader method * is "getFred". Note that the property name should start with a lower * case character, which will be capitalized in the method names. * * @param propertyName The programmatic name of the property. * @param beanClass The Class object for the target bean. For * example sun.beans.OurButton.class. * * @exception IntrospectionException if an exception occurs during * introspection. */ public MappedPropertyDescriptor(String propertyName, Class beanClass) throws IntrospectionException { super(propertyName, null, null); if (propertyName == null || propertyName.length() == 0) { throw new IntrospectionException("bad property name: " + propertyName + " on class: " + beanClass.getClass().getName()); } setName(propertyName); String base = capitalizePropertyName(propertyName); // Look for mapped read method and matching write method Method mappedReadMethod = null; Method mappedWriteMethod = null; try { try { mappedReadMethod = getMethod(beanClass, "get" + base, STRING_CLASS_PARAMETER); } catch (IntrospectionException e) { mappedReadMethod = getMethod(beanClass, "is" + base, STRING_CLASS_PARAMETER); } Class[] params = { String.class, mappedReadMethod.getReturnType() }; mappedWriteMethod = getMethod(beanClass, "set" + base, params); } catch (IntrospectionException e) { /* Swallow IntrospectionException * TODO: Why? */ } // If there's no read method, then look for just a write method if (mappedReadMethod == null) { mappedWriteMethod = getMethod(beanClass, "set" + base, 2); } if ((mappedReadMethod == null) && (mappedWriteMethod == null)) { throw new IntrospectionException("Property '" + propertyName + "' not found on " + beanClass.getName()); } mappedReadMethodRef = new MappedMethodReference(mappedReadMethod); mappedWriteMethodRef = new MappedMethodReference(mappedWriteMethod); findMappedPropertyType(); } /** * This constructor takes the name of a mapped property, and method * names for reading and writing the property. * * @param propertyName The programmatic name of the property. * @param beanClass The Class object for the target bean. For * example sun.beans.OurButton.class. * @param mappedGetterName The name of the method used for * reading one of the property values. May be null if the * property is write-only. * @param mappedSetterName The name of the method used for writing * one of the property values. May be null if the property is * read-only. * * @exception IntrospectionException if an exception occurs during * introspection. */ public MappedPropertyDescriptor(String propertyName, Class beanClass, String mappedGetterName, String mappedSetterName) throws IntrospectionException { super(propertyName, null, null); if (propertyName == null || propertyName.length() == 0) { throw new IntrospectionException("bad property name: " + propertyName); } setName(propertyName); // search the mapped get and set methods Method mappedReadMethod = null; Method mappedWriteMethod = null; mappedReadMethod = getMethod(beanClass, mappedGetterName, STRING_CLASS_PARAMETER); if (mappedReadMethod != null) { Class[] params = { String.class, mappedReadMethod.getReturnType() }; mappedWriteMethod = getMethod(beanClass, mappedSetterName, params); } else { mappedWriteMethod = getMethod(beanClass, mappedSetterName, 2); } mappedReadMethodRef = new MappedMethodReference(mappedReadMethod); mappedWriteMethodRef = new MappedMethodReference(mappedWriteMethod); findMappedPropertyType(); } /** * This constructor takes the name of a mapped property, and Method * objects for reading and writing the property. * * @param propertyName The programmatic name of the property. * @param mappedGetter The method used for reading one of * the property values. May be be null if the property * is write-only. * @param mappedSetter The method used for writing one the * property values. May be null if the property is read-only. * * @exception IntrospectionException if an exception occurs during * introspection. */ public MappedPropertyDescriptor(String propertyName, Method mappedGetter, Method mappedSetter) throws IntrospectionException { super(propertyName, mappedGetter, mappedSetter); if (propertyName == null || propertyName.length() == 0) { throw new IntrospectionException("bad property name: " + propertyName); } setName(propertyName); mappedReadMethodRef = new MappedMethodReference(mappedGetter); mappedWriteMethodRef = new MappedMethodReference(mappedSetter); findMappedPropertyType(); } // -------------------------------------------------------- Public Methods /** * Gets the Class object for the property values. * * @return The Java type info for the property values. Note that * the "Class" object may describe a built-in Java type such as "int". * The result may be "null" if this is a mapped property that * does not support non-keyed access. *

          * This is the type that will be returned by the mappedReadMethod. */ public Class getMappedPropertyType() { return mappedPropertyTypeRef.get(); } /** * Gets the method that should be used to read one of the property value. * * @return The method that should be used to read the property value. * May return null if the property can't be read. */ public Method getMappedReadMethod() { return mappedReadMethodRef.get(); } /** * Sets the method that should be used to read one of the property value. * * @param mappedGetter The mapped getter method. * @throws IntrospectionException If an error occurs finding the * mapped property */ public void setMappedReadMethod(Method mappedGetter) throws IntrospectionException { mappedReadMethodRef = new MappedMethodReference(mappedGetter); findMappedPropertyType(); } /** * Gets the method that should be used to write one of the property value. * * @return The method that should be used to write one of the property value. * May return null if the property can't be written. */ public Method getMappedWriteMethod() { return mappedWriteMethodRef.get(); } /** * Sets the method that should be used to write the property value. * * @param mappedSetter The mapped setter method. * @throws IntrospectionException If an error occurs finding the * mapped property */ public void setMappedWriteMethod(Method mappedSetter) throws IntrospectionException { mappedWriteMethodRef = new MappedMethodReference(mappedSetter); findMappedPropertyType(); } // ------------------------------------------------------- Private Methods /** * Introspect our bean class to identify the corresponding getter * and setter methods. */ private void findMappedPropertyType() throws IntrospectionException { try { Method mappedReadMethod = getMappedReadMethod(); Method mappedWriteMethod = getMappedWriteMethod(); Class mappedPropertyType = null; if (mappedReadMethod != null) { if (mappedReadMethod.getParameterTypes().length != 1) { throw new IntrospectionException ("bad mapped read method arg count"); } mappedPropertyType = mappedReadMethod.getReturnType(); if (mappedPropertyType == Void.TYPE) { throw new IntrospectionException ("mapped read method " + mappedReadMethod.getName() + " returns void"); } } if (mappedWriteMethod != null) { Class[] params = mappedWriteMethod.getParameterTypes(); if (params.length != 2) { throw new IntrospectionException ("bad mapped write method arg count"); } if (mappedPropertyType != null && mappedPropertyType != params[1]) { throw new IntrospectionException ("type mismatch between mapped read and write methods"); } mappedPropertyType = params[1]; } mappedPropertyTypeRef = new SoftReference>(mappedPropertyType); } catch (IntrospectionException ex) { throw ex; } } /** * Return a capitalized version of the specified property name. * * @param s The property name */ private static String capitalizePropertyName(String s) { if (s.length() == 0) { return s; } char[] chars = s.toCharArray(); chars[0] = Character.toUpperCase(chars[0]); return new String(chars); } /** * Find a method on a class with a specified number of parameters. */ private static Method internalGetMethod(Class initial, String methodName, int parameterCount) { // For overridden methods we need to find the most derived version. // So we start with the given class and walk up the superclass chain. for (Class clazz = initial; clazz != null; clazz = clazz.getSuperclass()) { Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method == null) { continue; } // skip static methods. int mods = method.getModifiers(); if (!Modifier.isPublic(mods) || Modifier.isStatic(mods)) { continue; } if (method.getName().equals(methodName) && method.getParameterTypes().length == parameterCount) { return method; } } } // Now check any inherited interfaces. This is necessary both when // the argument class is itself an interface, and when the argument // class is an abstract class. Class[] interfaces = initial.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { Method method = internalGetMethod(interfaces[i], methodName, parameterCount); if (method != null) { return method; } } return null; } /** * Find a method on a class with a specified number of parameters. */ private static Method getMethod(Class clazz, String methodName, int parameterCount) throws IntrospectionException { if (methodName == null) { return null; } Method method = internalGetMethod(clazz, methodName, parameterCount); if (method != null) { return method; } // No Method found throw new IntrospectionException("No method \"" + methodName + "\" with " + parameterCount + " parameter(s)"); } /** * Find a method on a class with a specified parameter list. */ private static Method getMethod(Class clazz, String methodName, Class[] parameterTypes) throws IntrospectionException { if (methodName == null) { return null; } Method method = MethodUtils.getMatchingAccessibleMethod(clazz, methodName, parameterTypes); if (method != null) { return method; } int parameterCount = (parameterTypes == null) ? 0 : parameterTypes.length; // No Method found throw new IntrospectionException("No method \"" + methodName + "\" with " + parameterCount + " parameter(s) of matching types."); } /** * Holds a {@link Method} in a {@link SoftReference} so that it * it doesn't prevent any ClassLoader being garbage collected, but * tries to re-create the method if the method reference has been * released. * * See http://issues.apache.org/jira/browse/BEANUTILS-291 */ private static class MappedMethodReference { private String className; private String methodName; private Reference methodRef; private Reference> classRef; private Reference> writeParamTypeRef0; private Reference> writeParamTypeRef1; private String[] writeParamClassNames; MappedMethodReference(Method m) { if (m != null) { className = m.getDeclaringClass().getName(); methodName = m.getName(); methodRef = new SoftReference(m); classRef = new WeakReference>(m.getDeclaringClass()); Class[] types = m.getParameterTypes(); if (types.length == 2) { writeParamTypeRef0 = new WeakReference>(types[0]); writeParamTypeRef1 = new WeakReference>(types[1]); writeParamClassNames = new String[2]; writeParamClassNames[0] = types[0].getName(); writeParamClassNames[1] = types[1].getName(); } } } private Method get() { if (methodRef == null) { return null; } Method m = methodRef.get(); if (m == null) { Class clazz = classRef.get(); if (clazz == null) { clazz = reLoadClass(); if (clazz != null) { classRef = new WeakReference>(clazz); } } if (clazz == null) { throw new RuntimeException("Method " + methodName + " for " + className + " could not be reconstructed - class reference has gone"); } Class[] paramTypes = null; if (writeParamClassNames != null) { paramTypes = new Class[2]; paramTypes[0] = writeParamTypeRef0.get(); if (paramTypes[0] == null) { paramTypes[0] = reLoadClass(writeParamClassNames[0]); if (paramTypes[0] != null) { writeParamTypeRef0 = new WeakReference>(paramTypes[0]); } } paramTypes[1] = writeParamTypeRef1.get(); if (paramTypes[1] == null) { paramTypes[1] = reLoadClass(writeParamClassNames[1]); if (paramTypes[1] != null) { writeParamTypeRef1 = new WeakReference>(paramTypes[1]); } } } else { paramTypes = STRING_CLASS_PARAMETER; } try { m = clazz.getMethod(methodName, paramTypes); // Un-comment following line for testing // System.out.println("Recreated Method " + methodName + " for " + className); } catch (NoSuchMethodException e) { throw new RuntimeException("Method " + methodName + " for " + className + " could not be reconstructed - method not found"); } methodRef = new SoftReference(m); } return m; } /** * Try to re-load the class */ private Class reLoadClass() { return reLoadClass(className); } /** * Try to re-load the class */ private Class reLoadClass(String name) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Try the context class loader if (classLoader != null) { try { return classLoader.loadClass(name); } catch (ClassNotFoundException e) { // ignore } } // Try this class's class loader classLoader = MappedPropertyDescriptor.class.getClassLoader(); try { return classLoader.loadClass(name); } catch (ClassNotFoundException e) { return null; } } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/MethodUtils.java100644 0 0 152051 12262570612 26355 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

          Utility reflection methods focused on methods in general rather than properties in particular.

          * *

          Known Limitations

          *

          Accessing Public Methods In A Default Access Superclass

          *

          There is an issue when invoking public methods contained in a default access superclass. * Reflection locates these methods fine and correctly assigns them as public. * However, an IllegalAccessException is thrown if the method is invoked.

          * *

          MethodUtils contains a workaround for this situation. * It will attempt to call setAccessible on this method. * If this call succeeds, then the method can be invoked as normal. * This call will only succeed when the application has sufficient security privilages. * If this call fails then a warning will be logged and the method may fail.

          * * @version $Id: MethodUtils.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class MethodUtils { // --------------------------------------------------------- Private Methods /** * Only log warning about accessibility work around once. *

          * Note that this is broken when this class is deployed via a shared * classloader in a container, as the warning message will be emitted * only once, not once per webapp. However making the warning appear * once per webapp means having a map keyed by context classloader * which introduces nasty memory-leak problems. As this warning is * really optional we can ignore this problem; only one of the webapps * will get the warning in its logs but that should be good enough. */ private static boolean loggedAccessibleWarning = false; /** * Indicates whether methods should be cached for improved performance. *

          * Note that when this class is deployed via a shared classloader in * a container, this will affect all webapps. However making this * configurable per webapp would mean having a map keyed by context classloader * which may introduce memory-leak problems. */ private static boolean CACHE_METHODS = true; /** An empty class array */ private static final Class[] EMPTY_CLASS_PARAMETERS = new Class[0]; /** An empty object array */ private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; /** * Stores a cache of MethodDescriptor -> Method in a WeakHashMap. *

          * The keys into this map only ever exist as temporary variables within * methods of this class, and are never exposed to users of this class. * This means that the WeakHashMap is used only as a mechanism for * limiting the size of the cache, ie a way to tell the garbage collector * that the contents of the cache can be completely garbage-collected * whenever it needs the memory. Whether this is a good approach to * this problem is doubtful; something like the commons-collections * LRUMap may be more appropriate (though of course selecting an * appropriate size is an issue). *

          * This static variable is safe even when this code is deployed via a * shared classloader because it is keyed via a MethodDescriptor object * which has a Class as one of its members and that member is used in * the MethodDescriptor.equals method. So two components that load the same * class via different classloaders will generate non-equal MethodDescriptor * objects and hence end up with different entries in the map. */ private static final Map> cache = Collections .synchronizedMap(new WeakHashMap>()); // --------------------------------------------------------- Public Methods /** * Set whether methods should be cached for greater performance or not, * default is true. * * @param cacheMethods true if methods should be * cached for greater performance, otherwise false * @since 1.8.0 */ public static synchronized void setCacheMethods(boolean cacheMethods) { CACHE_METHODS = cacheMethods; if (!CACHE_METHODS) { clearCache(); } } /** * Clear the method cache. * @return the number of cached methods cleared * @since 1.8.0 */ public static synchronized int clearCache() { int size = cache.size(); cache.clear(); return size; } /** *

          Invoke a named method whose parameter type matches the object type.

          * *

          The behaviour of this method is less deterministic * than invokeExactMethod(). * It loops through all methods with names that match * and then executes the first it finds with compatible parameters.

          * *

          This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean class * would match a boolean primitive.

          * *

          This is a convenient wrapper for * {@link #invokeMethod(Object object,String methodName,Object [] args)}. *

          * * @param object invoke method on this object * @param methodName get method with this name * @param arg use this argument. May be null (this will result in calling the * parameterless method with name {@code methodName}). * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeMethod( Object object, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Object[] args = toArray(arg); return invokeMethod(object, methodName, args); } /** *

          Invoke a named method whose parameter type matches the object type.

          * *

          The behaviour of this method is less deterministic * than {@link #invokeExactMethod(Object object,String methodName,Object [] args)}. * It loops through all methods with names that match * and then executes the first it finds with compatible parameters.

          * *

          This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean class * would match a boolean primitive.

          * *

          This is a convenient wrapper for * {@link #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}. *

          * * @param object invoke method on this object * @param methodName get method with this name * @param args use these arguments - treat null as empty array (passing null will * result in calling the parameterless method with name {@code methodName}). * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeMethod( Object object, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class[] parameterTypes = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeMethod(object, methodName, args, parameterTypes); } /** *

          Invoke a named method whose parameter type matches the object type.

          * *

          The behaviour of this method is less deterministic * than {@link * #invokeExactMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}. * It loops through all methods with names that match * and then executes the first it finds with compatible parameters.

          * *

          This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean class * would match a boolean primitive.

          * * * @param object invoke method on this object * @param methodName get method with this name * @param args use these arguments - treat null as empty array (passing null will * result in calling the parameterless method with name {@code methodName}). * @param parameterTypes match these parameters - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeMethod( Object object, String methodName, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (parameterTypes == null) { parameterTypes = EMPTY_CLASS_PARAMETERS; } if (args == null) { args = EMPTY_OBJECT_ARRAY; } Method method = getMatchingAccessibleMethod( object.getClass(), methodName, parameterTypes); if (method == null) { throw new NoSuchMethodException("No such accessible method: " + methodName + "() on object: " + object.getClass().getName()); } return method.invoke(object, args); } /** *

          Invoke a method whose parameter type matches exactly the object * type.

          * *

          This is a convenient wrapper for * {@link #invokeExactMethod(Object object,String methodName,Object [] args)}. *

          * * @param object invoke method on this object * @param methodName get method with this name * @param arg use this argument. May be null (this will result in calling the * parameterless method with name {@code methodName}). * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeExactMethod( Object object, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Object[] args = toArray(arg); return invokeExactMethod(object, methodName, args); } /** *

          Invoke a method whose parameter types match exactly the object * types.

          * *

          This uses reflection to invoke the method obtained from a call to * getAccessibleMethod().

          * * @param object invoke method on this object * @param methodName get method with this name * @param args use these arguments - treat null as empty array (passing null will * result in calling the parameterless method with name {@code methodName}). * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeExactMethod( Object object, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class[] parameterTypes = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeExactMethod(object, methodName, args, parameterTypes); } /** *

          Invoke a method whose parameter types match exactly the parameter * types given.

          * *

          This uses reflection to invoke the method obtained from a call to * getAccessibleMethod().

          * * @param object invoke method on this object * @param methodName get method with this name * @param args use these arguments - treat null as empty array (passing null will * result in calling the parameterless method with name {@code methodName}). * @param parameterTypes match these parameters - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeExactMethod( Object object, String methodName, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = EMPTY_OBJECT_ARRAY; } if (parameterTypes == null) { parameterTypes = EMPTY_CLASS_PARAMETERS; } Method method = getAccessibleMethod( object.getClass(), methodName, parameterTypes); if (method == null) { throw new NoSuchMethodException("No such accessible method: " + methodName + "() on object: " + object.getClass().getName()); } return method.invoke(object, args); } /** *

          Invoke a static method whose parameter types match exactly the parameter * types given.

          * *

          This uses reflection to invoke the method obtained from a call to * {@link #getAccessibleMethod(Class, String, Class[])}.

          * * @param objectClass invoke static method on this class * @param methodName get method with this name * @param args use these arguments - treat null as empty array (passing null will * result in calling the parameterless method with name {@code methodName}). * @param parameterTypes match these parameters - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection * @since 1.8.0 */ public static Object invokeExactStaticMethod( Class objectClass, String methodName, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = EMPTY_OBJECT_ARRAY; } if (parameterTypes == null) { parameterTypes = EMPTY_CLASS_PARAMETERS; } Method method = getAccessibleMethod( objectClass, methodName, parameterTypes); if (method == null) { throw new NoSuchMethodException("No such accessible method: " + methodName + "() on class: " + objectClass.getName()); } return method.invoke(null, args); } /** *

          Invoke a named static method whose parameter type matches the object type.

          * *

          The behaviour of this method is less deterministic * than {@link #invokeExactMethod(Object, String, Object[], Class[])}. * It loops through all methods with names that match * and then executes the first it finds with compatible parameters.

          * *

          This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean class * would match a boolean primitive.

          * *

          This is a convenient wrapper for * {@link #invokeStaticMethod(Class objectClass,String methodName,Object [] args)}. *

          * * @param objectClass invoke static method on this class * @param methodName get method with this name * @param arg use this argument. May be null (this will result in calling the * parameterless method with name {@code methodName}). * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection * @since 1.8.0 */ public static Object invokeStaticMethod( Class objectClass, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Object[] args = toArray(arg); return invokeStaticMethod (objectClass, methodName, args); } /** *

          Invoke a named static method whose parameter type matches the object type.

          * *

          The behaviour of this method is less deterministic * than {@link #invokeExactMethod(Object object,String methodName,Object [] args)}. * It loops through all methods with names that match * and then executes the first it finds with compatible parameters.

          * *

          This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean class * would match a boolean primitive.

          * *

          This is a convenient wrapper for * {@link #invokeStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes)}. *

          * * @param objectClass invoke static method on this class * @param methodName get method with this name * @param args use these arguments - treat null as empty array (passing null will * result in calling the parameterless method with name {@code methodName}). * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection * @since 1.8.0 */ public static Object invokeStaticMethod( Class objectClass, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class[] parameterTypes = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeStaticMethod (objectClass, methodName, args, parameterTypes); } /** *

          Invoke a named static method whose parameter type matches the object type.

          * *

          The behaviour of this method is less deterministic * than {@link * #invokeExactStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes)}. * It loops through all methods with names that match * and then executes the first it finds with compatible parameters.

          * *

          This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean class * would match a boolean primitive.

          * * * @param objectClass invoke static method on this class * @param methodName get method with this name * @param args use these arguments - treat null as empty array (passing null will * result in calling the parameterless method with name {@code methodName}). * @param parameterTypes match these parameters - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection * @since 1.8.0 */ public static Object invokeStaticMethod( Class objectClass, String methodName, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (parameterTypes == null) { parameterTypes = EMPTY_CLASS_PARAMETERS; } if (args == null) { args = EMPTY_OBJECT_ARRAY; } Method method = getMatchingAccessibleMethod( objectClass, methodName, parameterTypes); if (method == null) { throw new NoSuchMethodException("No such accessible method: " + methodName + "() on class: " + objectClass.getName()); } return method.invoke(null, args); } /** *

          Invoke a static method whose parameter type matches exactly the object * type.

          * *

          This is a convenient wrapper for * {@link #invokeExactStaticMethod(Class objectClass,String methodName,Object [] args)}. *

          * * @param objectClass invoke static method on this class * @param methodName get method with this name * @param arg use this argument. May be null (this will result in calling the * parameterless method with name {@code methodName}). * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection * @since 1.8.0 */ public static Object invokeExactStaticMethod( Class objectClass, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Object[] args = toArray(arg); return invokeExactStaticMethod (objectClass, methodName, args); } /** *

          Invoke a static method whose parameter types match exactly the object * types.

          * *

          This uses reflection to invoke the method obtained from a call to * {@link #getAccessibleMethod(Class, String, Class[])}.

          * * @param objectClass invoke static method on this class * @param methodName get method with this name * @param args use these arguments - treat null as empty array (passing null will * result in calling the parameterless method with name {@code methodName}). * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection * @since 1.8.0 */ public static Object invokeExactStaticMethod( Class objectClass, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class[] parameterTypes = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeExactStaticMethod(objectClass, methodName, args, parameterTypes); } private static Object[] toArray(Object arg) { Object[] args = null; if (arg != null) { args = new Object[] { arg }; } return args; } /** *

          Return an accessible method (that is, one that can be invoked via * reflection) with given name and a single parameter. If no such method * can be found, return null. * Basically, a convenience wrapper that constructs a Class * array for you.

          * * @param clazz get method from this class * @param methodName get method with this name * @param parameterType taking this type of parameter * @return The accessible method */ public static Method getAccessibleMethod( Class clazz, String methodName, Class parameterType) { Class[] parameterTypes = {parameterType}; return getAccessibleMethod(clazz, methodName, parameterTypes); } /** *

          Return an accessible method (that is, one that can be invoked via * reflection) with given name and parameters. If no such method * can be found, return null. * This is just a convenient wrapper for * {@link #getAccessibleMethod(Method method)}.

          * * @param clazz get method from this class * @param methodName get method with this name * @param parameterTypes with these parameters types * @return The accessible method */ public static Method getAccessibleMethod( Class clazz, String methodName, Class[] parameterTypes) { try { MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, true); // Check the cache first Method method = getCachedMethod(md); if (method != null) { return method; } method = getAccessibleMethod (clazz, clazz.getMethod(methodName, parameterTypes)); cacheMethod(md, method); return method; } catch (NoSuchMethodException e) { return (null); } } /** *

          Return an accessible method (that is, one that can be invoked via * reflection) that implements the specified Method. If no such method * can be found, return null.

          * * @param method The method that we wish to call * @return The accessible method */ public static Method getAccessibleMethod(Method method) { // Make sure we have a method to check if (method == null) { return (null); } return getAccessibleMethod(method.getDeclaringClass(), method); } /** *

          Return an accessible method (that is, one that can be invoked via * reflection) that implements the specified Method. If no such method * can be found, return null.

          * * @param clazz The class of the object * @param method The method that we wish to call * @return The accessible method * @since 1.8.0 */ public static Method getAccessibleMethod(Class clazz, Method method) { // Make sure we have a method to check if (method == null) { return (null); } // If the requested method is not public we cannot call it if (!Modifier.isPublic(method.getModifiers())) { return (null); } boolean sameClass = true; if (clazz == null) { clazz = method.getDeclaringClass(); } else { sameClass = clazz.equals(method.getDeclaringClass()); if (!method.getDeclaringClass().isAssignableFrom(clazz)) { throw new IllegalArgumentException(clazz.getName() + " is not assignable from " + method.getDeclaringClass().getName()); } } // If the class is public, we are done if (Modifier.isPublic(clazz.getModifiers())) { if (!sameClass && !Modifier.isPublic(method.getDeclaringClass().getModifiers())) { setMethodAccessible(method); // Default access superclass workaround } return (method); } String methodName = method.getName(); Class[] parameterTypes = method.getParameterTypes(); // Check the implemented interfaces and subinterfaces method = getAccessibleMethodFromInterfaceNest(clazz, methodName, parameterTypes); // Check the superclass chain if (method == null) { method = getAccessibleMethodFromSuperclass(clazz, methodName, parameterTypes); } return (method); } // -------------------------------------------------------- Private Methods /** *

          Return an accessible method (that is, one that can be invoked via * reflection) by scanning through the superclasses. If no such method * can be found, return null.

          * * @param clazz Class to be checked * @param methodName Method name of the method we wish to call * @param parameterTypes The parameter type signatures */ private static Method getAccessibleMethodFromSuperclass (Class clazz, String methodName, Class[] parameterTypes) { Class parentClazz = clazz.getSuperclass(); while (parentClazz != null) { if (Modifier.isPublic(parentClazz.getModifiers())) { try { return parentClazz.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { return null; } } parentClazz = parentClazz.getSuperclass(); } return null; } /** *

          Return an accessible method (that is, one that can be invoked via * reflection) that implements the specified method, by scanning through * all implemented interfaces and subinterfaces. If no such method * can be found, return null.

          * *

          There isn't any good reason why this method must be private. * It is because there doesn't seem any reason why other classes should * call this rather than the higher level methods.

          * * @param clazz Parent class for the interfaces to be checked * @param methodName Method name of the method we wish to call * @param parameterTypes The parameter type signatures */ private static Method getAccessibleMethodFromInterfaceNest (Class clazz, String methodName, Class[] parameterTypes) { Method method = null; // Search up the superclass chain for (; clazz != null; clazz = clazz.getSuperclass()) { // Check the implemented interfaces of the parent class Class[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { // Is this interface public? if (!Modifier.isPublic(interfaces[i].getModifiers())) { continue; } // Does the method exist on this interface? try { method = interfaces[i].getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { /* Swallow, if no method is found after the loop then this * method returns null. */ } if (method != null) { return method; } // Recursively check our parent interfaces method = getAccessibleMethodFromInterfaceNest(interfaces[i], methodName, parameterTypes); if (method != null) { return method; } } } // We did not find anything return (null); } /** *

          Find an accessible method that matches the given name and has compatible parameters. * Compatible parameters mean that every method parameter is assignable from * the given parameters. * In other words, it finds a method with the given name * that will take the parameters given.

          * *

          This method is slightly undeterministic since it loops * through methods names and return the first matching method.

          * *

          This method is used by * {@link * #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}. * *

          This method can match primitive parameter by passing in wrapper classes. * For example, a Boolean will match a primitive boolean * parameter. * * @param clazz find method in this class * @param methodName find method with this name * @param parameterTypes find method with compatible parameters * @return The accessible method */ public static Method getMatchingAccessibleMethod( Class clazz, String methodName, Class[] parameterTypes) { // trace logging Log log = LogFactory.getLog(MethodUtils.class); if (log.isTraceEnabled()) { log.trace("Matching name=" + methodName + " on " + clazz); } MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false); // see if we can find the method directly // most of the time this works and it's much faster try { // Check the cache first Method method = getCachedMethod(md); if (method != null) { return method; } method = clazz.getMethod(methodName, parameterTypes); if (log.isTraceEnabled()) { log.trace("Found straight match: " + method); log.trace("isPublic:" + Modifier.isPublic(method.getModifiers())); } setMethodAccessible(method); // Default access superclass workaround cacheMethod(md, method); return method; } catch (NoSuchMethodException e) { /* SWALLOW */ } // search through all methods int paramSize = parameterTypes.length; Method bestMatch = null; Method[] methods = clazz.getMethods(); float bestMatchCost = Float.MAX_VALUE; float myCost = Float.MAX_VALUE; for (int i = 0, size = methods.length; i < size ; i++) { if (methods[i].getName().equals(methodName)) { // log some trace information if (log.isTraceEnabled()) { log.trace("Found matching name:"); log.trace(methods[i]); } // compare parameters Class[] methodsParams = methods[i].getParameterTypes(); int methodParamSize = methodsParams.length; if (methodParamSize == paramSize) { boolean match = true; for (int n = 0 ; n < methodParamSize; n++) { if (log.isTraceEnabled()) { log.trace("Param=" + parameterTypes[n].getName()); log.trace("Method=" + methodsParams[n].getName()); } if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) { if (log.isTraceEnabled()) { log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]); } match = false; break; } } if (match) { // get accessible version of method Method method = getAccessibleMethod(clazz, methods[i]); if (method != null) { if (log.isTraceEnabled()) { log.trace(method + " accessible version of " + methods[i]); } setMethodAccessible(method); // Default access superclass workaround myCost = getTotalTransformationCost(parameterTypes,method.getParameterTypes()); if ( myCost < bestMatchCost ) { bestMatch = method; bestMatchCost = myCost; } } log.trace("Couldn't find accessible method."); } } } } if ( bestMatch != null ){ cacheMethod(md, bestMatch); } else { // didn't find a match log.trace("No match found."); } return bestMatch; } /** * Try to make the method accessible * @param method The source arguments */ private static void setMethodAccessible(Method method) { try { // // XXX Default access superclass workaround // // When a public class has a default access superclass // with public methods, these methods are accessible. // Calling them from compiled code works fine. // // Unfortunately, using reflection to invoke these methods // seems to (wrongly) to prevent access even when the method // modifer is public. // // The following workaround solves the problem but will only // work from sufficiently privilages code. // // Better workarounds would be greatfully accepted. // if (!method.isAccessible()) { method.setAccessible(true); } } catch (SecurityException se) { // log but continue just in case the method.invoke works anyway Log log = LogFactory.getLog(MethodUtils.class); if (!loggedAccessibleWarning) { boolean vulnerableJVM = false; try { String specVersion = System.getProperty("java.specification.version"); if (specVersion.charAt(0) == '1' && (specVersion.charAt(2) == '0' || specVersion.charAt(2) == '1' || specVersion.charAt(2) == '2' || specVersion.charAt(2) == '3')) { vulnerableJVM = true; } } catch (SecurityException e) { // don't know - so display warning vulnerableJVM = true; } if (vulnerableJVM) { log.warn( "Current Security Manager restricts use of workarounds for reflection bugs " + " in pre-1.4 JVMs."); } loggedAccessibleWarning = true; } log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se); } } /** * Returns the sum of the object transformation cost for each class in the source * argument list. * @param srcArgs The source arguments * @param destArgs The destination arguments * @return The total transformation cost */ private static float getTotalTransformationCost(Class[] srcArgs, Class[] destArgs) { float totalCost = 0.0f; for (int i = 0; i < srcArgs.length; i++) { Class srcClass, destClass; srcClass = srcArgs[i]; destClass = destArgs[i]; totalCost += getObjectTransformationCost(srcClass, destClass); } return totalCost; } /** * Gets the number of steps required needed to turn the source class into the * destination class. This represents the number of steps in the object hierarchy * graph. * @param srcClass The source class * @param destClass The destination class * @return The cost of transforming an object */ private static float getObjectTransformationCost(Class srcClass, Class destClass) { float cost = 0.0f; while (srcClass != null && !destClass.equals(srcClass)) { if (destClass.isPrimitive()) { Class destClassWrapperClazz = getPrimitiveWrapper(destClass); if (destClassWrapperClazz != null && destClassWrapperClazz.equals(srcClass)) { cost += 0.25f; break; } } if (destClass.isInterface() && isAssignmentCompatible(destClass,srcClass)) { // slight penalty for interface match. // we still want an exact match to override an interface match, but // an interface match should override anything where we have to get a // superclass. cost += 0.25f; break; } cost++; srcClass = srcClass.getSuperclass(); } /* * If the destination class is null, we've travelled all the way up to * an Object match. We'll penalize this by adding 1.5 to the cost. */ if (srcClass == null) { cost += 1.5f; } return cost; } /** *

          Determine whether a type can be used as a parameter in a method invocation. * This method handles primitive conversions correctly.

          * *

          In order words, it will match a Boolean to a boolean, * a Long to a long, * a Float to a float, * a Integer to a int, * and a Double to a double. * Now logic widening matches are allowed. * For example, a Long will not match a int. * * @param parameterType the type of parameter accepted by the method * @param parameterization the type of parameter being tested * * @return true if the assignment is compatible. */ public static final boolean isAssignmentCompatible(Class parameterType, Class parameterization) { // try plain assignment if (parameterType.isAssignableFrom(parameterization)) { return true; } if (parameterType.isPrimitive()) { // this method does *not* do widening - you must specify exactly // is this the right behaviour? Class parameterWrapperClazz = getPrimitiveWrapper(parameterType); if (parameterWrapperClazz != null) { return parameterWrapperClazz.equals(parameterization); } } return false; } /** * Gets the wrapper object class for the given primitive type class. * For example, passing boolean.class returns Boolean.class * @param primitiveType the primitive type class for which a match is to be found * @return the wrapper type associated with the given primitive * or null if no match is found */ public static Class getPrimitiveWrapper(Class primitiveType) { // does anyone know a better strategy than comparing names? if (boolean.class.equals(primitiveType)) { return Boolean.class; } else if (float.class.equals(primitiveType)) { return Float.class; } else if (long.class.equals(primitiveType)) { return Long.class; } else if (int.class.equals(primitiveType)) { return Integer.class; } else if (short.class.equals(primitiveType)) { return Short.class; } else if (byte.class.equals(primitiveType)) { return Byte.class; } else if (double.class.equals(primitiveType)) { return Double.class; } else if (char.class.equals(primitiveType)) { return Character.class; } else { return null; } } /** * Gets the class for the primitive type corresponding to the primitive wrapper class given. * For example, an instance of Boolean.class returns a boolean.class. * @param wrapperType the * @return the primitive type class corresponding to the given wrapper class, * null if no match is found */ public static Class getPrimitiveType(Class wrapperType) { // does anyone know a better strategy than comparing names? if (Boolean.class.equals(wrapperType)) { return boolean.class; } else if (Float.class.equals(wrapperType)) { return float.class; } else if (Long.class.equals(wrapperType)) { return long.class; } else if (Integer.class.equals(wrapperType)) { return int.class; } else if (Short.class.equals(wrapperType)) { return short.class; } else if (Byte.class.equals(wrapperType)) { return byte.class; } else if (Double.class.equals(wrapperType)) { return double.class; } else if (Character.class.equals(wrapperType)) { return char.class; } else { Log log = LogFactory.getLog(MethodUtils.class); if (log.isDebugEnabled()) { log.debug("Not a known primitive wrapper class: " + wrapperType); } return null; } } /** * Find a non primitive representation for given primitive class. * * @param clazz the class to find a representation for, not null * @return the original class if it not a primitive. Otherwise the wrapper class. Not null */ public static Class toNonPrimitiveClass(Class clazz) { if (clazz.isPrimitive()) { Class primitiveClazz = MethodUtils.getPrimitiveWrapper(clazz); // the above method returns if (primitiveClazz != null) { return primitiveClazz; } else { return clazz; } } else { return clazz; } } /** * Return the method from the cache, if present. * * @param md The method descriptor * @return The cached method */ private static Method getCachedMethod(MethodDescriptor md) { if (CACHE_METHODS) { Reference methodRef = cache.get(md); if (methodRef != null) { return methodRef.get(); } } return null; } /** * Add a method to the cache. * * @param md The method descriptor * @param method The method to cache */ private static void cacheMethod(MethodDescriptor md, Method method) { if (CACHE_METHODS) { if (method != null) { cache.put(md, new WeakReference(method)); } } } /** * Represents the key to looking up a Method by reflection. */ private static class MethodDescriptor { private final Class cls; private final String methodName; private final Class[] paramTypes; private final boolean exact; private final int hashCode; /** * The sole constructor. * * @param cls the class to reflect, must not be null * @param methodName the method name to obtain * @param paramTypes the array of classes representing the parameter types * @param exact whether the match has to be exact. */ public MethodDescriptor(Class cls, String methodName, Class[] paramTypes, boolean exact) { if (cls == null) { throw new IllegalArgumentException("Class cannot be null"); } if (methodName == null) { throw new IllegalArgumentException("Method Name cannot be null"); } if (paramTypes == null) { paramTypes = EMPTY_CLASS_PARAMETERS; } this.cls = cls; this.methodName = methodName; this.paramTypes = paramTypes; this.exact= exact; this.hashCode = methodName.length(); } /** * Checks for equality. * @param obj object to be tested for equality * @return true, if the object describes the same Method. */ @Override public boolean equals(Object obj) { if (!(obj instanceof MethodDescriptor)) { return false; } MethodDescriptor md = (MethodDescriptor)obj; return ( exact == md.exact && methodName.equals(md.methodName) && cls.equals(md.cls) && java.util.Arrays.equals(paramTypes, md.paramTypes) ); } /** * Returns the string length of method name. I.e. if the * hashcodes are different, the objects are different. If the * hashcodes are the same, need to use the equals method to * determine equality. * @return the string length of method name. */ @Override public int hashCode() { return hashCode; } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/MutableDynaClass.java100644 0 0 10372 12262570612 27266 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** *

          A specialized extension to DynaClass that allows properties * to be added or removed dynamically.

          * *

          WARNING - No guarantees that this will be in the final * APIs ... it's here primarily to preserve some concepts that were in the * original proposal for further discussion.

          * * @version $Id: MutableDynaClass.java 1540186 2013-11-08 21:08:30Z oheger $ */ public interface MutableDynaClass extends DynaClass { /** * Add a new dynamic property with no restrictions on data type, * readability, or writeability. * * @param name Name of the new dynamic property * * @exception IllegalArgumentException if name is null * @exception IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ public void add(String name); /** * Add a new dynamic property with the specified data type, but with * no restrictions on readability or writeability. * * @param name Name of the new dynamic property * @param type Data type of the new dynamic property (null for no * restrictions) * * @exception IllegalArgumentException if name is null * @exception IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ public void add(String name, Class type); /** * Add a new dynamic property with the specified data type, readability, * and writeability. * * @param name Name of the new dynamic property * @param type Data type of the new dynamic property (null for no * restrictions) * @param readable Set to true if this property value * should be readable * @param writeable Set to true if this property value * should be writeable * * @exception IllegalArgumentException if name is null * @exception IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ public void add(String name, Class type, boolean readable, boolean writeable); /** * Is this DynaClass currently restricted, if so, no changes to the * existing registration of property names, data types, readability, or * writeability are allowed. * * @return true if this Mutable {@link DynaClass} is restricted, * otherwise false */ public boolean isRestricted(); /** * Remove the specified dynamic property, and any associated data type, * readability, and writeability, from this dynamic class. * NOTE - This does NOT cause any * corresponding property values to be removed from DynaBean instances * associated with this DynaClass. * * @param name Name of the dynamic property to remove * * @exception IllegalArgumentException if name is null * @exception IllegalStateException if this DynaClass is currently * restricted, so no properties can be removed */ public void remove(String name); /** * Set the restricted state of this DynaClass to the specified value. * * @param restricted The new restricted state */ public void setRestricted(boolean restricted); } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/NestedNullException.java100644 0 0 3237 12262570612 30011 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * Thrown to indicate that the Bean Access Language cannot execute query * against given bean since a nested bean referenced is null. * * @since 1.7 * @version $Id: NestedNullException.java 1454597 2013-03-08 21:58:12Z britter $ */ public class NestedNullException extends BeanAccessLanguageException { // --------------------------------------------------------- Constuctors /** * Constructs a NestedNullException without a detail message. */ public NestedNullException() { super(); } /** * Constructs a NestedNullException without a detail message. * * @param message the detail message explaining this exception */ public NestedNullException(String message) { super(message); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/package-info.java100644 0 0 150747 12262570612 26452 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** *

          The Bean Introspection Utilities component of the Apache Commons * subproject offers low-level utility classes that assist in getting and setting * property values on Java classes that follow the naming design patterns outlined * in the JavaBeans Specification, as well as mechanisms for dynamically defining * and accessing bean properties.

          * *

          Table of Contents

          * * * * *

          1. Overview

          * * *

          1.1 Background

          * *

          The JavaBeans name comes from a * Java API * for a component architecture for the Java language. Writing Java classes that * conform to the JavaBeans design patterns makes it easier for Java developers * to understand the functionality provided by your class, as well as allowing * JavaBeans-aware tools to use Java's introspection capabilities to * learn about the properties and operations provided by your class, and present * them in a visually appealing manner in development tools.

          * *

          The JavaBeans * Specification describes the complete set of characteristics that makes * an arbitrary Java class a JavaBean or not -- and you should consider reading * this document to be an important part of developing your Java programming * skills. However, the required characteristics of JavaBeans that are * important for most development scenarios are listed here:

          *
            *
          • The class must be public, and provide a * public constructor that accepts no arguments. This allows * tools and applications to dynamically create new instances of your bean, * without necessarily knowing what Java class name will be used ahead of * time, like this: *
             *         String className = ...;
             *         Class beanClass = Class.forName(className);
             *         Object beanInstance = beanClass.newInstance();
             * 
          • *
          • As a necessary consequence of having a no-arguments constructor, * configuration of your bean's behavior must be accomplished separately * from its instantiation. This is typically done by defining a set of * properties of your bean, which can be used to modify its behavior * or the data that the bean represents. The normal convention for * property names is that they start with a lower case letter, and be * comprised only of characters that are legal in a Java identifier.
          • *
          • Typically, each bean property will have a public getter and * setter method that are used to retrieve or define the property's * value, respectively. The JavaBeans Specification defines a design * pattern for these names, using get or set as the * prefix for the property name with it's first character capitalized. Thus, * you a JavaBean representing an employee might have * (among others) properties named firstName, * lastName, and hireDate, with method signatures * like this: *
             *         public class Employee {
             *             public Employee();   // Zero-arguments constructor
             *             public String getFirstName();
             *             public void setFirstName(String firstName);
             *             public String getLastName();
             *             public void setLastName(String lastName);
             *             public Date getHireDate();
             *             public void setHireDate(Date hireDate);
             *             public boolean isManager();
             *             public void setManager(boolean manager);
             *             public String getFullName();
             *         }
             * 
          • *
          • As you can see from the above example, there is a special variant allowed * for boolean properties -- you can name the getter method with a * is prefix instead of a get prefix if that makes * for a more understandable method name.
          • *
          • If you have both a getter and a setter method for a * property, the data type returned by the getter must match the * data type accepted by the setter. In addition, it is contrary * to the JavaBeans specification to have more than one setter * with the same name, but different property types.
          • *
          • It is not required that you provide a getter and a * setter for every property. In the example above, the * fullName property is read-only, because there is no * setter method. It is also possible, but less common, to provide * write-only properties.
          • *
          • It is also possible to create a JavaBean where the getter and * setter methods do not match the naming pattern described above. * The standard JavaBeans support classes in the Java language, as well as * all classes in the BeanUtils package, allow you to describe the actual * property method names in a BeanInfo class associated with * your bean class. See the JavaBeans Specification for full details.
          • *
          • The JavaBeans Specification also describes many additional design patterns * for event listeners, wiring JavaBeans together into component hierarchies, * and other useful features that are beyond the scope of the BeanUtils * package.
          • *
          * *

          Using standard Java coding techniques, it is very easy to deal with * JavaBeans if you know ahead of time which bean classes you will be using, and * which properties you are interested in:

          *
           *         Employee employee = ...;
           *         System.out.println("Hello " + employee.getFirstName() + "!");
           * 
          * * *

          1.2 External Dependencies

          * *

          The commons-beanutils package requires that the following * additional packages be available in the application's class path at runtime: *

          * * * *

          2. Standard JavaBeans

          * * *

          2.1 Background

          * *

          As described above, the standard facilities of the Java programming language * make it easy and natural to access the property values of your beans using * calls to the appropriate getter methods. * But what happens in more sophisticated environments where you do not * necessarily know ahead of time which bean class you are going to be using, * or which property you want to retrieve or modify? The Java language provides * classes like java.beans.Introspector, which can examine a Java * class at runtime and identify for you the names of the property getter and * setter methods, plus the Reflection capabilities to dynamically call * such a method. However, these APIs can be difficult to use, and expose the * application developer to many unnecessary details of the underlying structure * of Java classes. The APIs in the BeanUtils package are intended to simplify * getting and setting bean properties dynamically, where the objects you are * accessing -- and the names of the properties you care about -- are determined * at runtime in your application, rather than as you are writing and compiling * your application's classes.

          * *

          This is the set of needs that are satisfied by the static methods of the * {@link org.apache.commons.beanutils.PropertyUtils} * class, which are described further in this section. First, however, some * further definitions will prove to be useful:

          * *

          The general set of possible property types supported by a JavaBean can be * broken into three categories -- some of which are supported by the standard * JavaBeans specification, and some of which are uniquely supported by the * BeanUtils package:

          *
            *
          • Simple - Simple, or scalar, properties have a single * value that may be retrieved or modified. The underlying property type * might be a Java language primitive (such as int, a simple * object (such as a java.lang.String), or a more complex * object whose class is defined either by the Java language, by the * application, or by a class library included with the application.
          • *
          • Indexed - An indexed property stores an ordered collection * of objects (all of the same type) that can be individually accessed by an * integer-valued, non-negative index (or subscript). Alternatively, the * entire set of values may be set or retrieved using an array. * As an extension to the JavaBeans specification, the * BeanUtils package considers any property whose underlying data * type is java.util.List (or an implementation of List) to be * indexed as well.
          • *
          • Mapped - As an extension to standard JavaBeans APIs, * the BeanUtils package considers any property whose underlying * value is a java.util.Map to be "mapped". You can set and * retrieve individual values via a String-valued key.
          • *
          * *

          A variety of API methods are provided in the * {@link org.apache.commons.beanutils.PropertyUtils} class to get and set * property values of all of these types. * In the code fragments below, assume that there are two bean classes defined * with the following method signatures:

          *
           *     public class Employee {
           *         public Address getAddress(String type);
           *         public void setAddress(String type, Address address);
           *         public Employee getSubordinate(int index);
           *         public void setSubordinate(int index, Employee subordinate);
           *         public String getFirstName();
           *         public void setFirstName(String firstName);
           *         public String getLastName();
           *         public void setLastName(String lastName);
           *     }
           * 
          * * *

          2.2 Basic Property Access

          * *

          Getting and setting simple property values is, well, * simple :-). Check out the following API signatures in the Javadocs:

          * *
            *
          • {@link org.apache.commons.beanutils.PropertyUtils#getSimpleProperty(Object, String)}
          • *
          • {@link org.apache.commons.beanutils.PropertyUtils#setSimpleProperty(Object, String, Object)}
          • *
          * *

          Using these methods, you might dynamically manipulate the employee's name * in an application:

          *
           *     Employee employee = ...;
           *     String firstName = (String)
           *       PropertyUtils.getSimpleProperty(employee, "firstName");
           *     String lastName = (String)
           *       PropertyUtils.getSimpleProperty(employee, "lastName");
           *     ... manipulate the values ...
           *     PropertyUtils.setSimpleProperty(employee, "firstName", firstName);
           *     PropertyUtils.setSimpleProperty(employee, "lastName", lastName);
           * 
          * *

          For indexed properties, you have two choices - you can * either build a subscript into the "property name" string, using square * brackets, or you can specify the subscript in a separate argument to the * method call:

          * *
            *
          • {@link org.apache.commons.beanutils.PropertyUtils#getIndexedProperty(Object, String)}
          • *
          • {@link org.apache.commons.beanutils.PropertyUtils#getIndexedProperty(Object, String, int)}
          • *
          • {@link org.apache.commons.beanutils.PropertyUtils#setIndexedProperty(Object, String, Object)}
          • *
          • {@link org.apache.commons.beanutils.PropertyUtils#setIndexedProperty(Object, String, int, Object)}
          • *
          * *

          Only integer constants are allowed when you add a subscript to the property * name. If you need to calculate the index of the entry you wish to retrieve, * you can use String concatenation to assemble the property name expression. * For example, you might do either of the following:

          *
           *     Employee employee = ...;
           *     int index = ...;
           *     String name = "subordinate[" + index + "]";
           *     Employee subordinate = (Employee)
           *       PropertyUtils.getIndexedProperty(employee, name);
           *
           *     Employee employee = ...;
           *     int index = ...;
           *     Employee subordinate = (Employee)
           *       PropertyUtils.getIndexedProperty(employee, "subordinate", index);
           * 
          * *

          In a similar manner, there are two possible method signatures for getting * and setting mapped properties. The difference is that the * extra argument is surrounded by parentheses ("(" and ")") instead of square * brackets, and it is considered to be a String-value key used to get or set * the appropriate value from an underlying map.

          * *
            *
          • {@link org.apache.commons.beanutils.PropertyUtils#getMappedProperty(Object, String)}
          • *
          • {@link org.apache.commons.beanutils.PropertyUtils#getMappedProperty(Object, String, String)}
          • *
          • {@link org.apache.commons.beanutils.PropertyUtils#setMappedProperty(Object, String, Object)}
          • *
          • {@link org.apache.commons.beanutils.PropertyUtils#setMappedProperty(Object, String, String, Object)}
          • *
          * *

          You can, for example, set the employee's home address in either of these * two manners:

          * *
           *     Employee employee = ...;
           *     Address address = ...;
           *     PropertyUtils.setMappedProperty(employee, "address(home)", address);
           *
           *     Employee employee = ...;
           *     Address address = ...;
           *     PropertyUtils.setMappedProperty(employee, "address", "home", address);
           * 
          * * *

          2.3 Nested Property Access

          * *

          In all of the examples above, we have assumed that you wished to retrieve * the value of a property of the bean being passed as the first argument to a * PropertyUtils method. However, what if the property value you retrieve is * really a Java object, and you wish to retrieve a property of that * object instead?

          * *

          For example, assume we really wanted the city property of the * employee's home address. Using standard Java programming techniques for direct * access to the bean properties, we might write:

          * *
           *     String city = employee.getAddress("home").getCity();
           * 
          * *

          The equivalent mechanism using the PropertyUtils class is called * nested property access. To use this approach, you concatenate * together the property names of the access path, using "." separators -- very * similar to the way you can perform nested property access in JavaScript.

          * *
            *
          • {@link org.apache.commons.beanutils.PropertyUtils#getNestedProperty(Object, String)}
          • *
          • {@link org.apache.commons.beanutils.PropertyUtils#setNestedProperty(Object, String, Object)}
          • *
          * *

          The PropertyUtils equivalent to the above Java expression would be:

          * *
           *     String city = (String)
           *       PropertyUtils.getNestedProperty(employee, "address(home).city");
           * 
          * *

          Finally, for convenience, PropertyUtils provides method signatures that * accept any arbitrary combination of simple, indexed, and mapped property * access, using any arbitrary level of nesting:

          * *
            *
          • {@link org.apache.commons.beanutils.PropertyUtils#getProperty(Object, String)}
          • *
          • {@link org.apache.commons.beanutils.PropertyUtils#setProperty(Object, String, Object)}
          • *
          * *

          which you might use like this:

          * *
           *     Employee employee = ...;
           *     String city = (String) PropertyUtils.getProperty(employee,
           *       "subordinate[3].address(home).city");
           * 
          * * *

          2.4 Customizing Introspection

          * *

          As was pointed out, BeanUtils relies on conventions defined by the * JavaBeans specification to determine the properties available for * a specific bean class. Thus all classes conforming to these conventions can * be used out of the box.

          * *

          Sometimes an application has to deal with classes using different * conventions. For instance, fluent APIs allowing method chaining are not * compliant to the JavaBeans specification because here set methods * have non-void return values. From version 1.9.0 onwards, BeanUtils supports * customization of its introspection mechanism. This allows an application * to extend or modify the default discovery of bean properties.

          * *

          The key to this extension mechanism is the {@link org.apache.commons.beanutils.BeanIntrospector} * interface. The purpose of an object implementing this interface is to * process a specific target class and create corresponding * PropertyDescriptor objects for the properties it detects. * Per default, BeanUtils uses a {@link org.apache.commons.beanutils.DefaultBeanIntrospector} * object which detects properties compatible with the JavaBeans * specification.

          * *

          In order to extend the property discovery mechanism, PropertyUtils * offers the {@link org.apache.commons.beanutils.PropertyUtils#addBeanIntrospector(BeanIntrospector)} * method. Here a custom BeanIntrospector implementation can be * passed in. During introspection of a class, this custom introspector is * then called, and it can add the properties it has detected to the total * result. As an example of such a custom BeanIntrospector * implementation, BeanUtils ships with the {@link org.apache.commons.beanutils.FluentPropertyBeanIntrospector} * class. This implementation can detect properties whose set methods have a * non-void return type - thus enabling support for typical properties in a * fluent API.

          * * *

          3. Dynamic Beans (DynaBeans)

          * * *

          3.1 Background

          * *

          The {@link org.apache.commons.beanutils.PropertyUtils} class described in the * preceding section is designed to provide dynamic property access on existing * JavaBean classes, without modifying them in any way. A different use case for * dynamic property access is when you wish to represent a dynamically calculated * set of property values as a JavaBean, but without having to actually * write a Java class to represent these properties. Besides the effort savings * in not having to create and maintain a separate Java class, this ability also * means you can deal with situations where the set of properties you care about * is determined dynamically (think of representing the result set of an SQL * select as a set of JavaBeans ...).

          * *

          To support this use case, the BeanUtils package provides the * {@link org.apache.commons.beanutils.DynaBean} interface, which must be implemented by a * bean class actually implementing the interface's methods, and the associated * {@link org.apache.commons.beanutils.DynaClass} interface that defines the set of * properties supported by a particular group of DynaBeans, in much the same way * that java.lang.Class defines the set of properties supported by * all instances of a particular JavaBean class.

          * *

          For example, the Employee class used in the examples above * might be implemented as a DynaBean, rather than as a standard JavaBean. You * can access its properties like this:

          * *
           *     DynaBean employee = ...; // Details depend on which
           *                              // DynaBean implementation you use
           *     String firstName = (String) employee.get("firstName");
           *     Address homeAddress = (Address) employee.get("address", "home");
           *     Object subordinate = employee.get("subordinate", 2);
           * 
          * *

          One very important convenience feature should be noted: the * PropertyUtils property getter and setter methods understand how to access * properties in DynaBeans. Therefore, if the bean you pass as the first * argument to, say, PropertyUtils.getSimpleProperty() is really a * DynaBean implementation, the call will get converted to the appropriate * DynaBean getter method transparently. Thus, you can base your application's * dynamic property access totally on the PropertyUtils APIs, if you wish, and * use them to access either standard JavaBeans or DynaBeans without having to * care ahead of time how a particular bean is implemented.

          * *

          Because DynaBean and DynaClass are interfaces, they may be implemented * multiple times, in different ways, to address different usage scenarios. The * following subsections describe the implementations that are provided as a part * of the standard BeanUtils package, although you are encouraged to * provide your own custom implementations for cases where the standard * implementations are not sufficient.

          * * *

          3.2 BasicDynaBean and BasicDynaClass

          * *

          The {@link org.apache.commons.beanutils.BasicDynaBean} and * {@link org.apache.commons.beanutils.BasicDynaClass} implementation provides a * basic set of * dynamic property capabilities where you want to dynamically define the * set of properties (described by instances of {@link org.apache.commons.beanutils.DynaProperty}). * You start by defining the DynaClass that establishes * the set of properties you care about:

          * *
           *     DynaProperty[] props = new DynaProperty[]{
           *         new DynaProperty("address", java.util.Map.class),
           *         new DynaProperty("subordinate", mypackage.Employee[].class),
           *         new DynaProperty("firstName", String.class),
           *         new DynaProperty("lastName",  String.class)
           *       };
           *     BasicDynaClass dynaClass = new BasicDynaClass("employee", null, props);
           * 
          * *

          Note that the 'dynaBeanClass' argument (in the constructor of * BasicDynaClass) can have the value of null. In this * case, the value of dynaClass.getDynaBeanClass will just be the * Class for BasicDynaBean.

          * *

          Next, you use the newInstance() method of this DynaClass to * create new DynaBean instances that conform to this DynaClass, and populate * its initial property values (much as you would instantiate a new standard * JavaBean and then call its property setters):

          * *
           *     DynaBean employee = dynaClass.newInstance();
           *     employee.set("address", new HashMap());
           *     employee.set("subordinate", new mypackage.Employee[0]);
           *     employee.set("firstName", "Fred");
           *     employee.set("lastName", "Flintstone");
           * 
          * *

          Note that the DynaBean class was declared to be * DynaBean instead of BasicDynaBean. In * general, if you are using DynaBeans, you will not want to care about the * actual implementation class that is being used -- you only care about * declaring that it is a DynaBean so that you can use the * DynaBean APIs.

          * *

          As stated above, you can pass a DynaBean instance as the first argument * to a PropertyUtils method that gets and sets properties, and it * will be interpreted as you expect -- the dynamic properties of the DynaBean * will be retrieved or modified, instead of underlying properties on the * actual BasicDynaBean implementation class.

          * * *

          3.3 ResultSetDynaClass (Wraps ResultSet in DynaBeans)

          * *

          A very common use case for DynaBean APIs is to wrap other collections of * "stuff" that do not normally present themselves as JavaBeans. One of the most * common collections that would be nice to wrap is the * java.sql.ResultSet that is returned when you ask a JDBC driver * to perform a SQL SELECT statement. Commons BeanUtils offers a standard * mechanism for making each row of the result set visible as a DynaBean, * which you can utilize as shown in this example:

          *
           *   Connection conn = ...;
           *   Statement stmt = conn.createStatement();
           *   ResultSet rs = stmt.executeQuery
           *     ("select account_id, name from customers");
           *   Iterator rows = (new ResultSetDynaClass(rs)).iterator();
           *   while (rows.hasNext()) {
           *     DynaBean row = (DynaBean) rows.next();
           *     System.out.println("Account number is " +
           *                        row.get("account_id") +
           *                        " and name is " + row.get("name"));
           *   }
           *   rs.close();
           *   stmt.close();
           * 
          * * * *

          3.4 RowSetDynaClass (Disconnected ResultSet as DynaBeans)

          *

          Although ResultSetDynaClass is * a very useful technique for representing the results of an SQL query as a * series of DynaBeans, an important problem is that the underlying * ResultSet must remain open throughout the period of time that the * rows are being processed by your application. This hinders the ability to use * ResultSetDynaClass as a means of communicating information from * the model layer to the view layer in a model-view-controller architecture * such as that provided by the Struts * Framework, because there is no easy mechanism to assure that the result set * is finally closed (and the underlying Connection returned to its * connection pool, if you are using one).

          * *

          The RowSetDynaClass class represents a different approach to * this problem. When you construct such an instance, the underlying data is * copied into a set of in-memory DynaBeans that represent the result. * The advantage of this technique, of course, is that you can immediately close * the ResultSet (and the corresponding Statement), normally before you even * process the actual data that was returned. The disadvantage, of course, is * that you must pay the performance and memory costs of copying the result data, * and the result data must fit entirely into available heap memory. For many * environments (particularly in web applications), this tradeoff is usually * quite beneficial.

          * *

          As an additional benefit, the RowSetDynaClass class is defined * to implement java.io.Serializable, so that it (and the * DynaBeans that correspond to each row of the result) can be conveniently * serialized and deserialized (as long as the underlying column values are * also Serializable). Thus, RowSetDynaClass represents a very * convenient way to transmit the results of an SQL query to a remote Java-based * client application (such as an applet).

          * *

          The normal usage pattern for a RowSetDynaClass will look * something like this:

          *
           *     Connection conn = ...;  // Acquire connection from pool
           *     Statement stmt = conn.createStatement();
           *     ResultSet rs = stmt.executeQuery("SELECT ...");
           *     RowSetDynaClass rsdc = new RowSetDynaClass(rs);
           *     rs.close();
           *     stmt.close();
           *     ...;                    // Return connection to pool
           *     List rows = rsdc.getRows();
           *     ...;                   // Process the rows as desired
           * 
          * * * *

          3.5 WrapDynaBean and WrapDynaClass

          * *

          OK, you've tried the DynaBeans APIs and they are cool -- very simple * get() and set() methods provide easy access to all * of the dynamically defined simple, indexed, and mapped properties of your * DynaBeans. You'd like to use the DynaBean APIs to access all * of your beans, but you've got a bunch of existing standard JavaBeans classes * to deal with as well. This is where the * {@link org.apache.commons.beanutils.WrapDynaBean} (and its associated * {@link org.apache.commons.beanutils.WrapDynaClass}) come into play. As the name * implies, a WrapDynaBean is used to "wrap" the DynaBean APIs around an * existing standard JavaBean class. To use it, simply create the wrapper * like this:

          * *
           *     MyBean bean = ...;
           *     DynaBean wrapper = new WrapDynaBean(bean);
           *     String firstName = wrapper.get("firstName");
           * 
          * *

          Note that, although appropriate WrapDynaClass instances are * created internally, you never need to deal with them.

          * * *

          3.6 Lazy DynaBeans

          * *
            *
          • 1. LazyDynaBean - A Lazy * {@link org.apache.commons.beanutils.DynaBean}
          • *
          • 2. LazyDynaMap - A light weight * {@link org.apache.commons.beanutils.DynaBean} facade to a Map * with lazy map/list processing
          • *
          • 3. LazyDynaList - A lazy list * for {@link org.apache.commons.beanutils.DynaBean DynaBean's}, * java.util.Map's or POJO beans.
          • *
          • 4. LazyDynaClass - A * {@link org.apache.commons.beanutils.MutableDynaClass} implementation.
          • *
          * *

          You bought into the DynaBeans because it saves coding all those POJO JavaBeans but * you're here because lazy caught your eye and wondered whats that about? * What makes these flavors of DynaBean lazy are the following features:

          *
            *
          • Lazy property addition - lazy beans use a * {@link org.apache.commons.beanutils.DynaClass} which implements * the {@link org.apache.commons.beanutils.MutableDynaClass} * interface. This provides the ability to add and remove a DynaClass's * properties. Lazy beans use this feature to automatically add * a property which doesn't exist to the DynaClass when * the set(name, value) method is called.
          • *
          • Lazy List/Array growth - If an indexed property is not large * enough to accomodate the index being set then the List or * Array is automatically grown so that it is.
          • *
          • Lazy List/Array instantiation - if an indexed * property doesn't exist then calling the {@link org.apache.commons.beanutils.DynaBean DynaBean's} * indexed property getter/setter methods (i.e. get(name, index) or * set(name, index, value)) results in either a new List * or Array being instantiated. If the indexed property has not been * defined in the DynaClass then it is automatically added and a default List * implementation instantiated.
          • *
          • Lazy Map instantiation - if a mapped * property doesn't exist then calling the {@link org.apache.commons.beanutils.DynaBean DynaBean's} * mapped property getter/setter methods (i.e. get(name, key) or * set(name, key, value)) results in a new Map * being instantiated. If the mapped property has not been defined in the DynaClass * then it is automatically added and a default Map implementation * instantiated.
          • *
          • Lazy Bean instantiation - if a property is defined in * the DynaClass as a DynaBean or regular bean and * doesn't exist in the DynaBean then LazyDynaBean wiill * try to instantiate the bean using a default empty constructor.
          • *
          * *

          1. {@link org.apache.commons.beanutils.LazyDynaBean} is the standard lazy bean * implementation. By default it is associated with a {@link org.apache.commons.beanutils.LazyDynaClass} * which implements the {@link org.apache.commons.beanutils.MutableDynaClass} interface - however * it can be used with any MutableDynaClass implementation. The question is how do * I use it? - well it can be as simple as creating a new bean and then calling the getters/setters...

          * *
           *     DynaBean dynaBean = new LazyDynaBean();
           *
           *     dynaBean.set("foo", "bar");                   // simple
           *
           *     dynaBean.set("customer", "title", "Mr");      // mapped
           *     dynaBean.set("customer", "surname", "Smith"); // mapped
           *
           *     dynaBean.set("address", 0, addressLine1);     // indexed
           *     dynaBean.set("address", 1, addressLine2);     // indexed
           *     dynaBean.set("address", 2, addressLine3);     // indexed
           * 
          * *

          2. {@link org.apache.commons.beanutils.LazyDynaMap} is a light weight * DynaBean facade to a Map with all the usual lazy features. Its * light weight because it doesn't have an associated DynaClass containing all the properties. * In fact it actually implements the DynaClass interface itself (and MutableDynaClass) * and derives all the DynaClass information from the actual contents of the Map. A * LazyDynaMap can be created around an existing Map or can instantiate its own * Map. After any DynaBean processing has finished the Map can be retrieved * and the DynaBean facade discarded.

          * *

          If you need a new Map then to use....

          * *
           *     DynaBean dynaBean = new LazyDynaMap();        // create DynaBean
           *
           *     dynaBean.set("foo", "bar");                   // simple
           *     dynaBean.set("customer", "title", "Mr");      // mapped
           *     dynaBean.set("address", 0, addressLine1);     // indexed
           *
           *     Map myMap = dynaBean.getMap()                 // retrieve the Map
           * 
          *

          or to use with an existing Map ....

          * *
           *     Map myMap = ....                             // exisitng Map
           *     DynaBean dynaBean = new LazyDynaMap(myMap);  // wrap Map in DynaBean
           *     dynaBean.set("foo", "bar");                  // set properties
           * 
          * *

          3. {@link org.apache.commons.beanutils.LazyDynaList} * is lazy list for {@link org.apache.commons.beanutils.DynaBean DynaBeans} * java.util.Map's or POJO beans. See the Javadoc * for more details and example usage.

          * *

          4. {@link org.apache.commons.beanutils.LazyDynaClass} * extends {@link org.apache.commons.beanutils.BasicDynaClass} and implements * the MutableDynaClass interface. * It can be used with other DynaBean implementations, but it * is the default DynaClass used by LazyDynaBean. * When using the LazyDynaBean there may be no need to have * anything to do with the DynaClass. However sometimes there * is a requirement to set up the DynaClass first - perhaps to * define the type of array for an indexed property, or if using the DynaBean * in restricted mode (see note below) is required. Doing so is * straight forward...

          * *

          Either create a LazyDynaClass first... * *

           *     MutableDynaClass dynaClass = new LazyDynaClass();    // create DynaClass
           *
           *     dynaClass.add("amount", java.lang.Integer.class);    // add property
           *     dynaClass.add("orders", OrderBean[].class);          // add indexed property
           *     dynaClass.add("orders", java.util.TreeMapp.class);   // add mapped property
           *
           *     DynaBean dynaBean = new LazyDynaBean(dynaClass);     // Create DynaBean with associated DynaClass
           * 
          * *

          or create a LazyDynaBean and get the DynaClass... * *

           *     DynaBean dynaBean = new LazyDynaBean();              // Create LazyDynaBean
           *     MutableDynaClass dynaClass =
           *              (MutableDynaClass)dynaBean.getDynaClass();  // get DynaClass
           *
           *     dynaClass.add("amount", java.lang.Integer.class);    // add property
           *     dynaClass.add("myBeans", myPackage.MyBean[].class);  // add 'array' indexed property
           *     dynaClass.add("myMap", java.util.TreeMapp.class);    // add mapped property
           * 
          * *

          NOTE: One feature of {@link org.apache.commons.beanutils.MutableDynaClass} is that it * has a Restricted property. When the DynaClass is restricted no properties can be added * or removed from the DynaClass. Neither the LazyDynaBean or LazyDynaMap * will add properties automatically if the DynaClass is restricted.

          * * * *

          4. Data Type Conversions

          * * *

          4.1 Background

          * *

          So far, we've only considered the cases where the data types of the * dynamically accessed properties are known, and where we can use Java casts * to perform type conversions. What happens if you want to automatically * perform type conversions when casting is not possible? The * BeanUtils package provides a variety of APIs and design patterns * for performing this task as well.

          * * *

          4.2 BeanUtils and ConvertUtils Conversions

          * *

          A very common use case (and the situation that caused the initial creation * of the BeanUtils package) was the desire to convert the set of request * parameters that were included in a * javax.servlet.HttpServletRequest received by a web application * into a set of corresponding property setter calls on an arbitrary JavaBean. * (This is one of the fundamental services provided by the * Struts Framework, which uses * BeanUtils internally to implement this functionality.)

          * *

          In an HTTP request, the set of included parameters is made available as a * series of String (or String array, if there is more than one value for the * same parameter name) instances, which need to be converted to the underlying * data type. The {@link org.apache.commons.beanutils.BeanUtils} class provides * property setter methods that accept String values, and automatically convert * them to appropriate property types for Java primitives (such as * int or boolean), and property getter methods that * perform the reverse conversion. Finally, a populate() method * is provided that accepts a java.util.Map containing a set of * property values (keyed by property name), and calls all of the appropriate * setters whenever the underlying bean has a property with the same name as * one of the request parameters. So, you can perform the all-in-one property * setting operation like this:

          * *
           *     HttpServletRequest request = ...;
           *     MyBean bean = ...;
           *     HashMap map = new HashMap();
           *     Enumeration names = request.getParameterNames();
           *     while (names.hasMoreElements()) {
           *       String name = (String) names.nextElement();
           *       map.put(name, request.getParameterValues(name));
           *     }
           *     BeanUtils.populate(bean, map);
           * 
          * *

          The BeanUtils class relies on conversion methods defined in * the {@link org.apache.commons.beanutils.ConvertUtils} class to perform the actual * conversions, and these methods are availablve for direct use as well. * WARNING - It is likely that the hard coded use of * ConvertUtils methods will be deprecated in the future, and * replaced with a mechanism that allows you to plug in your own implementations * of the {@link org.apache.commons.beanutils.Converter} interface instead. Therefore, * new code should not be written with reliance on ConvertUtils.

          * * *

          4.3 Defining Your Own Converters

          * *

          The ConvertUtils class supports the ability to define and * register your own String --> Object conversions for any given Java class. * Once registered, such converters will be used transparently by all of the * BeanUtils methods (including populate()). To * create and register your own converter, follow these steps:

          *
            *
          • Write a class that implements the {@link org.apache.commons.beanutils.Converter} * interface. The convert() method should accept the * java.lang.Class object of your application class (i.e. * the class that you want to convert to, and a String representing the * incoming value to be converted.
          • *
          • At application startup time, register an instance of your converter class * by calling the ConvertUtils.register() method.
          • *
          * * *

          4.4 Locale Aware Conversions

          *

          The standard classes in org.apache.commons.beanutils are not * locale aware. This gives them a cleaner interface and makes then easier to use * in situations where the locale is not important.

          *

          Extended, locale-aware analogues can be found in * org.apache.commons.beanutils.locale * . These are built along the same * lines as the basic classes but support localization.

          * * * *

          5. Utility Objects And Static Utility Classes

          * *

          Background

          *

          * So far, the examples have covered the static utility classes (BeanUtils, * ConvertUtils and PropertyUtils). These are easy to use but are * somewhat inflexible. These all share the same registered converters and the same caches. *

          *

          * This functionality can also be accessed through utility objects (in fact, the static utility * class use worker instances of these classes). For each static utility class, there is a corresponding * class with the same functionality that can be instantiated: *

          *

          * * * * * *
          Static Utility ClassUtility Object
          BeanUtilsBeanUtilsBean
          ConvertUtilsConvertUtilsBean
          PropertyUtilsPropertyUtilsBean
          *

          *

          * Creating an instances allow gives guarenteed control of the caching and registration * to the code that creates it. *

          * * *

          6. Collections

          * *

          6.1 Comparing Beans

          *

          * org.apache.commons.beanutils.BeanComparator is a Comparator implementation * that compares beans based on a shared property value. *

          * *

          6.2 Operating On Collections Of Beans

          *

          * The Closure interface in commons-collections encapsulates a block of code that * executes on an arbitrary input Object. Commons-collections contains code that allows * Closures to be applied to the contents of a Collection. For more details, see the * commons-collections * documentation. *

          *

          * BeanPropertyValueChangeClosure is a Closure that sets a specified property * to a particular value. A typical usage is to combine this with commons-collections * so that all the beans in a collection can have a particular property set to a particular value. *

          *

          * For example, set the activeEmployee property to TRUE for an entire collection: *

           *     // create the closure
           *     BeanPropertyValueChangeClosure closure =
           *         new BeanPropertyValueChangeClosure( "activeEmployee", Boolean.TRUE );
           *
           *     // update the Collection
           *     CollectionUtils.forAllDo( peopleCollection, closure );
           *   
          *

          * * *

          6.3 Querying Or Filtering Collections Of Beans

          *

          * The Predicate interface in commons-collections encapsulates an evaluation * of an input Object that returns either true or false. Commons-collections contains code * that allows * Predicates to be applied to be used to filter collections. For more details, see the * commons-collections * documentation. *

          *

          * BeanPropertyValueEqualsPredicate is a Predicate that evaluates a * set property value against a given value. A typical usage is * (in combination with commons-collections) * to filter collections on the basis of a property value. *

          *

          * For example, to filter a collection to find all beans where active employee is false use: *

           *     BeanPropertyValueEqualsPredicate predicate =
           *         new BeanPropertyValueEqualsPredicate( "activeEmployee", Boolean.FALSE );
           *
           *     // filter the Collection
           *     CollectionUtils.filter( peopleCollection, predicate );
           * 
          *

          * * *

          6.4 Transforming Collections Of Beans

          *

          * The Transformer interface in commons-collections encapsulates the transformation * of an input Object into an output object. Commons-collections contains code * that allows * Transformers to be applied produce a collection of outputs from a collection of inputs. * For more details, see the * commons-collections * documentation. *

          *

          * BeanToPropertyTransformer is a Transformer implementation * that transforms a bean into it's property value. *

          *

          * For example, to find all cities that are contained in the address of each person property of each bean in * a collection: *

           *     // create the transformer
           *     BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer( "person.address.city" );
           *
           *     // transform the Collection
           *     Collection peoplesCities = CollectionUtils.collect( peopleCollection, transformer );
           *     
          *

          * * *

          7. Frequently Asked Questions

          * * *

          Why Can't BeanUtils Find My Method?

          *

          The BeanUtils package relies on introspection rather than * reflection. This means that it will find only * JavaBean * compliant properties.

          *

          There are some subtleties of this specification that can catch out the unwary: *

            *
          • A property can have only one set and one get method. Overloading is not allowed.
          • *
          • The java.beans.Introspector searches widely for a custom BeanInfo * class. If your class has the same name as another with a custom BeanInfo * (typically a java API class) then the Introspector may use that instead of * creating via reflection based on your class. If this happens, the only solution is to * create your own BeanInfo.
          • *
          *

          * *

          How Do I Set The BeanComparator Order To Be Ascending/Descending?

          *

          * BeanComparator relies on an internal Comparator to perform the actual * comparisions. By default, * org.apache.commons.collections.comparators.ComparableComparator * is used which imposes a natural order. If you want to change the order, * then a custom Comparator should be created and passed into the * appropriate constructor. *

          *

          * For example: *

          *
           *     import org.apache.commons.collections.comparators.ComparableComparator;
           *     import org.apache.commons.collections.comparators.ReverseComparator;
           *     import org.apache.commons.beanutils.BeanComparator;
           *     ...
           *     BeanComparator reversedNaturalOrderBeanComparator
           *         = new BeanComparator("propertyName", new ReverseComparator(new ComparableComparator()));
           *     Collections.sort(myList, reversedNaturalOrderBeanComparator);
           *     ...
           * 
          */ package org.apache.commons.beanutils; commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/PropertyUtils.java100644 0 0 107256 12262570612 26770 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import org.apache.commons.collections.FastHashMap; /** *

          Utility methods for using Java Reflection APIs to facilitate generic * property getter and setter operations on Java objects.

          * *

          The implementations for these methods are provided by PropertyUtilsBean. * For more details see {@link PropertyUtilsBean}.

          * * @version $Id: PropertyUtils.java 1547898 2013-12-04 20:33:06Z oheger $ * @see PropertyUtilsBean * @see org.apache.commons.beanutils.expression.Resolver */ public class PropertyUtils { // ----------------------------------------------------- Manifest Constants /** * The delimiter that preceeds the zero-relative subscript for an * indexed reference. * * @deprecated The notation used for property name expressions is now * dependant on the {@link org.apache.commons.beanutils.expression.Resolver} * implementation being used. */ @Deprecated public static final char INDEXED_DELIM = '['; /** * The delimiter that follows the zero-relative subscript for an * indexed reference. * * @deprecated The notation used for property name expressions is now * dependant on the {@link org.apache.commons.beanutils.expression.Resolver} * implementation being used. */ @Deprecated public static final char INDEXED_DELIM2 = ']'; /** * The delimiter that preceeds the key of a mapped property. * * @deprecated The notation used for property name expressions is now * dependant on the {@link org.apache.commons.beanutils.expression.Resolver} * implementation being used. */ @Deprecated public static final char MAPPED_DELIM = '('; /** * The delimiter that follows the key of a mapped property. * * @deprecated The notation used for property name expressions is now * dependant on the {@link org.apache.commons.beanutils.expression.Resolver} * implementation being used. */ @Deprecated public static final char MAPPED_DELIM2 = ')'; /** * The delimiter that separates the components of a nested reference. * * @deprecated The notation used for property name expressions is now * dependant on the {@link org.apache.commons.beanutils.expression.Resolver} * implementation being used. */ @Deprecated public static final char NESTED_DELIM = '.'; // ------------------------------------------------------- Static Variables /** * The debugging detail level for this component. * * Note that this static variable will have unexpected side-effects if * this class is deployed in a shared classloader within a container. * However as it is actually completely ignored by this class due to its * deprecated status, it doesn't do any actual harm. * * @deprecated The debug static property is no longer used */ @Deprecated private static int debug = 0; /** * The debug static property is no longer used * @return debug property * @deprecated The debug static property is no longer used */ @Deprecated public static int getDebug() { return (debug); } /** * The debug static property is no longer used * @param newDebug debug property * @deprecated The debug static property is no longer used */ @Deprecated public static void setDebug(int newDebug) { debug = newDebug; } // --------------------------------------------------------- Public Methods /** * Clear any cached property descriptors information for all classes * loaded by any class loaders. This is useful in cases where class * loaders are thrown away to implement class reloading. * *

          For more details see PropertyUtilsBean.

          * * @see PropertyUtilsBean#clearDescriptors */ public static void clearDescriptors() { PropertyUtilsBean.getInstance().clearDescriptors(); } /** * Resets the registered {@link BeanIntrospector} objects to the initial default * state. * * @since 1.9 */ public static void resetBeanIntrospectors() { PropertyUtilsBean.getInstance().resetBeanIntrospectors(); } /** * Adds a BeanIntrospector. This object is invoked when the * property descriptors of a class need to be obtained. * * @param introspector the BeanIntrospector to be added (must * not be null * @throws IllegalArgumentException if the argument is null * @since 1.9 */ public static void addBeanIntrospector(BeanIntrospector introspector) { PropertyUtilsBean.getInstance().addBeanIntrospector(introspector); } /** * Removes the specified BeanIntrospector. * * @param introspector the BeanIntrospector to be removed * @return true if the BeanIntrospector existed and * could be removed, false otherwise * @since 1.9 */ public static boolean removeBeanIntrospector(BeanIntrospector introspector) { return PropertyUtilsBean.getInstance().removeBeanIntrospector( introspector); } /** *

          Copy property values from the "origin" bean to the "destination" bean * for all cases where the property names are the same (even though the * actual getter and setter methods might have been customized via * BeanInfo classes).

          * *

          For more details see PropertyUtilsBean.

          * * @param dest Destination bean whose properties are modified * @param orig Origin bean whose properties are retrieved * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if the dest or * orig argument is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#copyProperties */ public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyUtilsBean.getInstance().copyProperties(dest, orig); } /** *

          Return the entire set of properties for which the specified bean * provides a read method.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose properties are to be extracted * @return The set of properties for the bean * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#describe */ public static Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (PropertyUtilsBean.getInstance().describe(bean)); } /** *

          Return the value of the specified indexed property of the specified * bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be extracted * @param name propertyname[index] of the property value * to be extracted * @return the indexed property value * * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying property * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#getIndexedProperty(Object,String) */ public static Object getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (PropertyUtilsBean.getInstance().getIndexedProperty(bean, name)); } /** *

          Return the value of the specified indexed property of the specified * bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * @return the indexed property value * * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying property * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#getIndexedProperty(Object,String, int) */ public static Object getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (PropertyUtilsBean.getInstance().getIndexedProperty(bean, name, index)); } /** *

          Return the value of the specified mapped property of the * specified bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be extracted * @param name propertyname(key) of the property value * to be extracted * @return the mapped property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#getMappedProperty(Object,String) */ public static Object getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (PropertyUtilsBean.getInstance().getMappedProperty(bean, name)); } /** *

          Return the value of the specified mapped property of the specified * bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be extracted * @param name Mapped property name of the property value to be extracted * @param key Key of the property value to be extracted * @return the mapped property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#getMappedProperty(Object,String, String) */ public static Object getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getMappedProperty(bean, name, key); } /** *

          Return the mapped property descriptors for this bean class.

          * *

          For more details see PropertyUtilsBean.

          * * @param beanClass Bean class to be introspected * @return the mapped property descriptors * @see PropertyUtilsBean#getMappedPropertyDescriptors(Class) * @deprecated This method should not be exposed */ @Deprecated public static FastHashMap getMappedPropertyDescriptors(Class beanClass) { return PropertyUtilsBean.getInstance().getMappedPropertyDescriptors(beanClass); } /** *

          Return the mapped property descriptors for this bean.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean to be introspected * @return the mapped property descriptors * @see PropertyUtilsBean#getMappedPropertyDescriptors(Object) * @deprecated This method should not be exposed */ @Deprecated public static FastHashMap getMappedPropertyDescriptors(Object bean) { return PropertyUtilsBean.getInstance().getMappedPropertyDescriptors(bean); } /** *

          Return the value of the (possibly nested) property of the specified * name, for the specified bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * @return the nested property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception NestedNullException if a nested reference to a * property returns null * @exception InvocationTargetException * if the property accessor method throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#getNestedProperty */ public static Object getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getNestedProperty(bean, name); } /** *

          Return the value of the specified property of the specified bean, * no matter which property reference format is used, with no * type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * @return the property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#getProperty */ public static Object getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (PropertyUtilsBean.getInstance().getProperty(bean, name)); } /** *

          Retrieve the property descriptor for the specified property of the * specified bean, or return null if there is no such * descriptor.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean for which a property descriptor is requested * @param name Possibly indexed and/or nested name of the property for * which a property descriptor is requested * @return the property descriptor * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#getPropertyDescriptor */ public static PropertyDescriptor getPropertyDescriptor(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getPropertyDescriptor(bean, name); } /** *

          Retrieve the property descriptors for the specified class, * introspecting and caching them the first time a particular bean class * is encountered.

          * *

          For more details see PropertyUtilsBean.

          * * @param beanClass Bean class for which property descriptors are requested * @return the property descriptors * @exception IllegalArgumentException if beanClass is null * @see PropertyUtilsBean#getPropertyDescriptors(Class) */ public static PropertyDescriptor[] getPropertyDescriptors(Class beanClass) { return PropertyUtilsBean.getInstance().getPropertyDescriptors(beanClass); } /** *

          Retrieve the property descriptors for the specified bean, * introspecting and caching them the first time a particular bean class * is encountered.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean for which property descriptors are requested * @return the property descriptors * @exception IllegalArgumentException if bean is null * @see PropertyUtilsBean#getPropertyDescriptors(Object) */ public static PropertyDescriptor[] getPropertyDescriptors(Object bean) { return PropertyUtilsBean.getInstance().getPropertyDescriptors(bean); } /** *

          Return the Java Class repesenting the property editor class that has * been registered for this property (if any).

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean for which a property descriptor is requested * @param name Possibly indexed and/or nested name of the property for * which a property descriptor is requested * @return the property editor class * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#getPropertyEditorClass(Object,String) */ public static Class getPropertyEditorClass(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getPropertyEditorClass(bean, name); } /** *

          Return the Java Class representing the property type of the specified * property, or null if there is no such property for the * specified bean.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean for which a property descriptor is requested * @param name Possibly indexed and/or nested name of the property for * which a property descriptor is requested * @return The property type * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#getPropertyType(Object, String) */ public static Class getPropertyType(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getPropertyType(bean, name); } /** *

          Return an accessible property getter method for this property, * if there is one; otherwise return null.

          * *

          For more details see PropertyUtilsBean.

          * * @param descriptor Property descriptor to return a getter for * @return The read method * @see PropertyUtilsBean#getReadMethod(PropertyDescriptor) */ public static Method getReadMethod(PropertyDescriptor descriptor) { return (PropertyUtilsBean.getInstance().getReadMethod(descriptor)); } /** *

          Return the value of the specified simple property of the specified * bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @return The property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if the property name * is nested or indexed * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#getSimpleProperty */ public static Object getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getSimpleProperty(bean, name); } /** *

          Return an accessible property setter method for this property, * if there is one; otherwise return null.

          * *

          For more details see PropertyUtilsBean.

          * * @param descriptor Property descriptor to return a setter for * @return The write method * @see PropertyUtilsBean#getWriteMethod(PropertyDescriptor) */ public static Method getWriteMethod(PropertyDescriptor descriptor) { return PropertyUtilsBean.getInstance().getWriteMethod(descriptor); } /** *

          Return true if the specified property name identifies * a readable property on the specified bean; otherwise, return * false.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean to be examined (may be a {@link DynaBean} * @param name Property name to be evaluated * @return true if the property is readable, * otherwise false * * @exception IllegalArgumentException if bean * or name is null * @see PropertyUtilsBean#isReadable * @since BeanUtils 1.6 */ public static boolean isReadable(Object bean, String name) { return PropertyUtilsBean.getInstance().isReadable(bean, name); } /** *

          Return true if the specified property name identifies * a writeable property on the specified bean; otherwise, return * false.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean to be examined (may be a {@link DynaBean} * @param name Property name to be evaluated * @return true if the property is writeable, * otherwise false * * @exception IllegalArgumentException if bean * or name is null * @see PropertyUtilsBean#isWriteable * @since BeanUtils 1.6 */ public static boolean isWriteable(Object bean, String name) { return PropertyUtilsBean.getInstance().isWriteable(bean, name); } /** *

          Sets the value of the specified indexed property of the specified * bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be modified * @param name propertyname[index] of the property value * to be modified * @param value Value to which the specified property element * should be set * * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying property * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#setIndexedProperty(Object, String, Object) */ public static void setIndexedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyUtilsBean.getInstance().setIndexedProperty(bean, name, value); } /** *

          Sets the value of the specified indexed property of the specified * bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be set * @param name Simple property name of the property value to be set * @param index Index of the property value to be set * @param value Value to which the indexed property element is to be set * * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying property * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#setIndexedProperty(Object, String, Object) */ public static void setIndexedProperty(Object bean, String name, int index, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyUtilsBean.getInstance().setIndexedProperty(bean, name, index, value); } /** *

          Sets the value of the specified mapped property of the * specified bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be set * @param name propertyname(key) of the property value * to be set * @param value The property value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#setMappedProperty(Object, String, Object) */ public static void setMappedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyUtilsBean.getInstance().setMappedProperty(bean, name, value); } /** *

          Sets the value of the specified mapped property of the specified * bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be set * @param name Mapped property name of the property value to be set * @param key Key of the property value to be set * @param value The property value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#setMappedProperty(Object, String, String, Object) */ public static void setMappedProperty(Object bean, String name, String key, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyUtilsBean.getInstance().setMappedProperty(bean, name, key, value); } /** *

          Sets the value of the (possibly nested) property of the specified * name, for the specified bean, with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be modified * @param name Possibly nested name of the property to be modified * @param value Value to which the property is to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#setNestedProperty */ public static void setNestedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyUtilsBean.getInstance().setNestedProperty(bean, name, value); } /** *

          Set the value of the specified property of the specified bean, * no matter which property reference format is used, with no * type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be modified * @param name Possibly indexed and/or nested name of the property * to be modified * @param value Value to which this property is to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#setProperty */ public static void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyUtilsBean.getInstance().setProperty(bean, name, value); } /** *

          Set the value of the specified simple property of the specified bean, * with no type conversions.

          * *

          For more details see PropertyUtilsBean.

          * * @param bean Bean whose property is to be modified * @param name Name of the property to be modified * @param value Value to which the property should be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if the property name is * nested or indexed * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found * @see PropertyUtilsBean#setSimpleProperty */ public static void setSimpleProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyUtilsBean.getInstance().setSimpleProperty(bean, name, value); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/PropertyUtilsBean.java100644 0 0 271074 12262570612 27556 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IndexedPropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.beanutils.expression.DefaultResolver; import org.apache.commons.beanutils.expression.Resolver; import org.apache.commons.collections.FastHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Utility methods for using Java Reflection APIs to facilitate generic * property getter and setter operations on Java objects. Much of this * code was originally included in BeanUtils, but has been * separated because of the volume of code involved. *

          * In general, the objects that are examined and modified using these * methods are expected to conform to the property getter and setter method * naming conventions described in the JavaBeans Specification (Version 1.0.1). * No data type conversions are performed, and there are no usage of any * PropertyEditor classes that have been registered, although * a convenient way to access the registered classes themselves is included. *

          * For the purposes of this class, five formats for referencing a particular * property value of a bean are defined, with the default layout of an * identifying String in parentheses. However the notation for these formats * and how they are resolved is now (since BeanUtils 1.8.0) controlled by * the configured {@link Resolver} implementation: *

            *
          • Simple (name) - The specified * name identifies an individual property of a particular * JavaBean. The name of the actual getter or setter method to be used * is determined using standard JavaBeans instrospection, so that (unless * overridden by a BeanInfo class, a property named "xyz" * will have a getter method named getXyz() or (for boolean * properties only) isXyz(), and a setter method named * setXyz().
          • *
          • Nested (name1.name2.name3) The first * name element is used to select a property getter, as for simple * references above. The object returned for this property is then * consulted, using the same approach, for a property getter for a * property named name2, and so on. The property value that * is ultimately retrieved or modified is the one identified by the * last name element.
          • *
          • Indexed (name[index]) - The underlying * property value is assumed to be an array, or this JavaBean is assumed * to have indexed property getter and setter methods. The appropriate * (zero-relative) entry in the array is selected. List * objects are now also supported for read/write. You simply need to define * a getter that returns the List
          • *
          • Mapped (name(key)) - The JavaBean * is assumed to have an property getter and setter methods with an * additional attribute of type java.lang.String.
          • *
          • Combined (name1.name2[index].name3(key)) - * Combining mapped, nested, and indexed references is also * supported.
          • *
          * * @version $Id: PropertyUtilsBean.java 1555231 2014-01-03 19:38:03Z oheger $ * @see Resolver * @see PropertyUtils * @since 1.7 */ public class PropertyUtilsBean { private Resolver resolver = new DefaultResolver(); // --------------------------------------------------------- Class Methods /** * Return the PropertyUtils bean instance. * @return The PropertyUtils bean instance */ protected static PropertyUtilsBean getInstance() { return BeanUtilsBean.getInstance().getPropertyUtils(); } // --------------------------------------------------------- Variables /** * The cache of PropertyDescriptor arrays for beans we have already * introspected, keyed by the java.lang.Class of this object. */ private WeakFastHashMap, BeanIntrospectionData> descriptorsCache = null; private WeakFastHashMap, FastHashMap> mappedDescriptorsCache = null; /** An empty object array */ private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; /** Log instance */ private final Log log = LogFactory.getLog(PropertyUtils.class); /** The list with BeanIntrospector objects. */ private final List introspectors; // ---------------------------------------------------------- Constructors /** Base constructor */ public PropertyUtilsBean() { descriptorsCache = new WeakFastHashMap, BeanIntrospectionData>(); descriptorsCache.setFast(true); mappedDescriptorsCache = new WeakFastHashMap, FastHashMap>(); mappedDescriptorsCache.setFast(true); introspectors = new CopyOnWriteArrayList(); resetBeanIntrospectors(); } // --------------------------------------------------------- Public Methods /** * Return the configured {@link Resolver} implementation used by BeanUtils. *

          * The {@link Resolver} handles the property name * expressions and the implementation in use effectively * controls the dialect of the expression language * that BeanUtils recongnises. *

          * {@link DefaultResolver} is the default implementation used. * * @return resolver The property expression resolver. * @since 1.8.0 */ public Resolver getResolver() { return resolver; } /** * Configure the {@link Resolver} implementation used by BeanUtils. *

          * The {@link Resolver} handles the property name * expressions and the implementation in use effectively * controls the dialect of the expression language * that BeanUtils recongnises. *

          * {@link DefaultResolver} is the default implementation used. * * @param resolver The property expression resolver. * @since 1.8.0 */ public void setResolver(Resolver resolver) { if (resolver == null) { this.resolver = new DefaultResolver(); } else { this.resolver = resolver; } } /** * Resets the {@link BeanIntrospector} objects registered at this instance. After this * method was called, only the default {@code BeanIntrospector} is registered. * * @since 1.9 */ public final void resetBeanIntrospectors() { introspectors.clear(); introspectors.add(DefaultBeanIntrospector.INSTANCE); } /** * Adds a BeanIntrospector. This object is invoked when the * property descriptors of a class need to be obtained. * * @param introspector the BeanIntrospector to be added (must * not be null * @throws IllegalArgumentException if the argument is null * @since 1.9 */ public void addBeanIntrospector(BeanIntrospector introspector) { if (introspector == null) { throw new IllegalArgumentException( "BeanIntrospector must not be null!"); } introspectors.add(introspector); } /** * Removes the specified BeanIntrospector. * * @param introspector the BeanIntrospector to be removed * @return true if the BeanIntrospector existed and * could be removed, false otherwise * @since 1.9 */ public boolean removeBeanIntrospector(BeanIntrospector introspector) { return introspectors.remove(introspector); } /** * Clear any cached property descriptors information for all classes * loaded by any class loaders. This is useful in cases where class * loaders are thrown away to implement class reloading. */ public void clearDescriptors() { descriptorsCache.clear(); mappedDescriptorsCache.clear(); Introspector.flushCaches(); } /** *

          Copy property values from the "origin" bean to the "destination" bean * for all cases where the property names are the same (even though the * actual getter and setter methods might have been customized via * BeanInfo classes). No conversions are performed on the * actual property values -- it is assumed that the values retrieved from * the origin bean are assignment-compatible with the types expected by * the destination bean.

          * *

          If the origin "bean" is actually a Map, it is assumed * to contain String-valued simple property names as the keys, pointing * at the corresponding property values that will be set in the destination * bean.Note that this method is intended to perform * a "shallow copy" of the properties and so complex properties * (for example, nested ones) will not be copied.

          * *

          Note, that this method will not copy a List to a List, or an Object[] * to an Object[]. It's specifically for copying JavaBean properties.

          * * @param dest Destination bean whose properties are modified * @param orig Origin bean whose properties are retrieved * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if the dest or * orig argument is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (dest == null) { throw new IllegalArgumentException ("No destination bean specified"); } if (orig == null) { throw new IllegalArgumentException("No origin bean specified"); } if (orig instanceof DynaBean) { DynaProperty[] origDescriptors = ((DynaBean) orig).getDynaClass().getDynaProperties(); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if (isReadable(orig, name) && isWriteable(dest, name)) { try { Object value = ((DynaBean) orig).get(name); if (dest instanceof DynaBean) { ((DynaBean) dest).set(name, value); } else { setSimpleProperty(dest, name, value); } } catch (NoSuchMethodException e) { if (log.isDebugEnabled()) { log.debug("Error writing to '" + name + "' on class '" + dest.getClass() + "'", e); } } } } } else if (orig instanceof Map) { Iterator entries = ((Map) orig).entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Entry) entries.next(); String name = (String)entry.getKey(); if (isWriteable(dest, name)) { try { if (dest instanceof DynaBean) { ((DynaBean) dest).set(name, entry.getValue()); } else { setSimpleProperty(dest, name, entry.getValue()); } } catch (NoSuchMethodException e) { if (log.isDebugEnabled()) { log.debug("Error writing to '" + name + "' on class '" + dest.getClass() + "'", e); } } } } } else /* if (orig is a standard JavaBean) */ { PropertyDescriptor[] origDescriptors = getPropertyDescriptors(orig); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if (isReadable(orig, name) && isWriteable(dest, name)) { try { Object value = getSimpleProperty(orig, name); if (dest instanceof DynaBean) { ((DynaBean) dest).set(name, value); } else { setSimpleProperty(dest, name, value); } } catch (NoSuchMethodException e) { if (log.isDebugEnabled()) { log.debug("Error writing to '" + name + "' on class '" + dest.getClass() + "'", e); } } } } } } /** *

          Return the entire set of properties for which the specified bean * provides a read method. This map contains the unconverted property * values for all properties for which a read method is provided * (i.e. where the getReadMethod() returns non-null).

          * *

          FIXME - Does not account for mapped properties.

          * * @param bean Bean whose properties are to be extracted * @return The set of properties for the bean * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } Map description = new HashMap(); if (bean instanceof DynaBean) { DynaProperty[] descriptors = ((DynaBean) bean).getDynaClass().getDynaProperties(); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); description.put(name, getProperty(bean, name)); } } else { PropertyDescriptor[] descriptors = getPropertyDescriptors(bean); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); if (descriptors[i].getReadMethod() != null) { description.put(name, getProperty(bean, name)); } } } return (description); } /** * Return the value of the specified indexed property of the specified * bean, with no type conversions. The zero-relative index of the * required value must be included (in square brackets) as a suffix to * the property name, or IllegalArgumentException will be * thrown. In addition to supporting the JavaBeans specification, this * method has been extended to support List objects as well. * * @param bean Bean whose property is to be extracted * @param name propertyname[index] of the property value * to be extracted * @return the indexed property value * * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying array or List * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Object getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Identify the index of the requested individual property int index = -1; try { index = resolver.getIndex(name); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid indexed property '" + name + "' on bean class '" + bean.getClass() + "' " + e.getMessage()); } if (index < 0) { throw new IllegalArgumentException("Invalid indexed property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Isolate the name name = resolver.getProperty(name); // Request the specified indexed property value return (getIndexedProperty(bean, name, index)); } /** * Return the value of the specified indexed property of the specified * bean, with no type conversions. In addition to supporting the JavaBeans * specification, this method has been extended to support * List objects as well. * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * @return the indexed property value * * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying property * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Object getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null || name.length() == 0) { if (bean.getClass().isArray()) { return Array.get(bean, index); } else if (bean instanceof List) { return ((List)bean).get(index); } } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Handle DynaBean instances specially if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "' on bean class '" + bean.getClass() + "'"); } return (((DynaBean) bean).get(name, index)); } // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Call the indexed getter method if there is one if (descriptor instanceof IndexedPropertyDescriptor) { Method readMethod = ((IndexedPropertyDescriptor) descriptor). getIndexedReadMethod(); readMethod = MethodUtils.getAccessibleMethod(bean.getClass(), readMethod); if (readMethod != null) { Object[] subscript = new Object[1]; subscript[0] = new Integer(index); try { return (invokeMethod(readMethod,bean, subscript)); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof IndexOutOfBoundsException) { throw (IndexOutOfBoundsException) e.getTargetException(); } else { throw e; } } } } // Otherwise, the underlying property must be an array Method readMethod = getReadMethod(bean.getClass(), descriptor); if (readMethod == null) { throw new NoSuchMethodException("Property '" + name + "' has no " + "getter method on bean class '" + bean.getClass() + "'"); } // Call the property getter and return the value Object value = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY); if (!value.getClass().isArray()) { if (!(value instanceof java.util.List)) { throw new IllegalArgumentException("Property '" + name + "' is not indexed on bean class '" + bean.getClass() + "'"); } else { //get the List's value return ((java.util.List) value).get(index); } } else { //get the array's value try { return (Array.get(value, index)); } catch (ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + Array.getLength(value) + " for property '" + name + "'"); } } } /** * Return the value of the specified mapped property of the * specified bean, with no type conversions. The key of the * required value must be included (in brackets) as a suffix to * the property name, or IllegalArgumentException will be * thrown. * * @param bean Bean whose property is to be extracted * @param name propertyname(key) of the property value * to be extracted * @return the mapped property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Object getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Identify the key of the requested individual property String key = null; try { key = resolver.getKey(name); } catch (IllegalArgumentException e) { throw new IllegalArgumentException ("Invalid mapped property '" + name + "' on bean class '" + bean.getClass() + "' " + e.getMessage()); } if (key == null) { throw new IllegalArgumentException("Invalid mapped property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Isolate the name name = resolver.getProperty(name); // Request the specified indexed property value return (getMappedProperty(bean, name, key)); } /** * Return the value of the specified mapped property of the specified * bean, with no type conversions. * * @param bean Bean whose property is to be extracted * @param name Mapped property name of the property value to be extracted * @param key Key of the property value to be extracted * @return the mapped property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Object getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } if (key == null) { throw new IllegalArgumentException("No key specified for property '" + name + "' on bean class " + bean.getClass() + "'"); } // Handle DynaBean instances specially if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "'+ on bean class '" + bean.getClass() + "'"); } return (((DynaBean) bean).get(name, key)); } Object result = null; // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "'+ on bean class '" + bean.getClass() + "'"); } if (descriptor instanceof MappedPropertyDescriptor) { // Call the keyed getter method if there is one Method readMethod = ((MappedPropertyDescriptor) descriptor). getMappedReadMethod(); readMethod = MethodUtils.getAccessibleMethod(bean.getClass(), readMethod); if (readMethod != null) { Object[] keyArray = new Object[1]; keyArray[0] = key; result = invokeMethod(readMethod, bean, keyArray); } else { throw new NoSuchMethodException("Property '" + name + "' has no mapped getter method on bean class '" + bean.getClass() + "'"); } } else { /* means that the result has to be retrieved from a map */ Method readMethod = getReadMethod(bean.getClass(), descriptor); if (readMethod != null) { Object invokeResult = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY); /* test and fetch from the map */ if (invokeResult instanceof java.util.Map) { result = ((java.util.Map)invokeResult).get(key); } } else { throw new NoSuchMethodException("Property '" + name + "' has no mapped getter method on bean class '" + bean.getClass() + "'"); } } return result; } /** *

          Return the mapped property descriptors for this bean class.

          * *

          FIXME - Does not work with DynaBeans.

          * * @param beanClass Bean class to be introspected * @return the mapped property descriptors * @deprecated This method should not be exposed */ @Deprecated public FastHashMap getMappedPropertyDescriptors(Class beanClass) { if (beanClass == null) { return null; } // Look up any cached descriptors for this bean class return mappedDescriptorsCache.get(beanClass); } /** *

          Return the mapped property descriptors for this bean.

          * *

          FIXME - Does not work with DynaBeans.

          * * @param bean Bean to be introspected * @return the mapped property descriptors * @deprecated This method should not be exposed */ @Deprecated public FastHashMap getMappedPropertyDescriptors(Object bean) { if (bean == null) { return null; } return (getMappedPropertyDescriptors(bean.getClass())); } /** * Return the value of the (possibly nested) property of the specified * name, for the specified bean, with no type conversions. * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * @return the nested property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception NestedNullException if a nested reference to a * property returns null * @exception InvocationTargetException * if the property accessor method throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Object getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Resolve nested references while (resolver.hasNested(name)) { String next = resolver.next(name); Object nestedBean = null; if (bean instanceof Map) { nestedBean = getPropertyOfMapBean((Map) bean, next); } else if (resolver.isMapped(next)) { nestedBean = getMappedProperty(bean, next); } else if (resolver.isIndexed(next)) { nestedBean = getIndexedProperty(bean, next); } else { nestedBean = getSimpleProperty(bean, next); } if (nestedBean == null) { throw new NestedNullException ("Null property value for '" + name + "' on bean class '" + bean.getClass() + "'"); } bean = nestedBean; name = resolver.remove(name); } if (bean instanceof Map) { bean = getPropertyOfMapBean((Map) bean, name); } else if (resolver.isMapped(name)) { bean = getMappedProperty(bean, name); } else if (resolver.isIndexed(name)) { bean = getIndexedProperty(bean, name); } else { bean = getSimpleProperty(bean, name); } return bean; } /** * This method is called by getNestedProperty and setNestedProperty to * define what it means to get a property from an object which implements * Map. See setPropertyOfMapBean for more information. * * @param bean Map bean * @param propertyName The property name * @return the property value * * @throws IllegalArgumentException when the propertyName is regarded as * being invalid. * * @throws IllegalAccessException just in case subclasses override this * method to try to access real getter methods and find permission is denied. * * @throws InvocationTargetException just in case subclasses override this * method to try to access real getter methods, and find it throws an * exception when invoked. * * @throws NoSuchMethodException just in case subclasses override this * method to try to access real getter methods, and want to fail if * no simple method is available. * @since 1.8.0 */ protected Object getPropertyOfMapBean(Map bean, String propertyName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (resolver.isMapped(propertyName)) { String name = resolver.getProperty(propertyName); if (name == null || name.length() == 0) { propertyName = resolver.getKey(propertyName); } } if (resolver.isIndexed(propertyName) || resolver.isMapped(propertyName)) { throw new IllegalArgumentException( "Indexed or mapped properties are not supported on" + " objects of type Map: " + propertyName); } return bean.get(propertyName); } /** * Return the value of the specified property of the specified bean, * no matter which property reference format is used, with no * type conversions. * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * @return the property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Object getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (getNestedProperty(bean, name)); } /** *

          Retrieve the property descriptor for the specified property of the * specified bean, or return null if there is no such * descriptor. This method resolves indexed and nested property * references in the same manner as other methods in this class, except * that if the last (or only) name element is indexed, the descriptor * for the last resolved property itself is returned.

          * *

          FIXME - Does not work with DynaBeans.

          * * @param bean Bean for which a property descriptor is requested * @param name Possibly indexed and/or nested name of the property for * which a property descriptor is requested * @return the property descriptor * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public PropertyDescriptor getPropertyDescriptor(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Resolve nested references while (resolver.hasNested(name)) { String next = resolver.next(name); Object nestedBean = getProperty(bean, next); if (nestedBean == null) { throw new NestedNullException ("Null property value for '" + next + "' on bean class '" + bean.getClass() + "'"); } bean = nestedBean; name = resolver.remove(name); } // Remove any subscript from the final name value name = resolver.getProperty(name); // Look up and return this property from our cache // creating and adding it to the cache if not found. if (name == null) { return (null); } BeanIntrospectionData data = getIntrospectionData(bean.getClass()); PropertyDescriptor result = data.getDescriptor(name); if (result != null) { return result; } FastHashMap mappedDescriptors = getMappedPropertyDescriptors(bean); if (mappedDescriptors == null) { mappedDescriptors = new FastHashMap(); mappedDescriptors.setFast(true); mappedDescriptorsCache.put(bean.getClass(), mappedDescriptors); } result = (PropertyDescriptor) mappedDescriptors.get(name); if (result == null) { // not found, try to create it try { result = new MappedPropertyDescriptor(name, bean.getClass()); } catch (IntrospectionException ie) { /* Swallow IntrospectionException * TODO: Why? */ } if (result != null) { mappedDescriptors.put(name, result); } } return result; } /** *

          Retrieve the property descriptors for the specified class, * introspecting and caching them the first time a particular bean class * is encountered.

          * *

          FIXME - Does not work with DynaBeans.

          * * @param beanClass Bean class for which property descriptors are requested * @return the property descriptors * * @exception IllegalArgumentException if beanClass is null */ public PropertyDescriptor[] getPropertyDescriptors(Class beanClass) { return getIntrospectionData(beanClass).getDescriptors(); } /** *

          Retrieve the property descriptors for the specified bean, * introspecting and caching them the first time a particular bean class * is encountered.

          * *

          FIXME - Does not work with DynaBeans.

          * * @param bean Bean for which property descriptors are requested * @return the property descriptors * * @exception IllegalArgumentException if bean is null */ public PropertyDescriptor[] getPropertyDescriptors(Object bean) { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } return (getPropertyDescriptors(bean.getClass())); } /** *

          Return the Java Class repesenting the property editor class that has * been registered for this property (if any). This method follows the * same name resolution rules used by getPropertyDescriptor(), * so if the last element of a name reference is indexed, the property * editor for the underlying property's class is returned.

          * *

          Note that null will be returned if there is no property, * or if there is no registered property editor class. Because this * return value is ambiguous, you should determine the existence of the * property itself by other means.

          * *

          FIXME - Does not work with DynaBeans.

          * * @param bean Bean for which a property descriptor is requested * @param name Possibly indexed and/or nested name of the property for * which a property descriptor is requested * @return the property editor class * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Class getPropertyEditorClass(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor != null) { return (descriptor.getPropertyEditorClass()); } else { return (null); } } /** * Return the Java Class representing the property type of the specified * property, or null if there is no such property for the * specified bean. This method follows the same name resolution rules * used by getPropertyDescriptor(), so if the last element * of a name reference is indexed, the type of the property itself will * be returned. If the last (or only) element has no property with the * specified name, null is returned. * * @param bean Bean for which a property descriptor is requested * @param name Possibly indexed and/or nested name of the property for * which a property descriptor is requested * @return The property type * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Class getPropertyType(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Resolve nested references while (resolver.hasNested(name)) { String next = resolver.next(name); Object nestedBean = getProperty(bean, next); if (nestedBean == null) { throw new NestedNullException ("Null property value for '" + next + "' on bean class '" + bean.getClass() + "'"); } bean = nestedBean; name = resolver.remove(name); } // Remove any subscript from the final name value name = resolver.getProperty(name); // Special handling for DynaBeans if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { return (null); } Class type = descriptor.getType(); if (type == null) { return (null); } else if (type.isArray()) { return (type.getComponentType()); } else { return (type); } } PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { return (null); } else if (descriptor instanceof IndexedPropertyDescriptor) { return (((IndexedPropertyDescriptor) descriptor). getIndexedPropertyType()); } else if (descriptor instanceof MappedPropertyDescriptor) { return (((MappedPropertyDescriptor) descriptor). getMappedPropertyType()); } else { return (descriptor.getPropertyType()); } } /** *

          Return an accessible property getter method for this property, * if there is one; otherwise return null.

          * *

          FIXME - Does not work with DynaBeans.

          * * @param descriptor Property descriptor to return a getter for * @return The read method */ public Method getReadMethod(PropertyDescriptor descriptor) { return (MethodUtils.getAccessibleMethod(descriptor.getReadMethod())); } /** *

          Return an accessible property getter method for this property, * if there is one; otherwise return null.

          * *

          FIXME - Does not work with DynaBeans.

          * * @param clazz The class of the read method will be invoked on * @param descriptor Property descriptor to return a getter for * @return The read method */ Method getReadMethod(Class clazz, PropertyDescriptor descriptor) { return (MethodUtils.getAccessibleMethod(clazz, descriptor.getReadMethod())); } /** * Return the value of the specified simple property of the specified * bean, with no type conversions. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @return The property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if the property name * is nested or indexed * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Object getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Validate the syntax of the property name if (resolver.hasNested(name)) { throw new IllegalArgumentException ("Nested property names are not allowed: Property '" + name + "' on bean class '" + bean.getClass() + "'"); } else if (resolver.isIndexed(name)) { throw new IllegalArgumentException ("Indexed property names are not allowed: Property '" + name + "' on bean class '" + bean.getClass() + "'"); } else if (resolver.isMapped(name)) { throw new IllegalArgumentException ("Mapped property names are not allowed: Property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Handle DynaBean instances specially if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "' on dynaclass '" + ((DynaBean) bean).getDynaClass() + "'" ); } return (((DynaBean) bean).get(name)); } // Retrieve the property getter method for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "' on class '" + bean.getClass() + "'" ); } Method readMethod = getReadMethod(bean.getClass(), descriptor); if (readMethod == null) { throw new NoSuchMethodException("Property '" + name + "' has no getter method in class '" + bean.getClass() + "'"); } // Call the property getter and return the value Object value = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY); return (value); } /** *

          Return an accessible property setter method for this property, * if there is one; otherwise return null.

          * *

          Note: This method does not work correctly with custom bean * introspection under certain circumstances. It may return {@code null} * even if a write method is defined for the property in question. Use * {@link #getWriteMethod(Class, PropertyDescriptor)} to be sure that the * correct result is returned.

          *

          FIXME - Does not work with DynaBeans.

          * * @param descriptor Property descriptor to return a setter for * @return The write method */ public Method getWriteMethod(PropertyDescriptor descriptor) { return (MethodUtils.getAccessibleMethod(descriptor.getWriteMethod())); } /** *

          Return an accessible property setter method for this property, * if there is one; otherwise return null.

          * *

          FIXME - Does not work with DynaBeans.

          * * @param clazz The class of the read method will be invoked on * @param descriptor Property descriptor to return a setter for * @return The write method * @since 1.9.1 */ public Method getWriteMethod(Class clazz, PropertyDescriptor descriptor) { BeanIntrospectionData data = getIntrospectionData(clazz); return (MethodUtils.getAccessibleMethod(clazz, data.getWriteMethod(clazz, descriptor))); } /** *

          Return true if the specified property name identifies * a readable property on the specified bean; otherwise, return * false. * * @param bean Bean to be examined (may be a {@link DynaBean} * @param name Property name to be evaluated * @return true if the property is readable, * otherwise false * * @exception IllegalArgumentException if bean * or name is null * * @since BeanUtils 1.6 */ public boolean isReadable(Object bean, String name) { // Validate method parameters if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Resolve nested references while (resolver.hasNested(name)) { String next = resolver.next(name); Object nestedBean = null; try { nestedBean = getProperty(bean, next); } catch (IllegalAccessException e) { return false; } catch (InvocationTargetException e) { return false; } catch (NoSuchMethodException e) { return false; } if (nestedBean == null) { throw new NestedNullException ("Null property value for '" + next + "' on bean class '" + bean.getClass() + "'"); } bean = nestedBean; name = resolver.remove(name); } // Remove any subscript from the final name value name = resolver.getProperty(name); // Treat WrapDynaBean as special case - may be a write-only property // (see Jira issue# BEANUTILS-61) if (bean instanceof WrapDynaBean) { bean = ((WrapDynaBean)bean).getInstance(); } // Return the requested result if (bean instanceof DynaBean) { // All DynaBean properties are readable return (((DynaBean) bean).getDynaClass().getDynaProperty(name) != null); } else { try { PropertyDescriptor desc = getPropertyDescriptor(bean, name); if (desc != null) { Method readMethod = getReadMethod(bean.getClass(), desc); if (readMethod == null) { if (desc instanceof IndexedPropertyDescriptor) { readMethod = ((IndexedPropertyDescriptor) desc).getIndexedReadMethod(); } else if (desc instanceof MappedPropertyDescriptor) { readMethod = ((MappedPropertyDescriptor) desc).getMappedReadMethod(); } readMethod = MethodUtils.getAccessibleMethod(bean.getClass(), readMethod); } return (readMethod != null); } else { return (false); } } catch (IllegalAccessException e) { return (false); } catch (InvocationTargetException e) { return (false); } catch (NoSuchMethodException e) { return (false); } } } /** *

          Return true if the specified property name identifies * a writeable property on the specified bean; otherwise, return * false. * * @param bean Bean to be examined (may be a {@link DynaBean} * @param name Property name to be evaluated * @return true if the property is writeable, * otherwise false * * @exception IllegalArgumentException if bean * or name is null * * @since BeanUtils 1.6 */ public boolean isWriteable(Object bean, String name) { // Validate method parameters if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Resolve nested references while (resolver.hasNested(name)) { String next = resolver.next(name); Object nestedBean = null; try { nestedBean = getProperty(bean, next); } catch (IllegalAccessException e) { return false; } catch (InvocationTargetException e) { return false; } catch (NoSuchMethodException e) { return false; } if (nestedBean == null) { throw new NestedNullException ("Null property value for '" + next + "' on bean class '" + bean.getClass() + "'"); } bean = nestedBean; name = resolver.remove(name); } // Remove any subscript from the final name value name = resolver.getProperty(name); // Treat WrapDynaBean as special case - may be a read-only property // (see Jira issue# BEANUTILS-61) if (bean instanceof WrapDynaBean) { bean = ((WrapDynaBean)bean).getInstance(); } // Return the requested result if (bean instanceof DynaBean) { // All DynaBean properties are writeable return (((DynaBean) bean).getDynaClass().getDynaProperty(name) != null); } else { try { PropertyDescriptor desc = getPropertyDescriptor(bean, name); if (desc != null) { Method writeMethod = getWriteMethod(bean.getClass(), desc); if (writeMethod == null) { if (desc instanceof IndexedPropertyDescriptor) { writeMethod = ((IndexedPropertyDescriptor) desc).getIndexedWriteMethod(); } else if (desc instanceof MappedPropertyDescriptor) { writeMethod = ((MappedPropertyDescriptor) desc).getMappedWriteMethod(); } writeMethod = MethodUtils.getAccessibleMethod(bean.getClass(), writeMethod); } return (writeMethod != null); } else { return (false); } } catch (IllegalAccessException e) { return (false); } catch (InvocationTargetException e) { return (false); } catch (NoSuchMethodException e) { return (false); } } } /** * Set the value of the specified indexed property of the specified * bean, with no type conversions. The zero-relative index of the * required value must be included (in square brackets) as a suffix to * the property name, or IllegalArgumentException will be * thrown. In addition to supporting the JavaBeans specification, this * method has been extended to support List objects as well. * * @param bean Bean whose property is to be modified * @param name propertyname[index] of the property value * to be modified * @param value Value to which the specified property element * should be set * * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying property * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setIndexedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Identify the index of the requested individual property int index = -1; try { index = resolver.getIndex(name); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid indexed property '" + name + "' on bean class '" + bean.getClass() + "'"); } if (index < 0) { throw new IllegalArgumentException("Invalid indexed property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Isolate the name name = resolver.getProperty(name); // Set the specified indexed property value setIndexedProperty(bean, name, index, value); } /** * Set the value of the specified indexed property of the specified * bean, with no type conversions. In addition to supporting the JavaBeans * specification, this method has been extended to support * List objects as well. * * @param bean Bean whose property is to be set * @param name Simple property name of the property value to be set * @param index Index of the property value to be set * @param value Value to which the indexed property element is to be set * * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying property * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setIndexedProperty(Object bean, String name, int index, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null || name.length() == 0) { if (bean.getClass().isArray()) { Array.set(bean, index, value); return; } else if (bean instanceof List) { List list = toObjectList(bean); list.set(index, value); return; } } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Handle DynaBean instances specially if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "' on bean class '" + bean.getClass() + "'"); } ((DynaBean) bean).set(name, index, value); return; } // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Call the indexed setter method if there is one if (descriptor instanceof IndexedPropertyDescriptor) { Method writeMethod = ((IndexedPropertyDescriptor) descriptor). getIndexedWriteMethod(); writeMethod = MethodUtils.getAccessibleMethod(bean.getClass(), writeMethod); if (writeMethod != null) { Object[] subscript = new Object[2]; subscript[0] = new Integer(index); subscript[1] = value; try { if (log.isTraceEnabled()) { String valueClassName = value == null ? "" : value.getClass().getName(); log.trace("setSimpleProperty: Invoking method " + writeMethod +" with index=" + index + ", value=" + value + " (class " + valueClassName+ ")"); } invokeMethod(writeMethod, bean, subscript); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof IndexOutOfBoundsException) { throw (IndexOutOfBoundsException) e.getTargetException(); } else { throw e; } } return; } } // Otherwise, the underlying property must be an array or a list Method readMethod = getReadMethod(bean.getClass(), descriptor); if (readMethod == null) { throw new NoSuchMethodException("Property '" + name + "' has no getter method on bean class '" + bean.getClass() + "'"); } // Call the property getter to get the array or list Object array = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY); if (!array.getClass().isArray()) { if (array instanceof List) { // Modify the specified value in the List List list = toObjectList(array); list.set(index, value); } else { throw new IllegalArgumentException("Property '" + name + "' is not indexed on bean class '" + bean.getClass() + "'"); } } else { // Modify the specified value in the array Array.set(array, index, value); } } /** * Set the value of the specified mapped property of the * specified bean, with no type conversions. The key of the * value to set must be included (in brackets) as a suffix to * the property name, or IllegalArgumentException will be * thrown. * * @param bean Bean whose property is to be set * @param name propertyname(key) of the property value * to be set * @param value The property value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setMappedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Identify the key of the requested individual property String key = null; try { key = resolver.getKey(name); } catch (IllegalArgumentException e) { throw new IllegalArgumentException ("Invalid mapped property '" + name + "' on bean class '" + bean.getClass() + "'"); } if (key == null) { throw new IllegalArgumentException ("Invalid mapped property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Isolate the name name = resolver.getProperty(name); // Request the specified indexed property value setMappedProperty(bean, name, key, value); } /** * Set the value of the specified mapped property of the specified * bean, with no type conversions. * * @param bean Bean whose property is to be set * @param name Mapped property name of the property value to be set * @param key Key of the property value to be set * @param value The property value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setMappedProperty(Object bean, String name, String key, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } if (key == null) { throw new IllegalArgumentException("No key specified for property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Handle DynaBean instances specially if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "' on bean class '" + bean.getClass() + "'"); } ((DynaBean) bean).set(name, key, value); return; } // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "' on bean class '" + bean.getClass() + "'"); } if (descriptor instanceof MappedPropertyDescriptor) { // Call the keyed setter method if there is one Method mappedWriteMethod = ((MappedPropertyDescriptor) descriptor). getMappedWriteMethod(); mappedWriteMethod = MethodUtils.getAccessibleMethod(bean.getClass(), mappedWriteMethod); if (mappedWriteMethod != null) { Object[] params = new Object[2]; params[0] = key; params[1] = value; if (log.isTraceEnabled()) { String valueClassName = value == null ? "" : value.getClass().getName(); log.trace("setSimpleProperty: Invoking method " + mappedWriteMethod + " with key=" + key + ", value=" + value + " (class " + valueClassName +")"); } invokeMethod(mappedWriteMethod, bean, params); } else { throw new NoSuchMethodException ("Property '" + name + "' has no mapped setter method" + "on bean class '" + bean.getClass() + "'"); } } else { /* means that the result has to be retrieved from a map */ Method readMethod = getReadMethod(bean.getClass(), descriptor); if (readMethod != null) { Object invokeResult = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY); /* test and fetch from the map */ if (invokeResult instanceof java.util.Map) { java.util.Map map = toPropertyMap(invokeResult); map.put(key, value); } } else { throw new NoSuchMethodException("Property '" + name + "' has no mapped getter method on bean class '" + bean.getClass() + "'"); } } } /** * Set the value of the (possibly nested) property of the specified * name, for the specified bean, with no type conversions. *

          * Example values for parameter "name" are: *

            *
          • "a" -- sets the value of property a of the specified bean
          • *
          • "a.b" -- gets the value of property a of the specified bean, * then on that object sets the value of property b.
          • *
          • "a(key)" -- sets a value of mapped-property a on the specified * bean. This effectively means bean.setA("key").
          • *
          • "a[3]" -- sets a value of indexed-property a on the specified * bean. This effectively means bean.setA(3).
          • *
          * * @param bean Bean whose property is to be modified * @param name Possibly nested name of the property to be modified * @param value Value to which the property is to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setNestedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Resolve nested references while (resolver.hasNested(name)) { String next = resolver.next(name); Object nestedBean = null; if (bean instanceof Map) { nestedBean = getPropertyOfMapBean((Map)bean, next); } else if (resolver.isMapped(next)) { nestedBean = getMappedProperty(bean, next); } else if (resolver.isIndexed(next)) { nestedBean = getIndexedProperty(bean, next); } else { nestedBean = getSimpleProperty(bean, next); } if (nestedBean == null) { throw new NestedNullException ("Null property value for '" + name + "' on bean class '" + bean.getClass() + "'"); } bean = nestedBean; name = resolver.remove(name); } if (bean instanceof Map) { setPropertyOfMapBean(toPropertyMap(bean), name, value); } else if (resolver.isMapped(name)) { setMappedProperty(bean, name, value); } else if (resolver.isIndexed(name)) { setIndexedProperty(bean, name, value); } else { setSimpleProperty(bean, name, value); } } /** * This method is called by method setNestedProperty when the current bean * is found to be a Map object, and defines how to deal with setting * a property on a Map. *

          * The standard implementation here is to: *

            *
          • call bean.set(propertyName) for all propertyName values.
          • *
          • throw an IllegalArgumentException if the property specifier * contains MAPPED_DELIM or INDEXED_DELIM, as Map entries are essentially * simple properties; mapping and indexing operations do not make sense * when accessing a map (even thought the returned object may be a Map * or an Array).
          • *
          *

          * The default behaviour of beanutils 1.7.1 or later is for assigning to * "a.b" to mean a.put(b, obj) always. However the behaviour of beanutils * version 1.6.0, 1.6.1, 1.7.0 was for "a.b" to mean a.setB(obj) if such * a method existed, and a.put(b, obj) otherwise. In version 1.5 it meant * a.put(b, obj) always (ie the same as the behaviour in the current version). * In versions prior to 1.5 it meant a.setB(obj) always. [yes, this is * all very unfortunate] *

          * Users who would like to customise the meaning of "a.b" in method * setNestedProperty when a is a Map can create a custom subclass of * this class and override this method to implement the behaviour of * their choice, such as restoring the pre-1.4 behaviour of this class * if they wish. When overriding this method, do not forget to deal * with MAPPED_DELIM and INDEXED_DELIM characters in the propertyName. *

          * Note, however, that the recommended solution for objects that * implement Map but want their simple properties to come first is * for those objects to override their get/put methods to implement * that behaviour, and not to solve the problem by modifying the * default behaviour of the PropertyUtilsBean class by overriding this * method. * * @param bean Map bean * @param propertyName The property name * @param value the property value * * @throws IllegalArgumentException when the propertyName is regarded as * being invalid. * * @throws IllegalAccessException just in case subclasses override this * method to try to access real setter methods and find permission is denied. * * @throws InvocationTargetException just in case subclasses override this * method to try to access real setter methods, and find it throws an * exception when invoked. * * @throws NoSuchMethodException just in case subclasses override this * method to try to access real setter methods, and want to fail if * no simple method is available. * @since 1.8.0 */ protected void setPropertyOfMapBean(Map bean, String propertyName, Object value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (resolver.isMapped(propertyName)) { String name = resolver.getProperty(propertyName); if (name == null || name.length() == 0) { propertyName = resolver.getKey(propertyName); } } if (resolver.isIndexed(propertyName) || resolver.isMapped(propertyName)) { throw new IllegalArgumentException( "Indexed or mapped properties are not supported on" + " objects of type Map: " + propertyName); } bean.put(propertyName, value); } /** * Set the value of the specified property of the specified bean, * no matter which property reference format is used, with no * type conversions. * * @param bean Bean whose property is to be modified * @param name Possibly indexed and/or nested name of the property * to be modified * @param value Value to which this property is to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { setNestedProperty(bean, name, value); } /** * Set the value of the specified simple property of the specified bean, * with no type conversions. * * @param bean Bean whose property is to be modified * @param name Name of the property to be modified * @param value Value to which the property should be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if bean or * name is null * @exception IllegalArgumentException if the property name is * nested or indexed * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setSimpleProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Validate the syntax of the property name if (resolver.hasNested(name)) { throw new IllegalArgumentException ("Nested property names are not allowed: Property '" + name + "' on bean class '" + bean.getClass() + "'"); } else if (resolver.isIndexed(name)) { throw new IllegalArgumentException ("Indexed property names are not allowed: Property '" + name + "' on bean class '" + bean.getClass() + "'"); } else if (resolver.isMapped(name)) { throw new IllegalArgumentException ("Mapped property names are not allowed: Property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Handle DynaBean instances specially if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "' on dynaclass '" + ((DynaBean) bean).getDynaClass() + "'" ); } ((DynaBean) bean).set(name, value); return; } // Retrieve the property setter method for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "' on class '" + bean.getClass() + "'" ); } Method writeMethod = getWriteMethod(bean.getClass(), descriptor); if (writeMethod == null) { throw new NoSuchMethodException("Property '" + name + "' has no setter method in class '" + bean.getClass() + "'"); } // Call the property setter method Object[] values = new Object[1]; values[0] = value; if (log.isTraceEnabled()) { String valueClassName = value == null ? "" : value.getClass().getName(); log.trace("setSimpleProperty: Invoking method " + writeMethod + " with value " + value + " (class " + valueClassName + ")"); } invokeMethod(writeMethod, bean, values); } /** This just catches and wraps IllegalArgumentException. */ private Object invokeMethod( Method method, Object bean, Object[] values) throws IllegalAccessException, InvocationTargetException { if(bean == null) { throw new IllegalArgumentException("No bean specified " + "- this should have been checked before reaching this method"); } try { return method.invoke(bean, values); } catch (NullPointerException cause) { // JDK 1.3 and JDK 1.4 throw NullPointerException if an argument is // null for a primitive value (JDK 1.5+ throw IllegalArgumentException) String valueString = ""; if (values != null) { for (int i = 0; i < values.length; i++) { if (i>0) { valueString += ", " ; } if (values[i] == null) { valueString += ""; } else { valueString += (values[i]).getClass().getName(); } } } String expectedString = ""; Class[] parTypes = method.getParameterTypes(); if (parTypes != null) { for (int i = 0; i < parTypes.length; i++) { if (i > 0) { expectedString += ", "; } expectedString += parTypes[i].getName(); } } IllegalArgumentException e = new IllegalArgumentException( "Cannot invoke " + method.getDeclaringClass().getName() + "." + method.getName() + " on bean class '" + bean.getClass() + "' - " + cause.getMessage() // as per https://issues.apache.org/jira/browse/BEANUTILS-224 + " - had objects of type \"" + valueString + "\" but expected signature \"" + expectedString + "\"" ); if (!BeanUtils.initCause(e, cause)) { log.error("Method invocation failed", cause); } throw e; } catch (IllegalArgumentException cause) { String valueString = ""; if (values != null) { for (int i = 0; i < values.length; i++) { if (i>0) { valueString += ", " ; } if (values[i] == null) { valueString += ""; } else { valueString += (values[i]).getClass().getName(); } } } String expectedString = ""; Class[] parTypes = method.getParameterTypes(); if (parTypes != null) { for (int i = 0; i < parTypes.length; i++) { if (i > 0) { expectedString += ", "; } expectedString += parTypes[i].getName(); } } IllegalArgumentException e = new IllegalArgumentException( "Cannot invoke " + method.getDeclaringClass().getName() + "." + method.getName() + " on bean class '" + bean.getClass() + "' - " + cause.getMessage() // as per https://issues.apache.org/jira/browse/BEANUTILS-224 + " - had objects of type \"" + valueString + "\" but expected signature \"" + expectedString + "\"" ); if (!BeanUtils.initCause(e, cause)) { log.error("Method invocation failed", cause); } throw e; } } /** * Obtains the {@code BeanIntrospectionData} object describing the specified bean * class. This object is looked up in the internal cache. If necessary, introspection * is performed now on the affected bean class, and the results object is created. * * @param beanClass the bean class in question * @return the {@code BeanIntrospectionData} object for this class * @throws IllegalArgumentException if the bean class is null */ private BeanIntrospectionData getIntrospectionData(Class beanClass) { if (beanClass == null) { throw new IllegalArgumentException("No bean class specified"); } // Look up any cached information for this bean class BeanIntrospectionData data = descriptorsCache.get(beanClass); if (data == null) { data = fetchIntrospectionData(beanClass); descriptorsCache.put(beanClass, data); } return data; } /** * Performs introspection on the specified class. This method invokes all {@code BeanIntrospector} objects that were * added to this instance. * * @param beanClass the class to be inspected * @return a data object with the results of introspection */ private BeanIntrospectionData fetchIntrospectionData(Class beanClass) { DefaultIntrospectionContext ictx = new DefaultIntrospectionContext(beanClass); for (BeanIntrospector bi : introspectors) { try { bi.introspect(ictx); } catch (IntrospectionException iex) { log.error("Exception during introspection", iex); } } return new BeanIntrospectionData(ictx.getPropertyDescriptors()); } /** * Converts an object to a list of objects. This method is used when dealing * with indexed properties. It assumes that indexed properties are stored as * lists of objects. * * @param obj the object to be converted * @return the resulting list of objects */ private static List toObjectList(Object obj) { @SuppressWarnings("unchecked") // indexed properties are stored in lists of objects List list = (List) obj; return list; } /** * Converts an object to a map with property values. This method is used * when dealing with mapped properties. It assumes that mapped properties * are stored in a Map<String, Object>. * * @param obj the object to be converted * @return the resulting properties map */ private static Map toPropertyMap(Object obj) { @SuppressWarnings("unchecked") // mapped properties are stores in maps of type Map map = (Map) obj; return map; } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/ResultSetDynaClass.java100644 0 0 21535 12262570612 27632 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; /** *

          Implementation of DynaClass for DynaBeans that wrap the * java.sql.Row objects of a java.sql.ResultSet. * The normal usage pattern is something like:

          *
           *   ResultSet rs = ...;
           *   ResultSetDynaClass rsdc = new ResultSetDynaClass(rs);
           *   Iterator rows = rsdc.iterator();
           *   while (rows.hasNext())  {
           *     DynaBean row = (DynaBean) rows.next();
           *     ... process this row ...
           *   }
           *   rs.close();
           * 
          * *

          Each column in the result set will be represented as a DynaBean * property of the corresponding name (optionally forced to lower case * for portability).

          * *

          WARNING - Any {@link DynaBean} instance returned by * this class, or from the Iterator returned by the * iterator() method, is directly linked to the row that the * underlying result set is currently positioned at. This has the following * implications:

          *
            *
          • Once you retrieve a different {@link DynaBean} instance, you should * no longer use any previous instance.
          • *
          • Changing the position of the underlying result set will change the * data that the {@link DynaBean} references.
          • *
          • Once the underlying result set is closed, the {@link DynaBean} * instance may no longer be used.
          • *
          * *

          Any database data that you wish to utilize outside the context of the * current row of an open result set must be copied. For example, you could * use the following code to create standalone copies of the information in * a result set:

          *
           *   ArrayList results = new ArrayList(); // To hold copied list
           *   ResultSetDynaClass rsdc = ...;
           *   DynaProperty[] properties = rsdc.getDynaProperties();
           *   BasicDynaClass bdc =
           *     new BasicDynaClass("foo", BasicDynaBean.class,
           *                        rsdc.getDynaProperties());
           *   Iterator rows = rsdc.iterator();
           *   while (rows.hasNext()) {
           *     DynaBean oldRow = (DynaBean) rows.next();
           *     DynaBean newRow = bdc.newInstance();
           *     PropertyUtils.copyProperties(newRow, oldRow);
           *     results.add(newRow);
           *   }
           * 
          * * @version $Id: ResultSetDynaClass.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ResultSetDynaClass extends JDBCDynaClass implements DynaClass { // ----------------------------------------------------------- Constructors /** *

          Construct a new ResultSetDynaClass for the specified * ResultSet. The property names corresponding * to column names in the result set will be lower cased.

          * * @param resultSet The result set to be wrapped * * @exception NullPointerException if resultSet * is null * @exception SQLException if the metadata for this result set * cannot be introspected */ public ResultSetDynaClass(ResultSet resultSet) throws SQLException { this(resultSet, true); } /** *

          Construct a new ResultSetDynaClass for the specified * ResultSet. The property names corresponding * to the column names in the result set will be lower cased or not, * depending on the specified lowerCase value.

          * *

          WARNING - If you specify false * for lowerCase, the returned property names will * exactly match the column names returned by your JDBC driver. * Because different drivers might return column names in different * cases, the property names seen by your application will vary * depending on which JDBC driver you are using.

          * * @param resultSet The result set to be wrapped * @param lowerCase Should property names be lower cased? * * @exception NullPointerException if resultSet * is null * @exception SQLException if the metadata for this result set * cannot be introspected */ public ResultSetDynaClass(ResultSet resultSet, boolean lowerCase) throws SQLException { this(resultSet, lowerCase, false); } /** *

          Construct a new ResultSetDynaClass for the specified * ResultSet. The property names corresponding * to the column names in the result set will be lower cased or not, * depending on the specified lowerCase value.

          * *

          WARNING - If you specify false * for lowerCase, the returned property names will * exactly match the column names returned by your JDBC driver. * Because different drivers might return column names in different * cases, the property names seen by your application will vary * depending on which JDBC driver you are using.

          * * @param resultSet The result set to be wrapped * @param lowerCase Should property names be lower cased? * @param useColumnLabel true if the column label should be used, otherwise false * * @exception NullPointerException if resultSet * is null * @exception SQLException if the metadata for this result set * cannot be introspected * @since 1.8.3 */ public ResultSetDynaClass(ResultSet resultSet, boolean lowerCase, boolean useColumnLabel) throws SQLException { if (resultSet == null) { throw new NullPointerException(); } this.resultSet = resultSet; this.lowerCase = lowerCase; setUseColumnLabel(useColumnLabel); introspect(resultSet); } // ----------------------------------------------------- Instance Variables /** *

          The ResultSet we are wrapping.

          */ protected ResultSet resultSet = null; // --------------------------------------------------------- Public Methods /** *

          Return an Iterator of {@link DynaBean} instances for * each row of the wrapped ResultSet, in "forward" order. * Unless the underlying result set supports scrolling, this method * should be called only once.

          * @return An Iterator of {@link DynaBean} instances */ public Iterator iterator() { return (new ResultSetIterator(this)); } /** * Get a value from the {@link ResultSet} for the specified * property name. * * @param name The property name * @return The value * @throws SQLException if an error occurs * @since 1.8.0 */ public Object getObjectFromResultSet(String name) throws SQLException { return getObject(getResultSet(), name); } // -------------------------------------------------------- Package Methods /** *

          Return the result set we are wrapping.

          */ ResultSet getResultSet() { return (this.resultSet); } // ------------------------------------------------------ Protected Methods /** *

          Loads the class of the given name which by default uses the class loader used * to load this library. * Dervations of this class could implement alternative class loading policies such as * using custom ClassLoader or using the Threads's context class loader etc. *

          * @param className The name of the class to load * @return The loaded class * @throws SQLException if the class cannot be loaded */ @Override protected Class loadClass(String className) throws SQLException { try { return getClass().getClassLoader().loadClass(className); } catch (Exception e) { throw new SQLException("Cannot load column class '" + className + "': " + e); } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/ResultSetIterator.java100644 0 0 25415 12262570613 27544 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.sql.SQLException; import java.util.Iterator; import java.util.NoSuchElementException; /** *

          Implementation of java.util.Iterator returned by the * iterator() method of {@link ResultSetDynaClass}. Each * object returned by this iterator will be a {@link DynaBean} that * represents a single row from the result set being wrapped.

          * * @version $Id: ResultSetIterator.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ResultSetIterator implements DynaBean, Iterator { // ------------------------------------------------------------ Constructor /** *

          Construct an Iterator for the result set being wrapped * by the specified {@link ResultSetDynaClass}.

          * * @param dynaClass The {@link ResultSetDynaClass} wrapping the * result set we will iterate over */ ResultSetIterator(ResultSetDynaClass dynaClass) { this.dynaClass = dynaClass; } // ----------------------------------------------------- Instance Variables /** *

          Flag indicating whether the result set is currently positioned at a * row for which we have not yet returned an element in the iteration.

          */ protected boolean current = false; /** *

          The {@link ResultSetDynaClass} we are associated with.

          */ protected ResultSetDynaClass dynaClass = null; /** *

          Flag indicating whether the result set has indicated that there are * no further rows.

          */ protected boolean eof = false; // ------------------------------------------------------- DynaBean Methods /** * Does the specified mapped property contain a value for the specified * key value? * * @param name Name of the property to check * @param key Name of the key to check * @return true if the mapped property contains a value for * the specified key, otherwise false * * @exception IllegalArgumentException if there is no property * of the specified name */ public boolean contains(String name, String key) { throw new UnsupportedOperationException ("FIXME - mapped properties not currently supported"); } /** * Return the value of a simple property with the specified name. * * @param name Name of the property whose value is to be retrieved * @return The property's value * * @exception IllegalArgumentException if there is no property * of the specified name */ public Object get(String name) { if (dynaClass.getDynaProperty(name) == null) { throw new IllegalArgumentException(name); } try { return dynaClass.getObjectFromResultSet(name); } catch (SQLException e) { throw new RuntimeException ("get(" + name + "): SQLException: " + e); } } /** * Return the value of an indexed property with the specified name. * * @param name Name of the property whose value is to be retrieved * @param index Index of the value to be retrieved * @return The indexed property's value * * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property * @exception NullPointerException if no array or List has been * initialized for this property */ public Object get(String name, int index) { throw new UnsupportedOperationException ("FIXME - indexed properties not currently supported"); } /** * Return the value of a mapped property with the specified name, * or null if there is no value for the specified key. * * @param name Name of the property whose value is to be retrieved * @param key Key of the value to be retrieved * @return The mapped property's value * * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public Object get(String name, String key) { throw new UnsupportedOperationException ("FIXME - mapped properties not currently supported"); } /** * Return the DynaClass instance that describes the set of * properties available for this DynaBean. * * @return The associated DynaClass */ public DynaClass getDynaClass() { return (this.dynaClass); } /** * Remove any existing value for the specified key on the * specified mapped property. * * @param name Name of the property for which a value is to * be removed * @param key Key of the value to be removed * * @exception IllegalArgumentException if there is no property * of the specified name */ public void remove(String name, String key) { throw new UnsupportedOperationException ("FIXME - mapped operations not currently supported"); } /** * Set the value of a simple property with the specified name. * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception NullPointerException if an attempt is made to set a * primitive property to null */ public void set(String name, Object value) { if (dynaClass.getDynaProperty(name) == null) { throw new IllegalArgumentException(name); } try { dynaClass.getResultSet().updateObject(name, value); } catch (SQLException e) { throw new RuntimeException ("set(" + name + "): SQLException: " + e); } } /** * Set the value of an indexed property with the specified name. * * @param name Name of the property whose value is to be set * @param index Index of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property */ public void set(String name, int index, Object value) { throw new UnsupportedOperationException ("FIXME - indexed properties not currently supported"); } /** * Set the value of a mapped property with the specified name. * * @param name Name of the property whose value is to be set * @param key Key of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public void set(String name, String key, Object value) { throw new UnsupportedOperationException ("FIXME - mapped properties not currently supported"); } // ------------------------------------------------------- Iterator Methods /** *

          Return true if the iteration has more elements.

          * * @return true if the result set has another * row, otherwise false */ public boolean hasNext() { try { advance(); return (!eof); } catch (SQLException e) { throw new RuntimeException("hasNext(): SQLException: " + e); } } /** *

          Return the next element in the iteration.

          * * @return advance to the new row and return this */ public DynaBean next() { try { advance(); if (eof) { throw new NoSuchElementException(); } current = false; return (this); } catch (SQLException e) { throw new RuntimeException("next(): SQLException: " + e); } } /** *

          Remove the current element from the iteration. This method is * not supported.

          */ public void remove() { throw new UnsupportedOperationException("remove()"); } // ------------------------------------------------------ Protected Methods /** *

          Advance the result set to the next row, if there is not a current * row (and if we are not already at eof).

          * * @exception SQLException if the result set throws an exception */ protected void advance() throws SQLException { if (!current && !eof) { if (dynaClass.getResultSet().next()) { current = true; eof = false; } else { current = false; eof = true; } } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/RowSetDynaClass.java100644 0 0 30443 12262570612 27121 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** *

          Implementation of {@link DynaClass} that creates an in-memory collection * of {@link DynaBean}s representing the results of an SQL query. Once the * {@link DynaClass} instance has been created, the JDBC ResultSet * and Statement on which it is based can be closed, and the * underlying Connection can be returned to its connection pool * (if you are using one).

          * *

          The normal usage pattern is something like:

          *
           *   Connection conn = ...;  // Acquire connection from pool
           *   Statement stmt = conn.createStatement();
           *   ResultSet rs = stmt.executeQuery("SELECT ...");
           *   RowSetDynaClass rsdc = new RowSetDynaClass(rs);
           *   rs.close();
           *   stmt.close();
           *   ...;                    // Return connection to pool
           *   List rows = rsdc.getRows();
           *   ...;                   // Process the rows as desired
           * 
          * *

          Each column in the result set will be represented as a {@link DynaBean} * property of the corresponding name (optionally forced to lower case * for portability). There will be one {@link DynaBean} in the * List returned by getRows() for each * row in the original ResultSet.

          * *

          In general, instances of {@link RowSetDynaClass} can be serialized * and deserialized, which will automatically include the list of * {@link DynaBean}s representing the data content. The only exception * to this rule would be when the underlying property values that were * copied from the ResultSet originally cannot themselves * be serialized. Therefore, a {@link RowSetDynaClass} makes a very * convenient mechanism for transporting data sets to remote Java-based * application components.

          * * @version $Id: RowSetDynaClass.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class RowSetDynaClass extends JDBCDynaClass implements DynaClass, Serializable { // ----------------------------------------------------- Instance variables /** *

          Limits the size of the returned list. The call to * getRows() will return at most limit number of rows. * If less than or equal to 0, does not limit the size of the result. */ protected int limit = -1; /** *

          The list of {@link DynaBean}s representing the contents of * the original ResultSet on which this * {@link RowSetDynaClass} was based.

          */ protected List rows = new ArrayList(); // ----------------------------------------------------------- Constructors /** *

          Construct a new {@link RowSetDynaClass} for the specified * ResultSet. The property names corresponding * to column names in the result set will be lower cased.

          * * @param resultSet The result set to be wrapped * * @exception NullPointerException if resultSet * is null * @exception SQLException if the metadata for this result set * cannot be introspected */ public RowSetDynaClass(ResultSet resultSet) throws SQLException { this(resultSet, true, -1); } /** *

          Construct a new {@link RowSetDynaClass} for the specified * ResultSet. The property names corresponding * to column names in the result set will be lower cased.

          * * If limit is not less than 0, max limit * number of rows will be copied into the list. * * @param resultSet The result set to be wrapped * @param limit The maximum for the size of the result. * * @exception NullPointerException if resultSet * is null * @exception SQLException if the metadata for this result set * cannot be introspected */ public RowSetDynaClass(ResultSet resultSet, int limit) throws SQLException { this(resultSet, true, limit); } /** *

          Construct a new {@link RowSetDynaClass} for the specified * ResultSet. The property names corresponding * to the column names in the result set will be lower cased or not, * depending on the specified lowerCase value.

          * * If limit is not less than 0, max limit * number of rows will be copied into the resultset. * * * @param resultSet The result set to be wrapped * @param lowerCase Should property names be lower cased? * * @exception NullPointerException if resultSet * is null * @exception SQLException if the metadata for this result set * cannot be introspected */ public RowSetDynaClass(ResultSet resultSet, boolean lowerCase) throws SQLException { this(resultSet, lowerCase, -1); } /** *

          Construct a new {@link RowSetDynaClass} for the specified * ResultSet. The property names corresponding * to the column names in the result set will be lower cased or not, * depending on the specified lowerCase value.

          * *

          WARNING - If you specify false * for lowerCase, the returned property names will * exactly match the column names returned by your JDBC driver. * Because different drivers might return column names in different * cases, the property names seen by your application will vary * depending on which JDBC driver you are using.

          * * @param resultSet The result set to be wrapped * @param lowerCase Should property names be lower cased? * @param limit Maximum limit for the List of {@link DynaBean} * * @exception NullPointerException if resultSet * is null * @exception SQLException if the metadata for this result set * cannot be introspected */ public RowSetDynaClass(ResultSet resultSet, boolean lowerCase, int limit) throws SQLException { this(resultSet, lowerCase, limit, false); } /** *

          Construct a new {@link RowSetDynaClass} for the specified * ResultSet. The property names corresponding * to the column names in the result set will be lower cased or not, * depending on the specified lowerCase value.

          * *

          WARNING - If you specify false * for lowerCase, the returned property names will * exactly match the column names returned by your JDBC driver. * Because different drivers might return column names in different * cases, the property names seen by your application will vary * depending on which JDBC driver you are using.

          * * @param resultSet The result set to be wrapped * @param lowerCase Should property names be lower cased? * @param useColumnLabel true if the column label should be used, otherwise false * * @exception NullPointerException if resultSet * is null * @exception SQLException if the metadata for this result set * cannot be introspected * @since 1.8.3 */ public RowSetDynaClass(ResultSet resultSet, boolean lowerCase, boolean useColumnLabel) throws SQLException { this(resultSet, lowerCase, -1, useColumnLabel); } /** *

          Construct a new {@link RowSetDynaClass} for the specified * ResultSet. The property names corresponding * to the column names in the result set will be lower cased or not, * depending on the specified lowerCase value.

          * *

          WARNING - If you specify false * for lowerCase, the returned property names will * exactly match the column names returned by your JDBC driver. * Because different drivers might return column names in different * cases, the property names seen by your application will vary * depending on which JDBC driver you are using.

          * * @param resultSet The result set to be wrapped * @param lowerCase Should property names be lower cased? * @param limit Maximum limit for the List of {@link DynaBean} * @param useColumnLabel true if the column label should be used, otherwise false * * @exception NullPointerException if resultSet * is null * @exception SQLException if the metadata for this result set * cannot be introspected * @since 1.8.3 */ public RowSetDynaClass(ResultSet resultSet, boolean lowerCase, int limit, boolean useColumnLabel) throws SQLException { if (resultSet == null) { throw new NullPointerException(); } this.lowerCase = lowerCase; this.limit = limit; setUseColumnLabel(useColumnLabel); introspect(resultSet); copy(resultSet); } /** *

          Return a List containing the {@link DynaBean}s that * represent the contents of each Row from the * ResultSet that was the basis of this * {@link RowSetDynaClass} instance. These {@link DynaBean}s are * disconnected from the database itself, so there is no problem with * modifying the contents of the list, or the values of the properties * of these {@link DynaBean}s. However, it is the application's * responsibility to persist any such changes back to the database, * if it so desires.

          * * @return A List of {@link DynaBean} instances */ public List getRows() { return (this.rows); } // ------------------------------------------------------ Protected Methods /** *

          Copy the column values for each row in the specified * ResultSet into a newly created {@link DynaBean}, and add * this bean to the list of {@link DynaBean}s that will later by * returned by a call to getRows().

          * * @param resultSet The ResultSet whose data is to be * copied * * @exception SQLException if an error is encountered copying the data */ protected void copy(ResultSet resultSet) throws SQLException { int cnt = 0; while (resultSet.next() && (limit < 0 || cnt++ < limit) ) { DynaBean bean = createDynaBean(); for (int i = 0; i < properties.length; i++) { String name = properties[i].getName(); Object value = getObject(resultSet, name); bean.set(name, value); } rows.add(bean); } } /** *

          Create and return a new {@link DynaBean} instance to be used for * representing a row in the underlying result set.

          * * @return A new DynaBean instance */ protected DynaBean createDynaBean() { return (new BasicDynaBean(this)); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/WeakFastHashMap.java100644 0 0 55217 12262570612 27051 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; /** *

          A customized implementation of java.util.HashMap designed * to operate in a multithreaded environment where the large majority of * method calls are read-only, instead of structural changes. When operating * in "fast" mode, read calls are non-synchronized and write calls perform the * following steps:

          *
            *
          • Clone the existing collection *
          • Perform the modification on the clone *
          • Replace the existing collection with the (modified) clone *
          *

          When first created, objects of this class default to "slow" mode, where * all accesses of any type are synchronized but no cloning takes place. This * is appropriate for initially populating the collection, followed by a switch * to "fast" mode (by calling setFast(true)) after initialization * is complete.

          * *

          NOTE: If you are creating and accessing a * HashMap only within a single thread, you should use * java.util.HashMap directly (with no synchronization), for * maximum performance.

          * *

          NOTE: This class is not cross-platform. * Using it may cause unexpected failures on some architectures. * It suffers from the same problems as the double-checked locking idiom. * In particular, the instruction that clones the internal collection and the * instruction that sets the internal reference to the clone can be executed * or perceived out-of-order. This means that any read operation might fail * unexpectedly, as it may be reading the state of the internal collection * before the internal collection is fully formed. * For more information on the double-checked locking idiom, see the * * Double-Checked Locking Idiom Is Broken Declaration.

          * * @since Commons Collections 1.0 * @version $Id: WeakFastHashMap.java 1540186 2013-11-08 21:08:30Z oheger $ */ class WeakFastHashMap extends HashMap { /** * The underlying map we are managing. */ private Map map = null; /** * Are we currently operating in "fast" mode? */ private boolean fast = false; // Constructors // ---------------------------------------------------------------------- /** * Construct an empty map. */ public WeakFastHashMap() { super(); this.map = createMap(); } /** * Construct an empty map with the specified capacity. * * @param capacity the initial capacity of the empty map */ public WeakFastHashMap(int capacity) { super(); this.map = createMap(capacity); } /** * Construct an empty map with the specified capacity and load factor. * * @param capacity the initial capacity of the empty map * @param factor the load factor of the new map */ public WeakFastHashMap(int capacity, float factor) { super(); this.map = createMap(capacity, factor); } /** * Construct a new map with the same mappings as the specified map. * * @param map the map whose mappings are to be copied */ public WeakFastHashMap(Map map) { super(); this.map = createMap(map); } // Property access // ---------------------------------------------------------------------- /** * Returns true if this map is operating in fast mode. * * @return true if this map is operating in fast mode */ public boolean getFast() { return (this.fast); } /** * Sets whether this map is operating in fast mode. * * @param fast true if this map should operate in fast mode */ public void setFast(boolean fast) { this.fast = fast; } // Map access // ---------------------------------------------------------------------- // These methods can forward straight to the wrapped Map in 'fast' mode. // (because they are query methods) /** * Return the value to which this map maps the specified key. Returns * null if the map contains no mapping for this key, or if * there is a mapping with a value of null. Use the * containsKey() method to disambiguate these cases. * * @param key the key whose value is to be returned * @return the value mapped to that key, or null */ @Override public V get(Object key) { if (fast) { return (map.get(key)); } else { synchronized (map) { return (map.get(key)); } } } /** * Return the number of key-value mappings in this map. * * @return the current size of the map */ @Override public int size() { if (fast) { return (map.size()); } else { synchronized (map) { return (map.size()); } } } /** * Return true if this map contains no mappings. * * @return is the map currently empty */ @Override public boolean isEmpty() { if (fast) { return (map.isEmpty()); } else { synchronized (map) { return (map.isEmpty()); } } } /** * Return true if this map contains a mapping for the * specified key. * * @param key the key to be searched for * @return true if the map contains the key */ @Override public boolean containsKey(Object key) { if (fast) { return (map.containsKey(key)); } else { synchronized (map) { return (map.containsKey(key)); } } } /** * Return true if this map contains one or more keys mapping * to the specified value. * * @param value the value to be searched for * @return true if the map contains the value */ @Override public boolean containsValue(Object value) { if (fast) { return (map.containsValue(value)); } else { synchronized (map) { return (map.containsValue(value)); } } } // Map modification // ---------------------------------------------------------------------- // These methods perform special behaviour in 'fast' mode. // The map is cloned, updated and then assigned back. // See the comments at the top as to why this won't always work. /** * Associate the specified value with the specified key in this map. * If the map previously contained a mapping for this key, the old * value is replaced and returned. * * @param key the key with which the value is to be associated * @param value the value to be associated with this key * @return the value previously mapped to the key, or null */ @Override public V put(K key, V value) { if (fast) { synchronized (this) { Map temp = cloneMap(map); V result = temp.put(key, value); map = temp; return (result); } } else { synchronized (map) { return (map.put(key, value)); } } } /** * Copy all of the mappings from the specified map to this one, replacing * any mappings with the same keys. * * @param in the map whose mappings are to be copied */ @Override public void putAll(Map in) { if (fast) { synchronized (this) { Map temp = cloneMap(map); temp.putAll(in); map = temp; } } else { synchronized (map) { map.putAll(in); } } } /** * Remove any mapping for this key, and return any previously * mapped value. * * @param key the key whose mapping is to be removed * @return the value removed, or null */ @Override public V remove(Object key) { if (fast) { synchronized (this) { Map temp = cloneMap(map); V result = temp.remove(key); map = temp; return (result); } } else { synchronized (map) { return (map.remove(key)); } } } /** * Remove all mappings from this map. */ @Override public void clear() { if (fast) { synchronized (this) { map = createMap(); } } else { synchronized (map) { map.clear(); } } } // Basic object methods // ---------------------------------------------------------------------- /** * Compare the specified object with this list for equality. This * implementation uses exactly the code that is used to define the * list equals function in the documentation for the * Map.equals method. * * @param o the object to be compared to this list * @return true if the two maps are equal */ @Override public boolean equals(Object o) { // Simple tests that require no synchronization if (o == this) { return (true); } else if (!(o instanceof Map)) { return (false); } Map mo = (Map) o; // Compare the two maps for equality if (fast) { if (mo.size() != map.size()) { return (false); } for (Map.Entry e : map.entrySet()) { K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(mo.get(key) == null && mo.containsKey(key))) { return (false); } } else { if (!value.equals(mo.get(key))) { return (false); } } } return (true); } else { synchronized (map) { if (mo.size() != map.size()) { return (false); } for (Map.Entry e : map.entrySet()) { K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(mo.get(key) == null && mo.containsKey(key))) { return (false); } } else { if (!value.equals(mo.get(key))) { return (false); } } } return (true); } } } /** * Return the hash code value for this map. This implementation uses * exactly the code that is used to define the list hash function in the * documentation for the Map.hashCode method. * * @return suitable integer hash code */ @Override public int hashCode() { if (fast) { int h = 0; for (Map.Entry e : map.entrySet()) { h += e.hashCode(); } return (h); } else { synchronized (map) { int h = 0; for (Map.Entry e : map.entrySet()) { h += e.hashCode(); } return (h); } } } /** * Return a shallow copy of this FastHashMap instance. * The keys and values themselves are not copied. * * @return a clone of this map */ @Override public Object clone() { WeakFastHashMap results = null; if (fast) { results = new WeakFastHashMap(map); } else { synchronized (map) { results = new WeakFastHashMap(map); } } results.setFast(getFast()); return (results); } // Map views // ---------------------------------------------------------------------- /** * Return a collection view of the mappings contained in this map. Each * element in the returned collection is a Map.Entry. * @return the set of map Map entries */ @Override public Set> entrySet() { return new EntrySet(); } /** * Return a set view of the keys contained in this map. * @return the set of the Map's keys */ @Override public Set keySet() { return new KeySet(); } /** * Return a collection view of the values contained in this map. * @return the set of the Map's values */ @Override public Collection values() { return new Values(); } // Abstractions on Map creations (for subclasses such as WeakFastHashMap) // ---------------------------------------------------------------------- protected Map createMap() { return new WeakHashMap(); } protected Map createMap(int capacity) { return new WeakHashMap(capacity); } protected Map createMap(int capacity, float factor) { return new WeakHashMap(capacity, factor); } protected Map createMap(Map map) { return new WeakHashMap(map); } protected Map cloneMap(Map map) { return createMap(map); } // Map view inner classes // ---------------------------------------------------------------------- /** * Abstract collection implementation shared by keySet(), values() and entrySet(). * * @param the element type */ private abstract class CollectionView implements Collection { public CollectionView() { } protected abstract Collection get(Map map); protected abstract E iteratorNext(Map.Entry entry); public void clear() { if (fast) { synchronized (WeakFastHashMap.this) { map = createMap(); } } else { synchronized (map) { get(map).clear(); } } } public boolean remove(Object o) { if (fast) { synchronized (WeakFastHashMap.this) { Map temp = cloneMap(map); boolean r = get(temp).remove(o); map = temp; return r; } } else { synchronized (map) { return get(map).remove(o); } } } public boolean removeAll(Collection o) { if (fast) { synchronized (WeakFastHashMap.this) { Map temp = cloneMap(map); boolean r = get(temp).removeAll(o); map = temp; return r; } } else { synchronized (map) { return get(map).removeAll(o); } } } public boolean retainAll(Collection o) { if (fast) { synchronized (WeakFastHashMap.this) { Map temp = cloneMap(map); boolean r = get(temp).retainAll(o); map = temp; return r; } } else { synchronized (map) { return get(map).retainAll(o); } } } public int size() { if (fast) { return get(map).size(); } else { synchronized (map) { return get(map).size(); } } } public boolean isEmpty() { if (fast) { return get(map).isEmpty(); } else { synchronized (map) { return get(map).isEmpty(); } } } public boolean contains(Object o) { if (fast) { return get(map).contains(o); } else { synchronized (map) { return get(map).contains(o); } } } public boolean containsAll(Collection o) { if (fast) { return get(map).containsAll(o); } else { synchronized (map) { return get(map).containsAll(o); } } } public T[] toArray(T[] o) { if (fast) { return get(map).toArray(o); } else { synchronized (map) { return get(map).toArray(o); } } } public Object[] toArray() { if (fast) { return get(map).toArray(); } else { synchronized (map) { return get(map).toArray(); } } } @Override public boolean equals(Object o) { if (o == this) { return true; } if (fast) { return get(map).equals(o); } else { synchronized (map) { return get(map).equals(o); } } } @Override public int hashCode() { if (fast) { return get(map).hashCode(); } else { synchronized (map) { return get(map).hashCode(); } } } public boolean add(E o) { throw new UnsupportedOperationException(); } public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } public Iterator iterator() { return new CollectionViewIterator(); } private class CollectionViewIterator implements Iterator { private Map expected; private Map.Entry lastReturned = null; private final Iterator> iterator; public CollectionViewIterator() { this.expected = map; this.iterator = expected.entrySet().iterator(); } public boolean hasNext() { if (expected != map) { throw new ConcurrentModificationException(); } return iterator.hasNext(); } public E next() { if (expected != map) { throw new ConcurrentModificationException(); } lastReturned = iterator.next(); return iteratorNext(lastReturned); } public void remove() { if (lastReturned == null) { throw new IllegalStateException(); } if (fast) { synchronized (WeakFastHashMap.this) { if (expected != map) { throw new ConcurrentModificationException(); } WeakFastHashMap.this.remove(lastReturned.getKey()); lastReturned = null; expected = map; } } else { iterator.remove(); lastReturned = null; } } } } /** * Set implementation over the keys of the FastHashMap */ private class KeySet extends CollectionView implements Set { @Override protected Collection get(Map map) { return map.keySet(); } @Override protected K iteratorNext(Map.Entry entry) { return entry.getKey(); } } /** * Collection implementation over the values of the FastHashMap */ private class Values extends CollectionView { @Override protected Collection get(Map map) { return map.values(); } @Override protected V iteratorNext(Map.Entry entry) { return entry.getValue(); } } /** * Set implementation over the entries of the FastHashMap */ private class EntrySet extends CollectionView> implements Set> { @Override protected Collection> get(Map map) { return map.entrySet(); } @Override protected Map.Entry iteratorNext(Map.Entry entry) { return entry; } } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/WrapDynaBean.java100644 0 0 34164 12262570611 26412 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; /** *

          Implementation of DynaBean that wraps a standard JavaBean * instance, so that DynaBean APIs can be used to access its properties.

          * *

          * The most common use cases for this class involve wrapping an existing java bean. * (This makes it different from the typical use cases for other DynaBean's.) * For example: *

          *
           *  Object aJavaBean = ...;
           *  ...
           *  DynaBean db = new WrapDynaBean(aJavaBean);
           *  ...
           * 
          * *

          IMPLEMENTATION NOTE - This implementation does not * support the contains() and remove() methods.

          * * @version $Id: WrapDynaBean.java 1547902 2013-12-04 20:35:01Z oheger $ */ public class WrapDynaBean implements DynaBean, Serializable { // ---------------------------------------------------------- Constructors /** * Construct a new DynaBean associated with the specified * JavaBean instance. * * @param instance JavaBean instance to be wrapped */ public WrapDynaBean(Object instance) { this(instance, null); } /** * Creates a new instance of {@code WrapDynaBean}, associates it with the specified * JavaBean instance, and initializes the bean's {@code DynaClass}. Using this * constructor this {@code WrapDynaBean} instance can be assigned a class which has * been configured externally. If no {@code WrapDynaClass} is provided, a new one is * created using a standard mechanism. * * @param instance JavaBean instance to be wrapped * @param cls the optional {@code WrapDynaClass} to be used for this bean * @since 1.9 */ public WrapDynaBean(Object instance, WrapDynaClass cls) { this.instance = instance; this.dynaClass = (cls != null) ? cls : (WrapDynaClass) getDynaClass(); } // ---------------------------------------------------- Instance Variables /** * The DynaClass "base class" that this DynaBean * is associated with. */ protected transient WrapDynaClass dynaClass = null; /** * The JavaBean instance wrapped by this WrapDynaBean. */ protected Object instance = null; // ------------------------------------------------------ DynaBean Methods /** * Does the specified mapped property contain a value for the specified * key value? * * @param name Name of the property to check * @param key Name of the key to check * @return true if the mapped property contains a value for * the specified key, otherwise false * * @exception IllegalArgumentException if there is no property * of the specified name */ public boolean contains(String name, String key) { throw new UnsupportedOperationException ("WrapDynaBean does not support contains()"); } /** * Return the value of a simple property with the specified name. * * @param name Name of the property whose value is to be retrieved * @return The property's value * * @exception IllegalArgumentException if there is no property * of the specified name */ public Object get(String name) { Object value = null; try { value = getPropertyUtils().getSimpleProperty(instance, name); } catch (InvocationTargetException ite) { Throwable cause = ite.getTargetException(); throw new IllegalArgumentException ("Error reading property '" + name + "' nested exception - " + cause); } catch (Throwable t) { throw new IllegalArgumentException ("Error reading property '" + name + "', exception - " + t); } return (value); } /** * Return the value of an indexed property with the specified name. * * @param name Name of the property whose value is to be retrieved * @param index Index of the value to be retrieved * @return The indexed property's value * * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property * @exception NullPointerException if no array or List has been * initialized for this property */ public Object get(String name, int index) { Object value = null; try { value = getPropertyUtils().getIndexedProperty(instance, name, index); } catch (IndexOutOfBoundsException e) { throw e; } catch (InvocationTargetException ite) { Throwable cause = ite.getTargetException(); throw new IllegalArgumentException ("Error reading indexed property '" + name + "' nested exception - " + cause); } catch (Throwable t) { throw new IllegalArgumentException ("Error reading indexed property '" + name + "', exception - " + t); } return (value); } /** * Return the value of a mapped property with the specified name, * or null if there is no value for the specified key. * * @param name Name of the property whose value is to be retrieved * @param key Key of the value to be retrieved * @return The mapped property's value * * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public Object get(String name, String key) { Object value = null; try { value = getPropertyUtils().getMappedProperty(instance, name, key); } catch (InvocationTargetException ite) { Throwable cause = ite.getTargetException(); throw new IllegalArgumentException ("Error reading mapped property '" + name + "' nested exception - " + cause); } catch (Throwable t) { throw new IllegalArgumentException ("Error reading mapped property '" + name + "', exception - " + t); } return (value); } /** * Return the DynaClass instance that describes the set of * properties available for this DynaBean. * @return The associated DynaClass */ public DynaClass getDynaClass() { if (dynaClass == null) { dynaClass = WrapDynaClass.createDynaClass(instance.getClass()); } return (this.dynaClass); } /** * Remove any existing value for the specified key on the * specified mapped property. * * @param name Name of the property for which a value is to * be removed * @param key Key of the value to be removed * * @exception IllegalArgumentException if there is no property * of the specified name */ public void remove(String name, String key) { throw new UnsupportedOperationException ("WrapDynaBean does not support remove()"); } /** * Set the value of a simple property with the specified name. * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception NullPointerException if an attempt is made to set a * primitive property to null */ public void set(String name, Object value) { try { getPropertyUtils().setSimpleProperty(instance, name, value); } catch (InvocationTargetException ite) { Throwable cause = ite.getTargetException(); throw new IllegalArgumentException ("Error setting property '" + name + "' nested exception -" + cause); } catch (Throwable t) { throw new IllegalArgumentException ("Error setting property '" + name + "', exception - " + t); } } /** * Set the value of an indexed property with the specified name. * * @param name Name of the property whose value is to be set * @param index Index of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property */ public void set(String name, int index, Object value) { try { getPropertyUtils().setIndexedProperty(instance, name, index, value); } catch (IndexOutOfBoundsException e) { throw e; } catch (InvocationTargetException ite) { Throwable cause = ite.getTargetException(); throw new IllegalArgumentException ("Error setting indexed property '" + name + "' nested exception - " + cause); } catch (Throwable t) { throw new IllegalArgumentException ("Error setting indexed property '" + name + "', exception - " + t); } } /** * Set the value of a mapped property with the specified name. * * @param name Name of the property whose value is to be set * @param key Key of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public void set(String name, String key, Object value) { try { getPropertyUtils().setMappedProperty(instance, name, key, value); } catch (InvocationTargetException ite) { Throwable cause = ite.getTargetException(); throw new IllegalArgumentException ("Error setting mapped property '" + name + "' nested exception - " + cause); } catch (Throwable t) { throw new IllegalArgumentException ("Error setting mapped property '" + name + "', exception - " + t); } } /** * Gets the bean instance wrapped by this DynaBean. * For most common use cases, * this object should already be known * and this method safely be ignored. * But some creators of frameworks using DynaBean's may * find this useful. * * @return the java bean Object wrapped by this DynaBean */ public Object getInstance() { return instance; } // ------------------------------------------------------ Protected Methods /** * Return the property descriptor for the specified property name. * * @param name Name of the property for which to retrieve the descriptor * @return The descriptor for the specified property * * @exception IllegalArgumentException if this is not a valid property * name for our DynaClass */ protected DynaProperty getDynaProperty(String name) { DynaProperty descriptor = getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new IllegalArgumentException ("Invalid property name '" + name + "'"); } return (descriptor); } /** * Returns the {@code PropertyUtilsBean} instance to be used for accessing properties. * If available, this object is obtained from the associated {@code WrapDynaClass}. * * @return the associated {@code PropertyUtilsBean} */ private PropertyUtilsBean getPropertyUtils() { PropertyUtilsBean propUtils = null; if (dynaClass != null) { propUtils = dynaClass.getPropertyUtilsBean(); } return (propUtils != null) ? propUtils : PropertyUtilsBean.getInstance(); } } commons-beanutils-1.9.1-src/src/main/java/org/apache/commons/beanutils/WrapDynaClass.java100644 0 0 45036 12262570611 26612 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.PropertyDescriptor; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; /** *

          Implementation of DynaClass for DynaBeans that wrap * standard JavaBean instances.

          * *

          * It is suggested that this class should not usually need to be used directly * to create new WrapDynaBean instances. * It's usually better to call the WrapDynaBean constructor directly. * For example:

          *
           *   Object javaBean = ...;
           *   DynaBean wrapper = new WrapDynaBean(javaBean);
           * 
          *

          * * @version $Id: WrapDynaClass.java 1547902 2013-12-04 20:35:01Z oheger $ */ public class WrapDynaClass implements DynaClass { // ----------------------------------------------------------- Constructors /** * Construct a new WrapDynaClass for the specified JavaBean class. This * constructor is private; WrapDynaClass instances will be created as * needed via calls to the createDynaClass(Class) method. * * @param beanClass JavaBean class to be introspected around * @param propUtils the {@code PropertyUtilsBean} associated with this class */ private WrapDynaClass(Class beanClass, PropertyUtilsBean propUtils) { this.beanClassRef = new SoftReference>(beanClass); this.beanClassName = beanClass.getName(); propertyUtilsBean = propUtils; introspect(); } // ----------------------------------------------------- Instance Variables /** * Name of the JavaBean class represented by this WrapDynaClass. */ private String beanClassName = null; /** * Reference to the JavaBean class represented by this WrapDynaClass. */ private Reference> beanClassRef = null; /** Stores the associated {@code PropertyUtilsBean} instance. */ private final PropertyUtilsBean propertyUtilsBean; /** * The JavaBean Class which is represented by this * WrapDynaClass. * * @deprecated No longer initialized, use getBeanClass() method instead */ @Deprecated protected Class beanClass = null; /** * The set of PropertyDescriptors for this bean class. */ protected PropertyDescriptor[] descriptors = null; /** * The set of PropertyDescriptors for this bean class, keyed by the * property name. Individual descriptor instances will be the same * instances as those in the descriptors list. */ protected HashMap descriptorsMap = new HashMap(); /** * The set of dynamic properties that are part of this DynaClass. */ protected DynaProperty[] properties = null; /** * The set of dynamic properties that are part of this DynaClass, * keyed by the property name. Individual descriptor instances will * be the same instances as those in the properties list. */ protected HashMap propertiesMap = new HashMap(); // ------------------------------------------------------- Static Variables private static final ContextClassLoaderLocal> CLASSLOADER_CACHE = new ContextClassLoaderLocal>() { @Override protected Map initialValue() { return new WeakHashMap(); } }; /** * Get the wrap dyna classes cache. Note: This method only exists to * satisfy the deprecated {@code dynaClasses} hash map. */ @SuppressWarnings("unchecked") private static Map getDynaClassesMap() { @SuppressWarnings("rawtypes") Map cache = CLASSLOADER_CACHE.get(); return cache; } /** * Returns the cache for the already created class instances. For each * combination of bean class and {@code PropertyUtilsBean} instance an * entry is created in the cache. * @return the cache for already created {@code WrapDynaClass} instances */ private static Map getClassesCache() { return CLASSLOADER_CACHE.get(); } /** * The set of WrapDynaClass instances that have ever been * created, keyed by the underlying bean Class. The keys to this map * are Class objects, and the values are corresponding WrapDynaClass * objects. *

          * This static variable is safe even when this code is deployed via a * shared classloader because it is keyed via a Class object. The same * class loaded via two different classloaders will result in different * entries in this map. *

          * Note, however, that this HashMap can result in a memory leak. When * this class is in a shared classloader it will retain references to * classes loaded via a webapp classloader even after the webapp has been * undeployed. That will prevent the entire classloader and all the classes * it refers to and all their static members from being freed. * ************* !!!!!!!!!!!! PLEASE NOTE !!!!!!!!!!!! ************* * * THE FOLLOWING IS A NASTY HACK TO SO THAT BEANUTILS REMAINS BINARY * COMPATIBLE WITH PREVIOUS RELEASES. * * There are two issues here: * * 1) Memory Issues: The static HashMap caused memory problems (See BEANUTILS-59) * to resolve this it has been moved into a ContextClassLoaderLocal instance * (named CLASSLOADER_CACHE above) which holds one copy per * ClassLoader in a WeakHashMap. * * 2) Binary Compatibility: As the "dynaClasses" static HashMap is "protected" * removing it breaks BeanUtils binary compatibility with previous versions. * To resolve this all the methods have been overriden to delegate to the * Map for the ClassLoader in the ContextClassLoaderLocal. * * @deprecated The dynaClasses Map will be removed in a subsequent release */ @Deprecated protected static HashMap dynaClasses = new HashMap() { @Override public void clear() { getDynaClassesMap().clear(); } @Override public boolean containsKey(Object key) { return getDynaClassesMap().containsKey(key); } @Override public boolean containsValue(Object value) { return getDynaClassesMap().containsValue(value); } @Override public Set> entrySet() { return getDynaClassesMap().entrySet(); } @Override public boolean equals(Object o) { return getDynaClassesMap().equals(o); } @Override public Object get(Object key) { return getDynaClassesMap().get(key); } @Override public int hashCode() { return getDynaClassesMap().hashCode(); } @Override public boolean isEmpty() { return getDynaClassesMap().isEmpty(); } @Override public Set keySet() { // extract the classes from the key to stay backwards compatible Set result = new HashSet(); for (CacheKey k : getClassesCache().keySet()) { result.add(k.beanClass); } return result; } @Override public Object put(Object key, Object value) { return getClassesCache().put( new CacheKey((Class) key, PropertyUtilsBean.getInstance()), (WrapDynaClass) value); } @Override public void putAll(Map m) { for (Map.Entry e : m.entrySet()) { put(e.getKey(), e.getValue()); } } @Override public Object remove(Object key) { return getDynaClassesMap().remove(key); } @Override public int size() { return getDynaClassesMap().size(); } @Override public Collection values() { return getDynaClassesMap().values(); } }; // ------------------------------------------------------ DynaClass Methods /** * Return the class of the underlying wrapped bean. * * @return the class of the underlying wrapped bean * @since 1.8.0 */ protected Class getBeanClass() { return beanClassRef.get(); } /** * Return the name of this DynaClass (analogous to the * getName() method of java.lang.ClassDynaClass implementation class to support * different dynamic classes, with different sets of properties. * * @return the name of the DynaClass */ public String getName() { return beanClassName; } /** * Return a property descriptor for the specified property, if it exists; * otherwise, return null. * * @param name Name of the dynamic property for which a descriptor * is requested * @return The descriptor for the specified property * * @exception IllegalArgumentException if no property name is specified */ public DynaProperty getDynaProperty(String name) { if (name == null) { throw new IllegalArgumentException ("No property name specified"); } return (propertiesMap.get(name)); } /** *

          Return an array of ProperyDescriptors for the properties * currently defined in this DynaClass. If no properties are defined, a * zero-length array will be returned.

          * *

          FIXME - Should we really be implementing * getBeanInfo() instead, which returns property descriptors * and a bunch of other stuff?

          * * @return the set of properties for this DynaClass */ public DynaProperty[] getDynaProperties() { return (properties); } /** *

          Instantiates a new standard JavaBean instance associated with * this DynaClass and return it wrapped in a new WrapDynaBean * instance. NOTE the JavaBean should have a * no argument constructor.

          * * NOTE - Most common use cases should not need to use * this method. It is usually better to create new * WrapDynaBean instances by calling its constructor. * For example:

          *
               *   Object javaBean = ...;
               *   DynaBean wrapper = new WrapDynaBean(javaBean);
               * 
          *

          * (This method is needed for some kinds of DynaBean framework.) *

          * * @return A new DynaBean instance * @exception IllegalAccessException if the Class or the appropriate * constructor is not accessible * @exception InstantiationException if this Class represents an abstract * class, an array class, a primitive type, or void; or if instantiation * fails for some other reason */ public DynaBean newInstance() throws IllegalAccessException, InstantiationException { return new WrapDynaBean(getBeanClass().newInstance()); } // --------------------------------------------------------- Public Methods /** * Return the PropertyDescriptor for the specified property name, if any; * otherwise return null. * * @param name Name of the property to be retrieved * @return The descriptor for the specified property */ public PropertyDescriptor getPropertyDescriptor(String name) { return (descriptorsMap.get(name)); } // --------------------------------------------------------- Static Methods /** * Clear our cache of WrapDynaClass instances. */ public static void clear() { getClassesCache().clear(); } /** * Create (if necessary) and return a new WrapDynaClass * instance for the specified bean class. * * @param beanClass Bean class for which a WrapDynaClass is requested * @return A new Wrap {@link DynaClass} */ public static WrapDynaClass createDynaClass(Class beanClass) { return createDynaClass(beanClass, null); } /** * Create (if necessary) and return a new {@code WrapDynaClass} instance * for the specified bean class using the given {@code PropertyUtilsBean} * instance for introspection. Using this method a specially configured * {@code PropertyUtilsBean} instance can be hooked into the introspection * mechanism of the managed bean. The argument is optional; if no * {@code PropertyUtilsBean} object is provided, the default instance is used. * @param beanClass Bean class for which a WrapDynaClass is requested * @param pu the optional {@code PropertyUtilsBean} to be used for introspection * @return A new Wrap {@link DynaClass} * @since 1.9 */ public static WrapDynaClass createDynaClass(Class beanClass, PropertyUtilsBean pu) { PropertyUtilsBean propUtils = (pu != null) ? pu : PropertyUtilsBean.getInstance(); CacheKey key = new CacheKey(beanClass, propUtils); WrapDynaClass dynaClass = getClassesCache().get(key); if (dynaClass == null) { dynaClass = new WrapDynaClass(beanClass, propUtils); getClassesCache().put(key, dynaClass); } return (dynaClass); } // ------------------------------------------------------ Protected Methods /** * Returns the {@code PropertyUtilsBean} instance associated with this class. This * bean is used for introspection. * * @return the associated {@code PropertyUtilsBean} instance * @since 1.9 */ protected PropertyUtilsBean getPropertyUtilsBean() { return propertyUtilsBean; } /** * Introspect our bean class to identify the supported properties. */ protected void introspect() { // Look up the property descriptors for this bean class Class beanClass = getBeanClass(); PropertyDescriptor[] regulars = getPropertyUtilsBean().getPropertyDescriptors(beanClass); if (regulars == null) { regulars = new PropertyDescriptor[0]; } Map mappeds = PropertyUtils.getMappedPropertyDescriptors(beanClass); if (mappeds == null) { mappeds = new HashMap(); } // Construct corresponding DynaProperty information properties = new DynaProperty[regulars.length + mappeds.size()]; for (int i = 0; i < regulars.length; i++) { descriptorsMap.put(regulars[i].getName(), regulars[i]); properties[i] = new DynaProperty(regulars[i].getName(), regulars[i].getPropertyType()); propertiesMap.put(properties[i].getName(), properties[i]); } int j = regulars.length; Iterator names = mappeds.keySet().iterator(); while (names.hasNext()) { String name = (String) names.next(); PropertyDescriptor descriptor = (PropertyDescriptor) mappeds.get(name); properties[j] = new DynaProperty(descriptor.getName(), Map.class); propertiesMap.put(properties[j].getName(), properties[j]); j++; } } /** * A class representing the combined key for the cache of {@code WrapDynaClass} * instances. A single key consists of a bean class and an instance of * {@code PropertyUtilsBean}. Instances are immutable. */ private static class CacheKey { /** The bean class. */ private final Class beanClass; /** The instance of PropertyUtilsBean. */ private final PropertyUtilsBean propUtils; /** * Creates a new instance of {@code CacheKey}. * * @param beanCls the bean class * @param pu the instance of {@code PropertyUtilsBean} */ public CacheKey(Class beanCls, PropertyUtilsBean pu) { beanClass = beanCls; propUtils = pu; } @Override public int hashCode() { int factor = 31; int result = 17; result = factor * beanClass.hashCode() + result; result = factor * propUtils.hashCode() + result; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof CacheKey)) { return false; } CacheKey c = (CacheKey) obj; return beanClass.equals(c.beanClass) && propUtils.equals(c.propUtils); } } } commons-beanutils-1.9.1-src/src/main/java/overview.html100644 0 0 2741 12262570613 20275 0ustar 0 0 Overview Documentation for COMMONS-BEANUTILS

          The Bean Introspection Utilities component of the Apache Commons subproject offers low-level utility classes that assist in getting and setting property values on Java classes that follow the naming design patterns outlined in the JavaBeans Specification, as well as mechanisms for dynamically defining and accessing bean properties.

          See the Package Description for the org.apache.commons.beanutils package for more information.

          commons-beanutils-1.9.1-src/src/media/logo.xcf100644 0 0 55430 12262570606 16442 0ustar 0 0 gimp xcf file,dBBK gimp-commentCreated with The GIMPgimp-image-grid(style solid) (fgcolor (color-rgba 0.000000 0.000000 0.000000 1.000000)) (bgcolor (color-rgba 1.000000 1.000000 1.000000 1.000000)) (xspacing 10.000000) (yspacing 10.000000) (spacing-unit inches) (xoffset 0.000000) (yoffset 0.000000) (offset-unit inches) Æ0l,c;ŽY TMÿ     -8gimp-text-layer(text "TM") (font "Sans") (font-size 8.000000) (font-size-unit pixels) (hinting yes) (antialias yes) (language "en-us") (base-direction ltr) (color (color-rgb 0.000000 0.000000 0.000000)) (justify left) (box-mode fixed) (box-width 12.000000) (box-height 11.000000) (box-unit pixels) ­ Á Ñ„„„#°öɰ¥-É>ÉöÈ8Âx¡ÐöÈ8€²8wÈöÈ8€PÛÈöÈ8€?ÈúÈ8€þȬ" Text Layer#2ÿ     p2Ù¬"õT`¬" £ M€€€CûqÆU7üUâÿÿþU6ýÆâÿÿþU8ýâÿÿþU9þªÿÿþU9þªÿÿþU9þªÿÿþU9þªÿÿþU9þªÿÿþU9þªÿÿþU9þªÿÿþUû8UU8þ8UUUþªÿÿúUqâÿÿýâq ýÿÿýÆ8 ýqÆÿÿýÆUþªÿÿüUâÿÿýâ÷ÿÆqUUâÿÿþªòâÿâqqâÿÿþªÿÿøqâÿ⪪âÿÿýâüªÿªýâÿÿþªþÿÿþ8þ8ÿÿþ8þªÿÿâþ8ý8âÿÿþªüÿÆþ8ÿÿþ8þÆÿÿûÆÿÿªþªÿÿýâýâÿÿþ8û8ÿÿUþâÿÿþªÿþ8ûªÿÿâþªÿÿþqþÿÿþªüÆÿÿþªÿÿþâÿÿþþªÿÿþªÿÿþUþÿÿûÿÿâUUþªÿÿþUûªÆUþªÿÿþªÿÿþUþ8ÿÿû8UÿÿþU ý8âÿÿþªÿÿþUÿøUªÿÿªúâÆâÿÿþªÿÿþUþÆÿÿøUªÿÿªøUÆâªÿÿþªÿÿþUþªÿÿøUªÿÿâûqâÿqþªÿÿþªÿÿþUþªÿÿû8ªÿÿú8âÿâþªÿÿþªÿÿþUþªÿÿþªÿÿþUúUÿÿâþªÿÿþªÿÿþUûªÿÿÆþªÿÿþª úU8ÿÿþþªÿÿþªÿÿþUûâÿÿqþUÿÿþ ý8ÿþÿÿþUþªÿÿþªÿÿþUûÿÿâþÿÿþÆüâqþâÿÿþUþªÿÿþªÿÿþUûqÿÿUþÆÿÿþªüââÿþÆýâÿÿþªÿÿþUûâÿþÿÿýÆ8ûqâÿþªÿÿþqýqâÿÿþ8þªÿÿþªûâÿªþUÿÿþ⪪ÿþUþqÿÿøâªÆÿÿUÿÿþâýÆÿÿõÆqqââUþUÿÿýâþÆÿÿûâ88ÿÿü8ªâÿÿýÆq ýÿÿýÆqþÿÿýâqþªÿÿUþ8UU ûUU8ý8U8€€€yþ8<ýâ<ýÆÿ;üqÿÿ:þUÿÿ:þÿÿý8UUUþ8ýUâÿÿU÷UªÿªÿÿýâqýUªÿÿüUqÆÿÿþªþÿ ÿüqªÿÿûª8âÿÿþqþqÿÿþÿÿþªÿü8qªÿÿ÷ªUÿÆqUqâÿÿþÿþUÿÿþªÿ þÿÿüâÿqþÆÿÿþÿþUÿÿþªÿ þUÿÿþUþUÿÿþÆÿþUÿÿþªÿ þUÿÿþªÿÿþUÿÿþªÿ þUÿÿþªÿÿþUÿÿþªÿ þUÿÿþªÿÿþUÿÿþªÿ þUÿÿþªÿÿþUÿÿþªÿ þUÿÿþªÿÿþUÿÿþªÿ þUÿÿþªÿÿþUÿÿþªÿ þUÿÿþªÿÿþUÿÿþªÿ þUÿÿþªÿÿþUÿÿþªÿ þUÿÿþªÿÿþUÿÿþªÿ þUÿÿþªÿÿþUÿÿþªÿ þUÿÿþªÿÿþþqÿÿþªÿþ8 þUÿÿþªÿÿþqýâÿÿþªÿþUþ8þUÿÿþªÿþªÿÿþUüqâUÿÿþþÆÿÿþÆúƪâþUÿÿþªþÿÿþ8ÿÿøÆªªÿÿqÿÿýâqþÿÿøUqâqÿâþÆÿÿþâþqÿÿþqþªÿÿüÿÿýªUþÿÿ÷ªªUÆÿÿøâ8UªÿÿýªUþqÿÿýÆ8üÿÆUýUâÿÿýâqþUUü8UUUþþ Uþ8ØØØûª8 þUþâÿÿþ8úUªÿÿþUÿÿþªü8ªâÿÿþ8ÿÿþû8Uqâÿÿúªÿÿâþ8ÿÿý8U ÿ'ÿ'ÿ'ÿ'ÿ'ÿþ8ÿ Uþþ8úqÆÿªÿý8Æÿÿûâqqªü8qÆÿÿþªÿóUÿÿUÆÿÿªªÿþªÿû8ÿÿqüªÿªþÿÿþªÿüªÿÿüÿÿþUÿÿþªÿÿýÿþUÿÿþªÿÿþqýÿþUÿÿþªÿþâÿÿþ8þªþUÿÿþªÿþqÿÿý þUÿÿþªÿþâÿÿýþUÿÿþªÿýÆÿÿýâqþUÿÿþªÿ þÿÿýâUþUÿÿþªÿ ý8ÆÿÿþªþUÿÿþªÿ ý8ÆÿÿþªþUÿÿþªÿþUýUâÿÿþ8þUÿÿþªÿþÿýâÿÿþªþUÿÿþªÿýÿUþ8ÿÿþªþUÿÿþªÿýÿÆÿþþUÿÿþªÿÿþ8þÿÿþ8þqÿÿþªÿÿýâûÿÿªþÆÿÿþþqÿÿþqÿðq88ÿÿªUÆÿÿ÷âªU8qÆÿÿüªq8úâUUâÿÿýÆqþU Uü8UUþ8UþV+¼2Drop-Shadow#2w     m/¼22,K,W¼2Jf"ô € € €Ë7ô1ù  ú/ï  -î "" ,ì )1550' +ì  -:EKKD7(+ì(9JYa`WG4" +ì .BWhsrgT>( +ì 0F^r~s^E- +ê/G`w…†zdJ0æ,D_w‡Š~hM4  üüþå )A\v‡Š€kP8$ ø  øø ä '?Zt†‹‚nU>,! á   à %=Ys†Œ…s\G7.*)'%!     ï $>Ö;6/&  !%*-011-(   #&(*+à $MZ`^VKCAà $* -AZsˆ’‘‡zpnt|€|qbSGA@DLV_dc[N>1)(-6>BB>97;à $?>;:>à $=@à $;Wq„‰iN3 *B]v‡Š‚|}ƒ‰Š€nXB1&  #$%$!$-9CIJGB>?Ò $;Wqƒ‰iN3 (?Zr‚ˆ…}y{ƒŠ‹‚pXA.!ó#,9FQVTNE>=à $;WqƒˆiN3 (>Wn}}vsv€Š†u]E0!#+8HWad_TG>;à $;VpƒˆjO4  )?Vjvxslio{ˆŽ‹|gN8'"%+6EWgrsj[K?:à #:Uo‚ˆkP7#,@Ufnng_]dsƒŽ…s\G4'!$'*-3?Pcu€udQD>Ã"8Sm€†lS;'"1BS`daXPOWgzŠ‘€mYG90+*+-/0139DVk~ŠŠm[LFà 5Nh{ƒ~mWA." )5DQXYRIA@IZn‰|l[ND?<;;:866:EXn‚‘ˆxfXRÄ0H`s|zmZG6,')09DLNKC921:J_t„†{nbXQMIEA;646ASi~’€qd\Ä )>Tfqqi[K>4005;@DB<3*$#+:Mbu‚ˆ‡‚ypg_XQJB:2-/8I^t„Œ‹ƒvjbÄ !3EVad`WLA:5468:95.%*;N`oy~}yskcZQG=3*$%-;Oct~€{rg^Ä&5CMRRMF?953210-' )9IXdknmic[RH=2(!-=N^imkd[SÅ %08>@>;73/,*'$   '3@JRWXVQKB9/&+9FOTTOHAÅ &*-.-*(%"   )29=?>;6/(  &/7;;83-é  ß #'((&#  !$%# Ì     ýú  ÷á   þü ûüûý  € € €~ý:û9ú 8ù ï ýøè &. „    +7A        *;KW  € #$# "#!  ""'8L_l,,+)$ "(,-,**+.26873+"%-463," (0451)!#1E\q:<<:5,#*5=BDB><=AFKONI@4'%2>HKH>1$*6BIJE;/&$*9OhEHKKG>1%+:IU\]YSONQW]cd`VG7)!-=MZ`\P?.!$2BR\^XKUo†•JPWZXOA2%'6H[jssne]Y[`hpusj[H5(#&2EYiqm`K7&'7K^koiZG7/1?Vqˆ—IS]ef^O>.$$-=Si{……}qe][`ju~€zkVA0')5I`s}zkU=*(9Oeu{udO<11>To‡•FRamqk\H5)'/AXq……ueYTXcq~†„wcK7++6JbxƒrZA, '9Ph{‚|kT>10;Qkƒ’CQcrzufP;-(/AYsˆ”’†s_OIKVhy†‰lS=/,6Jcz‡†v^C-&8Pj~†oW@1.8Mg€ŽARew€|mW@/(.?Wrˆ“‘‚lVD;=J]s„‹„rYA1-6Jc{‰ˆy`D-$7PjˆƒqX@0,6Jd}‹BTh{…‚r[B0(,)!/Faz‰ˆzbH6/6Ibz‰‰zaE-#5Ni‰„rY@0+4Hbz‰DSgz†…v_F1')8Oj‰„qW=)!.Eaz‰‰zbI6/6Ibz‰‰{bG/ $7Pk€Š…rYA0+4Hbz‰APdx…„w`G2(*9Pj‰„qW=)!.Eaz‰‰zbH6/5HbzŠ‹}eJ2# '9Rm‚‹†tZB1,4Hbz‰@Odx…†ybI5+,:Qj‰„qW=)!.Eaz‰‰zbI6.5GazŠŒ€iO8)&->Vp…Žˆv\D2-4HazŠCRg{ˆ‰|gN:/0* "/Fbz‰‰{cI6.4F_xŠŽ„pXB3/6F\uˆŠx_F4.5Gaz‹KXk‹ŒmU@55@UmŠ…sY?+!#1Hc|ŠŠ|dJ6.3C\v‰ŠydOA;@KXchdYI9-'(2@Q`hh_P>."!,;L[flkf^VPMMQUWSJ>0$$1AR;9;AGKLG@8215=GOSPH<0&!#*5BMSSLA3&*7DNTURLD>:9;=>;5,"#/=)'(+0442-($$'-4:<:5-$ (18<<80&$.6;<:61+(&'((&" ) "&'&# %((%  !%&%"à         ï  ú  ü ü  ô   û üûúþûþþþ‘ ¸ ¸ ¸„4þþ#ó ôã   â    á (./+# #(+)$ à ,8?A;0$ *5=@>6* à &6DNOH;,+:HSWTI9(Ý);KUWOA0"$4FXflhZG1 Ü ):JTUN@0!'9Ndt|xhQ9# Ú  $3AJKE8*&9Qi|†‚qY>' Ú!   (3;<7-!#7PjЇw]A)  Ú1/)  %+,(!  3MhŒŠy_C* þÛEB9,    0Ie}‹Šz`D* üøÕ[VJ:*   -Gc|Љz`D*  ÷ Ôpi[H6&  ,Eaz‰‰y`D+ ö Ç‚ziU@/#!'+,)# +Daz‰‰z`D+ #&(()('%! Õ†t]H6)!!'08>@;2& +D`z‰‰zaE,&-2455ö3.' Ç—ŒyaK8,%$)3?KTUOC3#+D`z‰‰zaE-!+5=@A?>=>?>:2' ǘx_H6*%'0=N]hjcS?++D`z‰‰zaF/ !,9ELMJFBABDDA9.! Æ–ŠtZC1&#'2CWjwzr`I2,Daz‰‰zaF0#!)7FSYXQIB?@CEC<1# Æ’…nS<* $1D[q€…}iP7",Daz‰‰zaG1%%/@R_eaWLB<<>A@:0# ÆŽ€hM5#-AZr„Š‚nT9$,Daz‰‰zaG2'(4FZinj_QD<9:;:5,  ÇŒ}dI0(>Wq„‹„qV;%,Daz‰‰zaG2')6I^ovsiZLA;875/' ÇŠ{bF-$9Sn‚‹…qW<%,Daz‰‰zaG2'(4H^p{|tgYMD=83,# ljzaE+ !6Pk€Š„qW<&,Daz‰‰zaF1%%0BXm{€~uj^SI@7-# ljz`D+ 4Oj‰„qW<&,Daz‰‰zaF0#!):Oduƒ€zpeZNB5( ƉzaD+ 3Ni‰„qW<&,Daz‰‰zaF. "0CViw€„ƒwmaRC2# ƉzaD+ 3Mi‰„qW<&,Daz‰‰zaE.'6HYhu~ƒ…ƒ}seTA/ €VŠ{bE, 3Ni‰„qW<&,Daz‰‰zaE-!,:IWdpz‚††vfR<)Š|dH. 4Ni‰„qW<&,Daz‰‰zaE.'1;FQ]jv‡‰ƒuaJ3  ŒhL3 !5Oi‰„qW<&,Eaz‰‰zaF/  '.39AJWet‰‰mU<& ŽƒmS:'$7Pk€‰„rX='-Eaz‰‰zbG1" &,12369426@PbqzylX@) Œ‹€mYF8/-4CXoŠ…t\B- $4Ke{‰‰{eM8-*0:CHF@:67?L[ipnbO9% ƒ†~p^M>527DXl}„€qZC0$!'6KcwƒƒwcL9.,1;EJJF?;;@JU_d`TC0 tyuj\L?637CSetzviVB0&#(6H]oyyo]I8-*/8AGIFB>>AGOTUPD5% _fe]RE91/3=JYejg\L<.%"'2BRaii`RA3)&)08>@@=;;=AEGD>3' ÆHNNJA8/)'+2=HQURJ?2' "+7CNTTMC6*" %+13443356773,$ Ç1674/(" &-5;><7/&!)29==91( "%&''(()('# Ô"#!#'('$!&((%!ö Õ    ÷ þ  ï ô ûøüöú …^/ × Text Layerÿ      - ×-&;v;‚×-B1G5E9쀀€ý8qªªüUý8Uªªýq8üq8ýqâÿÿýª ýqâÿÿüâ úUªÿÿUõ8âÿÿ8ªÿÿþUôUâÿÿ8qâÿÿþUüqªÿÿþUúUÿÿÆþÆÿÿþUþqÿÿþUþªÿÿþªüªªÿÿüUÆûUÿÿâþqÿÿþâþUÿÿþUþªÿÿþªþqÿÿùªÿÆ8ÿÿþþÿÿþUþ8ÿÿþÆ þâÿÿþUÿþªûâÿÿþÆÿÿþþÆÿÿþU þ8ÿÿþâÿþÆþqÿÿþ8úâÿÿUþ8ÿÿ þâÿÿþqÿþªþÆÿÿ þþªÿÿþÆ þÿÿþÆÿûªÿÿþÆÿþª þ8ÿÿÿûªUÿÿþªþÿÿþª ÿþ8ÿûªÿÿþªþUÿÿþª þâÿÿþUÿûªªÿÿþªþUÿÿþª þªÿÿþUÿûªªÿÿþâþUÿÿ þªÿÿþUÿûªªÿÿþUÿÿ þªÿÿþ8ÿûªªÿÿþUÿþU þªÿÿÿûªUÿÿþÆ þ8þâÿÿþ þªÿÿþÆÿûª8ÿÿþ8 ýUâþÿÿþÆ ÿþqÿþªþâÿÿýâ ü8ÿ8þ8ÿÿþ8 þÿÿþÿþªþqÿÿýªü8âÆþÆÿÿþ þqÿÿþÿþªþâÿÿýâ8ûqÿÿþÿÿþûâÿÿâÿþªþUÿÿýâUUúâÿÿUþUÿÿþÆúqÿÿâÿþªþUÿ ÿþUþUÿÿþªúUÿÿâþÿÿþªþUÿ ÿýâU ý8âÿÿôâqUÆÿÿÆþqÿÿþýÆÿÿý ýqâÿÿýÆ8üUqÆÿÿýâªýUªªýUý8qªªýU ª€€€ù8qªª8ùUªª8 ý8ùUªªqùUª8ÆÿÿýÆýqâÿÿýÆúqÆÿÿýqâÿÿþýÿÿþÿÿþÆý8âÿÿþâü8ÆÿÿýÆÿÿþqþqÿÿúâUUÿÿùqUÿÿªUUýâÿÿþqüƪÆÿÿöUâÿÆqUUÆÿÿùªÿâUUþ8þÿÿúâUÿªýâÿÿþâþÆÿÿûªÿþqÿÿûªÿq þÿÿþªþqÿÿþ8þUÿÿþUþâÿÿþU þ8ÿÿþÆþ8ÿÿþUþUÿÿþqþÿÿþq ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU þÿÿþâÿþÆþqÿÿþUþqÿÿþ þqÿÿþUþqÿÿþþÆÿÿþÆþÆÿÿýâøU8qÆÿÿ÷ªU88qÆÿÿ÷âU8UâÿÿüÆUüUâÿÿóâUUª8qª ªûqqª ªýq8ª ª ªü8ª€€€ªýqüUªªýUü88ýqªªþUÿþ ý8Æÿÿýª8 õ8âÿÿUÿÿýâUÿþ ùÆÿÿÆUýUÆÿÿþªüUªâÿÿûU8âÿÿûUªÿÿþú8âÿÿªþUÿÿýâªÿUøÿâUUâÿÿþâþUÿÿþúâÿÿªþUÿÿýâþªÿÿûâÿªþÆÿÿþUþÆÿÿþâþâÿÿþþÿÿþªþUÿÿþUþ8ÿÿþªþÿÿþqÿÿþª þâÿÿþ8þUÿÿþqþâÿÿþâþUÿÿþUþâÿÿþU þÿÿþÆþUÿÿþUþªÿÿþUÿÿþUþUÿÿþ þ8ÿÿþþUÿÿþUþªÿÿþUÿÿþUþªÿÿ þâÿÿþUþUÿÿþUþªÿÿþUÿÿþUþÆÿÿ þªÿÿþþUÿÿþUþªÿÿþUÿÿþUÿ þÿÿþªþUÿÿþUþªÿÿþUÿÿþUÿ þUÿÿþªþUÿÿþUþªÿÿþUÿÿþUÿþU þUÿÿþªþUÿÿþUþªÿÿþUÿÿþUÿþU þUÿÿþþUÿÿþUþªÿÿþUÿÿþUþªÿÿþª þUÿÿþUþUÿÿþUþªÿÿþUÿÿþUþÿÿþâ þUÿÿþþUÿÿþUþªÿÿþUÿÿþUþ8ÿÿþ þªÿÿþÆþUÿÿþUþªÿÿþUÿÿþUþâÿÿþ þÆÿÿþqþUÿÿþUþªÿÿþUÿÿþUþqÿÿþâ þÿÿþâþUÿÿþUþªÿÿþUÿÿþUþÆÿÿþqþÿÿþ8þUÿÿþUþªÿÿþUÿÿþUýâÿÿþþÿÿþUþUÿÿþUþªÿÿþUÿÿþqýâÿÿýâúâÿÿUþqÿÿþUþâÿÿûÆÿÿþÆýªÿÿõ88ÿÿâUþâÿÿþÆþUÿÿüqâÿÿûÆqUý8Æÿÿýâqü8qâÿÿ÷âUUªÿÿ ªþ8ýUªªýq8 þqª ªþ8ªªVVV ýUªªúU óÿÿ⪪ÆÿÿªÆÿûÆÿâ8ý8Æÿÿûªÿÿ8üâÿÿû8ÿÿÆü8ÿÿûÿÿªýªÿûªÿÿâýUÿþªÿÿþqþÿþqÿÿþqþ8þÿÿýÆ8þÿÿýÆ þªÿÿý þÿÿýâq ý8âÿÿýâ þqÿÿýâU ýÿÿýâ ýªÿÿþýªqþUÿÿþ⪠þÿÿýªÿþÿÿüªÿqÿþÆûªÿâþÿÿþqûªÿÿªûÿÿªþªÿÿýÆ8öÿÿªÆqøªÆªªÿÿ⪪ÿýâqªþ8ý8ø8UªªUk 5á$ Drop-ShadowD       <6á$=:4," &Å +7BJOTX\_^WI7%   -:CJOSWZ]]ZQE5% #1@LÄ &8HTZ\\]bkw€€u_D*  )bŒeD( ;e‘±¹§Q*=eŠ ƒ]9 &Bh‘³Á¸šoD$*Ky©Ì0V}–”zT0 )Lt”¡”rI'.T€£¯wK'*Mz¦Ãȳ‹\3 >m¡È Bm“£”oD"  3QlxoV7 >j˜µµ˜i<  8d•½ÏÅ¢rC  6f›Ä+S¤ª‘d8 0BJE5"'M~ªÀ·‘_2Ü)Q„³ÏÏ´…R) 3c™Â5b‘¯­\0è  $" /[Ž¸È·ŒX,Ý Cu¨ËÔ¿“^1 2b™Â ?o·¯ŠX,é   6e™Á̸‹V*Ý8ižÇÖÆh8 2b™Á !Gx¦½²ŠW+ê ;l¡ÇѺŒW+Ý1_•ÁÕÊ£n<2b™Á $L­Â¶ŽZ-ï >p¤ÊÔ¾Z-Þ,Y½Óʤp>2b™Á%N‚°Ç¼•a3î >o¤Ë××a2Þ*U‹ºÑÈ¢n<2b™Á %M±Êßl< ì ;k ÉØÉ j:Ý)TЏÎÃh8 2b™Á "I|­Ëʬ}K&ë 6c˜ÄØÎªvD Ü+V‹·Ê¼“_1 2b™Á Bs¦ÉÑ»‘a7 é 0YŒ»ÔÒ´ƒP(Û.[·Ä±†S) 2b™Á8g›ÃÔɨ{O- é !,/*)K|­ÍÓ¾“`3€5c”·¼¢uE! 2b™Á-WŠ·ÑÓ¾špJ. )7@?2" =išÀÐÅ¢rC!  @nš³¯Ž`6 2b™Â !Et¤ÇÖÏ·”pQ;-%#%,7EPQF2-S¬ÆÈ°†X1 *NzªšuJ&3c™Â3[гÎÖÍ·›gVLHJQZabXC+ m ÆÂ*Kr˜·ÊÑÏÆ»°¦ž˜…s[@' -LoŽ¢¤•|aI:35>Ocu|t]@% )Jw¥ÆÃ .Mp‘«½ÅÇĽ´ªw^C*  -Ig€†veWPPV_hleT<% !8X~¤¾× -Gd~“¢ª¬©¡”„oX?)  )?Vjvyume`]]î[SF4!  )A\z•¦é &:Napz~|uiYG4" Þ  1AOY]][WSNH@5( (<82+# +7AIMî !##  í   ö !$&ñ  ð ÷  ÷þþþ?   @þ þð ó Ç      !! €)   ! )&(4>DE@6(  ,8AFFA6) !(*% ,8AFD=2# PI:+%*8HYgqtoaM6#,=N^ksuoaM5  (6EOOE4'%-m¡ÆÑ½“`4  #5Y‡±Ëʰ…W2 3Y‡²ÌÍ´‹]6Ķ–nI, 6V~¤¾ÆºœuO1 6U}£½Ä¶—pL2%$.DeŒ®ÂÁ¬‰b?&&Ad‹®ÃıhEª¡‹mO5!(>Zy”§¬¤sU:&)>Zx”¦ª¡‹nR<0/9Lg„›©¨šcF-.Geƒœ©ªž†iL€zm[F1!'9Nbs~|q_K7&'9Nbs}€zm[I90/7EWiw~vgT?,,@Viw€ykXDNLF<1$)5@HMOMG?4')5@HMNLF=3*%$)1;DJNNJC9-  -:DJNNKE;0&%# !$&&Ã$  !$&&%# #%&&%" "%&&%#  ó  õ  ô  ü þþþþþ>   Aøþüí  ù  ù á  " ì   Ý   "$0;CGE>2# Ä #+17;=><7/&  $+.+"%1$ .Hf…Ÿ¯¯ž„mceo|‹šªµ¶acgn{§ºÀ±Ža6 %A`y„}kTA516CXr¡§„a?$1Mp–¶Êʸ›€nfejt„›²ÁOHEHTl®ÃÁ¤wG"  <`“yZ='&9Uw™°¶¦†^9)Di”»ÓÖã‚fTJHN_z»6)$&1Jp›½Ç³ˆU+ 1Wœ¢ŽjD' 7Z„©¿¾¦~R.4Z‰¶ÒÖÂuR:,'+;Y‚¬ 3ZŠµÈ¼•a3 #Fr™®¦…Y1 !@k˜¼É½šk? (M~¯ÎÒºb<#"@l&L®Èžj:1ZŠ®¸¤yJ$,T…±Ì˰‚Q*"ExªÊͱƒR+  1^‘  FxªÇÅ£p??m¼¾ o? à Bs¥ÈÒ¿•b5 Cu¨ÈÉ«zH" +W‹  Cv¨ÇƦsA &K}­ÇÁi8Ã5c˜ÂÔÉ£p? Cu§ÇȨvD )T‰  Bu§ÇƦtB",U‰·ÎÜf6Ã,WŒºÓέzG$!Cu§ÇǧuB (R‡  Bu§ÇǧtC#0[‘¾ÓÆžg6Ä&Nƒ´Ñв€L'!Cu§ÇǧuB (R‡  Bu§ÇǧtC#2^•ÂÖÊ¢l:Ä "H|¯Îг‚N("Cu§ÇǧuB (R‡  Bu§ÇǧuC#1^”Â×ͨs@ Ä Ex«Ìα€L'!Cu§ÇǧuB (R‡  Bu§ÇǧuC#/Y¾×Ѱ}I" à DwªÉʬzH$!Cu§ÇǧuB (R‡  Bu§ÇǧuC"*R‡·ÔÔ¸ˆS)à FyªÇÄ¢p@ Cu§ÇǧuB (R‡  Bu§ÇǧuC!$Hz¬ÎÖÁ•a3à $K~¬Ã»–c6 Bu§ÇǧuB (R‡  Bu§ÇǧuB 43:H\p|yfJ-  1X‡²Ë˰†X3 "@kš*'@cŠ­ÁÁ­Šb@& &@]x‹‘Š{j[QOS\eki[E- "=b‹®Â­Šc@'/Nuœ3!/Gd‚›¨¨š‚dG. "7Odsywpha^]]\WK:(  (Cc‚œ©©›‚dG/#7Sr0!-@Uhw~~vhU@-+=94.& *7CJNNJC:.!%2>G "%&&%"    á"%&&%"  $ ø ð ù ó  þüþþ?¤¤¤ þ üú  øú í  ù- ë &-13321/,)! ùU>' ÷)8BGHHõJKNNI<) á‚eE( 1FUZWRNMRZeljX< €Ä©Œf?  0LdmgXI@?GVj{~kI'À«„W/&Fh}|hL6)'0B\upN*ɾœm> 4[€„d@%+EaqhK)ÇÈ­~K$ ?k‘žf=  /I[XB%ÁÌ·ŠU* !Etœª™sI( 3CE5 ¼Ì½’\. EtŸ´ªŠc@'".0& á¹ÍÀ–`0 >lš·º¦†eH1!á·ÌÁ—a12\НÀ½ªsXA.!â¶ÌÁ˜b2%Gr›¸Äµ ‡lS=+ á¶ÌÁ˜b2 0S{ž¸ÅÈÀ°šfL5" €̶ÌÁ˜b2 5Ux˜±ÂÊȽ«“x[?' ¶ÌÁ™b24PnŒ¦ºÆÊŸ¢†eD(¶ÌÁ™b2 .D^z•¬½ÈÉÀ¬Œf@"¶ÌÁ™b2 %7Mg›²ÃÊĬ‡[3¶ÌÁ™b2 )-$$,=Xuˆ‡pM+ºÆ¾¤}U4$@b|„yeQB;;BPbquiP3 ¤¬§”xX;$3Mcli_TLHINV^`YH2|}sbL5""3AHIGDCCEHJJD9*âMOMH@4&"&()+-/121.' &æ$!   è  þ)p8 ,d Backgroundÿ     Z(,dZHZô[[ ,dZ|ZˆZ”Z Z¬Z¸ZÄZÐZÜZèÿÿÿÿÿÿÿÿÿÿÿÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ0ÿ0ÿ0ÿ–2K% commons-beanutils-1.9.1-src/src/site/resources/download_beanutils.cgi100644 0 0 240 12262570613 23163 0ustar 0 0 #!/bin/sh # Just call the standard mirrors.cgi script. It will use download.html # as the input template. exec /www/www.apache.org/dyn/mirrors/mirrors.cgi $*commons-beanutils-1.9.1-src/src/site/resources/images/logo.png100644 0 0 33230 12262570612 21601 0ustar 0 0 ‰PNG  IHDR,d< ÀsRGB®ÎébKGDÿÿÿ ½§“ pHYs  šœtIMEÛ $$¬ì^!iTXtCommentCreated with The GIMPm°— IDATxÚí½yx”E¶?þé$NzŸ‹&„¤q¹àðÈ*„,ˆl*›aMÌÃêUQ‚„eœ‘¹w®0#x¹‚²;²VuXD$ !‚  bÒ I€²vºÓ]¿?üúÖ[o½ÝêÀ{žç}IíuêS§NsÊÂc0É$“Lú  sL2É$°L2É$“LÀ2É$“LÀ2É$“L2Ë$“L2É,“L2É,“L2É$°L2É$“LÀ2É$“LÀ2É$“L2Ë$“L2É,“L2É,“L2ɤ_…Ü®‚UA ,Ëm¯ãvÔÓ64¤î›Éûs·÷—šÏŸk.o×\üslV”——‡œœäææòßÙív$%%!)) v»O–üoCê(,,ĶmÛ4¿§:’’’x¹bÙ ©Çáp ;;ݺuãåÉmÈÍÍåý´ÛíHKKSÖ-×›¼¼<58¯¯1ÉÎÎÆ¼yó”‹]®3)) iii|>cÊ:rrr4c-æml{åòŶ‰<“––¦ä•†Ô“››‹mÛ¶aĈHLLÔäw8ضm›†_ÓÒÒ”õ6¤N*SìÍ1ù믿ŽÌÌÌFóè]Mì&)++‹ÙívÀç—’’Â.\¸Àêêê˜Ûíf‡y½^æõzýÖ1oÞ¼€ê°Ûí,##ƒ}÷ÝwÌår±úúú€ëÙºu+KKKãemÞ¼™¹\.æv»Y}}=;zô(KJJ2¬;!!?žÕÕÕñº©^í÷•WEEEElÞ¼yšö¸ÝnM{333}Ö9qâDæt:uóQXXȦL™âsœòB¹¹¹>ÇQæ™Ï>ûLÓ/s™““æL™¢éû¦M›˜Ëåb.—‹ýðÃlòäɆuÆÆÆ² 60§Ó©ã!_4uêT ¦¦¦²ÔÔT–˜˜¨éýŸÚh¿Lú‰ X¹¹¹¦˜4iûôÓOYuu5«¬¬dçÎcÆ Ó1Ä{ï½Çª««™ÓéôËìÙÙÙ~ë˜5k‹ÕÕ³nÝ:VSSc¸¨ŠŠŠXVV–¤Äoýúõ¬ªªŠUWW³ŒŒŒ€X||<»q㫪ªbN§“9r$  ¥…"æ•Ûœ››Ë¦Nj¸Ø«ªªXUUûöÛo5‹Ä×7kÖ,VQQÁÇ)333 |Xzzº&/-:#***Ò´=11‘mܸ‘ÕÔÔ°ªª*VQQÁÖ®]Ëâããuu 6ŒóŒ г³³Ùˆ# Çzݺu¬²²’>|XÉ+ªoíÚµ¬²²’ÕÖÖ2—Ëå“O©_v»9r„ÕÖÖr­¨¨`‡Òõ«²²’UUU<~&Ý`eggkïüù󬪪Š]¿~]½z•]¾|™•——³²²2§c†U«V±ëׯ³êêjÃÉÊÊÊÒäÙ°a«¬¬TÖQZZʬ«gèСìÆºz¼^/›:u*KKK3¬•+W²‚‚ÖµkW('NdëÖ­ck×®eãÇWæ›>}:+//gk×®å¿KMMe6l`ëÖ­ckÖ¬a¯¾ú*‹‰‰1Ì{ãÆ VSS£­¤¤$–––fXååålåÊ•¼Ü„„6{öl^'õCþ¾øâ võêU¾¹”ºaÃöÞ{ï±Õ«W+ÇVÌ[YYÉœN§á¢“7·””VUUÅnܸÁþùϲ+W®hærùò庺bbbØÙ³g•€Nóh4—+V¬àeÆÆÆ²×^{M3ª¹hÑ¢+--eÿüç?9ÿ¨@K¬ó³Ï>Ó¬ƒ+W®h>±žòòrvåÊvíÚ5VUUeX¾I7 X"XÙívV]]Í®_¿Î®\¹ÂÊÊÊØ¥K—XII ÿ¦OŸ®d†’’võêUåd‰uÐyíÚ5V^^®+Ÿ>‡ÃÁ’““uu 4ˆ]¹r…UTTèÝãñ0·ÛÍæÌ™£Ë÷Ì3Ï0¬K—.ìïÿ;»rå _\¥¥¥Ìáp°œœ]¾èèh¶hÑ"˜_ý5Ú+W®°K—.±ÂÂBvôèQ­ËûÃ?°ÒÒRvýúuV[[«YÇÃ\.KHHÐÕ;pà@€½üòËìÔ©SìêÕ«¼½Tçÿ÷ëò½ð |Üf͚ťïââböã?²… *ó²òòrVYY©\tEEE:°ºqãGÕ\³%K–(A«  €:I>ô¹\.–’’¢ä7šÓãdzòòrvùòeVVVÆŠ‹‹ÙÅ‹YçÎuù,XÀçSYÒÊÍÍÕlܼ_—.]b¥¥¥¬¬¬Œ•——³òòr¶gÏž¾°°±ÒÒRvíÚ5VSScJYPðŒ3f4Dé=`ÀþÿãÇÃf³¡®®n·ç'[‰  #88±±±X¶l™¦œªª*<ðÀhݺ5, ‚‚‚‹Å¢«#!!3fÌ@]]\.—²Ê›œœŒÍ›7£ªªŠçÿöÛoñÐCá‘Gá TúþÀF\\Þ~ûmMÏŸ?~ýúaÅŠhÑ¢cðz½ðx<ðx<¨¯¯GDD*++QPP éÛÞ½{1pà@üíoCÓ¦Myúúúzx<x½^DDDÀëõâóÏ?×äMLLDóæÍù˜ÐG7N^¯Mš4Á®]»4í½pá233ñ / iÓ¦¯×Ëëôx<èÔ©²³³5ãSPP€óçÏcÑ¢E=z4ï£ÛíÖämÕªŽ9‚ÒÒRž÷Ò¥KxöÙg5ó!Î%´kׇCsñŠºº:Ô××s¥¿8—AAAhÓ¦ nܸ“'Oò¼•••(,,Ä3Ï<£QˆÓ\RÛ屩ªªÂœ9s0aÂ4mÚ”Ï;õÍëõ¢U«VºËǃ¾}ûjx488˜×™••…¼¼<@||<žyæÞ/“Þ¯ØØX|ýõ×øöÛo1qâDÎË!!!št¦þÙa1‚ÿÿüs^†Ûí†×ëåc¢›I“&¡W¯^|ÅÍ588V« ºº¾üòK͘Ô××óºcš›Àüü|M:Æ/›úŠáÇs07!£y5©‘€%3_rr²†QU`E“´~ýzÄÄÄð¼³gÏÆ}÷ÝÇ™‡!77—ïXDýúõCmm-gÌ   X­VMô………¡{÷ ´´K—.åÌ'2¹ÑµuTT—Ѝ}$ „††",, èÞ½»2¯Ëåâã#/ÌððpDDDà‰'žÐå=pà\.—tÄëoU{ï¿ÿ~$Gí ÍfãuÒõ¾œ·®®NVâ8S^•™Çþýû5íÁcþüùš´ÔŒ‰ÅbÑ,hy.ÃÂÂ0dÈ]3gÎTnvFæ‘‘‘iŠ@\îŸ Ýn·fÃû'RII þö·¿ñ1 ^¡‚ú9räH€ÕjEHHˆ)QÝ.À’Åå:(Á*44”OMÖC=„³gÏ"??ß|ó   ㉠ÞyçM]ºtQ."±§EÆ:t¨raÉ»¥x12ú#攥ºððpÎèª|âP+Zˆ”_Eò‘LW:–ø2R ÕªËGGGZÔW8ÉKù½^/²³³5´oßN§“ó ‰<—4Ÿ6›ÛEÉ’ÏÅ‹5Ò=I.F$JÇÔ?šGÕ¸RÿE RðY³faÕªU|Îis¡vQß:Ä7s«ÕÊAË®[XEEEÉ'..Žï:´›HY­V.‚˜ÕjÅÃ?Ì1*Ý- vìØ¡©·yóæ\Dñ]®C\ÈV«Ust%:}ú4êêêø'–/&§¿‹ HŒF?«òü©ˆt1âKl‹Š±E}•ª>«ÕªÌ+‚¢8ÎbÞÃöŠú.ƶoß®K׬Y3Íq‰ÆTÖßÐ\†„„ {÷îˆÕ•õÅ_ð¹$©FUsùKݪ’mÞøñãqøðaî Ó¥K—ð?ÿó?¸pá·%£c¢É“·°RSSu¿Û´i“FÑÚPå0)eE†¥8K"}õÕW:…nc$bðÆê”Lj2—þ¼ þUæ“n°ÅK¥Ö­[ãÍ7ßÄÁƒñôÓO+AkÑ¢EJX´n°T·4gΜÁ—_~ÉuB  ª&]ù«¯¾ÒÔ(£Ë6]ä¦bp¸n=©6¹òòr”••iæ1ãlÓÕ±cG4oÞü«‘#Gbþüù³ ù&¼U«VX¸p!æÎ«Ë¿wï^˘y<¼E€•””¤4˜6mŠ‹‹u޽þ$«‘#GbëÖ­:ÆU1ùW_}…3gÎh”åþv!• èÄêË Ã¤[C‰‰‰JžÙ¼ysÀFóÙ¯_?å\þ¶L¹¹¹š>ÈÇæM›âž{îAJJ ž{î9MÞ²²2î'+ûEšRÖMê°222”;æœ9sPXX¨ñ}3b¼¼<Œ1IIIˆ×¹t$&&*:¤¹¾öw…-»½ð <‚h´iÖí=&©Œ*>¬qçñZ‡CcÓÕ¢E Œ3FgäêËðóvÒöíÛu§ 2á!Ð"i+==]—_öUôÇÛ&`È|“'OV¨Q£——§-q·ÈÊÊB·nÝàp8°qãFnô';¯®_¿^WÇ–-[PRR¢ñéòµ‰N·111xã7~ê¬àšA¶_&hÝ>Àš4iâããu›Ü† ”öpþæ,X œË_rÊÊÊÒ$‹ž¢£|ëÖ­uz8ÙWÑ”®n°D=Ïÿþïÿ*Ó”••!55:uÂÿøGlݺ•S§NÅ<€ßÿþ÷€7rA•ÅyË–-±fÍåñS”ÈŒv"1ªDll,víÚ¥±.³ý¹c4–îv¦£1 ºuëtÑ3Þyçk6,•”UTT¤¬eË–¡S§N¼lq.oX2— .ÄÅ‹uR’Ès¡¡¡¸zõªRM¡ºT2é&%¬   ¤¥¥aõêÕ†é.]º„¥K—bìØ±øÝï~‡Ñ£GãwÞá²nÝ:$''kâ‰Æs$â§¥¥aÅŠš²Ïœ9ƒ)S¦è|ÅÝ9;;›cll,öìÙƒÈÈHîl+Æ%­ëU:¯@AKö ½[c¯¬¬¬Á:†*¯ØÞ†Ryy¹OžyðÁ±ÿ~]¬©±cÇ¢¨¨H'e‹±¦DŸÐÕ«WcàÀg{šOr†·X,(..nt_Ž;æ·*+..Æý×qßFy&ipñâÅ<ÏÀñüóÏì½aRuX´[¤¦¦*ƒäù¢˜˜¬\¹ýû÷×ĤR¹öÐ䦥¥áý÷ß×Xþøc“Ë_VV–.ï™3g 륟U‘6mÚ¤I¹­Fy:ÄUÇ3úYÿCã$·QŽNðÐCaÏž=8p fŒúôéƒ7ß|999|:zô(—Êìv;Þ{ï=$''sPZâæc±X”m dlTáp¨* ’ÿÿá‡"99¹¹¹:I‹1†×_ï¾û.`È!Xºt©ÆÛÔ©ˆC,@€Ü Ün7jkkqá¼òÊ+šðÀ*zñÅñâ‹/"&&FÃÈbL"ÙŸP¬§ººK–,ÁÚµkQVVæ³®ÄÄDÌž=;wÖ¤#&§ØG6› ï¿ÿ>Š‹‹±}ûv¥£.ð“5uÇŽ1hÐ <ñÄøÍo~›Í†'N //Û¶m3Ì O?ý4 „ÿøÿ@¯^½†ãÇãØ±c>óFEE¡oß¾ˆG«V­Ðºukœ:u ùùùؾ}»¡„Õ¾}{tî܉‰‰5j"""`µZ±sçN^§QÞ¨¨(ôë׉‰‰èÑ£Z·nÐÐЀò¶oß Àƒ>ˆ=zà‘Gáqž(6˜ÓéDMM Ž=Š™3gâôéÓ>çÒn·ãµ×^Czzº&b}}=—–#""†S§NáØ±ci^Õ¿þýûkƦ¬¬Œ© ÈE]ÓÀ‘ššŠßüæ7 CHH~ûÛߢ¨¨ÑÑÑðx<سgß ãããùL&6v»&LÀK/½„êêj8Nx<X­V®œ ÓÄÈ2é&‹@Ëår¡¶¶555øî»ïpüøq8p€Rtt4:vìˆhvqG£KŠ"=ÕU__Ï•ŒëNœ8‚‚œ>}Zs•’’‚„„ÄÆÆre.5( íÈTßèÑ£5}cP‰»#SÓÓÓѳgOØl6,^¼˜É›€)S¦Àf³aÉ’% Ê›˜˜ˆîÝ»cÙ²ešñ‘ó‰Nâ!!!X³f """Ê-®E+s9/›ƒƒƒ1aÂôìÙ“çã{ù«÷µ×^C=4R,E÷¨««ãsùã?âÔ©S8xð &nZBB¿Eù€¤i:Rð½ÐÐP,\¸Pcˆ,:EMxx8 °`ÁMÿTñ÷‰w_}õUôìÙ“ƒÊ±cÇfÍš¡¦¦.— 'OžÄåË—qúôi”––"((v» 6lêëëùfêv»@v‰ÆÍ 7s“€%/-ÑŽDŒ°)îƒÊ©ÀJÜQäzh‚åÿbL#š`R^Š _¼':[ƒ8VWW£¦¦uuu|“!`DDo3ÕGàHÒ åõz½FXXÏ+îž²$YSS£ËKLLõR»½^¯fÓ ÃCZÌÔ^1-JZ0TåÀóŠuÒØŠy©¯ºZÌ+×+¶™@‹æRÜPT¡V@hNÅ›71–ñ Í%õÚHý:屡1¥ R”€‚‚‚`³Ùø1Œ²?;(9vÕ£2kPEª”%;Ì *æiqË/äÈR |»IàJÌ+^k«Bè¨ò†††êêU™_ˆq׃ƒƒ5Áe©SwÓbW\|¾‚1ÕKu«êUÍ¥ÕjUzH¨"ÖªæR®G._Õ?qlTýÁ‡6*Sú(}HHˆ¦ª9£:T‘]Ícà->ªtZrüqÙ¦F X&Þ<‰åË×àFÑ=‚ ÊeRd)D¯+‡ó«â2‰ýWIxFyÅzEiK>2Ëö;ò£zÊýUÅ—Û+.ì@òªÂ@Ë Q<¶ËVââ\Êó© _º¹@Û¨Ò}2b^£*3yœý¿4é–(eˆG+úWÞYÄêt,_›Ëamĸì²dæËÆEf4#‹kyÉ‹EÎïKZTéêŒòŠ˜bÿü…Û‘Û*ÆÍôU^”þòÙÉmW•©’š}9¬ËGÂ@ûgt¤ô5ª“/Óùwª>™@õ3–Ѥ-¼›Žàoçjh]FíöœPµø’W–òŒÜ(¯ÑX:?G_å©Úào>o†ìÏü‹?^•U·b-˜€u‹ÈˆÜjòÞøV•Hù?WÞFMðMÖ§¬ÆÖÝØñoL|ùÛÝ¿†ž~Žõ`–I&™dÒMÒ°aÃüäº×¢E 4iÒÓ¦MÃK/½„ƒâÞ{ïÅ?þñüáPºGiÔKæpšd’I·“vïÞÝ»wÃb±`÷îÝØ¸q#ª««¹!5¬Zµ uuu~Ë2Ë$“î r8øýï‘#G"//ÏÐ5Ðxr·3^þ“O>‰œœäåå¡mÛ¶ 3ëndØùóç£[·nÈÎÎV^¹›Z€;—üqdeeaÛ¶mèÖ­rrr”æ3"/8lÛ¶ #GŽ„ÅbÁÈ‘#uÑ€}Ý,ß ýçþ'ÆŒƒñãÇ”>Äœâ}"GêmÛ¶iÂÝm‘H ¹u3é_äpGóçÏÇÆuæ"ùùùx÷Ýw‘——§t—ãÍÝ®·†Šÿ÷ǽ÷ÞkÖݲ£:e\.2‚”™U¶#2AëÎ Õc1111º¸sdýŸ’’‚¤¤$e” ÿ$€‹®j·‚w, zõêxzó–ðÎ x'2Þºuë0tèPkŠ×þΦ#FðP9±±±8pàš7o®ñ%w òdÈÏÏG=4å\»vMçb'ºýR¼cJXw1Æ‹ÄÄD `Q$•Ÿ¡¸;š õ림¼<$%%Ä[·nENN~üñG <uuu¨««Ó8è“¿*ð“ÿ£wjkk5áuÈ÷Svú¹%t°î Ð’‰‹ôXb˜hóŽ r89r$ •ó¬2 NHHàA,)t’ÎF>ªx€BQ¤«ÕÊÓªÜÌLÀ2©A`¥º½q¹\¨©©á€Eákä÷üD_L“~]4räHº©æN0@ããË÷—̤l6›NÒú%´I&`ÝÁDÁìÜn7ƒ"†v‘_ë6Aë×EóçÏGnn®„äK_äËwÑW^ñA r§ðN¿$ߘ€u“øæ1WHHˆ.ìŠ V¿>Ú¶m¦NÊÿ¯z¿QCþ½ß‹ÔbØ #Ðy‡ÊÃI&_`#¾”¤ù¿|$0ë×A¤·RÍ£h%ßøŠü ƒIIâ{Žþnúä8c¿Ãc°îЯ   ÃÃ?Œ'žxBc£#ƒV –——ÇíÀc1b„NßÒÐ2É=„ÊËTE õ‡ƒß´‰íÝPüÕ¡zY‡Ò¦¥¥éÚCeËá„€Ÿl¦•yèmM‘²³³uñ퇮“žÄ£bHHŽ?Ž.]ºhô— ‰rª é¤ Ã#ŽMRRìv»†?ä[ÎFoŒÌ¤yòz½Ìãñ°ÔÔT€óæÍcyyyìÓO?eééé,**Jów,66–Í™3‡ÕÕÕ1—ËÅ\.s»Ý¬¾¾žy<æõz™×ëÕÕYTTĦNª+¾¤¤$väÈæv»ùW__¯)W¦¬¬,Ö­[7ŸenÞ¼YW¦ÇãQ–™ÍFŒÁ°´´4žîâÅ‹lòäɺòív;›;w.s»Ý|Ä:¶nÝÊÒÒÒ”m£a999ìôéÓì‡~`—/_fUUUìÈ‘#ʾ‰c9wî\ÞWqþ}ñ–/2ë!`eee±>ø€EFFúeþØ×„üßIDATØXöí·ß²êêjV[[ËœN'_H2sP%%%±yóæ±-[¶°-[¶°É“'3»Ý®)7%%…ÕÔÔð2 Eà***b-[¶äŒž™™É.^¼ÈÓœ9s4åfddðòÄv^¼x‘eff*A%55•¹\.öüC×Fù›={6«©©Ñ´[òÌÌL]žÚÚZ]„úúz¥¤¤æQHQQ»pá;wî;{ö,ûúë¯Ù… ˜Ãá`ûöíco¿ý6KHHÐåKIIaUUU¬¢¢‚UTT°ÊÊJn"¸Êù¾üòKvôèQöÉ'Ÿ(kݺu<í”)S4óµiÓ&˜Ôš+y\Œ6/#2„w0•––böìÙ¸|ù2"##Ñ®];ãìÙ³(--Õ¤-..FïÞ½ñÑG¡eË–ý%È1vûöíHKKÃÖ­[5ÎÕC‡Ezz:úôéߌ߹s'F÷Þ{O£½¸¸=ôoÇ–-[ÀŸóz½HOOG\\žzê)À‚ 0dÈ$$$hÊ,,,4Ô¯ÐëÎÏ>û,0aÂÄÆÆ¢¸¸‹-Òÿüsþ2éOc5j”¦Íñññʇ9:uê„®]»âĉ´V­Z¥‡¸¸8$$$`Ò¤I°Ûíšgë;†;wâ­·ÞÂ+¯¼¢·—^z äeÀÂ… 1}út+‹‘ÞG´&_ß¡<ò;X*—UùN§SXä­„Å‹óGeív;-Z¤,2mðdð @uÄ^ºt)ÿ9##C÷˜}ùË_°k×.ìÞ½[X²‹˜x)à¯-fx™;œV®\‰¶mÛj^5v»ÝhÛ¶-6n܈èèhMú={öàóÏ?çÂ:N¸\.=z”1©üÊ6ÙîtìØQ·Û/^¼˜?ÜJŽº\.]„Éœœþx®øèj]]¦­Ç‡Óéä•GïVÊî&ÅÅÅX¶lžþyþP*µÇétâÅ_Ô¤ÏÏÏçÍŠã@OÙ©ENO6prä,ñ]q\È E–àh\èg*[|±ªk×®ºÛE;¹Ù¦*Púàƒ”æâ¼¹\.Üÿý7no¿ø7ñIÀ†´Á¬;˜ÆŽ‹¨¨(ͱMd®fÍšq)L¤åË—£ººš¿œìt:ñÆoð¿>œ¿`,•hløØciÊÜ»w¯rAÇÆÆjÒEEEi^ûÁH”R.]º¤I#-d‘ „§Ÿ~UUU¨ªªâý#°xúé§5é tièyy¹l’°´(-…üî¢(aÉ@ByTæ)òóe²M”ü4™0Šmk `‰ôÎ;ïp÷$±´PÛ‰_T€ˆÉ„y$¼ƒ‰$•«½P|ÿý÷ãw¿û6nÜÈó:tÕÕÕ …ÇãAqq1Ž?à§b`@Ñ6È_DË>øýû÷×XÙïÙ³Ó§OGII ÒÓÓ©ax1Z€Jê_ͪJÒ%ñØ«:Š8NX,Ýkæ*¢K–áäƒ'êå#<é¤ÄW²1/uQF PÔgj[cpeŒ!&&%%%€?ýéOèÔ©:v쨑&iΚ7oŽääd¡2©=‚¦ Xw8©ž½’™£oß¾À€“'O¢S§Nðz½šc[qq1ž{î¹Fµ¥¾¾N§“&éÌH9K»0I2AAA(((À©S§t‹‘@ÒÒB‘‹1Æ¥ ,ñ¥fÒ Éí¥²E=“êo’8ëëë9x¸ÝnØl6][¨=”‡€_4êô¥£4z`VeJcJ ~g«ÕÊ£6¨Úç‹^yåLŸ>ÿÿ™gžÁ‹/¾ˆ1cÆ 22Rwy°téRÿù{_Ô,“t·Wä[§K[ZZŠG}Œ1ìÝ»Ws´Z¾|¹F%‹ü²µÛíæÇˆÄ×´É[Ô³‘d·aÃ8p-Z´PJ¢»•)K[´PD}‘hl©"Uˆ¸‰§ÅbQ¾Ê­j?õ!88ا>G¾Q3ze[Õ:ŽQÙ䞥:ª XË—/×ܬ®Zµ «V­Â³Ï>‹±cÇÂn·ë Yêiê°îR„4…™¡[CYçDŒ.F«”V¢~IÖÕ½¼-‚’J'Ãþ}û0zôhŒ3‹[·nÅÎ;Ñ¥K%Hˆ@$»¯ÈéU×ü²¿ fDâÂ7’fåÛ2G9vº/ÀR™Pù;ÞÉ·¹7ãß¾}:?lذcÆŒÁš5k4ó ß6öÕk°îRÉJ,YùMŒ//ÐS§N锫"Xˆ N¬Wew£Rö'%%!##ħŸ~Š?ýéOˆUwdН§æå>’KXT§\/©Duô ôèîï1Yq‘ }é£T€ÝXŠÅþýûù- Heee˜;w.zõê…?üP£ÿ“¶¡ÀeÖ]V²t%KXaaa:½L‹-4G5ñ¨(_¯«@B\X"H’ކŽVAAA8yò$âââ0cÆ X,;v /¿ü².Jj¥£…¨2Z¤cXb½âBoÌ1Êx6d>¨ýþV90ÿå/ÁöíÛÑ©S'¥Z!##¯¾úªfã“ÛÛ@€&`ÝE– Z´PI—%Òc=Æu"2sïÛ·KU*[TÇÏððpnèøÑGaèС())ALL öîÝ‹–-[jŒ.Z–üIF Eí4Ò‰ÇÙ@$¡_b3ò%¥øú[cKî]»bóæÍX³f Ú·o¯<>Ž?^³¹5–LÀº‹$,•ÈÌ=ö1“8pÀ¨ärE°úä“OPQQˆˆ„‡‡ãܹsHOOçå6Œ+kÅcŽÑÂR¿ü‰ü‰u o‡dr»t•¾ú}«èÃ?ÔHÏ´ùuîÜ+W®Ä_ÿúWDEEiòì߿ǎÓÙ`5ôèlÖ] \2€‘$''krÏž=5e>|¥¥¥J}•|$À:wî222ЪU+4iÒáááØ·oŸ¦\ò ôuõ}«%’@tC@«1mÓßj@¼ßË/¿¬<îÛl6„††¢oß¾Xºt)"##5ùV¯^­3•íøLÀ2É¸˜¿¶ƒ—_~YX*1ÿÍ7ßÔÙÏÈGNbä+W®`ܸq˜5k?Úl6|øá‡:”|ƒhd).J@ª#O Ìïïå9Ž•¯EUVVæ³.2´l,>}úW%ÉíÞ½[wëL e³Ù‹·ÞzK“×ãñp«~ñ†YusiÖ]T¾hçÎüç·ÞzK'EGG£]»všsX%%%8yòd@G†J) uþUÑ %§ââb,^¼ø¦$19ºF @z»hñâźMJ¼Ä ÓÙ÷Ýÿýp¹\Ü·QöÏ Ä Ä¬»´Þ}÷]Àĉ1tèP%ðÌœ9S—÷³Ï>Ãk¯½†3gÎ(m-Z„'Ÿ|ÅÅÅøì³Ït×ØÃ† Ó”wâÄ ,]ºTãðìv»±jÕ*¤¦¦j"KÀ™3gxYgÏžýYî Aƒ4ÿÏÌÌÄáÇu`´råJ$''ëÆoÿþý(--UêßcºÅ¾~ýzD7fÌ.yþÜá‹?Žüü|¥}]®Ü¸qC“§wïÞJ¿CÑ¥Ç_LK÷;˜>úè#Ý‹¾âÎìp8Я_?#%%o¿ý6êêêt€„˜˜Ìž=Ó¦MÓ”uîÜ9L˜0QQQèÔ©¿ÙûûßÿÎÓlذ111ºç¥âãã±{÷nMy³fÍÂÊ•+Ѿ}{”••᫯¾ðS8™3gÎ`ÅŠ<íþð´k×gΜAï޽ѹsçF/܆Ù^yåMàÏþ3Ú¶m‹ÈÈHá“O>LŸ>ƒÖ•‘œœŒÈÈH¤¥¥aÔ¨Qš¶wíÚ_|ñ…æH¸`Á´iÓåå娱cž}öYM*¯×«{rþV˜XÞ˜1cpèÐ!î…@&"`›6mâiŸzê)tìØ‘KÌ\V«Uycä¦cÖD™™™(**B~~>¬’’ôêÕ ={öDLL c(--ÅÆ±råJ()))š¸IZtÝŒäädX­VeÌñòòrþøcìÙ³GÙ—>}ú gÏžèÝ»7BCCѤI4mÚ Á’%K0cÆ ]¾¶mÛbÊ”)ˆGDDl6|ðAtéÒÏ=÷z÷îÍýx<\‘Ê ÃÞ½{y$ q\RSSñÛßþááᨬ¬Ä7ß|ƒ3gÎàäÉ“šÛ^±ßmÛ¶E=СC<ðÀøî»ïðõ×_cß¾}º Cìû£>ŠvíÚá±ÇC“&MpÏ=÷ G˜9s&, òóóñþûï+%Ô¸¸8$''ãùçŸçz+ŠhA³FDD iÓ¦hÒ¤ ·Íóe{gÖXuuu8((Hcã#¶A! ,ZÓÓ¢¢öR[éø¤ŠSUSSƒªª*ÔÔÔðXR¡¡¡\" À IO‹’1ÆÇÂf³ñq €7ê§ÍfC“&M¸a­Ø1 "/ é³Ùl|±{<ÍÆEs$ö[>uuu¨®®æ}'&ICÔ>«Õ ‹Å‰@K…CÜ08)ÄMxx8"""¸*ò‹©t¿Kne'gbÚýhшў%Æ}Ëã™ÓïD$`£+±\9Šh6AGCÑÏô2b=bÜ(ê‹N>zÒïe—!1PžÊíF"Ö'ŽxCF’ ]ÏSÛÅq¦|r”j§ü¸©\>)¨©oâ‹AIZ’û­z%Z'¹ïrˆ‘_TAÅüª€}$ÒFD›¿G]MÀºJ\`d¸i³ÙønOŒ)‡zodDŸCùÑMùÁ‘9é)sE…ª¯8NT†èÄ €õDfV-ÅúÅ Kö7š{±Q¢¦²ÄþÊ@mÖ]ZÄÒÎ)2‡(Mù’V|Å-KÞ 8äpŲ»Ž`âU>‰žýb9bœ*Y*Ó‰:#ÈÅxëâOº<:žPDÀ•¦åp:4âÓZrÙæH±ýòüˆ› ˆ4ž”ÆW¿e#€û.KEÀ×¾'ŠqíÅ9R y$¼‹ÀŠ‚¼øbV©Äó«ôCª™|ÿTÇ 92¦<ªEIåÉR¡¸ÀT¯ÅÈ@,})4°LN~oPt’4dIIŽÓ%¥EcH¹M²TcäÒ$JbâüˆÒ*0ÿfÔoY²‘-×e›<•¤(ªd[*Àä±ð%±)yܼ%¼3o ôd†2 'ÿ¬ŠX ?¤ªrÏñSVþªÊR«œO”TTa™Å¶ŠG`#”ŸÒ’Ó«Â߈‘IÅqPm F:HUP;Y±n4.Fã©j‹*J©jNUŠ{•‚\æ-Uô _/?Ǭ;´dër£]O^þ¿©Ê—×(¬?T¹ØøŠÊ §ÿUÝdùê§Q@@8È:2£8ÙSõ3WfŒòÈsïü}ÝúùÚÄ∭’è ƒcÖ]\þ˜I*Ð(þâ˜-*£8S*g`9*ô‹\ŸQ;€Â¨-þ€Å¨ÑتþHœx#VõÅß«ò͡ѸùÛ}½ X&*CU1Ào¶|#Fmª~¾™`t kìÜ}®¿qh옫Ê÷•ÿVö[•§¡1Ènv.MÀ2É$“þeÈŒ‡e’I&™€e’I&™d–I&™d–I&™d’ X&™d’I·ˆþ?Ä è$sdÊIEND®B`‚commons-beanutils-1.9.1-src/src/site/site.xml100644 0 0 5761 12262570613 16333 0ustar 0 0 Commons BeanUtils /images/logo.png /index.html commons-beanutils-1.9.1-src/src/site/xdoc/bean-collections.xml100644 0 0 6741 12262570613 21544 0ustar 0 0 Commons Commons Documentation Team

          Dealing with collections of beans is a common feature of development in Java. A lot of time is spent creating bean-specific implementations for standard collection manipulators such as functors and comparators.

          BeanUtils Bean collections is a library intended to improve developer productivity by using sophisticated bean introspection (from BeanUtils) to allow general library classes to be used (rather than creating bean specific implementation classes).

          But won't this be slower? Yes, reflection is slower than direct references but in real life applications, this is typically insignificant. So why not use these classes to speed development and then substitute faster implementations only where the profiler indicates there is a problem :)

          Many of the classes in bean-collections are functor implementations specialized for bean properties. This is a very quick guide (aimed to let java developer know why functors make for elegant code).

          The word functor is mathematical in origin but comes into object oriented development from functional and logic coding. In Java terms, a functor is a function that is encapsulated as an object (and so can be manipulated as an object). This allows elegant, concise and powerful techniques to be used. For example, Commons Collections contains utilities that allow functions (as functors) to be easily applied to Collections.

          This is actually pretty useful when it comes to collections of beans. It's a common problem to want to extract information from a collection of beans or to change all properties to a particular value. Functors can be a particularly elegant way to do this. So try them! You might just like them!

          For more information about functors, please read the introduction to the Commons Functor component.

          BeanUtils Bean-Collections is distributed as an optional jar within the main beanutils distribution. For details, see the main BeanUtils website

          commons-beanutils-1.9.1-src/src/site/xdoc/building.xml100644 0 0 4355 12262570613 20117 0ustar 0 0 Building Commons Documentation Team

          Commons BeanUtils can be built using Maven 2 or Ant as the build system.

          Further details can be found in the commons build instructions.

          To build a jar file, change into BeanUtils's root directory and run mvn package. The result will be in the "target" subdirectory.

          To build the full website, run mvn site. The result will be in "target/site" subdirectory.

          To build the full distribution, run mvn -Prc package. The result will be in "target" subdirectory.

          To build a jar file and the javadocs, change into BeanUtils's root directory and run ant dist. The result will be in the "dist" subdirectory.

          commons-beanutils-1.9.1-src/src/site/xdoc/download_beanutils.xml100644 0 0 16027 12262570613 22216 0ustar 0 0 Download Apache Commons BeanUtils Commons Documentation Team

          We recommend you use a mirror to download our release builds, but you must verify the integrity of the downloaded files using signatures downloaded from our main distribution directories. Recent releases (48 hours) may not yet be available from the mirrors.

          You are currently using [preferred]. If you encounter a problem with this mirror, please select another mirror. If all mirrors are failing, there are backup mirrors (at the end of the mirrors list) that should be available.

          [if-any logo][end]

          Other mirrors:

          The KEYS link links to the code signing keys used to sign the product. The PGP link downloads the OpenPGP compatible signature from our main site. The MD5 link downloads the checksum from the main site.

          commons-beanutils-1.9.1-bin.tar.gz md5 pgp
          commons-beanutils-1.9.1-bin.zip md5 pgp
          commons-beanutils-1.9.1-src.tar.gz md5 pgp
          commons-beanutils-1.9.1-src.zip md5 pgp

          Older releases can be obtained from the archives.

          commons-beanutils-1.9.1-src/src/site/xdoc/index.xml100644 0 0 23773 12262570612 17455 0ustar 0 0 Commons Commons Documentation Team

          Most Java developers are used to creating Java classes that conform to the JavaBeans naming patterns for property getters and setters. It is natural to then access these methods directly, using calls to the corresponding getXxx and setXxx methods. However, there are some occasions where dynamic access to Java object properties (without compiled-in knowledge of the property getter and setter methods to be called) is needed. Example use cases include:

          • Building scripting languages that interact with the Java object model (such as the Bean Scripting Framework).
          • Building template language processors for web presentation and similar uses (such as JSP or Velocity).
          • Building custom tag libraries for JSP and XSP environments (such as Jakarta Taglibs, Struts, Cocoon).
          • Consuming XML-based configuration resources (such as Ant build scripts, web application deployment descriptors, Tomcat's server.xml file).

          The Java language provides Reflection and Introspection APIs (see the java.lang.reflect and java.beans packages in the JDK Javadocs). However, these APIs can be quite complex to understand and utilize. The BeanUtils component provides easy-to-use wrappers around these capabilities.

          The 1.7.x and 1.8.x releases of BeanUtils have distributed three jars:

          • commons-beanutils.jar - contains everything
          • commons-beanutils-core.jar - excludes Bean Collections classes
          • commons-beanutils-bean-collections.jar - only Bean Collections classes
          The main commons-beanutils.jar has an optional dependency on Commons Collections

          Version 1.9.0 reverts this split for reasons outlined at BEANUTILS-379. There is now only one jar for the BeanUtils library.

          Bean collections is a library combining BeanUtils with Commons Collections to provide services for collections of beans. One class (BeanComparator) was previously released, the rest are new. This new distribution strategy should allow this sub-component to evolve naturally without the concerns about size and scope that might otherwise happen.

          Bean Collections has an additional dependency on Commons Collections.

          The User Guide is part of the package JavaDocs.

          The Release Notes document the new features and bug fixes that have been included in this release.

          The JavaDoc API documents are available online. In particular, you should note the property reference syntax options described in the PropertyUtils class description.

          BeanUtils 1.9.x releases are binary compatible (with a minor exception described in the release notes) with version 1.8.3 and require a minimum of JDK 1.5.

          The latest BeanUtils release is available to download here.

          BeanUtils 1.8.x releases are binary compatible with version 1.7.0 and require a minimum of JDK 1.3.

          BeanUtils 1.7.0 is a service release which removes the dependency upon a specific commons-collection library version. It may be safely used together with either the 2.x or 3.x series of commons-collections releases. It also introduces a number of important enhancements. It is backward compatible with the 1.6 release.

          This important service release is intended to help downstream applications solve dependency issues. The dependency on commons collections (which has become problematic now that there are two incompatible series of commons collections releases) has been factored into a separate optional sub-component plus a small number of stable and mature org.apache.commons.collections packaged classes (which are distributed with the BeanUtils core). This arrangement means that the BeanUtils core sub-component (which is the primary dependency for most downsteam applications) can now be safely included on the same classpath as commons collections 2.x, 3.x or indeed neither.

          The distribution now contains alternative jar sets. The all-in-one jar contains all classes. The modular jar set consists of a core jar dependent only on commons logging and an optional bean collections jar (containing classes that provide easy and efficient ways to manage collections of beans) which depends on commons collections 3.

          The commons mailing lists act as the main support forum. The user list is suitable for most library usage queries. The dev list is intended for the development discussion. Please remember that the lists are shared between all commons components, so prefix your email by [beanutils].

          Issues may be reported via ASF JIRA.

          commons-beanutils-1.9.1-src/src/site/xdoc/issue-tracking.xml100644 0 0 13451 12262570613 21267 0ustar 0 0 Commons BeanUtils Issue tracking Commons Documentation Team

          Commons BeanUtils uses ASF JIRA for tracking issues. See the Commons BeanUtils JIRA project page.

          To use JIRA you may need to create an account (if you have previously created/updated Commons issues using Bugzilla an account will have been automatically created and you can use the Forgot Password page to get a new password).

          If you would like to report a bug, or raise an enhancement request with Commons BeanUtils please do the following:

          1. Search existing open bugs. If you find your issue listed then please add a comment with your details.
          2. Search the mailing list archive(s). You may find your issue or idea has already been discussed.
          3. Decide if your issue is a bug or an enhancement.
          4. Submit either a bug report or enhancement request.

          Please also remember these points:

          • the more information you provide, the better we can help you
          • test cases are vital, particularly for any proposed enhancements
          • the developers of Commons BeanUtils are all unpaid volunteers

          For more information on subversion and creating patches see the Apache Contributors Guide.

          You may also find these links useful:

          commons-beanutils-1.9.1-src/src/site/xdoc/mail-lists.xml100644 0 0 22632 12262570612 20415 0ustar 0 0 Commons BeanUtils Mailing Lists Commons Documentation Team

          Commons BeanUtils shares mailing lists with all the other Commons Components. To make it easier for people to only read messages related to components they are interested in, the convention in Commons is to prefix the subject line of messages with the component's name, for example:

          • [beanutils] Problem with the ...

          Questions related to the usage of Commons BeanUtils should be posted to the User List.
          The Developer List is for questions and discussion related to the development of Commons BeanUtils.
          Please do not cross-post; developers are also subscribed to the user list.

          Note: please don't send patches or attachments to any of the mailing lists. Patches are best handled via the Issue Tracking system. Otherwise, please upload the file to a public server and include the URL in the mail.

          Please prefix the subject line of any messages for Commons BeanUtils with [beanutils] - thanks!

          Name Subscribe Unsubscribe Post Archive Other Archives
          Commons User List

          Questions on using Commons BeanUtils.

          Subscribe Unsubscribe Post mail-archives.apache.org markmail.org
          www.mail-archive.com
          news.gmane.org
          Commons Developer List

          Discussion of development of Commons BeanUtils.

          Subscribe Unsubscribe Post mail-archives.apache.org markmail.org
          www.mail-archive.com
          news.gmane.org
          Commons Issues List

          Only for e-mails automatically generated by the issue tracking system.

          Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
          www.mail-archive.com
          Commons Commits List

          Only for e-mails automatically generated by the source control sytem.

          Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
          www.mail-archive.com

          Other mailing lists which you may find useful include:

          Name Subscribe Unsubscribe Post Archive Other Archives
          Apache Announce List

          General announcements of Apache project releases.

          Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
          old.nabble.com
          www.mail-archive.com
          news.gmane.org
          commons-beanutils-1.9.1-src/src/site/xdoc/proposal.xml100644 0 0 13405 12262570613 20175 0ustar 0 0 Proposal for BeanUtils Package

          Most Java developers are used to creating Java classes that conform to the JavaBeans naming patterns for property getters and setters. It is natural to then access these methods directly, using calls to the corresponding getXxx and setXxx methods. However, there are some occasions where dynamic access to Java object properties (without compiled-in knowledge of the property getter and setter methods to be called) is needed. Example use cases include:

          • Building scripting languages that interact with the Java object model (such as the Bean Scripting Framework).
          • Building template language processors for web presentation and similar uses (such as JSP or Velocity).
          • Building custom tag libraries for JSP and XSP environments (such as Jakarta Taglibs, Struts, Cocoon).
          • Consuming XML-based configuration resources (such as Ant build scripts, web application deployment descriptors, Tomcat's server.xml file).

          The Java language provides Reflection and Introspection APIs (see the java.lang.reflect and java.beans packages in the JDK Javadocs). However, these APIs can be quite complex to understand and utilize. The proposed BeanUtils component provides easy-to-use wrappers around these capabilities.

          This proposal is to create a package of Java utility methods for accessing and modifying the properties of arbitrary JavaBeans. No dependencies outside of the JDK are required, so the use of this package is very lightweight.

          In addition to wrapping the reflection and introspection APIs of the standard JDK, BeanUtils components shall support a syntax for directly accessing nested and indexed properties, in a manner that will be familar to users of scripting languages like JavaScript. For example, the following property accessor expressions are supported:

          • customer - Equivalent to getCustomer().
          • customer.address - Equivalent to getCustomer().getAddress().
          • customer.address[2].street - Equivalent to getCustomer().getAddress(2).getStreet() (access to indexed properties also works if the underlying property is an array rather than providing indexed getter and setter methods).

          BeanUtils relies only on standard JDK 1.2 (or later) APIs for production deployment. It utilizes the JUnit unit testing framework for developing and executing unit tests, but this is of interest only to developers of the component. BeanUtils will also be a dependency for several future proposed components for the Jakarta Commons subproject.

          No external configuration files are utilized.

          The three original Java classes (BeanUtils, ConvertUtils, and PropertyUtils) are an integral part of the Struts Framework. However, they have very few dependencies on other aspects of Struts, and those dependencies have been removed in the proposed code base. Once accepted and released as a Jakarta Commons component, Struts will be modified to use the Commons version of these classes, and its internal versions will be deprecated.

          The proposed package name for the new component is org.apache.commons.beanutils.

          • CVS Repository - New directory beanutils in the jakarta-commons CVS repository. All initial committers are already committers on jakarta-commons, so no additional user setups are required.
          • Mailing List - Discussions will take place on the general jakarta-commons@jakarta.apache.org mailing list. To help list subscribers identify messages of interest, it is suggested that the message subject of messages about this component be prefixed with [BeanUtils].
          • Bugzilla - New component "BeanUtils" under the "Commons" product category, with appropriate version identifiers as needed.
          • Jyve FAQ - New category "commons-beanutils" (when available).

          The initial committers on the BeanUtils component shall be Craig McClanahan and Geir Magnusson Jr.

          commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/A.java100644 0 0 2172 12262570610 24263 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.OutputStream; /** *

          Class used in MethodUtils test

          * * @version $Id: A.java 1454597 2013-03-08 21:58:12Z britter $ */ public class A { boolean called = false; public void foo(OutputStream os) { called = true; } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/AbstractChild.java100644 0 0 2233 12262570610 26610 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * @version $Id: AbstractChild.java 1454597 2013-03-08 21:58:12Z britter $ */ public class AbstractChild implements Child { private String name; protected void setName(String name) { this.name = name; } public String getName() { return name; } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/AbstractParent.java100644 0 0 3254 12262570610 27022 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * @version $Id: AbstractParent.java 1454597 2013-03-08 21:58:12Z britter $ */ public abstract class AbstractParent { private Child child; public Child getChild() { return child; } /** * Method which matches signature but which has wrong parameters */ public String testAddChild(String badParameter) { return null; } /** * Method which matches signature but which has wrong parameters */ public String testAddChild2(String ignore, String badParameter) { return null; } public String testAddChild(Child child) { this.child = child; return child.getName(); } public String testAddChild2(String ignore, Child child) { this.child = child; return child.getName(); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/AlphaBean.java100644 0 0 2573 12262570610 25723 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * @version $Id: AlphaBean.java 1454597 2013-03-08 21:58:12Z britter $ */ public class AlphaBean extends AbstractParent implements Child { private String name; public AlphaBean() {} public AlphaBean(String name) { setName(name); } public String getName() { return name; } public void setName(String name) { this.name = name; } /** * Used for testing that correct exception is thrown. */ public void bogus(String badParameter){} } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BasicDynaBeanTestCase.java100644 0 0 76172 12262570607 30223 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; /** *

          Test Case for the BasicDynaBean implementation class. * These tests were based on the ones in PropertyUtilsTestCase * because the two classes provide similar levels of functionality.

          * * @version $Id: BasicDynaBeanTestCase.java 1479595 2013-05-06 14:59:37Z sebb $ */ public class BasicDynaBeanTestCase extends TestCase { // ---------------------------------------------------- Instance Variables /** * The basic test bean for each test. */ protected DynaBean bean = null; /** * The set of property names we expect to have returned when calling * getDynaProperties(). You should update this list * when new properties are added to TestBean. */ protected final static String[] properties = { "booleanProperty", "booleanSecond", "doubleProperty", "floatProperty", "intArray", "intIndexed", "intProperty", "listIndexed", "longProperty", "mappedProperty", "mappedIntProperty", "nullProperty", "shortProperty", "stringArray", "stringIndexed", "stringProperty", }; // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public BasicDynaBeanTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { // Instantiate a new DynaBean instance DynaClass dynaClass = createDynaClass(); bean = dynaClass.newInstance(); // Initialize the DynaBean's property values (like TestBean) bean.set("booleanProperty", new Boolean(true)); bean.set("booleanSecond", new Boolean(true)); bean.set("doubleProperty", new Double(321.0)); bean.set("floatProperty", new Float((float) 123.0)); int intArray[] = { 0, 10, 20, 30, 40 }; bean.set("intArray", intArray); int intIndexed[] = { 0, 10, 20, 30, 40 }; bean.set("intIndexed", intIndexed); bean.set("intProperty", new Integer(123)); List listIndexed = new ArrayList(); listIndexed.add("String 0"); listIndexed.add("String 1"); listIndexed.add("String 2"); listIndexed.add("String 3"); listIndexed.add("String 4"); bean.set("listIndexed", listIndexed); bean.set("longProperty", new Long(321)); HashMap mappedProperty = new HashMap(); mappedProperty.put("First Key", "First Value"); mappedProperty.put("Second Key", "Second Value"); bean.set("mappedProperty", mappedProperty); HashMap mappedIntProperty = new HashMap(); mappedIntProperty.put("One", new Integer(1)); mappedIntProperty.put("Two", new Integer(2)); bean.set("mappedIntProperty", mappedIntProperty); // Property "nullProperty" is not initialized, so it should return null bean.set("shortProperty", new Short((short) 987)); String stringArray[] = { "String 0", "String 1", "String 2", "String 3", "String 4" }; bean.set("stringArray", stringArray); String stringIndexed[] = { "String 0", "String 1", "String 2", "String 3", "String 4" }; bean.set("stringIndexed", stringIndexed); bean.set("stringProperty", "This is a string"); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(BasicDynaBeanTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { bean = null; } // ------------------------------------------------ Individual Test Methods /** * Corner cases on getDynaProperty invalid arguments. */ public void testGetDescriptorArguments() { try { DynaProperty descriptor = bean.getDynaClass().getDynaProperty("unknown"); assertNull("Unknown property descriptor should be null", descriptor); } catch (Throwable t) { fail("Threw " + t + " instead of returning null"); } try { bean.getDynaClass().getDynaProperty(null); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException"); } } /** * Positive getDynaProperty on property booleanProperty. */ public void testGetDescriptorBoolean() { testGetDescriptorBase("booleanProperty", Boolean.TYPE); } /** * Positive getDynaProperty on property doubleProperty. */ public void testGetDescriptorDouble() { testGetDescriptorBase("doubleProperty", Double.TYPE); } /** * Positive getDynaProperty on property floatProperty. */ public void testGetDescriptorFloat() { testGetDescriptorBase("floatProperty", Float.TYPE); } /** * Positive getDynaProperty on property intProperty. */ public void testGetDescriptorInt() { testGetDescriptorBase("intProperty", Integer.TYPE); } /** * Positive getDynaProperty on property longProperty. */ public void testGetDescriptorLong() { testGetDescriptorBase("longProperty", Long.TYPE); } /** * Positive getDynaProperty on property booleanSecond * that uses an "is" method as the getter. */ public void testGetDescriptorSecond() { testGetDescriptorBase("booleanSecond", Boolean.TYPE); } /** * Positive getDynaProperty on property shortProperty. */ public void testGetDescriptorShort() { testGetDescriptorBase("shortProperty", Short.TYPE); } /** * Positive getDynaProperty on property stringProperty. */ public void testGetDescriptorString() { testGetDescriptorBase("stringProperty", String.class); } /** * Positive test for getDynaPropertys(). Each property name * listed in properties should be returned exactly once. */ public void testGetDescriptors() { DynaProperty pd[] = bean.getDynaClass().getDynaProperties(); assertNotNull("Got descriptors", pd); int count[] = new int[properties.length]; for (int i = 0; i < pd.length; i++) { String name = pd[i].getName(); for (int j = 0; j < properties.length; j++) { if (name.equals(properties[j])) count[j]++; } } for (int j = 0; j < properties.length; j++) { if (count[j] < 0) fail("Missing property " + properties[j]); else if (count[j] > 1) fail("Duplicate property " + properties[j]); } } /** * Corner cases on getIndexedProperty invalid arguments. */ public void testGetIndexedArguments() { try { bean.get("intArray", -1); fail("Should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IndexOutOfBoundsException"); } } /** * Positive and negative tests on getIndexedProperty valid arguments. */ public void testGetIndexedValues() { Object value = null; for (int i = 0; i < 5; i++) { try { value = bean.get("intArray", i); assertNotNull("intArray returned value " + i, value); assertTrue("intArray returned Integer " + i, value instanceof Integer); assertEquals("intArray returned correct " + i, i * 10, ((Integer) value).intValue()); } catch (Throwable t) { fail("intArray " + i + " threw " + t); } try { value = bean.get("intIndexed", i); assertNotNull("intIndexed returned value " + i, value); assertTrue("intIndexed returned Integer " + i, value instanceof Integer); assertEquals("intIndexed returned correct " + i, i * 10, ((Integer) value).intValue()); } catch (Throwable t) { fail("intIndexed " + i + " threw " + t); } try { value = bean.get("listIndexed", i); assertNotNull("listIndexed returned value " + i, value); assertTrue("list returned String " + i, value instanceof String); assertEquals("listIndexed returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("listIndexed " + i + " threw " + t); } try { value = bean.get("stringArray", i); assertNotNull("stringArray returned value " + i, value); assertTrue("stringArray returned String " + i, value instanceof String); assertEquals("stringArray returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("stringArray " + i + " threw " + t); } try { value = bean.get("stringIndexed", i); assertNotNull("stringIndexed returned value " + i, value); assertTrue("stringIndexed returned String " + i, value instanceof String); assertEquals("stringIndexed returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("stringIndexed " + i + " threw " + t); } } } /** * Corner cases on getMappedProperty invalid arguments. */ public void testGetMappedArguments() { try { Object value = bean.get("mappedProperty", "unknown"); assertNull("Should not return a value", value); } catch (Throwable t) { fail("Threw " + t + " instead of returning null"); } } /** * Positive and negative tests on getMappedProperty valid arguments. */ public void testGetMappedValues() { Object value = null; try { value = bean.get("mappedProperty", "First Key"); assertEquals("Can find first value", "First Value", value); } catch (Throwable t) { fail("Finding first value threw " + t); } try { value = bean.get("mappedProperty", "Second Key"); assertEquals("Can find second value", "Second Value", value); } catch (Throwable t) { fail("Finding second value threw " + t); } try { value = bean.get("mappedProperty", "Third Key"); assertNull("Can not find third value", value); } catch (Throwable t) { fail("Finding third value threw " + t); } } /** * Corner cases on getSimpleProperty invalid arguments. */ public void testGetSimpleArguments() { try { bean.get(null); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException"); } } /** * Test getSimpleProperty on a boolean property. */ public void testGetSimpleBoolean() { try { Object value = bean.get("booleanProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Boolean)); assertTrue("Got correct value", ((Boolean) value).booleanValue() == true); } catch (Throwable e) { fail("Exception: " + e); } } /** * Test getSimpleProperty on a double property. */ public void testGetSimpleDouble() { try { Object value = bean.get("doubleProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Double)); assertEquals("Got correct value", ((Double) value).doubleValue(), 321.0, 0.005); } catch (Throwable t) { fail("Exception: " + t); } } /** * Test getSimpleProperty on a float property. */ public void testGetSimpleFloat() { try { Object value = bean.get("floatProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Float)); assertEquals("Got correct value", ((Float) value).floatValue(), (float) 123.0, (float) 0.005); } catch (Throwable t) { fail("Exception: " + t); } } /** * Test getSimpleProperty on a int property. */ public void testGetSimpleInt() { try { Object value = bean.get("intProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Integer)); assertEquals("Got correct value", ((Integer) value).intValue(), 123); } catch (Throwable t) { fail("Exception: " + t); } } /** * Test getSimpleProperty on a long property. */ public void testGetSimpleLong() { try { Object value = bean.get("longProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Long)); assertEquals("Got correct value", ((Long) value).longValue(), 321); } catch (Throwable t) { fail("Exception: " + t); } } /** * Test getSimpleProperty on a short property. */ public void testGetSimpleShort() { try { Object value = bean.get("shortProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Short)); assertEquals("Got correct value", ((Short) value).shortValue(), (short) 987); } catch (Throwable t) { fail("Exception: " + t); } } /** * Test getSimpleProperty on a String property. */ public void testGetSimpleString() { try { Object value = bean.get("stringProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof String)); assertEquals("Got correct value", (String) value, "This is a string"); } catch (Throwable t) { fail("Exception: " + t); } } /** * Test contains() method for mapped properties. */ public void testMappedContains() { try { assertTrue("Can see first key", bean.contains("mappedProperty", "First Key")); } catch (Throwable t) { fail("Exception: " + t); } try { assertTrue("Can not see unknown key", !bean.contains("mappedProperty", "Unknown Key")); } catch (Throwable t) { fail("Exception: " + t); } } /** * Test remove() method for mapped properties. */ public void testMappedRemove() { try { assertTrue("Can see first key", bean.contains("mappedProperty", "First Key")); bean.remove("mappedProperty", "First Key"); assertTrue("Can not see first key", !bean.contains("mappedProperty", "First Key")); } catch (Throwable t) { fail("Exception: " + t); } try { assertTrue("Can not see unknown key", !bean.contains("mappedProperty", "Unknown Key")); bean.remove("mappedProperty", "Unknown Key"); assertTrue("Can not see unknown key", !bean.contains("mappedProperty", "Unknown Key")); } catch (Throwable t) { fail("Exception: " + t); } } /** * Test serialization and deserialization. */ public void testSerialization() { // Serialize the test bean ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(bean); oos.flush(); oos.close(); } catch (Exception e) { fail("Exception during serialization: " + e); } // Deserialize the test bean try { bean = null; ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); bean = (DynaBean) ois.readObject(); bais.close(); } catch (Exception e) { fail("Exception during deserialization: " + e); } // Confirm property values testGetDescriptorArguments(); testGetDescriptorBoolean(); testGetDescriptorDouble(); testGetDescriptorFloat(); testGetDescriptorInt(); testGetDescriptorLong(); testGetDescriptorSecond(); testGetDescriptorShort(); testGetDescriptorString(); testGetDescriptors(); testGetIndexedArguments(); testGetIndexedValues(); testGetMappedArguments(); testGetMappedValues(); testGetSimpleArguments(); testGetSimpleBoolean(); testGetSimpleDouble(); testGetSimpleFloat(); testGetSimpleInt(); testGetSimpleLong(); testGetSimpleShort(); testGetSimpleString(); testMappedContains(); testMappedRemove(); // Ensure that we can create a new instance of the same DynaClass try { bean = bean.getDynaClass().newInstance(); } catch (Exception e) { fail("Exception creating new instance: " + e); } testGetDescriptorArguments(); testGetDescriptorBoolean(); testGetDescriptorDouble(); testGetDescriptorFloat(); testGetDescriptorInt(); testGetDescriptorLong(); testGetDescriptorSecond(); testGetDescriptorShort(); testGetDescriptorString(); testGetDescriptors(); } /** * Corner cases on setIndexedProperty invalid arguments. */ public void testSetIndexedArguments() { try { bean.set("intArray", -1, new Integer(0)); fail("Should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IndexOutOfBoundsException"); } } /** * Positive and negative tests on setIndexedProperty valid arguments. */ public void testSetIndexedValues() { Object value = null; try { bean.set("intArray", 0, new Integer(1)); value = bean.get("intArray", 0); assertNotNull("Returned new value 0", value); assertTrue("Returned Integer new value 0", value instanceof Integer); assertEquals("Returned correct new value 0", 1, ((Integer) value).intValue()); } catch (Throwable t) { fail("Threw " + t); } try { bean.set("intIndexed", 1, new Integer(11)); value = bean.get("intIndexed", 1); assertNotNull("Returned new value 1", value); assertTrue("Returned Integer new value 1", value instanceof Integer); assertEquals("Returned correct new value 1", 11, ((Integer) value).intValue()); } catch (Throwable t) { fail("Threw " + t); } try { bean.set("listIndexed", 2, "New Value 2"); value = bean.get("listIndexed", 2); assertNotNull("Returned new value 2", value); assertTrue("Returned String new value 2", value instanceof String); assertEquals("Returned correct new value 2", "New Value 2", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { bean.set("stringArray", 3, "New Value 3"); value = bean.get("stringArray", 3); assertNotNull("Returned new value 3", value); assertTrue("Returned String new value 3", value instanceof String); assertEquals("Returned correct new value 3", "New Value 3", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { bean.set("stringIndexed", 4, "New Value 4"); value = bean.get("stringIndexed", 4); assertNotNull("Returned new value 4", value); assertTrue("Returned String new value 4", value instanceof String); assertEquals("Returned correct new value 4", "New Value 4", (String) value); } catch (Throwable t) { fail("Threw " + t); } } /** * Positive and negative tests on setMappedProperty valid arguments. */ public void testSetMappedValues() { try { bean.set("mappedProperty", "First Key", "New First Value"); assertEquals("Can replace old value", "New First Value", (String) bean.get("mappedProperty", "First Key")); } catch (Throwable t) { fail("Finding fourth value threw " + t); } try { bean.set("mappedProperty", "Fourth Key", "Fourth Value"); assertEquals("Can set new value", "Fourth Value", (String) bean.get("mappedProperty", "Fourth Key")); } catch (Throwable t) { fail("Finding fourth value threw " + t); } } /** * Test setSimpleProperty on a boolean property. */ public void testSetSimpleBoolean() { try { boolean oldValue = ((Boolean) bean.get("booleanProperty")).booleanValue(); boolean newValue = !oldValue; bean.set("booleanProperty", new Boolean(newValue)); assertTrue("Matched new value", newValue == ((Boolean) bean.get("booleanProperty")).booleanValue()); } catch (Throwable e) { fail("Exception: " + e); } } /** * Test setSimpleProperty on a double property. */ public void testSetSimpleDouble() { try { double oldValue = ((Double) bean.get("doubleProperty")).doubleValue(); double newValue = oldValue + 1.0; bean.set("doubleProperty", new Double(newValue)); assertEquals("Matched new value", newValue, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); } catch (Throwable e) { fail("Exception: " + e); } } /** * Test setSimpleProperty on a float property. */ public void testSetSimpleFloat() { try { float oldValue = ((Float) bean.get("floatProperty")).floatValue(); float newValue = oldValue + (float) 1.0; bean.set("floatProperty", new Float(newValue)); assertEquals("Matched new value", newValue, ((Float) bean.get("floatProperty")).floatValue(), (float) 0.005); } catch (Throwable e) { fail("Exception: " + e); } } /** * Test setSimpleProperty on a int property. */ public void testSetSimpleInt() { try { int oldValue = ((Integer) bean.get("intProperty")).intValue(); int newValue = oldValue + 1; bean.set("intProperty", new Integer(newValue)); assertEquals("Matched new value", newValue, ((Integer) bean.get("intProperty")).intValue()); } catch (Throwable e) { fail("Exception: " + e); } } /** * Test setSimpleProperty on a long property. */ public void testSetSimpleLong() { try { long oldValue = ((Long) bean.get("longProperty")).longValue(); long newValue = oldValue + 1; bean.set("longProperty", new Long(newValue)); assertEquals("Matched new value", newValue, ((Long) bean.get("longProperty")).longValue()); } catch (Throwable e) { fail("Exception: " + e); } } /** * Test setSimpleProperty on a short property. */ public void testSetSimpleShort() { try { short oldValue = ((Short) bean.get("shortProperty")).shortValue(); short newValue = (short) (oldValue + 1); bean.set("shortProperty", new Short(newValue)); assertEquals("Matched new value", newValue, ((Short) bean.get("shortProperty")).shortValue()); } catch (Throwable e) { fail("Exception: " + e); } } /** * Test setSimpleProperty on a String property. */ public void testSetSimpleString() { try { String oldValue = (String) bean.get("stringProperty"); String newValue = oldValue + " Extra Value"; bean.set("stringProperty", newValue); assertEquals("Matched new value", newValue, (String) bean.get("stringProperty")); } catch (Throwable e) { fail("Exception: " + e); } } // ------------------------------------------------------ Protected Methods /** * Create and return a DynaClass instance for our test * DynaBean. */ protected DynaClass createDynaClass() { int intArray[] = new int[0]; String stringArray[] = new String[0]; DynaClass dynaClass = new BasicDynaClass ("TestDynaClass", null, new DynaProperty[]{ new DynaProperty("booleanProperty", Boolean.TYPE), new DynaProperty("booleanSecond", Boolean.TYPE), new DynaProperty("doubleProperty", Double.TYPE), new DynaProperty("floatProperty", Float.TYPE), new DynaProperty("intArray", intArray.getClass()), new DynaProperty("intIndexed", intArray.getClass()), new DynaProperty("intProperty", Integer.TYPE), new DynaProperty("listIndexed", List.class), new DynaProperty("longProperty", Long.TYPE), new DynaProperty("mappedProperty", Map.class), new DynaProperty("mappedIntProperty", Map.class), new DynaProperty("nullProperty", String.class), new DynaProperty("shortProperty", Short.TYPE), new DynaProperty("stringArray", stringArray.getClass()), new DynaProperty("stringIndexed", stringArray.getClass()), new DynaProperty("stringProperty", String.class), }); return (dynaClass); } /** * Base for testGetDescriptorXxxxx() series of tests. * * @param name Name of the property to be retrieved * @param type Expected class type of this property */ protected void testGetDescriptorBase(String name, Class type) { try { DynaProperty descriptor = bean.getDynaClass().getDynaProperty(name); assertNotNull("Got descriptor", descriptor); assertEquals("Got correct type", type, descriptor.getType()); } catch (Throwable t) { fail("Threw an exception: " + t); } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanComparatorTestCase.java100644 0 0 16150 12262570607 30463 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** *

          * Test Case for the BeanComparator class. * * @version $Id: BeanComparatorTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class BeanComparatorTestCase extends TestCase { // ---------------------------------------------------- Instance Variables /** * The test beans for each test. */ protected TestBean bean = null; protected AlphaBean alphaBean1 = null; protected AlphaBean alphaBean2 = null; // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public BeanComparatorTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { bean = new TestBean(); alphaBean1 = new AlphaBean("alphaBean1"); alphaBean2 = new AlphaBean("alphaBean2"); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(BeanComparatorTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { bean = null; alphaBean1 = null; alphaBean2 = null; } // ------------------------------------------------ Individual Test Methods /** * tests comparing two beans via their name using the default Comparator */ public void testSimpleCompare() { BeanComparator beanComparator = new BeanComparator( "name"); int result = beanComparator.compare(alphaBean1, alphaBean2); assertTrue("Comparator did not sort properly. Result:" + result, result == -1); } /** * tests comparing two beans via their name using the default Comparator, but the inverse */ public void testSimpleCompareInverse() { BeanComparator beanComparator = new BeanComparator( "name"); int result = beanComparator.compare(alphaBean2, alphaBean1); assertTrue("Comparator did not sort properly. Result:" + result, result == 1); } /** * tests comparing two beans via their name using the default Comparator where they have the same value. */ public void testCompareIdentical() { alphaBean1 = new AlphaBean("alphabean"); alphaBean2 = new AlphaBean("alphabean"); BeanComparator beanComparator = new BeanComparator( "name"); int result = beanComparator.compare(alphaBean1, alphaBean2); assertTrue("Comparator did not sort properly. Result:" + result, result == 0); } /** * tests comparing one bean against itself. */ public void testCompareBeanAgainstSelf() { BeanComparator beanComparator = new BeanComparator( "name"); int result = beanComparator.compare(alphaBean1, alphaBean1); assertTrue("Comparator did not sort properly. Result:" + result, result == 0); } /** * tests comparing two beans via their name using the default Comparator, but with one of the beans * being null. */ public void testCompareWithNulls() { try { BeanComparator beanComparator = new BeanComparator("name"); beanComparator.compare(alphaBean2, null); fail("Should not be able to compare a null value."); } catch (Exception e) { // expected result } } /** * tests comparing two beans who don't have a property */ public void testCompareOnMissingProperty() { try { BeanComparator beanComparator = new BeanComparator("bogusName"); beanComparator.compare(alphaBean2, alphaBean1); fail("should not be able to compare"); } catch (Exception e) { assertTrue("Wrong exception was thrown: " + e, e.toString().indexOf("Unknown property") > -1); } } /** * tests comparing two beans on a boolean property, which is not possible. */ public void testCompareOnBooleanProperty() { try { TestBean testBeanA = new TestBean(); TestBean testBeanB = new TestBean(); testBeanA.setBooleanProperty(true); testBeanB.setBooleanProperty(false); BeanComparator beanComparator = new BeanComparator("booleanProperty"); beanComparator.compare(testBeanA, testBeanB); // **** java.lang.Boolean implements Comparable from JDK 1.5 onwards // so this test no longer fails // fail("BeanComparator should throw an exception when comparing two booleans."); } catch (ClassCastException cce){ // Expected result } } /** * tests comparing two beans on a boolean property, then changing the property and testing */ public void testSetProperty() { TestBean testBeanA = new TestBean(); TestBean testBeanB = new TestBean(); testBeanA.setDoubleProperty(5.5); testBeanB.setDoubleProperty(1.0); BeanComparator beanComparator = new BeanComparator( "doubleProperty"); int result = beanComparator.compare(testBeanA, testBeanB); assertTrue("Comparator did not sort properly. Result:" + result, result == 1); testBeanA.setStringProperty("string 1"); testBeanB.setStringProperty("string 2"); beanComparator.setProperty("stringProperty"); result = beanComparator.compare(testBeanA, testBeanB); assertTrue("Comparator did not sort properly. Result:" + result, result == -1); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanificationTestCase.java100644 0 0 44321 12262570610 30314 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.logging.LogFactory; /** *

          * Test Case for changes made during Beanutils Beanification *

          * * @version $Id: BeanificationTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class BeanificationTestCase extends TestCase { // ---------------------------------------------------- Constants /** Maximum number of iterations before our test fails */ public static final int MAX_GC_ITERATIONS = 50; // ---------------------------------------------------- Instance Variables // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public BeanificationTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { ConvertUtils.deregister(); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(BeanificationTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { // No action required } // ------------------------------------------------ Individual Test Methods /** Test of the methodology we'll use for some of the later tests */ public void testMemoryTestMethodology() throws Exception { // test methodology // many thanks to Juozas Baliuka for suggesting this method ClassLoader loader = new ClassLoader(this.getClass().getClassLoader()) {}; WeakReference reference = new WeakReference(loader); @SuppressWarnings("unused") Class myClass = loader.loadClass("org.apache.commons.beanutils.BetaBean"); assertNotNull("Weak reference released early", reference.get()); // dereference class loader and class: loader = null; myClass = null; int iterations = 0; int bytz = 2; while(true) { System.gc(); if(iterations++ > MAX_GC_ITERATIONS){ fail("Max iterations reached before resource released."); } if( reference.get() == null ) { break; } else { // create garbage: @SuppressWarnings("unused") byte[] b = new byte[bytz]; bytz = bytz * 2; } } } /** Tests whether classloaders and beans are released from memory by the map used by beanutils */ public void testMemoryLeak2() throws Exception { // tests when the map used by beanutils has the right behaviour if (BeanUtilsTestCase.isPre14JVM()) { System.out.println("WARNING: CANNOT TEST MEMORY LEAK ON PRE1.4 JVM"); return; } // many thanks to Juozas Baliuka for suggesting this methodology TestClassLoader loader = new TestClassLoader(); ReferenceQueue queue = new ReferenceQueue(); WeakReference loaderReference = new WeakReference(loader, queue); Integer test = new Integer(1); WeakReference testReference = new WeakReference(test, queue); //Map map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.HARD, true); Map map = new WeakHashMap(); map.put(loader, test); assertEquals("In map", test, map.get(loader)); assertNotNull("Weak reference released early (1)", loaderReference.get()); assertNotNull("Weak reference released early (2)", testReference.get()); // dereference strong references loader = null; test = null; int iterations = 0; int bytz = 2; while(true) { System.gc(); if(iterations++ > MAX_GC_ITERATIONS){ fail("Max iterations reached before resource released."); } map.isEmpty(); if( loaderReference.get() == null && testReference.get() == null) { break; } else { // create garbage: @SuppressWarnings("unused") byte[] b = new byte[bytz]; bytz = bytz * 2; } } } /** Tests whether classloaders and beans are released from memory */ public void testMemoryLeak() throws Exception { if (BeanUtilsTestCase.isPre14JVM()) { System.out.println("WARNING: CANNOT TEST MEMORY LEAK ON PRE1.4 JVM"); return; } // many thanks to Juozas Baliuka for suggesting this methodology TestClassLoader loader = new TestClassLoader(); WeakReference loaderReference = new WeakReference(loader); BeanUtilsBean.getInstance(); class GetBeanUtilsBeanThread extends Thread { BeanUtilsBean beanUtils; ConvertUtilsBean convertUtils; PropertyUtilsBean propertyUtils; GetBeanUtilsBeanThread() {} @Override public void run() { beanUtils = BeanUtilsBean.getInstance(); convertUtils = ConvertUtilsBean.getInstance(); propertyUtils = PropertyUtilsBean.getInstance(); // XXX Log keeps a reference around! LogFactory.releaseAll(); } @Override public String toString() { return "GetBeanUtilsBeanThread"; } } GetBeanUtilsBeanThread thread = new GetBeanUtilsBeanThread(); @SuppressWarnings("unused") WeakReference threadWeakReference = new WeakReference(thread); thread.setContextClassLoader(loader); thread.start(); thread.join(); WeakReference beanUtilsReference = new WeakReference(thread.beanUtils); WeakReference propertyUtilsReference = new WeakReference(thread.propertyUtils); WeakReference convertUtilsReference = new WeakReference(thread.convertUtils); assertNotNull("Weak reference released early (1)", loaderReference.get()); assertNotNull("Weak reference released early (2)", beanUtilsReference.get()); assertNotNull("Weak reference released early (3)", propertyUtilsReference.get()); assertNotNull("Weak reference released early (4)", convertUtilsReference.get()); // dereference strong references loader = null; thread.setContextClassLoader(null); thread = null; int iterations = 0; int bytz = 2; while(true) { BeanUtilsBean.getInstance(); System.gc(); if(iterations++ > MAX_GC_ITERATIONS){ fail("Max iterations reached before resource released."); } if( loaderReference.get() == null && beanUtilsReference.get() == null && propertyUtilsReference.get() == null && convertUtilsReference.get() == null) { break; } else { // create garbage: @SuppressWarnings("unused") byte[] b = new byte[bytz]; bytz = bytz * 2; } } } /** * Tests whether difference instances are loaded by different * context classloaders. */ public void testGetByContextClassLoader() throws Exception { class GetBeanUtilsBeanThread extends Thread { private final Signal signal; GetBeanUtilsBeanThread(Signal signal) { this.signal = signal; } @Override public void run() { signal.setSignal(2); signal.setBean(BeanUtilsBean.getInstance()); signal.setConvertUtils(ConvertUtilsBean.getInstance()); signal.setPropertyUtils(PropertyUtilsBean.getInstance()); } @Override public String toString() { return "GetBeanUtilsBeanThread"; } } Signal signal = new Signal(); signal.setSignal(1); GetBeanUtilsBeanThread thread = new GetBeanUtilsBeanThread(signal); thread.setContextClassLoader(new TestClassLoader()); thread.start(); thread.join(); assertEquals("Signal not set by test thread", 2, signal.getSignal()); assertTrue( "Different BeanUtilsBean instances per context classloader", BeanUtilsBean.getInstance() != signal.getBean()); assertTrue( "Different ConvertUtilsBean instances per context classloader", ConvertUtilsBean.getInstance() != signal.getConvertUtils()); assertTrue( "Different PropertyUtilsBean instances per context classloader", PropertyUtilsBean.getInstance() != signal.getPropertyUtils()); } /** * Tests whether difference instances are loaded by different * context classloaders. */ public void testContextClassLoaderLocal() throws Exception { class CCLLTesterThread extends Thread { private final Signal signal; private final ContextClassLoaderLocal ccll; CCLLTesterThread(Signal signal, ContextClassLoaderLocal ccll) { this.signal = signal; this.ccll = ccll; } @Override public void run() { ccll.set(new Integer(1789)); signal.setSignal(2); signal.setMarkerObject(ccll.get()); } @Override public String toString() { return "CCLLTesterThread"; } } ContextClassLoaderLocal ccll = new ContextClassLoaderLocal(); ccll.set(new Integer(1776)); assertEquals("Start thread sets value", new Integer(1776), ccll.get()); Signal signal = new Signal(); signal.setSignal(1); CCLLTesterThread thread = new CCLLTesterThread(signal, ccll); thread.setContextClassLoader(new TestClassLoader()); thread.start(); thread.join(); assertEquals("Signal not set by test thread", 2, signal.getSignal()); assertEquals("Second thread preserves value", new Integer(1776), ccll.get()); assertEquals("Second thread gets value it set", new Integer(1789), signal.getMarkerObject()); } /** Tests whether calls are independent for different classloaders */ public void testContextClassloaderIndependence() throws Exception { class TestIndependenceThread extends Thread { private final Signal signal; private final PrimitiveBean bean; TestIndependenceThread(Signal signal, PrimitiveBean bean) { this.signal = signal; this.bean = bean; } @Override public void run() { try { signal.setSignal(3); ConvertUtils.register(new Converter() { public T convert(Class type, Object value) { return ConvertUtils.primitiveToWrapper(type).cast(new Integer(9)); } }, Integer.TYPE); BeanUtils.setProperty(bean, "int", new Integer(1)); } catch (Exception e) { e.printStackTrace(); signal.setException(e); } } @Override public String toString() { return "TestIndependenceThread"; } } PrimitiveBean bean = new PrimitiveBean(); BeanUtils.setProperty(bean, "int", new Integer(1)); assertEquals("Wrong property value (1)", 1, bean.getInt()); ConvertUtils.register(new Converter() { public T convert(Class type, Object value) { return ConvertUtils.primitiveToWrapper(type).cast(new Integer(5)); } }, Integer.TYPE); BeanUtils.setProperty(bean, "int", new Integer(1)); assertEquals("Wrong property value(2)", 5, bean.getInt()); Signal signal = new Signal(); signal.setSignal(1); TestIndependenceThread thread = new TestIndependenceThread(signal, bean); thread.setContextClassLoader(new TestClassLoader()); thread.start(); thread.join(); assertNull("Exception thrown by test thread:" + signal.getException(), signal.getException()); assertEquals("Signal not set by test thread", 3, signal.getSignal()); assertEquals("Wrong property value(3)", 9, bean.getInt()); } /** Tests whether different threads can set beanutils instances correctly */ public void testBeanUtilsBeanSetInstance() throws Exception { class SetInstanceTesterThread extends Thread { private final Signal signal; private final BeanUtilsBean bean; SetInstanceTesterThread(Signal signal, BeanUtilsBean bean) { this.signal = signal; this.bean = bean; } @Override public void run() { BeanUtilsBean.setInstance(bean); signal.setSignal(21); signal.setBean(BeanUtilsBean.getInstance()); } @Override public String toString() { return "SetInstanceTesterThread"; } } Signal signal = new Signal(); signal.setSignal(1); BeanUtilsBean beanOne = new BeanUtilsBean(); BeanUtilsBean beanTwo = new BeanUtilsBean(); SetInstanceTesterThread thread = new SetInstanceTesterThread(signal, beanTwo); thread.setContextClassLoader(new TestClassLoader()); BeanUtilsBean.setInstance(beanOne); assertEquals("Start thread gets right instance", beanOne, BeanUtilsBean.getInstance()); thread.start(); thread.join(); assertEquals("Signal not set by test thread", 21, signal.getSignal()); assertEquals("Second thread preserves value", beanOne, BeanUtilsBean.getInstance()); assertEquals("Second thread gets value it set", beanTwo, signal.getBean()); } /** Tests whether the unset method works*/ public void testContextClassLoaderUnset() throws Exception { BeanUtilsBean beanOne = new BeanUtilsBean(); ContextClassLoaderLocal ccll = new ContextClassLoaderLocal(); ccll.set(beanOne); assertEquals("Start thread gets right instance", beanOne, ccll.get()); ccll.unset(); assertTrue("Unset works", !beanOne.equals(ccll.get())); } // ---- Auxillary classes class TestClassLoader extends ClassLoader { @Override public String toString() { return "TestClassLoader"; } } class Signal { private Exception e; private int signal = 0; private BeanUtilsBean bean; private PropertyUtilsBean propertyUtils; private ConvertUtilsBean convertUtils; private Object marker; public Exception getException() { return e; } public void setException(Exception e) { this.e = e; } public int getSignal() { return signal; } public void setSignal(int signal) { this.signal = signal; } public Object getMarkerObject() { return marker; } public void setMarkerObject(Object marker) { this.marker = marker; } public BeanUtilsBean getBean() { return bean; } public void setBean(BeanUtilsBean bean) { this.bean = bean; } public PropertyUtilsBean getPropertyUtils() { return propertyUtils; } public void setPropertyUtils(PropertyUtilsBean propertyUtils) { this.propertyUtils = propertyUtils; } public ConvertUtilsBean getConvertUtils() { return convertUtils; } public void setConvertUtils(ConvertUtilsBean convertUtils) { this.convertUtils = convertUtils; } } } ././@LongLink100644 0 0 152 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanIntrospectionDataTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanIntrospectionDataTestCase100644 0 0 11157 12262570610 31062 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * Test class for {@code BeanIntrospectionData}. * * @version $Id: BeanIntrospectionDataTestCase.java 1555233 2014-01-03 19:41:04Z oheger $ */ public class BeanIntrospectionDataTestCase extends TestCase { /** Constant for the test bean class. */ private static final Class BEAN_CLASS = FluentIntrospectionTestBean.class; /** Constant for the name of the test property. */ private static final String TEST_PROP = "fluentGetProperty"; /** * Creates an array with property descriptors for the test bean class. * * @return the array with property descriptors */ private static PropertyDescriptor[] fetchDescriptors() { PropertyUtilsBean pub = new PropertyUtilsBean(); pub.addBeanIntrospector(new FluentPropertyBeanIntrospector()); return pub.getPropertyDescriptors(BEAN_CLASS); } /** * Creates a test instance which is initialized with default property descriptors. * * @return the test instance */ private static BeanIntrospectionData setUpData() { return new BeanIntrospectionData(fetchDescriptors()); } /** * Returns the property descriptor for the test property. * * @param bid the data object * @return the test property descriptor */ private static PropertyDescriptor fetchTestDescriptor(BeanIntrospectionData bid) { return bid.getDescriptor(TEST_PROP); } /** * Tests whether a write method can be queried if it is defined in the descriptor. */ public void testGetWriteMethodDefined() { BeanIntrospectionData data = setUpData(); PropertyDescriptor pd = fetchTestDescriptor(data); assertNotNull("No write method", pd.getWriteMethod()); assertEquals("Wrong write method", pd.getWriteMethod(), data.getWriteMethod(BEAN_CLASS, pd)); } /** * Tests whether a write method can be queried that is currently not available in the * property descriptor. */ public void testGetWriteMethodUndefined() throws Exception { BeanIntrospectionData data = setUpData(); PropertyDescriptor pd = fetchTestDescriptor(data); Method writeMethod = pd.getWriteMethod(); pd.setWriteMethod(null); assertEquals("Wrong write method", writeMethod, data.getWriteMethod(BEAN_CLASS, pd)); assertEquals("Method not set in descriptor", writeMethod, pd.getWriteMethod()); } /** * Tests getWriteMethod() if the method cannot be resolved. (This is a corner case * which should normally not happen in practice.) */ public void testGetWriteMethodNonExisting() throws Exception { PropertyDescriptor pd = new PropertyDescriptor(TEST_PROP, BEAN_CLASS.getMethod("getFluentGetProperty"), BEAN_CLASS.getMethod( "setFluentGetProperty", String.class)); Map methods = new HashMap(); methods.put(TEST_PROP, "hashCode"); BeanIntrospectionData data = new BeanIntrospectionData( new PropertyDescriptor[] { pd }, methods); pd.setWriteMethod(null); assertNull("Got a write method", data.getWriteMethod(BEAN_CLASS, pd)); } /** * Tests getWriteMethod() for a property for which no write method is known. */ public void testGetWriteMethodUnknown() { BeanIntrospectionData data = setUpData(); PropertyDescriptor pd = data.getDescriptor("class"); assertNull("Got a write method", data.getWriteMethod(BEAN_CLASS, pd)); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanMapTestCase.java100644 0 0 51131 12262570607 27067 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.beanutils.bugs.other.Jira87BeanFactory; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.map.AbstractTestMap; /** * Test cases for BeanMap * * @version $Id: BeanMapTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ @SuppressWarnings("deprecation") public class BeanMapTestCase extends AbstractTestMap { public BeanMapTestCase(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(BeanMapTestCase.class); } /* note to self. The getter and setter methods were generated by copying the field declarations and using the following regular expression search and replace: From: private \(.*\) some\(.*\); To: public \1 getSome\2Value() { return some\2; } public void setSome\2Value(\1 value) { some\2 = value; } Also note: The sample keys and mappings were generated manually. */ public static class BeanWithProperties implements Serializable { private int someInt; private long someLong; private double someDouble; private float someFloat; private short someShort; private byte someByte; private char someChar; private Integer someInteger; private String someString; private Object someObject; public int getSomeIntValue() { return someInt; } public void setSomeIntValue(int value) { someInt = value; } public long getSomeLongValue() { return someLong; } public void setSomeLongValue(long value) { someLong = value; } public double getSomeDoubleValue() { return someDouble; } public void setSomeDoubleValue(double value) { someDouble = value; } public float getSomeFloatValue() { return someFloat; } public void setSomeFloatValue(float value) { someFloat = value; } public short getSomeShortValue() { return someShort; } public void setSomeShortValue(short value) { someShort = value; } public byte getSomeByteValue() { return someByte; } public void setSomeByteValue(byte value) { someByte = value; } public char getSomeCharValue() { return someChar; } public void setSomeCharValue(char value) { someChar = value; } public String getSomeStringValue() { return someString; } public void setSomeStringValue(String value) { someString = value; } public Integer getSomeIntegerValue() { return someInteger; } public void setSomeIntegerValue(Integer value) { someInteger = value; } public Object getSomeObjectValue() { return someObject; } public void setSomeObjectValue(Object value) { someObject = value; } } public static class BeanThrowingExceptions extends BeanWithProperties { private static final long serialVersionUID = 1L; public void setValueThrowingException(String value) { throw new TestException(); } public String getValueThrowingException() { throw new TestException(); } } /** * Exception for testing exception handling. */ public static class TestException extends RuntimeException { private static final long serialVersionUID = 1L; } // note to self. The Sample keys were generated by copying the field // declarations and using the following regular expression search and replace: // // From: // private \(.*\) some\(.*\); // To: // "some\2Value", // // Then, I manually added the "class" key, which is a property that exists for // all beans (and all objects for that matter. @Override public Object[] getSampleKeys() { Object[] keys = new Object[] { "someIntValue", "someLongValue", "someDoubleValue", "someFloatValue", "someShortValue", "someByteValue", "someCharValue", "someIntegerValue", "someStringValue", "someObjectValue", "class", }; return keys; } /** * An object value that will be stored in the bean map as a value. Need * to save this externally so that we can make sure the object instances * are equivalent since getSampleValues() would otherwise construct a new * and different Object each time. **/ private final Object objectInFullMap = new Object(); // note to self: the sample values were created manually @Override public Object[] getSampleValues() { Object[] values = new Object[] { new Integer(1234), new Long(1298341928234L), new Double(123423.34), new Float(1213332.12f), new Short((short)134), new Byte((byte)10), new Character('a'), new Integer(1432), "SomeStringValue", objectInFullMap, BeanWithProperties.class, }; return values; } @Override public Object[] getNewSampleValues() { Object[] values = new Object[] { new Integer(223), new Long(23341928234L), new Double(23423.34), new Float(213332.12f), new Short((short)234), new Byte((byte)20), new Character('b'), new Integer(232), "SomeNewStringValue", new Object(), null, }; return values; } /** * Values is a dead copy in BeanMap, so refresh each time. */ @Override public void verifyValues() { values = map.values(); super.verifyValues(); } /** * The mappings in a BeanMap are fixed on the properties the underlying * bean has. Adding and removing mappings is not possible, thus this * method is overridden to return false. */ @Override public boolean isPutAddSupported() { return false; } /** * The mappings in a BeanMap are fixed on the properties the underlying * bean has. Adding and removing mappings is not possible, thus this * method is overridden to return false. */ @Override public boolean isRemoveSupported() { return false; } @Override public Map makeFullMap() { // note: These values must match (i.e. .equals() must return true) // those returned from getSampleValues(). BeanWithProperties bean = new BeanWithProperties(); bean.setSomeIntValue(1234); bean.setSomeLongValue(1298341928234L); bean.setSomeDoubleValue(123423.34); bean.setSomeFloatValue(1213332.12f); bean.setSomeShortValue((short)134); bean.setSomeByteValue((byte)10); bean.setSomeCharValue('a'); bean.setSomeIntegerValue(new Integer(1432)); bean.setSomeStringValue("SomeStringValue"); bean.setSomeObjectValue(objectInFullMap); return new BeanMap(bean); } @Override public Map makeEmptyMap() { return new BeanMap(); } @Override public String[] ignoredTests() { // Ignore the serialization tests on collection views. return new String[] { "TestBeanMap.bulkTestMapEntrySet.testCanonicalEmptyCollectionExists", "TestBeanMap.bulkTestMapEntrySet.testCanonicalFullCollectionExists", "TestBeanMap.bulkTestMapKeySet.testCanonicalEmptyCollectionExists", "TestBeanMap.bulkTestMapKeySet.testCanonicalFullCollectionExists", "TestBeanMap.bulkTestMapValues.testCanonicalEmptyCollectionExists", "TestBeanMap.bulkTestMapValues.testCanonicalFullCollectionExists", "TestBeanMap.bulkTestMapEntrySet.testSimpleSerialization", "TestBeanMap.bulkTestMapKeySet.testSimpleSerialization", "TestBeanMap.bulkTestMapEntrySet.testSerializeDeserializeThenCompare", "TestBeanMap.bulkTestMapKeySet.testSerializeDeserializeThenCompare" }; } /** * Need to override this method because the "clear()" method on the bean * map just returns the bean properties to their default states. It does * not actually remove the mappings as per the map contract. The default * testClear() methods checks that the clear method throws an * UnsupportedOperationException since this class is not add/remove * modifiable. In our case though, we do not always throw that exception. */ @Override public void testMapClear() { //TODO: make sure a call to BeanMap.clear returns the bean to its //default initialization values. } /** * Need to override this method because the "put()" method on the bean * doesn't work for this type of Map. */ @Override public void testMapPut() { // see testBeanMapPutAllWriteable } public void testBeanMapClone() { BeanMap map = (BeanMap)makeFullMap(); try { BeanMap map2 = (BeanMap)map.clone(); // make sure containsKey is working to verify the bean was cloned // ok, and the read methods were properly initialized Object[] keys = getSampleKeys(); for(int i = 0; i < keys.length; i++) { assertTrue("Cloned BeanMap should contain the same keys", map2.containsKey(keys[i])); } } catch (CloneNotSupportedException exception) { fail("BeanMap.clone() should not throw a " + "CloneNotSupportedException when clone should succeed."); } } public void testBeanMapPutAllWriteable() { BeanMap map1 = (BeanMap)makeFullMap(); BeanMap map2 = (BeanMap)makeFullMap(); map2.put("someIntValue", new Integer(0)); map1.putAllWriteable(map2); assertEquals(map1.get("someIntValue"), new Integer(0)); } public void testMethodAccessor() throws Exception { BeanMap map = (BeanMap) makeFullMap(); Method method = BeanWithProperties.class.getDeclaredMethod("getSomeIntegerValue"); assertEquals(method, map.getReadMethod("someIntegerValue")); } public void testMethodMutator() throws Exception { BeanMap map = (BeanMap) makeFullMap(); Method method = BeanWithProperties.class.getDeclaredMethod("setSomeIntegerValue", new Class[] {Integer.class}); assertEquals(method, map.getWriteMethod("someIntegerValue")); } /** * Test the default transformers using the getTypeTransformer() method */ public void testGetTypeTransformerMethod() { BeanMap beanMap = new BeanMap(); assertEquals("Boolean.TYPE", Boolean.TRUE, beanMap.getTypeTransformer(Boolean.TYPE).transform("true")); assertEquals("Character.TYPE", new Character('B'), beanMap.getTypeTransformer(Character.TYPE).transform("BCD")); assertEquals("Byte.TYPE", new Byte((byte)1), beanMap.getTypeTransformer(Byte.TYPE).transform("1")); assertEquals("Short.TYPE", new Short((short)2), beanMap.getTypeTransformer(Short.TYPE).transform("2")); assertEquals("Integer.TYPE", new Integer(3), beanMap.getTypeTransformer(Integer.TYPE).transform("3")); assertEquals("Long.TYPE", new Long(4), beanMap.getTypeTransformer(Long.TYPE).transform("4")); assertEquals("Float.TYPE", new Float("5"), beanMap.getTypeTransformer(Float.TYPE).transform("5")); assertEquals("Double.TYPE", new Double("6"), beanMap.getTypeTransformer(Double.TYPE).transform("6")); } /** * Test the default transformers via the public static Map instance */ public void testGetDefaultTransformersMap() { assertEquals("Boolean.TYPE", Boolean.TRUE, ((Transformer)BeanMap.defaultTransformers.get(Boolean.TYPE)).transform("true")); assertEquals("Character.TYPE", new Character('B'), ((Transformer)BeanMap.defaultTransformers.get(Character.TYPE)).transform("BCD")); assertEquals("Byte.TYPE", new Byte((byte)1), ((Transformer)BeanMap.defaultTransformers.get(Byte.TYPE)).transform("1")); assertEquals("Short.TYPE", new Short((short)2), ((Transformer)BeanMap.defaultTransformers.get(Short.TYPE)).transform("2")); assertEquals("Integer.TYPE", new Integer(3), ((Transformer)BeanMap.defaultTransformers.get(Integer.TYPE)).transform("3")); assertEquals("Long.TYPE", new Long(4), ((Transformer)BeanMap.defaultTransformers.get(Long.TYPE)).transform("4")); assertEquals("Float.TYPE", new Float("5"), ((Transformer)BeanMap.defaultTransformers.get(Float.TYPE)).transform("5")); assertEquals("Double.TYPE", new Double("6"), ((Transformer)BeanMap.defaultTransformers.get(Double.TYPE)).transform("6")); } /** * Test the default transformers HashMap */ public void testDefaultTransformersMap() { assertEquals("Size", 8, BeanMap.defaultTransformers.size()); assertEquals("entrySet", 8, BeanMap.defaultTransformers.entrySet().size()); assertEquals("keySet", 8, BeanMap.defaultTransformers.keySet().size()); assertEquals("values", 8, BeanMap.defaultTransformers.values().size()); assertFalse("isEmpty", BeanMap.defaultTransformers.isEmpty()); assertTrue("containsKey(Double)", BeanMap.defaultTransformers.containsKey(Double.TYPE)); assertFalse("containsKey(Object)", BeanMap.defaultTransformers.containsKey(Object.class)); assertTrue("containsValue(double)", BeanMap.defaultTransformers.containsValue(BeanMap.defaultTransformers.get(Double.TYPE))); assertFalse("containsValue(Object)", BeanMap.defaultTransformers.containsValue(Object.class)); try { BeanMap.defaultTransformers.clear(); fail("clear() - expected UnsupportedOperationException"); } catch(UnsupportedOperationException e) { // expected result } try { BeanMap.defaultTransformers.put("FOO", null); fail("put() - expected UnsupportedOperationException"); } catch(UnsupportedOperationException e) { // expected result } try { BeanMap.defaultTransformers.putAll(new HashMap()); fail("putAll() - expected UnsupportedOperationException"); } catch(UnsupportedOperationException e) { // expected result } try { BeanMap.defaultTransformers.remove("FOO"); fail("remove() - expected UnsupportedOperationException"); } catch(UnsupportedOperationException e) { // expected result } } /** * Test that the cause of exception thrown by a clone() is initialised. */ public void testExceptionThrowFromClone() { if (BeanUtilsTestCase.isPre14JVM()) { System.out.println("testExceptionThrowFromClone() skipped on pre 1.4 JVM"); return; } // Test cloning a non-public bean (instantiation exception) try { Object bean = Jira87BeanFactory.createMappedPropertyBean(); BeanMap map = new BeanMap(bean); map.clone(); fail("Non-public bean clone() - expected CloneNotSupportedException"); } catch (CloneNotSupportedException e) { Throwable cause = null; try { cause = (Throwable)PropertyUtils.getProperty(e, "cause"); } catch (Exception e2) { fail("Non-public bean - retrieving the cause threw " + e2); } assertNotNull("Non-public bean cause null", cause); assertEquals("Non-public bean cause", IllegalAccessException.class, cause.getClass()); } // Test cloning a bean that throws exception try { BeanMap map = new BeanMap(new BeanThrowingExceptions()); map.clone(); fail("Setter Exception clone() - expected CloneNotSupportedException"); } catch (CloneNotSupportedException e) { Throwable cause = null; try { cause = (Throwable)PropertyUtils.getProperty(e, "cause"); } catch (Exception e2) { fail("Setter Exception - retrieving the cause threw " + e2); } assertNotNull("Setter Exception cause null", cause); assertEquals("Setter Exception cause", IllegalArgumentException.class, cause.getClass()); } } /** * Test that the cause of exception thrown by clear() is initialised. */ public void testExceptionThrowFromClear() { if (BeanUtilsTestCase.isPre14JVM()) { System.out.println("testExceptionThrowFromClear() skipped on pre 1.4 JVM"); return; } try { Object bean = Jira87BeanFactory.createMappedPropertyBean(); BeanMap map = new BeanMap(bean); map.clear(); fail("clear() - expected UnsupportedOperationException"); } catch (UnsupportedOperationException e) { Throwable cause = null; try { cause = (Throwable)PropertyUtils.getProperty(e, "cause"); } catch (Exception e2) { fail("Retrieving the cause threw " + e2); } assertNotNull("Cause null", cause); assertEquals("Cause", IllegalAccessException.class, cause.getClass()); } } /** * Test that the cause of exception thrown by put() is initialized. */ public void testExceptionThrowFromPut() { if (BeanUtilsTestCase.isPre14JVM()) { System.out.println("testExceptionThrowFromPut() skipped on pre 1.4 JVM"); return; } try { Map map = new BeanMap(new BeanThrowingExceptions()); map.put("valueThrowingException", "value"); fail("Setter exception - expected IllegalArgumentException"); } catch (IllegalArgumentException e) { Throwable cause1 = null; Throwable cause2 = null; try { cause1 = (Throwable)PropertyUtils.getProperty(e, "cause"); cause2 = (Throwable)PropertyUtils.getProperty(e, "cause.cause"); } catch (Exception e2) { fail("Setter exception - retrieving the cause threw " + e2); } assertNotNull("Setter exception cause 1 null", cause1); assertEquals("Setter exception cause 1", InvocationTargetException.class, cause1.getClass()); assertNotNull("Setter exception cause 2 null", cause2); assertEquals("Setter exception cause 2", TestException.class, cause2.getClass()); } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanPredicateTestCase.java100644 0 0 5015 12262570607 30232 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import junit.framework.TestCase; import org.apache.commons.collections.functors.EqualPredicate; import org.apache.commons.collections.functors.InstanceofPredicate; import org.apache.commons.collections.functors.NotPredicate; import org.apache.commons.collections.functors.NullPredicate; /** * @version $Id: BeanPredicateTestCase.java 1454597 2013-03-08 21:58:12Z britter $ */ public class BeanPredicateTestCase extends TestCase { public BeanPredicateTestCase(String name) { super(name); } public void testEqual() { BeanPredicate predicate = new BeanPredicate("stringProperty",new EqualPredicate("foo")); assertTrue(predicate.evaluate(new TestBean("foo"))); assertTrue(!predicate.evaluate(new TestBean("bar"))); } public void testNotEqual() { BeanPredicate predicate = new BeanPredicate("stringProperty",new NotPredicate( new EqualPredicate("foo"))); assertTrue(!predicate.evaluate(new TestBean("foo"))); assertTrue(predicate.evaluate(new TestBean("bar"))); } public void testInstanceOf() { BeanPredicate predicate = new BeanPredicate("stringProperty",new InstanceofPredicate( String.class )); assertTrue(predicate.evaluate(new TestBean("foo"))); assertTrue(predicate.evaluate(new TestBean("bar"))); } public void testNull() { BeanPredicate predicate = new BeanPredicate("stringProperty", NullPredicate.INSTANCE); String nullString = null; assertTrue(predicate.evaluate(new TestBean(nullString))); assertTrue(!predicate.evaluate(new TestBean("bar"))); } } ././@LongLink100644 0 0 163 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanPropertyValueChangeClosureTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanPropertyValueChangeClosur100644 0 0 30472 12262570610 31114 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import junit.framework.TestCase; /** * Test cases for BeanPropertyValueChangeClosure. * * @version $Id: BeanPropertyValueChangeClosureTestCase.java 1454597 2013-03-08 21:58:12Z britter $ */ public class BeanPropertyValueChangeClosureTestCase extends TestCase { private static final Integer expectedIntegerValue = new Integer(123); private static final Float expectedFloatValue = new Float(123.123f); private static final Double expectedDoubleValue = new Double(567879.12344d); private static final Boolean expectedBooleanValue = Boolean.TRUE; private static final Byte expectedByteValue = new Byte("12"); /** * Constructor for BeanPropertyValueChangeClosureTest. * * @param name Name of this test case. */ public BeanPropertyValueChangeClosureTestCase(String name) { super(name); } /** * Test execute with simple float property and Float value. */ public void testExecuteWithSimpleFloatPropertyAndFloatValue() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("floatProperty", expectedFloatValue).execute(testBean); assertTrue(expectedFloatValue.floatValue() == testBean.getFloatProperty()); } /** * Test execute with simple float property and String value. */ public void testExecuteWithSimpleFloatPropertyAndStringValue() { try { new BeanPropertyValueChangeClosure("floatProperty", "123").execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with simple float property and Double value. */ public void testExecuteWithSimpleFloatPropertyAndDoubleValue() { try { new BeanPropertyValueChangeClosure("floatProperty", expectedDoubleValue).execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with simple float property and Integer value. */ public void testExecuteWithSimpleFloatPropertyAndIntegerValue() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("floatProperty", expectedIntegerValue).execute(testBean); assertTrue(expectedIntegerValue.floatValue() == testBean.getFloatProperty()); } /** * Test execute with simple double property and Double value. */ public void testExecuteWithSimpleDoublePropertyAndDoubleValue() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("doubleProperty", expectedDoubleValue).execute(testBean); assertTrue(expectedDoubleValue.doubleValue() == testBean.getDoubleProperty()); } /** * Test execute with simple double property and String value. */ public void testExecuteWithSimpleDoublePropertyAndStringValue() { try { new BeanPropertyValueChangeClosure("doubleProperty", "123").execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with simple double property and Float value. */ public void testExecuteWithSimpleDoublePropertyAndFloatValue() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("doubleProperty", expectedFloatValue).execute(testBean); assertTrue(expectedFloatValue.doubleValue() == testBean.getDoubleProperty()); } /** * Test execute with simple double property and Integer value. */ public void testExecuteWithSimpleDoublePropertyAndIntegerValue() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("doubleProperty", expectedIntegerValue).execute(testBean); assertTrue(expectedIntegerValue.doubleValue() == testBean.getDoubleProperty()); } /** * Test execute with simple int property and Double value. */ public void testExecuteWithSimpleIntPropertyAndDoubleValue() { try { new BeanPropertyValueChangeClosure("intProperty", expectedDoubleValue).execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with simple int property and String value. */ public void testExecuteWithSimpleIntPropertyAndStringValue() { try { new BeanPropertyValueChangeClosure("intProperty", "123").execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with simple int property and Float value. */ public void testExecuteWithSimpleIntPropertyAndFloatValue() { try { new BeanPropertyValueChangeClosure("intProperty", expectedFloatValue).execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with simple int property and Integer value. */ public void testExecuteWithSimpleIntPropertyAndIntegerValue() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("intProperty", expectedIntegerValue).execute(testBean); assertTrue(expectedIntegerValue.intValue() == testBean.getIntProperty()); } /** * Test execute with simple boolean property and Boolean value. */ public void testExecuteWithSimpleBooleanPropertyAndBooleanValue() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("booleanProperty", expectedBooleanValue).execute(testBean); assertTrue(expectedBooleanValue.booleanValue() == testBean.getBooleanProperty()); } /** * Test execute with simple boolean property and String value. */ public void testExecuteWithSimpleBooleanPropertyAndStringValue() { try { new BeanPropertyValueChangeClosure("booleanProperty", "true").execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with simple byte property and Byte value. */ public void testExecuteWithSimpleBytePropertyAndByteValue() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("byteProperty", expectedByteValue).execute(testBean); assertTrue(expectedByteValue.byteValue() == testBean.getByteProperty()); } /** * Test execute with simple boolean property and String value. */ public void testExecuteWithSimpleBytePropertyAndStringValue() { try { new BeanPropertyValueChangeClosure("byteProperty", "foo").execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with simple primitive property and null value. */ public void testExecuteWithSimplePrimitivePropertyAndNullValue() { try { new BeanPropertyValueChangeClosure("intProperty", null).execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with read only property. */ public void testExecuteWithReadOnlyProperty() { try { new BeanPropertyValueChangeClosure("readOnlyProperty", "foo").execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with write only property. */ public void testExecuteWithWriteOnlyProperty() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("writeOnlyProperty", "foo").execute(testBean); assertEquals("foo", testBean.getWriteOnlyPropertyValue()); } /** * Test execute with a nested property. */ public void testExecuteWithNestedProperty() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("nested.stringProperty", "bar").execute(testBean); assertEquals("bar", testBean.getNested().getStringProperty()); } /** * Test execute with a nested property and null in the property path. */ public void testExecuteWithNullInPropertyPath() { try { new BeanPropertyValueChangeClosure("anotherNested.stringProperty", "foo").execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } /** * Test execute with a nested property and null in the property path and ignoreNull = true. */ public void testExecuteWithNullInPropertyPathAngIgnoreTrue() { TestBean testBean = new TestBean(); // create a closure that will attempt to set a property on the null bean in the path BeanPropertyValueChangeClosure closure = new BeanPropertyValueChangeClosure("anotherNested.stringProperty", "Should ignore exception", true); try { closure.execute(testBean); } catch (IllegalArgumentException e) { fail("Should have ignored the exception."); } } /** * Test execute with indexed property. */ public void testExecuteWithIndexedProperty() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("intIndexed[0]", expectedIntegerValue).execute(testBean); assertTrue(expectedIntegerValue.intValue() == testBean.getIntIndexed(0)); } /** * Test execute with mapped property. */ public void testExecuteWithMappedProperty() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("mappedProperty(fred)", "barney").execute(testBean); assertEquals("barney", testBean.getMappedProperty("fred")); } /** * Test execute with a simple String property. */ public void testExecuteWithSimpleStringProperty() { TestBean testBean = new TestBean(); new BeanPropertyValueChangeClosure("stringProperty", "barney").execute(testBean); assertEquals("barney", testBean.getStringProperty()); } /** * Test execute with an invalid property name. */ public void testExecuteWithInvalidPropertyName() { try { new BeanPropertyValueChangeClosure("bogusProperty", "foo").execute(new TestBean()); fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException e) { /* this is what we expect */ } } } ././@LongLink100644 0 0 165 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanPropertyValueEqualsPredicateTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanPropertyValueEqualsPredic100644 0 0 24636 12262570607 31133 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import junit.framework.TestCase; /** * Test cases for BeanPropertyValueEqualsPredicateTest. * * @version $Id: BeanPropertyValueEqualsPredicateTestCase.java 1454597 2013-03-08 21:58:12Z britter $ */ public class BeanPropertyValueEqualsPredicateTestCase extends TestCase { private static final Integer expectedIntegerValue = new Integer(123); private static final Float expectedFloatValue = new Float(123.123f); private static final Double expectedDoubleValue = new Double(567879.12344d); private static final Boolean expectedBooleanValue = Boolean.TRUE; private static final Byte expectedByteValue = new Byte("12"); /** * Constructor for BeanPropertyValueEqualsPredicateTest. * * @param name Name of this test case. */ public BeanPropertyValueEqualsPredicateTestCase(String name) { super(name); } /** * Test evaluate with simple String property. */ public void testEvaluateWithSimpleStringProperty() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("stringProperty","foo"); assertTrue(predicate.evaluate(new TestBean("foo"))); assertTrue(!predicate.evaluate(new TestBean("bar"))); } /** * Test evaluate with simple String property and null values. */ public void testEvaluateWithSimpleStringPropertyWithNullValues() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("stringProperty",null); assertTrue(predicate.evaluate(new TestBean((String) null))); assertTrue(!predicate.evaluate(new TestBean("bar"))); } /** * Test evaluate with nested property. */ public void testEvaluateWithNestedProperty() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("anotherNested.stringProperty","match"); TestBean testBean = new TestBean(); TestBean nestedBean = new TestBean("match"); testBean.setAnotherNested(nestedBean); assertTrue(predicate.evaluate(testBean)); testBean.setAnotherNested(new TestBean("no-match")); assertTrue(!predicate.evaluate(testBean)); } /** * Test evaluate with null in property path and ignore=false. */ public void testEvaluateWithNullInPath() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("anotherNested.stringProperty","foo"); try { // try to evaluate the predicate predicate.evaluate(new TestBean()); fail("Should have throw IllegalArgumentException"); } catch (IllegalArgumentException e) { /* ignore this is what should happen */ } } /** * Test evaluate with null in property path and ignore=true. */ public void testEvaluateWithNullInPathAndIgnoreTrue() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("anotherNested.stringProperty","foo", true); try { assertTrue(!predicate.evaluate(new TestBean())); } catch (IllegalArgumentException e) { fail("Should not have throw IllegalArgumentException"); } } /** * Test evaluate with int property. */ public void testEvaluateWithIntProperty() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("intProperty",expectedIntegerValue); assertTrue(predicate.evaluate(new TestBean(expectedIntegerValue.intValue()))); assertTrue(!predicate.evaluate(new TestBean(expectedIntegerValue.intValue() - 1))); } /** * Test evaluate with float property. */ public void testEvaluateWithFloatProperty() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("floatProperty",expectedFloatValue); assertTrue(predicate.evaluate(new TestBean(expectedFloatValue.floatValue()))); assertTrue(!predicate.evaluate(new TestBean(expectedFloatValue.floatValue() - 1))); } /** * Test evaluate with double property. */ public void testEvaluateWithDoubleProperty() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("doubleProperty",expectedDoubleValue); assertTrue(predicate.evaluate(new TestBean(expectedDoubleValue.doubleValue()))); assertTrue(!predicate.evaluate(new TestBean(expectedDoubleValue.doubleValue() - 1))); } /** * Test evaluate with boolean property. */ public void testEvaluateWithBooleanProperty() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("booleanProperty",expectedBooleanValue); assertTrue(predicate.evaluate(new TestBean(expectedBooleanValue.booleanValue()))); assertTrue(!predicate.evaluate(new TestBean(!expectedBooleanValue.booleanValue()))); } /** * Test evaluate with byte property. */ public void testEvaluateWithByteProperty() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("byteProperty",expectedByteValue); TestBean testBean = new TestBean(); testBean.setByteProperty(expectedByteValue.byteValue()); assertTrue(predicate.evaluate(testBean)); testBean.setByteProperty((byte) (expectedByteValue.byteValue() - 1)); assertTrue(!predicate.evaluate(testBean)); } /** * Test evaluate with mapped property. */ public void testEvaluateWithMappedProperty() { // try a key that is in the map BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("mappedProperty(test-key)","match"); TestBean testBean = new TestBean(); testBean.setMappedProperty("test-key", "match"); assertTrue(predicate.evaluate(testBean)); testBean.setMappedProperty("test-key", "no-match"); assertTrue(!predicate.evaluate(testBean)); // try a key that isn't in the map predicate = new BeanPropertyValueEqualsPredicate("mappedProperty(invalid-key)", "match"); assertTrue(!predicate.evaluate(testBean)); } /** * Test evaluate with indexed property. */ public void testEvaluateWithIndexedProperty() { // try a valid index BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("intIndexed[0]",expectedIntegerValue); TestBean testBean = new TestBean(); testBean.setIntIndexed(0, expectedIntegerValue.intValue()); assertTrue(predicate.evaluate(testBean)); testBean.setIntIndexed(0, expectedIntegerValue.intValue() - 1); assertTrue(!predicate.evaluate(testBean)); // try an invalid index predicate = new BeanPropertyValueEqualsPredicate("intIndexed[999]", "exception-ahead"); try { assertTrue(!predicate.evaluate(testBean)); } catch (ArrayIndexOutOfBoundsException e) { /* this is what should happen */ } } /** * Test evaluate with primitive property and null value. */ public void testEvaluateWithPrimitiveAndNull() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("intProperty",null); assertTrue(!predicate.evaluate(new TestBean(0))); predicate = new BeanPropertyValueEqualsPredicate("booleanProperty", null); assertTrue(!predicate.evaluate(new TestBean(true))); predicate = new BeanPropertyValueEqualsPredicate("floatProperty", null); assertTrue(!predicate.evaluate(new TestBean(expectedFloatValue.floatValue()))); } /** * Test evaluate with nested mapped property. */ public void testEvaluateWithNestedMappedProperty() { BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("anotherNested.mappedProperty(test-key)","match"); TestBean testBean = new TestBean(); TestBean nestedBean = new TestBean(); nestedBean.setMappedProperty("test-key", "match"); testBean.setAnotherNested(nestedBean); assertTrue(predicate.evaluate(testBean)); nestedBean.setMappedProperty("test-key", "no-match"); assertTrue(!predicate.evaluate(testBean)); } /** * Test evaluate with write only property. */ public void testEvaluateWithWriteOnlyProperty() { try { new BeanPropertyValueEqualsPredicate("writeOnlyProperty", null).evaluate(new TestBean()); } catch (IllegalArgumentException e) { /* This is what should happen */ } } /** * Test evaluate with read only property. */ public void testEvaluateWithReadOnlyProperty() { TestBean testBean = new TestBean(); BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("readOnlyProperty",testBean.getReadOnlyProperty()); assertTrue(predicate.evaluate(new TestBean())); } /** * Test evaluate with an invalid property name. */ public void testEvaluateWithInvalidPropertyName() { try { new BeanPropertyValueEqualsPredicate("bogusProperty", null).evaluate(new TestBean()); } catch (IllegalArgumentException e) { /* This is what should happen */ } } }././@LongLink100644 0 0 163 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanToPropertyValueTransformerTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanToPropertyValueTransforme100644 0 0 22526 12262570610 31163 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import junit.framework.TestCase; /** * Test cases for BeanToPropertyValueTransformer. * * @version $Id: BeanToPropertyValueTransformerTestCase.java 1454597 2013-03-08 21:58:12Z britter $ */ public class BeanToPropertyValueTransformerTestCase extends TestCase { private static final Integer expectedIntegerValue = new Integer(123); private static final Long expectedLongValue = new Long(123); private static final Float expectedFloatValue = new Float(123.123f); private static final Double expectedDoubleValue = new Double(567879.12344d); private static final Boolean expectedBooleanValue = Boolean.TRUE; private static final Byte expectedByteValue = new Byte("12"); /** * Constructor for BeanToPropertyValueTransformerTestCase. * * @param name Name of this test case. */ public BeanToPropertyValueTransformerTestCase(String name) { super(name); } /** * Test transform with simple String property. */ public void testTransformWithSimpleStringProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("stringProperty"); TestBean testBean = new TestBean("foo"); assertEquals("foo", transformer.transform(testBean)); } /** * Test transform with simple String property and null value. * */ public void testTransformWithSimpleStringPropertyAndNullValue() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("stringProperty"); TestBean testBean = new TestBean((String) null); assertNull(transformer.transform(testBean)); } /** * Test transform with simple int property. */ public void testTransformWithSimpleIntProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("intProperty"); TestBean testBean = new TestBean(expectedIntegerValue.intValue()); assertEquals(expectedIntegerValue, transformer.transform(testBean)); } /** * Test transform with simple long property. */ public void testTransformWithSimpleLongProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("longProperty"); TestBean testBean = new TestBean(); testBean.setLongProperty(expectedLongValue.longValue()); assertEquals(expectedLongValue, transformer.transform(testBean)); } /** * Test transform with simple float property. */ public void testTransformWithSimpleFloatProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("floatProperty"); TestBean testBean = new TestBean(expectedFloatValue.floatValue()); assertEquals(expectedFloatValue, transformer.transform(testBean)); } /** * Test transform with simple double property. */ public void testTransformWithSimpleDoubleProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("doubleProperty"); TestBean testBean = new TestBean(expectedDoubleValue.doubleValue()); assertEquals(expectedDoubleValue, transformer.transform(testBean)); } /** * Test transform with simple byte property. */ public void testTransformWithSimpleByteProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("byteProperty"); TestBean testBean = new TestBean(); testBean.setByteProperty(expectedByteValue.byteValue()); assertEquals(expectedByteValue, transformer.transform(testBean)); } /** * Test transform with simple boolean property. */ public void testTransformWithSimpleBooleanProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("booleanProperty"); TestBean testBean = new TestBean(expectedBooleanValue.booleanValue()); assertEquals(expectedBooleanValue, transformer.transform(testBean)); } /** * Test transform with write only property. */ public void testTransformWithWriteOnlyProperty() { try { new BeanToPropertyValueTransformer("writeOnlyProperty").transform(new TestBean()); } catch (IllegalArgumentException e) { /* This is what should happen */ } } /** * Test transform with read only property. */ public void testTransformWithReadOnlyProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("readOnlyProperty"); TestBean testBean = new TestBean(); assertEquals(testBean.getReadOnlyProperty(), transformer.transform(testBean)); } /** * Test transform with invalid property. */ public void testTransformWithInvalidProperty() { try { new BeanToPropertyValueTransformer("bogusProperty").transform(new TestBean()); } catch (IllegalArgumentException e) { /* This is what should happen */ } } /** * Test transform with nested property. */ public void testTransformWithNestedProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("anotherNested.stringProperty"); TestBean testBean = new TestBean(); TestBean nestedBean = new TestBean("foo"); testBean.setAnotherNested(nestedBean); assertEquals("foo", transformer.transform(testBean)); } /** * Test transform with mapped property. */ public void testTransformWithMappedProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("mappedProperty(test-key)"); TestBean testBean = new TestBean(); // try a valid key testBean.setMappedProperty("test-key", "test-value"); assertEquals("test-value", transformer.transform(testBean)); // now try an invalid key transformer = new BeanToPropertyValueTransformer("mappedProperty(bogus-key)"); assertEquals(null, transformer.transform(testBean)); } /** * Test transform with indexed property. */ public void testTransformWithIndexedProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("intIndexed[0]"); TestBean testBean = new TestBean(); testBean.setIntIndexed(0, expectedIntegerValue.intValue()); assertEquals(expectedIntegerValue, transformer.transform(testBean)); // test index out of range transformer = new BeanToPropertyValueTransformer("intIndexed[9999]"); try { transformer.transform(testBean); fail("Should have thrown an ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException e) { /* this is what should happen */ } } /** * Test transform with nested indexed property. */ public void testTransformWithNestedIndexedProperty() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("anotherNested.intIndexed[0]"); TestBean testBean = new TestBean(); TestBean nestedBean = new TestBean(); nestedBean.setIntIndexed(0, expectedIntegerValue.intValue()); testBean.setAnotherNested(nestedBean); assertEquals(expectedIntegerValue, transformer.transform(testBean)); } /** * Test transform with null in property path. */ public void testTransformWithNullInPath() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("anotherNested.stringProperty"); try { transformer.transform(new TestBean()); fail("Should have throw IllegalArgumentException"); } catch (IllegalArgumentException e) { /* ignore this is what should happen */ } } /** * Test transform with null in property path and ignore = true. */ public void testTransformWithNullInPathAndIgnoreTrue() { BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("anotherNested.stringProperty",true); assertEquals(null, transformer.transform(new TestBean())); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanUtils2TestCase.java100644 0 0 15226 12262570610 27533 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import junit.framework.Test; import junit.framework.TestSuite; /** * Test Case for the {@link BeanUtilsBean2}. * * @version $Id: BeanUtils2TestCase.java 1454606 2013-03-08 22:30:51Z britter $ */ public class BeanUtils2TestCase extends BeanUtilsTestCase { // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public BeanUtils2TestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { ConvertUtils.deregister(); BeanUtilsBean.setInstance(new BeanUtilsBean2()); setUpShared(); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(BeanUtils2TestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { bean = null; } /** * Test copyProperty() converting to a String. */ @Override public void testCopyPropertyConvertToString() { try { BeanUtils.copyProperty(bean, "stringProperty", testUtilDate); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date --> String", testStringDate, bean.getStringProperty()); } /** * Test copyProperty() converting to a String. */ @Override public void testCopyPropertyConvertToStringArray() { try { bean.setStringArray(null); BeanUtils.copyProperty(bean, "stringArray", new java.util.Date[] {testUtilDate}); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date[] --> String[] length", 1, bean.getStringArray().length); assertEquals("java.util.Date[] --> String[] value ", testStringDate, bean.getStringArray()[0]); } /** * Test copyProperty() converting to a String on indexed property */ @Override public void testCopyPropertyConvertToStringIndexed() { try { bean.setStringArray(new String[1]); BeanUtils.copyProperty(bean, "stringArray[0]", testUtilDate); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date[] --> String[] length", 1, bean.getStringArray().length); assertEquals("java.util.Date[] --> String[] value ", testStringDate, bean.getStringArray()[0]); } /** * Test getArrayProperty() converting to a String. */ @Override public void testGetArrayPropertyDate() { String[] value = null; try { bean.setDateArrayProperty(new java.util.Date[] {testUtilDate}); value = BeanUtils.getArrayProperty(bean, "dateArrayProperty"); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date[] --> String[] length", 1, value.length); assertEquals("java.util.Date[] --> String[] value ", testStringDate, value[0]); } /** * Test getArrayProperty() converting to a String. */ @Override public void testGetIndexedPropertyDate() { String value = null; try { bean.setDateArrayProperty(new java.util.Date[] {testUtilDate}); value = BeanUtils.getIndexedProperty(bean, "dateArrayProperty[0]"); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date[0] --> String", testStringDate, value); } /** * Test getSimpleProperty() converting to a String. */ @Override public void testGetSimplePropertyDate() { String value = null; try { bean.setDateProperty(testUtilDate); value = BeanUtils.getSimpleProperty(bean, "dateProperty"); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date --> String", testStringDate, value); } /** * Test setProperty() converting to a String. */ @Override public void testSetPropertyConvertToString() { try { BeanUtils.setProperty(bean, "stringProperty", testUtilDate); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date --> String", testStringDate, bean.getStringProperty()); } /** * Test setProperty() converting to a String array. */ @Override public void testSetPropertyConvertToStringArray() { try { bean.setStringArray(null); BeanUtils.setProperty(bean, "stringArray", new java.util.Date[] {testUtilDate}); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date[] --> String[] length", 1, bean.getStringArray().length); assertEquals("java.util.Date[] --> String[] value ", testStringDate, bean.getStringArray()[0]); } /** * Test setProperty() converting to a String on indexed property */ @Override public void testSetPropertyConvertToStringIndexed() { try { bean.setStringArray(new String[1]); BeanUtils.setProperty(bean, "stringArray[0]", testUtilDate); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date --> String[]", testStringDate, bean.getStringArray()[0]); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanUtilsBenchCase.java100644 0 0 30002 12262570610 27536 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * JUnit Test Case containing microbenchmarks for BeanUtils. * * @version $Id: BeanUtilsBenchCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class BeanUtilsBenchCase extends TestCase { // ------------------------------------------------------------ Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public BeanUtilsBenchCase(String name) { super(name); } // ------------------------------------------------------ Instance Variables // Basic loop counter private long counter = 100000; // DynaClass for inDyna and outDyna private DynaClass dynaClass = null; // Input objects that have identical sets of properties and values. private BenchBean inBean = null; private DynaBean inDyna = null; private Map inMap = null; // Map of Objects requiring no conversion private Map inStrs = null; // Map of Strings requiring conversion // Output objects that have identical sets of properties. private BenchBean outBean = null; private DynaBean outDyna = null; // BeanUtilsBean instance to be used private BeanUtilsBean bu = null; // ---------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { // Set up loop counter (if property specified) String prop = System.getProperty("counter"); if (prop != null) { counter = Long.parseLong(prop); } // Set up DynaClass for our DynaBean instances dynaClass = new BasicDynaClass ("BenchDynaClass", null, new DynaProperty[]{ new DynaProperty("booleanProperty", Boolean.TYPE), new DynaProperty("byteProperty", Byte.TYPE), new DynaProperty("doubleProperty", Double.TYPE), new DynaProperty("floatProperty", Float.TYPE), new DynaProperty("intProperty", Integer.TYPE), new DynaProperty("longProperty", Long.TYPE), new DynaProperty("shortProperty", Short.TYPE), new DynaProperty("stringProperty", String.class), }); // Create input instances inBean = new BenchBean(); inMap = new HashMap(); inMap.put("booleanProperty", new Boolean(inBean.getBooleanProperty())); inMap.put("byteProperty", new Byte(inBean.getByteProperty())); inMap.put("doubleProperty", new Double(inBean.getDoubleProperty())); inMap.put("floatProperty", new Float(inBean.getFloatProperty())); inMap.put("intProperty", new Integer(inBean.getIntProperty())); inMap.put("longProperty", new Long(inBean.getLongProperty())); inMap.put("shortProperty", new Short(inBean.getShortProperty())); inMap.put("stringProperty", inBean.getStringProperty()); inDyna = dynaClass.newInstance(); Iterator inKeys = inMap.keySet().iterator(); while (inKeys.hasNext()) { String inKey = inKeys.next(); inDyna.set(inKey, inMap.get(inKey)); } inStrs = new HashMap(); inKeys = inMap.keySet().iterator(); while (inKeys.hasNext()) { String inKey = inKeys.next(); inStrs.put(inKey, inMap.get(inKey).toString()); } // Create output instances outBean = new BenchBean(); outDyna = dynaClass.newInstance(); Iterator outKeys = inMap.keySet().iterator(); while (outKeys.hasNext()) { String outKey = outKeys.next(); outDyna.set(outKey, inMap.get(outKey)); } // Set up BeanUtilsBean instance we will use bu = BeanUtilsBean.getInstance(); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(BeanUtilsBenchCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { dynaClass = null; inBean = null; inDyna = null; inMap = null; outBean = null; outDyna = null; bu = null; } // ------------------------------------------------- Individual Test Methods // Time copyProperties() from a bean public void testCopyPropertiesBean() throws Exception { long start; long stop; // Bean->Bean for (long i = 0; i < counter; i++) { bu.copyProperties(outBean, inBean); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.copyProperties(outBean, inBean); } stop = System.currentTimeMillis(); System.err.println("BU.copyProperties(bean,bean), count=" + counter + ", time=" + (stop - start)); // Bean->Dyna for (long i = 0; i < counter; i++) { bu.copyProperties(outDyna, inBean); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.copyProperties(outDyna, inBean); } stop = System.currentTimeMillis(); System.err.println("BU.copyProperties(dyna,bean), count=" + counter + ", time=" + (stop - start)); } // Time copyProperties() from a DynaBean public void testCopyPropertiesDyna() throws Exception { long start; long stop; // Dyna->Bean for (long i = 0; i < counter; i++) { bu.copyProperties(outBean, inDyna); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.copyProperties(outBean, inDyna); } stop = System.currentTimeMillis(); System.err.println("BU.copyProperties(bean,dyna), count=" + counter + ", time=" + (stop - start)); // Dyna->Dyna for (long i = 0; i < counter; i++) { bu.copyProperties(outDyna, inDyna); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.copyProperties(outDyna, inDyna); } stop = System.currentTimeMillis(); System.err.println("BU.copyProperties(dyna,dyna), count=" + counter + ", time=" + (stop - start)); } // Time copyProperties() from a Map of Objects public void testCopyPropertiesMap() throws Exception { long start; long stop; // Map->Bean for (long i = 0; i < counter; i++) { bu.copyProperties(outBean, inMap); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.copyProperties(outBean, inMap); } stop = System.currentTimeMillis(); System.err.println("BU.copyProperties(bean, map), count=" + counter + ", time=" + (stop - start)); // Map->Dyna for (long i = 0; i < counter; i++) { bu.copyProperties(outDyna, inMap); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.copyProperties(outDyna, inMap); } stop = System.currentTimeMillis(); System.err.println("BU.copyProperties(dyna, map), count=" + counter + ", time=" + (stop - start)); } // Time copyProperties() from a Map of Strings public void testCopyPropertiesStrs() throws Exception { long start; long stop; // Strs->Bean for (long i = 0; i < counter; i++) { bu.copyProperties(outBean, inStrs); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.copyProperties(outBean, inStrs); } stop = System.currentTimeMillis(); System.err.println("BU.copyProperties(bean,strs), count=" + counter + ", time=" + (stop - start)); // Strs->Dyna for (long i = 0; i < counter; i++) { bu.copyProperties(outDyna, inStrs); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.copyProperties(outDyna, inStrs); } stop = System.currentTimeMillis(); System.err.println("BU.copyProperties(dyna,strs), count=" + counter + ", time=" + (stop - start)); } // Time populate() from a Map of Objects public void testPopulateMap() throws Exception { long start; long stop; // Map->Bean for (long i = 0; i < counter; i++) { bu.populate(outBean, inMap); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.populate(outBean, inMap); } stop = System.currentTimeMillis(); System.err.println("BU.populate(bean, map), count=" + counter + ", time=" + (stop - start)); // Map->Dyna for (long i = 0; i < counter; i++) { bu.populate(outDyna, inMap); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.populate(outDyna, inMap); } stop = System.currentTimeMillis(); System.err.println("BU.populate(dyna, map), count=" + counter + ", time=" + (stop - start)); } // Time populate() from a Map of Strings // NOTE - This simulates what Struts does when processing form beans public void testPopulateStrs() throws Exception { long start; long stop; // Strs->Bean for (long i = 0; i < counter; i++) { bu.populate(outBean, inStrs); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.populate(outBean, inStrs); } stop = System.currentTimeMillis(); System.err.println("BU.populate(bean,strs), count=" + counter + ", time=" + (stop - start)); // Strs->Dyna for (long i = 0; i < counter; i++) { bu.populate(outDyna, inStrs); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { bu.populate(outDyna, inStrs); } stop = System.currentTimeMillis(); System.err.println("BU.populate(dyna,strs), count=" + counter + ", time=" + (stop - start)); } // --------------------------------------------------------- Support Methods } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanUtilsTestCase.java100644 0 0 174662 12262570610 27503 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.InvocationTargetException; import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.converters.ArrayConverter; import org.apache.commons.beanutils.converters.DateConverter; /** *

          * Test Case for the BeanUtils class. The majority of these tests use * instances of the TestBean class, so be sure to update the tests if you * change the characteristics of that class. *

          * *

          * Template for this stolen from Craigs PropertyUtilsTestCase *

          * *

          * Note that the tests are dependant upon the static aspects * (such as array sizes...) of the TestBean.java class, so ensure * than all changes to TestBean are reflected here. *

          * *

          * So far, this test case has tests for the following methods of the * BeanUtils class: *

          *
            *
          • getArrayProperty(Object bean, String name)
          • *
          * * @version $Id: BeanUtilsTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class BeanUtilsTestCase extends TestCase { // ---------------------------------------------------- Instance Variables /** * The test bean for each test. */ protected TestBean bean = null; /** * The set of properties that should be described. */ protected String describes[] = { "booleanProperty", "booleanSecond", "byteProperty", "doubleProperty", "dupProperty", "floatProperty", "intArray", // "intIndexed", "longProperty", "listIndexed", "longProperty", // "mappedProperty", // "mappedIntProperty", "nested", "nullProperty", "readOnlyProperty", "shortProperty", "stringArray", // "stringIndexed", "stringProperty" }; /** Test Calendar value */ protected java.util.Calendar testCalendar; /** Test java.util.Date value */ protected java.util.Date testUtilDate; /** Test String Date value */ protected String testStringDate; // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public BeanUtilsTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { ConvertUtils.deregister(); BeanUtilsBean.setInstance(new BeanUtilsBean()); setUpShared(); } /** * Shared Set up. */ protected void setUpShared() { bean = new TestBean(); DateConverter dateConverter = new DateConverter(null); dateConverter.setLocale(Locale.US); dateConverter.setPattern("dd.MM.yyyy"); ConvertUtils.register(dateConverter, java.util.Date.class); ArrayConverter dateArrayConverter = new ArrayConverter(java.util.Date[].class, dateConverter, 0); ConvertUtils.register(dateArrayConverter, java.util.Date[].class); testCalendar = Calendar.getInstance(); testCalendar.set(1992, 11, 28, 0, 0, 0); testCalendar.set(Calendar.MILLISECOND, 0); testUtilDate = testCalendar.getTime(); testStringDate = "28.12.1992"; } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(BeanUtilsTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { bean = null; } // ------------------------------------------------ Individual Test Methods /** * Test the copyProperties() method from a DynaBean. */ public void testCopyPropertiesDynaBean() { // Set up an origin bean with customized properties DynaClass dynaClass = DynaBeanUtilsTestCase.createDynaClass(); DynaBean orig = null; try { orig = dynaClass.newInstance(); } catch (Exception e) { fail("newInstance(): " + e); } orig.set("booleanProperty", Boolean.FALSE); orig.set("byteProperty", new Byte((byte) 111)); orig.set("doubleProperty", new Double(333.33)); orig.set("dupProperty", new String[] { "New 0", "New 1", "New 2" }); orig.set("intArray", new int[] { 100, 200, 300 }); orig.set("intProperty", new Integer(333)); orig.set("longProperty", new Long(3333)); orig.set("shortProperty", new Short((short) 33)); orig.set("stringArray", new String[] { "New 0", "New 1" }); orig.set("stringProperty", "Custom string"); // Copy the origin bean to our destination test bean try { BeanUtils.copyProperties(bean, orig); } catch (Exception e) { fail("Threw exception: " + e); } // Validate the results for scalar properties assertEquals("Copied boolean property", false, bean.getBooleanProperty()); assertEquals("Copied byte property", (byte) 111, bean.getByteProperty()); assertEquals("Copied double property", 333.33, bean.getDoubleProperty(), 0.005); assertEquals("Copied int property", 333, bean.getIntProperty()); assertEquals("Copied long property", 3333, bean.getLongProperty()); assertEquals("Copied short property", (short) 33, bean.getShortProperty()); assertEquals("Copied string property", "Custom string", bean.getStringProperty()); // Validate the results for array properties String dupProperty[] = bean.getDupProperty(); assertNotNull("dupProperty present", dupProperty); assertEquals("dupProperty length", 3, dupProperty.length); assertEquals("dupProperty[0]", "New 0", dupProperty[0]); assertEquals("dupProperty[1]", "New 1", dupProperty[1]); assertEquals("dupProperty[2]", "New 2", dupProperty[2]); int intArray[] = bean.getIntArray(); assertNotNull("intArray present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 100, intArray[0]); assertEquals("intArray[1]", 200, intArray[1]); assertEquals("intArray[2]", 300, intArray[2]); String stringArray[] = bean.getStringArray(); assertNotNull("stringArray present", stringArray); assertEquals("stringArray length", 2, stringArray.length); assertEquals("stringArray[0]", "New 0", stringArray[0]); assertEquals("stringArray[1]", "New 1", stringArray[1]); } /** * Test copyProperties() when the origin is a a Map. */ public void testCopyPropertiesMap() { Map map = new HashMap(); map.put("booleanProperty", "false"); map.put("byteProperty", "111"); map.put("doubleProperty", "333.0"); map.put("dupProperty", new String[] { "New 0", "New 1", "New 2" }); map.put("floatProperty", "222.0"); map.put("intArray", new String[] { "0", "100", "200" }); map.put("intProperty", "111"); map.put("longProperty", "444"); map.put("shortProperty", "555"); map.put("stringProperty", "New String Property"); try { BeanUtils.copyProperties(bean, map); } catch (Throwable t) { fail("Threw " + t.toString()); } // Scalar properties assertEquals("booleanProperty", false, bean.getBooleanProperty()); assertEquals("byteProperty", (byte) 111, bean.getByteProperty()); assertEquals("doubleProperty", 333.0, bean.getDoubleProperty(), 0.005); assertEquals("floatProperty", (float) 222.0, bean.getFloatProperty(), (float) 0.005); assertEquals("longProperty", 111, bean.getIntProperty()); assertEquals("longProperty", 444, bean.getLongProperty()); assertEquals("shortProperty", (short) 555, bean.getShortProperty()); assertEquals("stringProperty", "New String Property", bean.getStringProperty()); // Indexed Properties String dupProperty[] = bean.getDupProperty(); assertNotNull("dupProperty present", dupProperty); assertEquals("dupProperty length", 3, dupProperty.length); assertEquals("dupProperty[0]", "New 0", dupProperty[0]); assertEquals("dupProperty[1]", "New 1", dupProperty[1]); assertEquals("dupProperty[2]", "New 2", dupProperty[2]); int intArray[] = bean.getIntArray(); assertNotNull("intArray present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 0, intArray[0]); assertEquals("intArray[1]", 100, intArray[1]); assertEquals("intArray[2]", 200, intArray[2]); } /** * Test the copyProperties() method from a standard JavaBean. */ public void testCopyPropertiesStandard() { // Set up an origin bean with customized properties TestBean orig = new TestBean(); orig.setBooleanProperty(false); orig.setByteProperty((byte) 111); orig.setDoubleProperty(333.33); orig.setDupProperty(new String[] { "New 0", "New 1", "New 2" }); orig.setIntArray(new int[] { 100, 200, 300 }); orig.setIntProperty(333); orig.setLongProperty(3333); orig.setShortProperty((short) 33); orig.setStringArray(new String[] { "New 0", "New 1" }); orig.setStringProperty("Custom string"); // Copy the origin bean to our destination test bean try { BeanUtils.copyProperties(bean, orig); } catch (Exception e) { fail("Threw exception: " + e); } // Validate the results for scalar properties assertEquals("Copied boolean property", false, bean.getBooleanProperty()); assertEquals("Copied byte property", (byte) 111, bean.getByteProperty()); assertEquals("Copied double property", 333.33, bean.getDoubleProperty(), 0.005); assertEquals("Copied int property", 333, bean.getIntProperty()); assertEquals("Copied long property", 3333, bean.getLongProperty()); assertEquals("Copied short property", (short) 33, bean.getShortProperty()); assertEquals("Copied string property", "Custom string", bean.getStringProperty()); // Validate the results for array properties String dupProperty[] = bean.getDupProperty(); assertNotNull("dupProperty present", dupProperty); assertEquals("dupProperty length", 3, dupProperty.length); assertEquals("dupProperty[0]", "New 0", dupProperty[0]); assertEquals("dupProperty[1]", "New 1", dupProperty[1]); assertEquals("dupProperty[2]", "New 2", dupProperty[2]); int intArray[] = bean.getIntArray(); assertNotNull("intArray present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 100, intArray[0]); assertEquals("intArray[1]", 200, intArray[1]); assertEquals("intArray[2]", 300, intArray[2]); String stringArray[] = bean.getStringArray(); assertNotNull("stringArray present", stringArray); assertEquals("stringArray length", 2, stringArray.length); assertEquals("stringArray[0]", "New 0", stringArray[0]); assertEquals("stringArray[1]", "New 1", stringArray[1]); } /** * Test the describe() method. */ public void testDescribe() { Map map = null; try { map = BeanUtils.describe(bean); } catch (Exception e) { fail("Threw exception " + e); } // Verify existence of all the properties that should be present for (int i = 0; i < describes.length; i++) { assertTrue("Property '" + describes[i] + "' is present", map.containsKey(describes[i])); } assertTrue("Property 'writeOnlyProperty' is not present", !map.containsKey("writeOnlyProperty")); // Verify the values of scalar properties assertEquals("Value of 'booleanProperty'", "true", map.get("booleanProperty")); assertEquals("Value of 'byteProperty'", "121", map.get("byteProperty")); assertEquals("Value of 'doubleProperty'", "321.0", map.get("doubleProperty")); assertEquals("Value of 'floatProperty'", "123.0", map.get("floatProperty")); assertEquals("Value of 'intProperty'", "123", map.get("intProperty")); assertEquals("Value of 'longProperty'", "321", map.get("longProperty")); assertEquals("Value of 'shortProperty'", "987", map.get("shortProperty")); assertEquals("Value of 'stringProperty'", "This is a string", map.get("stringProperty")); } /** * tests the string and int arrays of TestBean */ public void testGetArrayProperty() { try { String arr[] = BeanUtils.getArrayProperty(bean, "stringArray"); String comp[] = bean.getStringArray(); assertTrue("String array length = " + comp.length, (comp.length == arr.length)); arr = BeanUtils.getArrayProperty(bean, "intArray"); int iarr[] = bean.getIntArray(); assertTrue("String array length = " + iarr.length, (iarr.length == arr.length)); // Test property which isn't array or collection arr = BeanUtils.getArrayProperty(bean, "shortProperty"); String shortAsString = "" + bean.getShortProperty(); assertEquals("Short List Test lth", 1, arr.length); assertEquals("Short Test value", shortAsString, arr[0]); // Test comma delimited list bean.setStringProperty("ABC"); arr = BeanUtils.getArrayProperty(bean, "stringProperty"); assertEquals("Delimited List Test lth", 1, arr.length); assertEquals("Delimited List Test value1", "ABC", arr[0]); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getArrayProperty() converting to a String. */ public void testGetArrayPropertyDate() { String[] value = null; try { bean.setDateArrayProperty(new java.util.Date[] {testUtilDate}); value = BeanUtils.getArrayProperty(bean, "dateArrayProperty"); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date[] --> String[] length", 1, value.length); assertEquals("java.util.Date[] --> String[] value ", testUtilDate.toString(), value[0]); } /** * tests getting an indexed property */ public void testGetIndexedProperty1() { try { String val = BeanUtils.getIndexedProperty(bean, "intIndexed[3]"); String comp = String.valueOf(bean.getIntIndexed(3)); assertTrue("intIndexed[3] == " + comp, val.equals(comp)); val = BeanUtils.getIndexedProperty(bean, "stringIndexed[3]"); comp = bean.getStringIndexed(3); assertTrue("stringIndexed[3] == " + comp, val.equals(comp)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getArrayProperty() converting to a String. */ public void testGetIndexedPropertyDate() { String value = null; try { bean.setDateArrayProperty(new java.util.Date[] {testUtilDate}); value = BeanUtils.getIndexedProperty(bean, "dateArrayProperty[0]"); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date[0] --> String", testUtilDate.toString(), value); } /** * tests getting an indexed property */ public void testGetIndexedProperty2() { try { String val = BeanUtils.getIndexedProperty(bean, "intIndexed", 3); String comp = String.valueOf(bean.getIntIndexed(3)); assertTrue("intIndexed,3 == " + comp, val.equals(comp)); val = BeanUtils.getIndexedProperty(bean, "stringIndexed", 3); comp = bean.getStringIndexed(3); assertTrue("stringIndexed,3 == " + comp, val.equals(comp)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * tests getting a nested property */ public void testGetNestedProperty() { try { String val = BeanUtils.getNestedProperty(bean, "nested.stringProperty"); String comp = bean.getNested().getStringProperty(); assertTrue("nested.StringProperty == " + comp, val.equals(comp)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * tests getting a 'whatever' property */ public void testGetGeneralProperty() { try { String val = BeanUtils.getProperty(bean, "nested.intIndexed[2]"); String comp = String.valueOf(bean.getIntIndexed(2)); assertTrue("nested.intIndexed[2] == " + comp, val.equals(comp)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * tests getting a 'whatever' property */ public void testGetSimpleProperty() { try { String val = BeanUtils.getSimpleProperty(bean, "shortProperty"); String comp = String.valueOf(bean.getShortProperty()); assertTrue("shortProperty == " + comp, val.equals(comp)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty() converting to a String. */ public void testGetSimplePropertyDate() { String value = null; try { bean.setDateProperty(testUtilDate); value = BeanUtils.getSimpleProperty(bean, "dateProperty"); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date --> String", testUtilDate.toString(), value); } /** * Test populate() method on individual array elements. */ public void testPopulateArrayElements() { try { HashMap map = new HashMap(); map.put("intIndexed[0]", "100"); map.put("intIndexed[2]", "120"); map.put("intIndexed[4]", "140"); BeanUtils.populate(bean, map); assertEquals("intIndexed[0] is 100", 100, bean.getIntIndexed(0)); assertEquals("intIndexed[1] is 10", 10, bean.getIntIndexed(1)); assertEquals("intIndexed[2] is 120", 120, bean.getIntIndexed(2)); assertEquals("intIndexed[3] is 30", 30, bean.getIntIndexed(3)); assertEquals("intIndexed[4] is 140", 140, bean.getIntIndexed(4)); map.clear(); map.put("stringIndexed[1]", "New String 1"); map.put("stringIndexed[3]", "New String 3"); BeanUtils.populate(bean, map); assertEquals("stringIndexed[0] is \"String 0\"", "String 0", bean.getStringIndexed(0)); assertEquals("stringIndexed[1] is \"New String 1\"", "New String 1", bean.getStringIndexed(1)); assertEquals("stringIndexed[2] is \"String 2\"", "String 2", bean.getStringIndexed(2)); assertEquals("stringIndexed[3] is \"New String 3\"", "New String 3", bean.getStringIndexed(3)); assertEquals("stringIndexed[4] is \"String 4\"", "String 4", bean.getStringIndexed(4)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } } /** * Test populate() method on array properties as a whole. */ public void testPopulateArrayProperties() { try { HashMap map = new HashMap(); int intArray[] = new int[] { 123, 456, 789 }; map.put("intArray", intArray); String stringArray[] = new String[] { "New String 0", "New String 1" }; map.put("stringArray", stringArray); BeanUtils.populate(bean, map); intArray = bean.getIntArray(); assertNotNull("intArray is present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 123, intArray[0]); assertEquals("intArray[1]", 456, intArray[1]); assertEquals("intArray[2]", 789, intArray[2]); stringArray = bean.getStringArray(); assertNotNull("stringArray is present", stringArray); assertEquals("stringArray length", 2, stringArray.length); assertEquals("stringArray[0]", "New String 0", stringArray[0]); assertEquals("stringArray[1]", "New String 1", stringArray[1]); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } } /** * Test populate() on mapped properties. */ public void testPopulateMapped() { try { HashMap map = new HashMap(); map.put("mappedProperty(First Key)", "New First Value"); map.put("mappedProperty(Third Key)", "New Third Value"); BeanUtils.populate(bean, map); assertEquals("mappedProperty(First Key)", "New First Value", bean.getMappedProperty("First Key")); assertEquals("mappedProperty(Second Key)", "Second Value", bean.getMappedProperty("Second Key")); assertEquals("mappedProperty(Third Key)", "New Third Value", bean.getMappedProperty("Third Key")); assertNull("mappedProperty(Fourth Key", bean.getMappedProperty("Fourth Key")); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } } /** * Test populate() method on nested properties. */ public void testPopulateNested() { try { HashMap map = new HashMap(); map.put("nested.booleanProperty", "false"); // booleanSecond is left at true map.put("nested.doubleProperty", "432.0"); // floatProperty is left at 123.0 map.put("nested.intProperty", "543"); // longProperty is left at 321 map.put("nested.shortProperty", "654"); // stringProperty is left at "This is a string" map.put("nested.writeOnlyProperty", "New writeOnlyProperty value"); BeanUtils.populate(bean, map); assertTrue("booleanProperty is false", !bean.getNested().getBooleanProperty()); assertTrue("booleanSecond is true", bean.getNested().isBooleanSecond()); assertEquals("doubleProperty is 432.0", 432.0, bean.getNested().getDoubleProperty(), 0.005); assertEquals("floatProperty is 123.0", (float) 123.0, bean.getNested().getFloatProperty(), (float) 0.005); assertEquals("intProperty is 543", 543, bean.getNested().getIntProperty()); assertEquals("longProperty is 321", 321, bean.getNested().getLongProperty()); assertEquals("shortProperty is 654", (short) 654, bean.getNested().getShortProperty()); assertEquals("stringProperty is \"This is a string\"", "This is a string", bean.getNested().getStringProperty()); assertEquals("writeOnlyProperty is \"New writeOnlyProperty value\"", "New writeOnlyProperty value", bean.getNested().getWriteOnlyPropertyValue()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } } /** * Test populate() method on scalar properties. */ public void testPopulateScalar() { try { bean.setNullProperty("Non-null value"); HashMap map = new HashMap(); map.put("booleanProperty", "false"); // booleanSecond is left at true map.put("byteProperty", "111"); map.put("doubleProperty", "432.0"); // floatProperty is left at 123.0 map.put("intProperty", "543"); map.put("longProperty", ""); map.put("nullProperty", null); map.put("shortProperty", "654"); // stringProperty is left at "This is a string" map.put("writeOnlyProperty", "New writeOnlyProperty value"); map.put("readOnlyProperty", "New readOnlyProperty value"); BeanUtils.populate(bean, map); assertTrue("booleanProperty is false", !bean.getBooleanProperty()); assertTrue("booleanSecond is true", bean.isBooleanSecond()); assertEquals("byteProperty is 111", (byte) 111, bean.getByteProperty()); assertEquals("doubleProperty is 432.0", 432.0, bean.getDoubleProperty(), 0.005); assertEquals("floatProperty is 123.0", (float) 123.0, bean.getFloatProperty(), (float) 0.005); assertEquals("intProperty is 543", 543, bean.getIntProperty()); assertEquals("longProperty is 0", 0, bean.getLongProperty()); assertNull("nullProperty is null", bean.getNullProperty()); assertEquals("shortProperty is 654", (short) 654, bean.getShortProperty()); assertEquals("stringProperty is \"This is a string\"", "This is a string", bean.getStringProperty()); assertEquals("writeOnlyProperty is \"New writeOnlyProperty value\"", "New writeOnlyProperty value", bean.getWriteOnlyPropertyValue()); assertEquals("readOnlyProperty is \"Read Only String Property\"", "Read Only String Property", bean.getReadOnlyProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } } /** * Test calling setProperty() with null property values. */ public void testSetPropertyNullValues() throws Exception { Object oldValue = null; Object newValue = null; // Scalar value into array oldValue = PropertyUtils.getSimpleProperty(bean, "stringArray"); BeanUtils.setProperty(bean, "stringArray", (String) null); newValue = PropertyUtils.getSimpleProperty(bean, "stringArray"); assertNotNull("stringArray is not null", newValue); assertTrue("stringArray of correct type", newValue instanceof String[]); assertEquals("stringArray length", 1, ((String[]) newValue).length); PropertyUtils.setProperty(bean, "stringArray", oldValue); // Indexed value into array oldValue = PropertyUtils.getSimpleProperty(bean, "stringArray"); BeanUtils.setProperty(bean, "stringArray[2]", (String) null); newValue = PropertyUtils.getSimpleProperty(bean, "stringArray"); assertNotNull("stringArray is not null", newValue); assertTrue("stringArray of correct type", newValue instanceof String[]); assertEquals("stringArray length", 5, ((String[]) newValue).length); assertTrue("stringArray[2] is null", ((String[]) newValue)[2] == null); PropertyUtils.setProperty(bean, "stringArray", oldValue); // Value into scalar BeanUtils.setProperty(bean, "stringProperty", null); assertTrue("stringProperty is now null", BeanUtils.getProperty(bean, "stringProperty") == null); } /** * Test converting to and from primitive wrapper types. */ public void testSetPropertyOnPrimitiveWrappers() throws Exception { BeanUtils.setProperty(bean,"intProperty", new Integer(1)); assertEquals(1,bean.getIntProperty()); BeanUtils.setProperty(bean,"stringProperty", new Integer(1)); assertEquals(1, Integer.parseInt(bean.getStringProperty())); } /** * Test narrowing and widening conversions on byte. */ public void testSetPropertyByte() throws Exception { BeanUtils.setProperty(bean, "byteProperty", new Byte((byte) 123)); assertEquals((byte) 123, bean.getByteProperty()); /* BeanUtils.setProperty(bean, "byteProperty", new Double((double) 123)); assertEquals((byte) 123, bean.getByteProperty()); BeanUtils.setProperty(bean, "byteProperty", new Float((float) 123)); assertEquals((byte) 123, bean.getByteProperty()); */ BeanUtils.setProperty(bean, "byteProperty", new Integer(123)); assertEquals((byte) 123, bean.getByteProperty()); BeanUtils.setProperty(bean, "byteProperty", new Long(123)); assertEquals((byte) 123, bean.getByteProperty()); BeanUtils.setProperty(bean, "byteProperty", new Short((short) 123)); assertEquals((byte) 123, bean.getByteProperty()); } /** * Test setProperty() conversion. */ public void testSetPropertyConvert() { try { BeanUtils.setProperty(bean, "dateProperty", testCalendar); } catch (Throwable t) { fail("Threw " + t); } assertEquals("Calendar --> java.util.Date", testUtilDate, bean.getDateProperty()); } /** * Test setProperty() converting from a String. */ public void testSetPropertyConvertFromString() { try { BeanUtils.setProperty(bean, "dateProperty", testStringDate); } catch (Throwable t) { fail("Threw " + t); } assertEquals("String --> java.util.Date", testUtilDate, bean.getDateProperty()); } /** * Test setProperty() converting to a String. */ public void testSetPropertyConvertToString() { try { BeanUtils.setProperty(bean, "stringProperty", testUtilDate); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date --> String", testUtilDate.toString(), bean.getStringProperty()); } /** * Test setProperty() converting to a String array. */ public void testSetPropertyConvertToStringArray() { try { bean.setStringArray(null); BeanUtils.setProperty(bean, "stringArray", new java.util.Date[] {testUtilDate}); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date[] --> String[] length", 1, bean.getStringArray().length); assertEquals("java.util.Date[] --> String[] value ", testUtilDate.toString(), bean.getStringArray()[0]); } /** * Test setProperty() converting to a String on indexed property */ public void testSetPropertyConvertToStringIndexed() { try { bean.setStringArray(new String[1]); BeanUtils.setProperty(bean, "stringArray[0]", testUtilDate); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date --> String[]", testUtilDate.toString(), bean.getStringArray()[0]); } /** * Test narrowing and widening conversions on double. */ public void testSetPropertyDouble() throws Exception { BeanUtils.setProperty(bean, "doubleProperty", new Byte((byte) 123)); assertEquals(123, bean.getDoubleProperty(), 0.005); BeanUtils.setProperty(bean, "doubleProperty", new Double(123)); assertEquals(123, bean.getDoubleProperty(), 0.005); BeanUtils.setProperty(bean, "doubleProperty", new Float(123)); assertEquals(123, bean.getDoubleProperty(), 0.005); BeanUtils.setProperty(bean, "doubleProperty", new Integer(123)); assertEquals(123, bean.getDoubleProperty(), 0.005); BeanUtils.setProperty(bean, "doubleProperty", new Long(123)); assertEquals(123, bean.getDoubleProperty(), 0.005); BeanUtils.setProperty(bean, "doubleProperty", new Short((short) 123)); assertEquals(123, bean.getDoubleProperty(), 0.005); } /** * Test narrowing and widening conversions on float. */ public void testSetPropertyFloat() throws Exception { BeanUtils.setProperty(bean, "floatProperty", new Byte((byte) 123)); assertEquals(123, bean.getFloatProperty(), 0.005); BeanUtils.setProperty(bean, "floatProperty", new Double(123)); assertEquals(123, bean.getFloatProperty(), 0.005); BeanUtils.setProperty(bean, "floatProperty", new Float(123)); assertEquals(123, bean.getFloatProperty(), 0.005); BeanUtils.setProperty(bean, "floatProperty", new Integer(123)); assertEquals(123, bean.getFloatProperty(), 0.005); BeanUtils.setProperty(bean, "floatProperty", new Long(123)); assertEquals(123, bean.getFloatProperty(), 0.005); BeanUtils.setProperty(bean, "floatProperty", new Short((short) 123)); assertEquals(123, bean.getFloatProperty(), 0.005); } /** * Test narrowing and widening conversions on int. */ public void testSetPropertyInteger() throws Exception { BeanUtils.setProperty(bean, "longProperty", new Byte((byte) 123)); assertEquals(123, bean.getIntProperty()); /* BeanUtils.setProperty(bean, "longProperty", new Double((double) 123)); assertEquals((int) 123, bean.getIntProperty()); BeanUtils.setProperty(bean, "longProperty", new Float((float) 123)); assertEquals((int) 123, bean.getIntProperty()); */ BeanUtils.setProperty(bean, "longProperty", new Integer(123)); assertEquals(123, bean.getIntProperty()); BeanUtils.setProperty(bean, "longProperty", new Long(123)); assertEquals(123, bean.getIntProperty()); BeanUtils.setProperty(bean, "longProperty", new Short((short) 123)); assertEquals(123, bean.getIntProperty()); } /** * Test narrowing and widening conversions on long. */ public void testSetPropertyLong() throws Exception { BeanUtils.setProperty(bean, "longProperty", new Byte((byte) 123)); assertEquals(123, bean.getLongProperty()); /* BeanUtils.setProperty(bean, "longProperty", new Double((double) 123)); assertEquals((long) 123, bean.getLongProperty()); BeanUtils.setProperty(bean, "longProperty", new Float((float) 123)); assertEquals((long) 123, bean.getLongProperty()); */ BeanUtils.setProperty(bean, "longProperty", new Integer(123)); assertEquals(123, bean.getLongProperty()); BeanUtils.setProperty(bean, "longProperty", new Long(123)); assertEquals(123, bean.getLongProperty()); BeanUtils.setProperty(bean, "longProperty", new Short((short) 123)); assertEquals(123, bean.getLongProperty()); } /** * Test setting a null property value. */ public void testSetPropertyNull() throws Exception { bean.setNullProperty("non-null value"); BeanUtils.setProperty(bean, "nullProperty", null); assertNull("nullProperty is null", bean.getNullProperty()); } /** * Test narrowing and widening conversions on short. */ public void testSetPropertyShort() throws Exception { BeanUtils.setProperty(bean, "shortProperty", new Byte((byte) 123)); assertEquals((short) 123, bean.getShortProperty()); /* BeanUtils.setProperty(bean, "shortProperty", new Double((double) 123)); assertEquals((short) 123, bean.getShortProperty()); BeanUtils.setProperty(bean, "shortProperty", new Float((float) 123)); assertEquals((short) 123, bean.getShortProperty()); */ BeanUtils.setProperty(bean, "shortProperty", new Integer(123)); assertEquals((short) 123, bean.getShortProperty()); BeanUtils.setProperty(bean, "shortProperty", new Long(123)); assertEquals((short) 123, bean.getShortProperty()); BeanUtils.setProperty(bean, "shortProperty", new Short((short) 123)); assertEquals((short) 123, bean.getShortProperty()); } /** * Test setting a String value to a String array property */ public void testSetPropertyStringToArray() throws Exception { BeanUtils.setProperty(bean, "stringArray", "ABC,DEF,GHI"); String[] strArray = bean.getStringArray(); assertEquals("length", 3, strArray.length); assertEquals("value[0]", "ABC", strArray[0]); assertEquals("value[1]", "DEF", strArray[1]); assertEquals("value[2]", "GHI", strArray[2]); BeanUtils.setProperty(bean, "intArray", "0, 10, 20, 30, 40"); int[] intArray = bean.getIntArray(); assertEquals("length", 5, intArray.length); assertEquals("value[0]", 0, intArray[0]); assertEquals("value[1]", 10, intArray[1]); assertEquals("value[2]", 20, intArray[2]); assertEquals("value[3]", 30, intArray[3]); assertEquals("value[4]", 40, intArray[4]); } /** * Test narrowing and widening conversions on byte. */ public void testCopyPropertyByte() throws Exception { BeanUtils.copyProperty(bean, "byteProperty", new Byte((byte) 123)); assertEquals((byte) 123, bean.getByteProperty()); BeanUtils.copyProperty(bean, "byteProperty", new Double(123)); assertEquals((byte) 123, bean.getByteProperty()); BeanUtils.copyProperty(bean, "byteProperty", new Float(123)); assertEquals((byte) 123, bean.getByteProperty()); BeanUtils.copyProperty(bean, "byteProperty", new Integer(123)); assertEquals((byte) 123, bean.getByteProperty()); BeanUtils.copyProperty(bean, "byteProperty", new Long(123)); assertEquals((byte) 123, bean.getByteProperty()); BeanUtils.copyProperty(bean, "byteProperty", new Short((short) 123)); assertEquals((byte) 123, bean.getByteProperty()); } /** * Test copyProperty() conversion. */ public void testCopyPropertyConvert() { try { BeanUtils.copyProperty(bean, "dateProperty", testCalendar); } catch (Throwable t) { fail("Threw " + t); } assertEquals("Calendar --> java.util.Date", testUtilDate, bean.getDateProperty()); } /** * Test copyProperty() converting from a String. */ public void testCopyPropertyConvertFromString() { try { BeanUtils.copyProperty(bean, "dateProperty", testStringDate); } catch (Throwable t) { fail("Threw " + t); } assertEquals("String --> java.util.Date", testUtilDate, bean.getDateProperty()); } /** * Test copyProperty() converting to a String. */ public void testCopyPropertyConvertToString() { try { BeanUtils.copyProperty(bean, "stringProperty", testUtilDate); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date --> String", testUtilDate.toString(), bean.getStringProperty()); } /** * Test copyProperty() converting to a String. */ public void testCopyPropertyConvertToStringArray() { try { bean.setStringArray(null); BeanUtils.copyProperty(bean, "stringArray", new java.util.Date[] {testUtilDate}); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date[] --> String[] length", 1, bean.getStringArray().length); assertEquals("java.util.Date[] --> String[] value ", testUtilDate.toString(), bean.getStringArray()[0]); } /** * Test copyProperty() converting to a String on indexed property */ public void testCopyPropertyConvertToStringIndexed() { try { bean.setStringArray(new String[1]); BeanUtils.copyProperty(bean, "stringArray[0]", testUtilDate); } catch (Throwable t) { fail("Threw " + t); } assertEquals("java.util.Date --> String[]", testUtilDate.toString(), bean.getStringArray()[0]); } /** * Test narrowing and widening conversions on double. */ public void testCopyPropertyDouble() throws Exception { BeanUtils.copyProperty(bean, "doubleProperty", new Byte((byte) 123)); assertEquals(123, bean.getDoubleProperty(), 0.005); BeanUtils.copyProperty(bean, "doubleProperty", new Double(123)); assertEquals(123, bean.getDoubleProperty(), 0.005); BeanUtils.copyProperty(bean, "doubleProperty", new Float(123)); assertEquals(123, bean.getDoubleProperty(), 0.005); BeanUtils.copyProperty(bean, "doubleProperty", new Integer(123)); assertEquals(123, bean.getDoubleProperty(), 0.005); BeanUtils.copyProperty(bean, "doubleProperty", new Long(123)); assertEquals(123, bean.getDoubleProperty(), 0.005); BeanUtils.copyProperty(bean, "doubleProperty", new Short((short) 123)); assertEquals(123, bean.getDoubleProperty(), 0.005); } /** * Test narrowing and widening conversions on float. */ public void testCopyPropertyFloat() throws Exception { BeanUtils.copyProperty(bean, "floatProperty", new Byte((byte) 123)); assertEquals(123, bean.getFloatProperty(), 0.005); BeanUtils.copyProperty(bean, "floatProperty", new Double(123)); assertEquals(123, bean.getFloatProperty(), 0.005); BeanUtils.copyProperty(bean, "floatProperty", new Float(123)); assertEquals(123, bean.getFloatProperty(), 0.005); BeanUtils.copyProperty(bean, "floatProperty", new Integer(123)); assertEquals(123, bean.getFloatProperty(), 0.005); BeanUtils.copyProperty(bean, "floatProperty", new Long(123)); assertEquals(123, bean.getFloatProperty(), 0.005); BeanUtils.copyProperty(bean, "floatProperty", new Short((short) 123)); assertEquals(123, bean.getFloatProperty(), 0.005); } /** * Test narrowing and widening conversions on int. */ public void testCopyPropertyInteger() throws Exception { BeanUtils.copyProperty(bean, "longProperty", new Byte((byte) 123)); assertEquals(123, bean.getIntProperty()); BeanUtils.copyProperty(bean, "longProperty", new Double(123)); assertEquals(123, bean.getIntProperty()); BeanUtils.copyProperty(bean, "longProperty", new Float(123)); assertEquals(123, bean.getIntProperty()); BeanUtils.copyProperty(bean, "longProperty", new Integer(123)); assertEquals(123, bean.getIntProperty()); BeanUtils.copyProperty(bean, "longProperty", new Long(123)); assertEquals(123, bean.getIntProperty()); BeanUtils.copyProperty(bean, "longProperty", new Short((short) 123)); assertEquals(123, bean.getIntProperty()); } /** * Test narrowing and widening conversions on long. */ public void testCopyPropertyLong() throws Exception { BeanUtils.copyProperty(bean, "longProperty", new Byte((byte) 123)); assertEquals(123, bean.getLongProperty()); BeanUtils.copyProperty(bean, "longProperty", new Double(123)); assertEquals(123, bean.getLongProperty()); BeanUtils.copyProperty(bean, "longProperty", new Float(123)); assertEquals(123, bean.getLongProperty()); BeanUtils.copyProperty(bean, "longProperty", new Integer(123)); assertEquals(123, bean.getLongProperty()); BeanUtils.copyProperty(bean, "longProperty", new Long(123)); assertEquals(123, bean.getLongProperty()); BeanUtils.copyProperty(bean, "longProperty", new Short((short) 123)); assertEquals(123, bean.getLongProperty()); } /** * Test narrowing and widening conversions on short. */ public void testCopyPropertyShort() throws Exception { BeanUtils.copyProperty(bean, "shortProperty", new Byte((byte) 123)); assertEquals((short) 123, bean.getShortProperty()); BeanUtils.copyProperty(bean, "shortProperty", new Double(123)); assertEquals((short) 123, bean.getShortProperty()); BeanUtils.copyProperty(bean, "shortProperty", new Float(123)); assertEquals((short) 123, bean.getShortProperty()); BeanUtils.copyProperty(bean, "shortProperty", new Integer(123)); assertEquals((short) 123, bean.getShortProperty()); BeanUtils.copyProperty(bean, "shortProperty", new Long(123)); assertEquals((short) 123, bean.getShortProperty()); BeanUtils.copyProperty(bean, "shortProperty", new Short((short) 123)); assertEquals((short) 123, bean.getShortProperty()); } /** * Test copying a property using a nested indexed array expression, * with and without conversions. */ public void testCopyPropertyNestedIndexedArray() throws Exception { int origArray[] = { 0, 10, 20, 30, 40 }; int intArray[] = { 0, 0, 0 }; bean.getNested().setIntArray(intArray); int intChanged[] = { 0, 0, 0 }; // No conversion required BeanUtils.copyProperty(bean, "nested.intArray[1]", new Integer(1)); checkIntArray(bean.getIntArray(), origArray); intChanged[1] = 1; checkIntArray(bean.getNested().getIntArray(), intChanged); // Widening conversion required BeanUtils.copyProperty(bean, "nested.intArray[1]", new Byte((byte) 2)); checkIntArray(bean.getIntArray(), origArray); intChanged[1] = 2; checkIntArray(bean.getNested().getIntArray(), intChanged); // Narrowing conversion required BeanUtils.copyProperty(bean, "nested.intArray[1]", new Long(3)); checkIntArray(bean.getIntArray(), origArray); intChanged[1] = 3; checkIntArray(bean.getNested().getIntArray(), intChanged); // String conversion required BeanUtils.copyProperty(bean, "nested.intArray[1]", "4"); checkIntArray(bean.getIntArray(), origArray); intChanged[1] = 4; checkIntArray(bean.getNested().getIntArray(), intChanged); } /** * Test copying a property using a nested mapped map property. */ public void testCopyPropertyNestedMappedMap() throws Exception { Map origMap = new HashMap(); origMap.put("First Key", "First Value"); origMap.put("Second Key", "Second Value"); Map changedMap = new HashMap(); changedMap.put("First Key", "First Value"); changedMap.put("Second Key", "Second Value"); // No conversion required BeanUtils.copyProperty(bean, "nested.mapProperty(Second Key)", "New Second Value"); checkMap(bean.getMapProperty(), origMap); changedMap.put("Second Key", "New Second Value"); checkMap(bean.getNested().getMapProperty(), changedMap); } /** * Test copying a property using a nested simple expression, with and * without conversions. */ public void testCopyPropertyNestedSimple() throws Exception { bean.setIntProperty(0); bean.getNested().setIntProperty(0); // No conversion required BeanUtils.copyProperty(bean, "nested.intProperty", new Integer(1)); assertNotNull(bean.getNested()); assertEquals(0, bean.getIntProperty()); assertEquals(1, bean.getNested().getIntProperty()); // Widening conversion required BeanUtils.copyProperty(bean, "nested.intProperty", new Byte((byte) 2)); assertNotNull(bean.getNested()); assertEquals(0, bean.getIntProperty()); assertEquals(2, bean.getNested().getIntProperty()); // Narrowing conversion required BeanUtils.copyProperty(bean, "nested.intProperty", new Long(3)); assertNotNull(bean.getNested()); assertEquals(0, bean.getIntProperty()); assertEquals(3, bean.getNested().getIntProperty()); // String conversion required BeanUtils.copyProperty(bean, "nested.intProperty", "4"); assertNotNull(bean.getNested()); assertEquals(0, bean.getIntProperty()); assertEquals(4, bean.getNested().getIntProperty()); } /** * Test copying a null property value. */ public void testCopyPropertyNull() throws Exception { bean.setNullProperty("non-null value"); BeanUtils.copyProperty(bean, "nullProperty", null); assertNull("nullProperty is null", bean.getNullProperty()); } /** * Test copying a new value to a write-only property, with and without * conversions. */ public void testCopyPropertyWriteOnly() throws Exception { bean.setWriteOnlyProperty("Original value"); // No conversion required BeanUtils.copyProperty(bean, "writeOnlyProperty", "New value"); assertEquals("New value", bean.getWriteOnlyPropertyValue()); // Integer->String conversion required BeanUtils.copyProperty(bean, "writeOnlyProperty", new Integer(123)); assertEquals("123", bean.getWriteOnlyPropertyValue()); } /** * Test setting a new value to a write-only property, with and without * conversions. */ public void testSetPropertyWriteOnly() throws Exception { bean.setWriteOnlyProperty("Original value"); // No conversion required BeanUtils.setProperty(bean, "writeOnlyProperty", "New value"); assertEquals("New value", bean.getWriteOnlyPropertyValue()); // Integer->String conversion required BeanUtils.setProperty(bean, "writeOnlyProperty", new Integer(123)); assertEquals("123", bean.getWriteOnlyPropertyValue()); } /** * Test setting a value out of a mapped Map */ public void testSetMappedMap() { TestBean bean = new TestBean(); Map map = new HashMap(); map.put("sub-key-1", "sub-value-1"); map.put("sub-key-2", "sub-value-2"); map.put("sub-key-3", "sub-value-3"); bean.getMapProperty().put("mappedMap", map); assertEquals("BEFORE", "sub-value-3", ((Map)bean.getMapProperty().get("mappedMap")).get("sub-key-3")); try { BeanUtils.setProperty(bean, "mapProperty(mappedMap)(sub-key-3)", "SUB-KEY-3-UPDATED"); } catch (Throwable t) { fail("Threw " + t + ""); } assertEquals("AFTER", "SUB-KEY-3-UPDATED", ((Map)bean.getMapProperty().get("mappedMap")).get("sub-key-3")); } /** Tests that separate instances can register separate instances */ public void testSeparateInstances() throws Exception { BeanUtilsBean utilsOne = new BeanUtilsBean( new ConvertUtilsBean(), new PropertyUtilsBean()); BeanUtilsBean utilsTwo = new BeanUtilsBean( new ConvertUtilsBean(), new PropertyUtilsBean()); TestBean bean = new TestBean(); // Make sure what we're testing works bean.setBooleanProperty(false); utilsOne.setProperty(bean, "booleanProperty", "true"); assertEquals("Set property failed (1)", bean.getBooleanProperty(), true); bean.setBooleanProperty(false); utilsTwo.setProperty(bean, "booleanProperty", "true"); assertEquals("Set property failed (2)", bean.getBooleanProperty(), true); // now change the registered conversion utilsOne.getConvertUtils().register(new ThrowExceptionConverter(), Boolean.TYPE); try { bean.setBooleanProperty(false); utilsOne.setProperty(bean, "booleanProperty", "true"); fail("Registered conversion not used."); } catch (PassTestException e) { /* Do nothing */ } // make sure that this conversion has no been registered in the other instance try { bean.setBooleanProperty(false); utilsTwo.setProperty(bean, "booleanProperty", "true"); assertEquals("Set property failed (3)", bean.getBooleanProperty(), true); } catch (PassTestException e) { fail("Registed converter is used by other instances"); } } public void testArrayPropertyConversion() throws Exception { BeanUtilsBean beanUtils = new BeanUtilsBean( new ConvertUtilsBean(), new PropertyUtilsBean()); TestBean bean = new TestBean(); String [] results = beanUtils.getArrayProperty(bean, "intArray"); int[] values = bean.getIntArray(); assertEquals( "Converted array size not equal to property array size.", results.length, values.length); for (int i=0, size=values.length ; i actual, Map expected) { assertNotNull("actual map not null", actual); assertEquals("actual map size", expected.size(), actual.size()); Iterator keys = expected.keySet().iterator(); while (keys.hasNext()) { Object key = keys.next(); assertEquals("actual map value(" + key + ")", expected.get(key), actual.get(key)); } } public void testMappedProperty() throws Exception { MappedPropertyTestBean bean = new MappedPropertyTestBean(); BeanUtils.setProperty(bean, "mapproperty(this.that.the-other)", "some.dotty.value"); assertEquals( "Mapped property set correctly", "some.dotty.value", bean.getMapproperty("this.that.the-other")); } /** * Test for {@link BeanUtilsBean#initCause(Throwable, Throwable)} method. */ public void testInitCause() { if (isPre14JVM()) { return; } String parentMsg = "PARENT-THROWABLE"; String causeMsg = "THROWABLE-CAUSE"; try { initCauseAndThrowException(parentMsg, causeMsg); } catch (Throwable thrownParent) { assertEquals("Parent", parentMsg, thrownParent.getMessage()); try { assertEquals("Parent", parentMsg, thrownParent.getMessage()); Throwable thrownCause = getCause(thrownParent); assertNotNull("Cause Null", thrownCause); assertEquals("Cause", causeMsg, thrownCause.getMessage()); } catch (Throwable testError) { fail("If you're running JDK 1.3 then don't worry this should fail," + " if not then needs checking out: " + testError); } } } /** * Use reflection to get the cause */ private Throwable getCause(Throwable t) throws Throwable { return (Throwable)PropertyUtils.getProperty(t, "cause"); } /** * Catch a cause, initialize using BeanUtils.initCause() and throw new exception */ private void initCauseAndThrowException(String parent, String cause) throws Throwable { try { throwException(cause); } catch (Throwable e) { Throwable t = new Exception(parent); BeanUtils.initCause(t, e); throw t; } } /** * Throw an exception with the specified message. */ private void throwException(String msg) throws Throwable { throw new Exception(msg); } /** * Test for JDK 1.4 */ public static boolean isPre14JVM() { String version = System.getProperty("java.specification.version"); StringTokenizer tokenizer = new StringTokenizer(version,"."); if (tokenizer.nextToken().equals("1")) { String minorVersion = tokenizer.nextToken(); if (minorVersion.equals("0")) return true; if (minorVersion.equals("1")) return true; if (minorVersion.equals("2")) return true; if (minorVersion.equals("3")) return true; } return false; } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BeanWithInnerBean.java100644 0 0 2714 12262570607 27376 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.Properties; /** * Bean with inner bean. * * @version $Id: BeanWithInnerBean.java 1454597 2013-03-08 21:58:12Z britter $ */ public class BeanWithInnerBean { private final InnerBean innerBean = new InnerBean(); public BeanWithInnerBean() {} public InnerBean getInnerBean(){ return innerBean; } public class InnerBean { private final Properties fish = new Properties(); public String getFish(String key){ return fish.getProperty(key); } public void setFish(String key, String value){ fish.setProperty(key, value); } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BenchBean.java100644 0 0 6570 12262570610 25716 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * Plain old java bean (POJO) for microbenchmarks. * * @version $Id: BenchBean.java 1454597 2013-03-08 21:58:12Z britter $ */ public class BenchBean { // -------------------------------------------------------------- Properties /** * A boolean property. */ private boolean booleanProperty = true; public boolean getBooleanProperty() { return (booleanProperty); } public void setBooleanProperty(boolean booleanProperty) { this.booleanProperty = booleanProperty; } /** * A byte property. */ private byte byteProperty = (byte) 121; public byte getByteProperty() { return (this.byteProperty); } public void setByteProperty(byte byteProperty) { this.byteProperty = byteProperty; } /** * A double property. */ private double doubleProperty = 321.0; public double getDoubleProperty() { return (this.doubleProperty); } public void setDoubleProperty(double doubleProperty) { this.doubleProperty = doubleProperty; } /** * A float property. */ private float floatProperty = (float) 123.0; public float getFloatProperty() { return (this.floatProperty); } public void setFloatProperty(float floatProperty) { this.floatProperty = floatProperty; } /** * An integer property. */ private int intProperty = 123; public int getIntProperty() { return (this.intProperty); } public void setIntProperty(int intProperty) { this.intProperty = intProperty; } /** * A long property. */ private long longProperty = 321; public long getLongProperty() { return (this.longProperty); } public void setLongProperty(long longProperty) { this.longProperty = longProperty; } /** * A short property. */ private short shortProperty = (short) 987; public short getShortProperty() { return (this.shortProperty); } public void setShortProperty(short shortProperty) { this.shortProperty = shortProperty; } /** * A String property. */ private String stringProperty = "This is a string"; public String getStringProperty() { return (this.stringProperty); } public void setStringProperty(String stringProperty) { this.stringProperty = stringProperty; } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/BetaBean.java100644 0 0 2546 12262570610 25551 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * @version $Id: BetaBean.java 1454597 2013-03-08 21:58:12Z britter $ */ public class BetaBean extends AbstractChild { private String secret = "utah"; public String getSecret() { return secret; } public void setNoGetterProperty(String secret) { this.secret = secret; } public void setNoGetterMappedProperty(String secret, String key) { this.secret = "MAP:" + secret; } public BetaBean(String name) { setName(name); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira157TestCase.java100644 0 0 13701 12262570610 27641 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import java.io.Serializable; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Beanutils's describe() method cannot determine reader methods for anonymous * class - see Jira issue# BEANUTILS-157. * * @version $Id: Jira157TestCase.java 1540186 2013-11-08 21:08:30Z oheger $ * @see https://issues.apache.org/jira/browse/BEANUTILS-157 */ public class Jira157TestCase extends TestCase { private final Log log = LogFactory.getLog(Jira157TestCase.class); /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira157TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira157TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test with an private class that overrides a public method * of a "grand parent" public class. *

          * See Jira issue# BEANUTILS-157. */ public void testIssue_BEANUTILS_157_BeanUtils_Describe_Serializable() { Object bean = new Serializable() { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") public String getX() { return "x-value"; } @SuppressWarnings("unused") public String getY() { return "y-value"; } }; Map result = null; try { result = BeanUtils.describe(bean); } catch (Throwable t) { log.error("Describe Serializable: " + t.getMessage(), t); fail("Describe Serializable Threw exception: " + t); } assertEquals("Check Size", 1, result.size()); assertTrue("Class", result.containsKey("class")); } /** * Test with an private class that overrides a public method * of a "grand parent" public class. *

          * See Jira issue# BEANUTILS-157. */ public void testIssue_BEANUTILS_157_BeanUtils_Describe_Interface() { Object bean = new XY() { public String getX() { return "x-value"; } public String getY() { return "y-value"; } }; Map result = null; try { result = BeanUtils.describe(bean); } catch (Throwable t) { log.error("Describe Interface: " + t.getMessage(), t); fail("Describe Interface Threw exception: " + t); } assertEquals("Check Size", 3, result.size()); assertTrue("Class", result.containsKey("class")); assertTrue("X Key", result.containsKey("x")); assertTrue("Y Key", result.containsKey("y")); assertEquals("X Value", "x-value", result.get("x")); assertEquals("Y Value", "y-value", result.get("y")); } /** * Test with an private class that overrides a public method * of a "grand parent" public class. *

          * See Jira issue# BEANUTILS-157. */ public void testIssue_BEANUTILS_157_BeanUtils_Describe_Bean() { Object bean = new FooBar(); Map result = null; try { result = BeanUtils.describe(bean); } catch (Throwable t) { log.error("Describe Bean: " + t.getMessage(), t); fail("Describe Bean Threw exception: " + t); } assertEquals("Check Size", 2, result.size()); assertTrue("Class", result.containsKey("class")); assertTrue("publicFoo Key", result.containsKey("publicFoo")); assertEquals("publicFoo Value", "PublicFoo Value", result.get("publicFoo")); } public static interface XY { String getX(); String getY(); } public static class FooBar { String getPackageFoo() { return "Package Value"; } @SuppressWarnings("unused") private String getPrivateFoo() { return "PrivateFoo Value"; } protected String getProtectedFoo() { return "ProtectedFoo Value"; } public String getPublicFoo() { return "PublicFoo Value"; } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira18TestCase.java100644 0 0 23303 12262570610 27554 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.bugs.other.Jira18BeanFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Test case for Jira issue# BEANUTILS-18. *

          This test case demonstrates the issue. * * @version $Id: Jira18TestCase.java 1456817 2013-03-15 09:05:17Z britter $ * @see https://issues.apache.org/jira/browse/BEANUTILS-18 */ public class Jira18TestCase extends TestCase { private final Log log = LogFactory.getLog(Jira18TestCase.class); private Object bean; /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira18TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira18TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); bean = Jira18BeanFactory.createBean(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link PropertyUtils#isReadable(Object, String)} * for simple properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isReadable() { boolean result = false; try { result = PropertyUtils.isReadable(bean, "simple"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isReadable(bean, \"simple\") returned true", result); } /** * Test {@link PropertyUtils#isWriteable(Object, String)} * for simple properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isWriteable() { boolean result = false; try { result = PropertyUtils.isWriteable(bean, "simple"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isWriteable(bean, \"simple\") returned true", result); } /** * Test {@link PropertyUtils#isReadable(Object, String)} * for indexed properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isReadable_Indexed() { boolean result = false; try { result = PropertyUtils.isReadable(bean, "indexed"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isReadable(bean, \"indexed\") returned true", result); } /** * Test {@link PropertyUtils#isWriteable(Object, String)} * for indexed properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isWriteable_Indexed() { boolean result = false; try { result = PropertyUtils.isWriteable(bean, "indexed"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isWriteable(bean, \"indexed\") returned true", result); } /** * Test {@link PropertyUtils#isReadable(Object, String)} * for Mapped properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isReadable_Mapped() { boolean result = false; try { result = PropertyUtils.isReadable(bean, "mapped"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isReadable(bean, \"mapped\") returned true", result); } /** * Test {@link PropertyUtils#isWriteable(Object, String)} * for Mapped properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isWriteable_Mapped() { boolean result = false; try { result = PropertyUtils.isWriteable(bean, "mapped"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isWriteable(bean, \"mapped\") returned true", result); } /** * Test {@link PropertyUtils#getProperty(Object, String)} * for simple properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_getProperty() { boolean threwNoSuchMethodException = false; Object result = null; try { result = PropertyUtils.getProperty(bean, "simple"); } catch (NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException but returned '" + result + "'", threwNoSuchMethodException); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} * for simple properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_setProperty() { boolean threwNoSuchMethodException = false; try { PropertyUtils.setProperty(bean, "simple", "BAR"); } catch (NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException", threwNoSuchMethodException); } /** * Test {@link PropertyUtils#getProperty(Object, String)} * for indexed properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_getProperty_Indexed() { boolean threwNoSuchMethodException = false; Object result = null; try { result = PropertyUtils.getProperty(bean, "indexed[0]"); } catch (NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException but returned '" + result + "'", threwNoSuchMethodException); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} * for indexed properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_setProperty_Indexed() { boolean threwNoSuchMethodException = false; try { PropertyUtils.setProperty(bean, "indexed[0]", "BAR"); } catch (NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException", threwNoSuchMethodException); } /** * Test {@link PropertyUtils#getProperty(Object, String)} * for mapped properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_getProperty_Mapped() { boolean threwNoSuchMethodException = false; Object result = null; try { result = PropertyUtils.getProperty(bean, "mapped(foo-key)"); } catch (NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException but returned '" + result + "'", threwNoSuchMethodException); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} * for mapped properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_setProperty_Mapped() { boolean threwNoSuchMethodException = false; try { PropertyUtils.setProperty(bean, "mapped(foo-key)", "BAR"); } catch (NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException", threwNoSuchMethodException); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira273TestCase.java100644 0 0 14343 12262570610 27643 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.bugs.other.Jira273BeanFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Public methods overriden in anonymous or private subclasses * are not recognized by PropertyUtils - see issue# BEANUTILS-273. * * @version $Id: Jira273TestCase.java 1456817 2013-03-15 09:05:17Z britter $ * @see https://issues.apache.org/jira/browse/BEANUTILS-273 */ public class Jira273TestCase extends TestCase { private final Log log = LogFactory.getLog(Jira273TestCase.class); /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira273TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira273TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test with an annonymous class that overrides a public method * of a public class. */ public void testIssue_BEANUTILS_273_AnnonymousOverriden() { Object bean = Jira273BeanFactory.createAnnonymousOverriden(); Object result = null; try { result = PropertyUtils.getProperty(bean, "beanValue"); } catch (Throwable t) { log.error("AnnonymousOverriden: " + t.getMessage(), t); fail("AnnonymousOverriden Threw exception: " + t); } assertEquals("AnnonymousOverriden", result); } /** * Test with an annonymous class that inherits a public method * of a public class. */ public void testIssue_BEANUTILS_273_AnnonymousNotOverriden() { Object bean = Jira273BeanFactory.createAnnonymousNotOverriden(); Object result = null; try { result = PropertyUtils.getProperty(bean, "beanValue"); } catch (Throwable t) { log.error("AnnonymousNotOverriden: " + t.getMessage(), t); fail("AnnonymousNotOverriden Threw exception: " + t); } assertEquals("PublicBeanWithMethod", result); } /** * Test with an private class that inherits a public method * of a public class. */ public void testIssue_BEANUTILS_273_PrivatePublicNotOverriden() { Object bean = Jira273BeanFactory.createPrivatePublicNotOverriden(); Object result = null; try { result = PropertyUtils.getProperty(bean, "beanValue"); } catch (Throwable t) { log.error("PrivatePublicNotOverriden: " + t.getMessage(), t); fail("PrivatePublicNotOverriden Threw exception: " + t); } assertEquals("PublicBeanWithMethod", result); } /** * Test with an private class that overrides a public method * of a public class. */ public void testIssue_BEANUTILS_273_PrivatePublicOverriden() { Object bean = Jira273BeanFactory.createPrivatePublicOverriden(); Object result = null; try { result = PropertyUtils.getProperty(bean, "beanValue"); } catch (Throwable t) { log.error("PrivatePublicOverriden: " + t.getMessage(), t); fail("PrivatePublicOverriden Threw exception: " + t); } assertEquals("PrivatePublicOverriden", result); } /** * Test with an private class that inherits a public method * of a "grand parent" public class. */ public void testIssue_BEANUTILS_273_PrivatePrivatePublicNotOverriden() { Object bean = Jira273BeanFactory.createPrivatePrivatePublicNotOverriden(); Object result = null; try { result = PropertyUtils.getProperty(bean, "beanValue"); } catch (Throwable t) { log.error("PrivatePrivatePublicNotOverriden: " + t.getMessage(), t); fail("PrivatePrivatePublicNotOverriden Threw exception: " + t); } assertEquals("PublicBeanWithMethod", result); } /** * Test with an private class that overrides a public method * of a "grand parent" public class. */ public void testIssue_BEANUTILS_273_PrivatePrivatePublicOverriden() { Object bean = Jira273BeanFactory.createPrivatePrivatePublicOverriden(); Object result = null; try { result = PropertyUtils.getProperty(bean, "beanValue"); } catch (Throwable t) { log.error("PrivatePrivatePublicOverriden: " + t.getMessage(), t); fail("PrivatePrivatePublicOverriden Threw exception: " + t); } assertEquals("PrivatePrivatePublicOverriden", result); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira298TestCase.java100644 0 0 10314 12262570610 27644 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import java.lang.reflect.Method; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.MethodUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.bugs.other.Jira298BeanFactory; import org.apache.commons.beanutils.bugs.other.Jira298BeanFactory.IX; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @version $Id: Jira298TestCase.java 1540186 2013-11-08 21:08:30Z oheger $ * @see https://issues.apache.org/jira/browse/BEANUTILS-298 */ public class Jira298TestCase extends TestCase { private final Log log = LogFactory.getLog(Jira298TestCase.class); /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira298TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira298TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link PropertyUtils#getProperty(Object, String)} */ public void testIssue_BEANUTILS_298_PropertyUtils_getProperty() { Object bean = Jira298BeanFactory.createImplX(); Object result = null; try { result = PropertyUtils.getProperty(bean, "name"); } catch (Throwable t) { log.error("Failed: " + t.getMessage(), t); fail("Threw exception: " + t); } assertEquals("BaseX name value", result); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} */ public void testIssue_BEANUTILS_298_PropertyUtils_setProperty() { Object bean = Jira298BeanFactory.createImplX(); assertEquals("BaseX name value", ((IX)bean).getName()); try { PropertyUtils.setProperty(bean, "name", "new name"); } catch (Throwable t) { log.error("Failed: " + t.getMessage(), t); fail("Threw exception: " + t); } assertEquals("new name", ((IX)bean).getName()); } /** * Test {@link MethodUtils#getAccessibleMethod(Class, Method)} */ public void testIssue_BEANUTILS_298_MethodUtils_getAccessibleMethod() { Object bean = Jira298BeanFactory.createImplX(); Object result = null; try { Method m2 = MethodUtils.getAccessibleMethod(bean.getClass(), "getName", new Class[0]); result = m2.invoke(bean); } catch (Throwable t) { log.error("Failed: " + t.getMessage(), t); fail("Threw exception: " + t); } assertEquals("BaseX name value", result); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira339TestCase.java100644 0 0 10131 12262570610 27635 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @version $Id: Jira339TestCase.java 1540186 2013-11-08 21:08:30Z oheger $ * @see https://issues.apache.org/jira/browse/BEANUTILS-339 */ public class Jira339TestCase extends TestCase { private final Log log = LogFactory.getLog(Jira339TestCase.class); /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira339TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira339TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} */ public void testIssue_BEANUTILS_339_BeanUtilsBean_setProperty() { TestBean bean = new TestBean(); try { BeanUtils.setProperty(bean, "comparator", null); } catch (Throwable t) { log.error("Failed: " + t.getMessage(), t); fail("Threw exception: " + t); } assertNull("TestBean comparator should be null", bean.getComparator()); } /** * Test {@link BeanUtils#populate(Object, Map)} */ public void testIssue_BEANUTILS_331_BeanUtilsBean_populate() { TestBean bean = new TestBean(); try { Map properties = new HashMap(); properties.put("comparator", null); BeanUtils.populate(bean, properties); } catch (Throwable t) { log.error("Failed: " + t.getMessage(), t); fail("Threw exception: " + t); } assertNull("TestBean comparator should be null", bean.getComparator()); } /** * Test Bean. */ public static class TestBean { private Comparator comparator; /** * Return the comparator. * * @return the comparator */ public Comparator getComparator() { return comparator; } /** * Set the comparator. * * @param comparator the comparator */ public void setComparator(Comparator comparator) { this.comparator = comparator; } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira345TestCase.java100644 0 0 6660 12262570610 27626 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.BeanUtils; /** * @version $Id: Jira345TestCase.java 1456817 2013-03-15 09:05:17Z britter $ * @see https://issues.apache.org/jira/browse/BEANUTILS-345 */ public class Jira345TestCase extends TestCase { /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira345TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira345TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link BeanUtils} setProperty() with 2D array. */ public void testBeanUtilsSetProperty_2DArray() throws Exception{ MyBean myBean = new MyBean(); BeanUtils.setProperty(myBean, "matr[0][0]","Sample"); assertEquals("Sample", myBean.getMatr()[0][0]); } /** * Test {@link BeanUtils} setProperty() with 3D array. */ public void testBeanUtilsSetProperty_3DArray() throws Exception{ MyBean myBean = new MyBean(); BeanUtils.setProperty(myBean, "matr3D[0][0][0]","Sample"); assertEquals("Sample", myBean.getMatr3D()[0][0][0]); } /** Example Bean */ public static class MyBean { private String[][] matr = new String[][]{{"1","2"},{"3","4"}}; private String[][][] matr3D = new String[][][] { {{"11","12"}, {"13","14"}}, {{"21","22"}, {"23","24"}}, }; public String[][] getMatr() { return matr; } public void setMatr(String[][] matr) { this.matr = matr; } public String[][][] getMatr3D() { return matr3D; } public void setMatr3D(String[][][] matr3D) { this.matr3D = matr3D; } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira347TestCase.java100644 0 0 15412 12262570610 27643 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import java.beans.IntrospectionException; import java.lang.ref.SoftReference; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import junit.framework.TestCase; import org.apache.commons.beanutils.MappedPropertyDescriptor; import org.apache.commons.beanutils.memoryleaktests.MemoryLeakTestCase; /** * Test case for Jira issue# BEANUTILS-347. * * @version $Id: Jira347TestCase.java 1546738 2013-11-30 16:24:19Z oheger $ * @see https://issues.apache.org/jira/browse/BEANUTILS-347 */ public class Jira347TestCase extends TestCase { /** * Tests that MappedPropertyDescriptor does not throw an exception while re-creating a Method reference after it * has been garbage collected under the following circumstances. * - a class has a property 'mappedProperty' * - there is no getter for this property * - there is method setMappedProperty(MappedPropertyTestBean,MappedPropertyTestBean) * * In this case getMappedWriteMethod should not throw an exception after the method reference has been garbage collected. * It is essential that in both cases the same method is returned or in both cases null. * If the constructor of the MappedPropertyDescriptor would recognize the situation (of the first param not being of type String) * this would be fine as well. */ public void testMappedPropertyDescriptor_AnyArgsProperty() throws Exception { String className = "org.apache.commons.beanutils.MappedPropertyTestBean"; ClassLoader loader = newClassLoader(); Class beanClass = loader.loadClass(className); beanClass.newInstance(); // ----------------------------------------------------------------------------- // Sanity checks only assertNotNull("ClassLoader is null", loader); assertNotNull("BeanClass is null", beanClass); assertNotSame("ClassLoaders should be different..", getClass().getClassLoader(), beanClass.getClassLoader()); assertSame("BeanClass ClassLoader incorrect", beanClass.getClassLoader(), loader); // now start the test MappedPropertyDescriptor descriptor = null; try { descriptor = new MappedPropertyDescriptor("anyMapped", beanClass); } catch (IntrospectionException e) { // this would be fine as well } if (descriptor != null) { String m1 = getMappedWriteMethod(descriptor); forceGarbageCollection(); try { String m2 = getMappedWriteMethod(descriptor); assertEquals("Method returned post garbage collection differs from Method returned prior to gc", m1, m2); } catch (RuntimeException e) { fail("getMappedWriteMethod threw an exception after garbage collection " + e); } } } /** * Retrieves the string representation of the mapped write method * for the given descriptor. * This conversion is needed as there must not be strong reference to the * Method object outside of this method as otherwise the garbage collector will not * clean up the soft reference within the MappedPropertyDescriptor. * * @return the string representation or null if mapped write method does not exist */ private String getMappedWriteMethod(MappedPropertyDescriptor descriptor) { Method m = descriptor.getMappedWriteMethod(); return m == null ? null : m.toString(); } /** * Try to force the garbage collector to run by filling up memory and calling System.gc(). */ private void forceGarbageCollection() throws Exception { // Fill up memory SoftReference ref = new SoftReference(new Object()); int count = 0; while(ref.get() != null && count++ < 5) { ArrayList list = new ArrayList(); try { long i = 0; while (true && ref.get() != null) { list.add("A Big String A Big String A Big String A Big String A Big String A Big String A Big String A Big String A Big String A Big String " + (i++)); } } catch (Throwable ignored) { } list.clear(); list = null; // System.out.println("Count " + count + " : " + getMemoryStats()); System.gc(); Thread.sleep(1000); } // System.out.println("After GC: " + getMemoryStats()); if (ref.get() != null) { throw new IllegalStateException("Your JVM is not releasing SoftReference, try running the testcase with less memory (-Xmx)"); } } /** * Create a new class loader instance. */ private static URLClassLoader newClassLoader() throws MalformedURLException { String dataFilePath = MemoryLeakTestCase.class.getResource("pojotests").getFile(); //System.out.println("dataFilePath: " + dataFilePath); String location = "file://" + dataFilePath.substring(0,dataFilePath.length()-"org.apache.commons.beanutils.memoryleaktests.pojotests".length()); //System.out.println("location: " + location); StringBuilder newString = new StringBuilder(); for (int i=0;ihttps://issues.apache.org/jira/browse/BEANUTILS-349 */ public class Jira349TestCase extends TestCase { private final Log log = LogFactory.getLog(Jira349TestCase .class); /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira349TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira349TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link PropertyUtils#copyProperties(Object, Object)} */ public void testIssue_BEANUTILS_349_PropertyUtils_copyProperties() { PrimitiveBean dest = new PrimitiveBean(); ObjectBean origin = new ObjectBean (); try { PropertyUtils.copyProperties(dest, origin); } catch (NullPointerException e) { log.error("Failed", e); fail("Threw NullPointerException"); } catch (IllegalArgumentException e) { log.warn("Expected Result", e); } catch (Throwable t) { log.error("Failed", t); fail("Threw exception: " + t); } } /** * Test Bean with a primitive boolean property. */ public static class PrimitiveBean { private boolean testProperty; public boolean getTestProperty() { return testProperty; } public void setTestProperty(boolean testProperty) { this.testProperty = testProperty; } } /** * Test Bean with a Boolean object property. */ public static class ObjectBean { private Boolean testProperty; public Boolean getTestProperty() { return testProperty; } public void setTestProperty(Boolean testProperty) { this.testProperty = testProperty; } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira357TestCase.java100644 0 0 13751 12262570610 27650 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import java.beans.PropertyDescriptor; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.PropertyUtils; /** * @version $Id: Jira357TestCase.java 1540186 2013-11-08 21:08:30Z oheger $ * @see https://issues.apache.org/jira/browse/BEANUTILS-357 */ public class Jira357TestCase extends TestCase { /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira357TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira357TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link PropertyUtils#getPropertyDescriptors(Class)} */ public void testPropertyUtils_getPropertyDescriptors_Foo() throws Exception { checkReadMethod("foo", ConcreteTestBean.class); } /** * Test {@link PropertyUtils#getPropertyDescriptors(Class)} */ public void testPropertyUtils_getPropertyDescriptors_Bar() throws Exception { // FIXME the isBar() method returning AbstractTestBean.class as the // declaring class instead of ConcreteTestBean.class // causing this test to fail - so its commented out for now //checkReadMethod("bar", ConcreteTestBean.class); } /** * Test {@link PropertyUtils#getPropertyDescriptors(Class)} */ public void testPropertyUtils_getPropertyDescriptors_InnerClassProperty() throws Exception { checkReadMethod("innerClassProperty", ConcreteTestBean.class); } /** * Test {@link PropertyUtils#getPropertyDescriptors(Class)} */ private void checkReadMethod(String propertyName, Class expectedDeclaringClass) throws Exception { PropertyDescriptor[] descriptors = null; try { descriptors = PropertyUtils.getPropertyDescriptors(ConcreteTestBean.class); } catch (Exception e) { e.printStackTrace(); fail("Threw: " + e); } // Test InnerClassProperty PropertyDescriptor descriptor = findDescriptor(propertyName, descriptors); assertNotNull(propertyName + "descriptor", descriptor); assertEquals(propertyName + " read method declaring class", expectedDeclaringClass, descriptor.getReadMethod().getDeclaringClass()); } /** * Find a property descriptor. */ private PropertyDescriptor findDescriptor(String propertyName, PropertyDescriptor[] descriptors) { if (descriptors != null) { for (int i = 0; i < descriptors.length; i++) { if (propertyName.equals(descriptors[i].getName())) { return descriptors[i]; } } } return null; // not found } /** * Abstract test bean. */ public abstract static class AbstractTestBean { public abstract String getFoo(); public abstract void setFoo(String foo); public abstract boolean isBar(); public abstract void setBar(boolean bar); public abstract AbstractTestBean.InnerClass getInnerClassProperty(); /** Inner Class */ public abstract static class InnerClass { private String firstName; public String getInnerName() { return firstName; } public void setInnerName(String firstName) { this.firstName = firstName; } } } /** * Concrete bean implementation. */ public static class ConcreteTestBean extends AbstractTestBean { private String foo; private boolean bar; private ConcreteTestBean.InnerClass innerClassProperty; @Override public String getFoo() { return foo; } @Override public void setFoo(String foo) { this.foo = foo; } @Override public boolean isBar() { return bar; } @Override public void setBar(boolean bar) { this.bar = bar; } @Override public ConcreteTestBean.InnerClass getInnerClassProperty() { return innerClassProperty; } public void setInnerClassProperty(ConcreteTestBean.InnerClass innerClassProperty) { this.innerClassProperty = innerClassProperty; } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira358TestCase.java100644 0 0 6246 12262570610 27632 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.TestBean; /** * @version $Id: Jira358TestCase.java 1456817 2013-03-15 09:05:17Z britter $ * @see https://issues.apache.org/jira/browse/BEANUTILS-358 */ public class Jira358TestCase extends TestCase { /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira358TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira358TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link PropertyUtils#getIndexedProperty(Object, String, int)} */ public void testPropertyUtils_getIndexedProperty_Array() throws Exception { TestBean bean = new TestBean(); try { PropertyUtils.getIndexedProperty(bean, "intArray", bean.getIntArray().length); fail("Expected ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException e) { // expected result } } /** * Test {@link PropertyUtils#getIndexedProperty(Object, String, int)} */ public void testPropertyUtils_getIndexedProperty_List() throws Exception { TestBean bean = new TestBean(); try { PropertyUtils.getIndexedProperty(bean, "listIndexed", bean.getListIndexed().size()); fail("Expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected result } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira359TestCase.java100644 0 0 14134 12262570610 27646 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.converters.ArrayConverter; import org.apache.commons.beanutils.converters.StringConverter; /** * @version $Id: Jira359TestCase.java 1456817 2013-03-15 09:05:17Z britter $ * @see https://issues.apache.org/jira/browse/BEANUTILS-359 */ public class Jira359TestCase extends TestCase { /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira359TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira359TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link BeanUtils} setProperty() String to array with colon value */ public void testBeanUtilsSetProperty_CustomConvertStringToArray_WithColonValue() throws Exception{ ArrayConverter converter = new ArrayConverter(String[].class, new StringConverter()); converter.setAllowedChars(new char[] {'.', '-', ':'}); BeanUtilsBean utils = new BeanUtilsBean(); utils.getConvertUtils().register(converter, String[].class); SimplePojoData simplePojo = new SimplePojoData(); utils.setProperty(simplePojo, "jcrMixinTypes", "mix:rereferencible,mix:simple"); showArray("Custom WithColonValue", simplePojo.getJcrMixinTypes()); assertEquals("array size", 2, simplePojo.getJcrMixinTypes().length); assertEquals("mix:rereferencible", simplePojo.getJcrMixinTypes()[0]); assertEquals("mix:simple", simplePojo.getJcrMixinTypes()[1]); } /** * Test {@link BeanUtils} setProperty() String to array with colon value */ public void testBeanUtilsSetProperty_DefaultConvertStringToArray_WithColonValue() throws Exception{ SimplePojoData simplePojo = new SimplePojoData(); BeanUtils.setProperty(simplePojo, "jcrMixinTypes", "mix:rereferencible,mix:simple"); showArray("Default WithColonValue", simplePojo.getJcrMixinTypes()); assertEquals("array size", 4, simplePojo.getJcrMixinTypes().length); assertEquals("mix", simplePojo.getJcrMixinTypes()[0]); assertEquals("rereferencible", simplePojo.getJcrMixinTypes()[1]); assertEquals("mix", simplePojo.getJcrMixinTypes()[2]); assertEquals("simple", simplePojo.getJcrMixinTypes()[3]); } /** * Test {@link BeanUtils} setProperty() String to array without colon value */ public void testBeanUtilsSetProperty_DefaultConvertStringToArray_WithoutColonValue() throws Exception{ SimplePojoData simplePojo = new SimplePojoData(); BeanUtils.setProperty(simplePojo, "jcrMixinTypes", "mixrereferencible,mixsimple"); showArray("Default WithoutColonValue", simplePojo.getJcrMixinTypes()); assertEquals("array size", 2, simplePojo.getJcrMixinTypes().length); assertEquals("mixrereferencible", simplePojo.getJcrMixinTypes()[0]); assertEquals("mixsimple", simplePojo.getJcrMixinTypes()[1]); } /** * Test {@link BeanUtils} setProperty() String to array without colon value and no comma */ public void testBeanUtilsSetProperty_DefaultConvertStringToArray_WithoutColonValueAndNocoma() throws Exception{ SimplePojoData simplePojo = new SimplePojoData(); BeanUtils.setProperty(simplePojo, "jcrMixinTypes", "mixrereferencible"); showArray("Default WithoutColonAndNocoma", simplePojo.getJcrMixinTypes()); assertEquals("array size", 1, simplePojo.getJcrMixinTypes().length); assertEquals("mixrereferencible", simplePojo.getJcrMixinTypes()[0]); } /** * Show array contents. */ private void showArray(String text, String[] array) { if (array == null) { System.out.println(text + " array is null"); } else { System.out.println(text + " array length=" + array.length); for (int i = 0; i < array.length; i++) { System.out.println(text + " array[" + i + "]=" + array[i]); } } } public static class SimplePojoData { private String[] jcrMixinTypes = new String[1]; public SimplePojoData() { } public String[] getJcrMixinTypes() { return this.jcrMixinTypes; } public void setJcrMixinTypes(String[] mixinTypes) { this.jcrMixinTypes = mixinTypes; } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira368TestCase.java100644 0 0 5201 12262570610 27621 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.BeanUtils; /** * @version $Id: Jira368TestCase.java 1456817 2013-03-15 09:05:17Z britter $ * @see https://issues.apache.org/jira/browse/BEANUTILS-368 */ public class Jira368TestCase extends TestCase { /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira368TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira368TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link BeanUtils} setProperty() with Null value */ public void testBeanUtilsSetProperty_NullBean() throws Exception { try { BeanUtils.setProperty(null, "foo", "bar"); } catch (NullPointerException e) { fail("Threw NullPointerException"); } catch (IllegalArgumentException e) { // expected result } catch (Exception e) { fail("Threw " + e); } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira369TestCase.java100644 0 0 10010 12262570610 27634 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.BeanUtils; /** * @version $Id: Jira369TestCase.java 1456817 2013-03-15 09:05:17Z britter $ * @see https://issues.apache.org/jira/browse/BEANUTILS-369 */ public class Jira369TestCase extends TestCase { /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira369TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira369TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link BeanUtils} getProperty() for property "aRatedCd". */ public void testBeanUtilsGetProperty_aRatedCd() throws Exception { TestBean bean = new TestBean(); bean.setARatedCd("foo"); try { assertEquals("foo", BeanUtils.getProperty(bean, "aRatedCd")); fail("Expected NoSuchMethodException"); } catch (NoSuchMethodException e) { // expected result } catch (Exception e) { fail("Threw " + e); } } /** * Test {@link BeanUtils} getProperty() for property "ARatedCd". */ public void testBeanUtilsGetProperty_ARatedCd() throws Exception { TestBean bean = new TestBean(); bean.setARatedCd("foo"); try { assertEquals("foo", BeanUtils.getProperty(bean, "ARatedCd")); } catch (Exception e) { fail("Threw " + e); } } /** * Test {@link BeanUtils} getProperty() for property "bRatedCd". */ public void testBeanUtilsGetProperty_bRatedCd() throws Exception { TestBean bean = new TestBean(); bean.setbRatedCd("foo"); try { assertEquals("foo", BeanUtils.getProperty(bean, "bRatedCd")); } catch (Exception e) { fail("Threw " + e); } } /** * Test Bean */ public static class TestBean { private String aproperty; private String bproperty; public String getARatedCd() { return aproperty; } public void setARatedCd(String aproperty) { this.aproperty = aproperty; } public String getbRatedCd() { return bproperty; } public void setbRatedCd(String bproperty) { this.bproperty = bproperty; } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira381TestCase.java100644 0 0 5410 12262570610 27616 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import java.lang.reflect.Method; import junit.framework.TestCase; import org.apache.commons.beanutils.MethodUtils; /** * MethodUtils's getMatchingAccessibleMethod() does not correctly * handle inheritance and method overloading. * * @version $Id: Jira381TestCase.java 1540186 2013-11-08 21:08:30Z oheger $ * @see https://issues.apache.org/jira/browse/BEANUTILS-381 */ public class Jira381TestCase extends TestCase { /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira381TestCase(String name) { super(name); } /** * Test with an private class that overrides a public method * of a "grand parent" public class. *

          * See Jira issue# BEANUTILS-381. */ public void testIssue_BEANUTILS_381_getMatchingAccessibleMethod() { Class target = TestServiceBean.class; String methodName = "performOp"; Class[] runtimeClasses = new Class[]{TestObjectSubclass.class}; Method returned = MethodUtils.getMatchingAccessibleMethod(target, methodName, runtimeClasses); assertEquals(target, returned.getDeclaringClass()); assertEquals(methodName, returned.getName()); assertEquals(TestObject.class, returned.getParameterTypes()[0]); } /** * Test bean. */ public class TestServiceBean{ /** * Generic object method */ public void performOp(Object o){ } /** * Object method */ public void performOp(TestObject o){ } } /** * Test object. * */ public class TestObject{ } /** * Used to match performop with test object */ public class TestObjectSubclass extends TestObject{ } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira411TestCase.java100644 0 0 3622 12262570610 27613 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import junit.framework.TestCase; import org.apache.commons.beanutils.BeanUtilsBean; /** * BeanUtilsBean.setProperty throws IllegalArgumentException if getter of nested * property returns null * * @version $Id: Jira411TestCase.java 1456817 2013-03-15 09:05:17Z britter $ * @see https://issues.apache.org/jira/browse/BEANUTILS-411 */ public class Jira411TestCase extends TestCase { private BeanUtilsBean instance; private DummyBean testBean; @Override protected void setUp() throws Exception { instance = new BeanUtilsBean(); testBean = new DummyBean(); } public void testSetProperty() throws Exception { instance.setProperty(testBean, "imgLink.x", "1"); } public class DummyBean { private String imgLink = null; public String getImgLink() { return imgLink; } public void setImgLink(String imgLink) { this.imgLink = imgLink; } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira422TestCase.java100644 0 0 4463 12262570610 27621 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import java.util.List; import junit.framework.TestCase; import org.apache.commons.beanutils.PropertyUtils; /** * getPropertyType return null on second descendant class * * @version $Id: Jira422TestCase.java 1540186 2013-11-08 21:08:30Z oheger $ * @see https://issues.apache.org/jira/browse/BEANUTILS-422 */ public class Jira422TestCase extends TestCase { public void testRootBean() throws Exception { RootBean bean = new FirstChildBean(); Class propertyType = PropertyUtils.getPropertyType(bean, "file[0]"); assertEquals(String.class.getName(), propertyType.getName()); } public void testSecondChildBean() throws Exception { RootBean bean = new SecondChildBean(); Class propertyType = PropertyUtils.getPropertyType(bean, "file[0]"); assertEquals(String.class.getName(), propertyType.getName()); } } @SuppressWarnings("rawtypes") class RootBean { private List file; public List getFile() { return file; } public void setFile(List file) { this.file = file; } public String getFile(int i) { return (String) file.get(i); } @SuppressWarnings("unchecked") public void setFile(int i, String file) { this.file.set(i, file); } } class FirstChildBean extends RootBean { } class SecondChildBean extends RootBean { } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira454TestCase.java100644 0 0 3361 12262570610 27622 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import java.util.Date; import junit.framework.TestCase; import org.apache.commons.beanutils.BeanUtils; /** * copyProperties() throws a ConversionException : No value specified for 'Date' * when the field is a java.util.Date with a null value * * @version $Id: Jira454TestCase.java 1546740 2013-11-30 16:26:31Z oheger $ */ public class Jira454TestCase extends TestCase { public void testCopyProperties() throws Exception { TestBean bean = new TestBean(); TestBean b2 = new TestBean(); BeanUtils.copyProperties(b2, bean); assertNull("Got a creation date", b2.getCreatedAt()); } public static class TestBean { private Date createdAt; public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira456TestCase.java100644 0 0 6363 12262570610 27631 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import java.beans.PropertyDescriptor; import junit.framework.TestCase; import org.apache.commons.beanutils.FluentIntrospectionTestBean; import org.apache.commons.beanutils.FluentPropertyBeanIntrospector; import org.apache.commons.beanutils.PropertyUtilsBean; /** * Write methods for PropertyDescriptors created during custom introspection are lost. See * JIRA issue * BEANUTILS-456. * * @version $Id: Jira456TestCase.java 1555233 2014-01-03 19:41:04Z oheger $ */ public class Jira456TestCase extends TestCase { /** Constant for the name of the test property. */ private static final String TEST_PROP = "fluentGetProperty"; /** The PropertyUtilsBean used by the tests. */ private PropertyUtilsBean pub; @Override protected void setUp() throws Exception { super.setUp(); pub = new PropertyUtilsBean(); pub.addBeanIntrospector(new FluentPropertyBeanIntrospector()); } /** * Clears the reference to the write method in the property descriptor of the test * property. This simulates that the write method reference is freed by the GC. * * @return the bean instance used for testing * @throws Exception if an error occurs */ private FluentIntrospectionTestBean clearWriteMethodRef() throws Exception { FluentIntrospectionTestBean bean = new FluentIntrospectionTestBean(); PropertyDescriptor pd = pub.getPropertyDescriptor(bean, TEST_PROP); // simulate that the write method reference is freed pd.setWriteMethod(null); return bean; } /** * Tests whether a lost write method is automatically recovered and can be invoked. */ public void testWriteMethodRecover() throws Exception { FluentIntrospectionTestBean bean = clearWriteMethodRef(); final String value = "Test value"; pub.setProperty(bean, TEST_PROP, value); assertEquals("Property not set", value, bean.getFluentGetProperty()); } /** * Tests whether a property is recognized as writable even if the reference to its * write method was freed. */ public void testPropertyIsWritable() throws Exception { FluentIntrospectionTestBean bean = clearWriteMethodRef(); assertTrue("Not writable", pub.isWriteable(bean, TEST_PROP)); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira61TestCase.java100644 0 0 43431 12262570610 27556 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.WrapDynaBean; import org.apache.commons.beanutils.bugs.other.Jira61BeanFactory; import org.apache.commons.beanutils.bugs.other.Jira61BeanFactory.TestBean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Test case for Jira issue# BEANUTILS-61. * *

          * {@link WrapDynaBean} is a secial case for the PropertyUtils's * isReadable() and isWriteable() methods - since the bean being * wrapped may have read-only or write-only properties (unlike * regular DynaBeans. * * @version $Id: Jira61TestCase.java 1540186 2013-11-08 21:08:30Z oheger $ * @see https://issues.apache.org/jira/browse/BEANUTILS-61 */ public class Jira61TestCase extends TestCase { private final Log log = LogFactory.getLog(Jira61TestCase.class); private Jira61BeanFactory.TestBean testBean; private WrapDynaBean wrapDynaBean; /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira61TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira61TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); testBean = Jira61BeanFactory.createBean(); PropertyUtils.getPropertyDescriptor(testBean, "mappedReadOnly"); PropertyUtils.getPropertyDescriptor(testBean, "mappedWriteOnly"); wrapDynaBean = new WrapDynaBean(testBean); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link PropertyUtils#isReadable(Object, String)} * for simple properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_isReadable() { boolean result = false; try { result = PropertyUtils.isReadable(wrapDynaBean, "simpleReadOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("simpleReadOnly Threw exception: " + t); } assertTrue("PropertyUtils.isReadable(bean, \"simpleReadOnly\") returned " + result, result); try { result = PropertyUtils.isReadable(wrapDynaBean, "simpleWriteOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("simpleWriteOnly Threw exception: " + t); } assertFalse("PropertyUtils.isReadable(bean, \"simpleWriteOnly\") returned " + result, result); } /** * Test {@link PropertyUtils#isWriteable(Object, String)} * for simple properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_isWriteable() { boolean result = false; try { result = PropertyUtils.isWriteable(wrapDynaBean, "simpleReadOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("simpleReadOnly Threw exception: " + t); } assertFalse("PropertyUtils.isWriteable(bean, \"simpleReadOnly\") returned " + result, result); try { result = PropertyUtils.isWriteable(wrapDynaBean, "simpleWriteOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("simpleWriteOnly Threw exception: " + t); } assertTrue("PropertyUtils.isWriteable(bean, \"simpleWriteOnly\") returned " + result, result); } /** * Test {@link PropertyUtils#isReadable(Object, String)} * for indexed properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_isReadable_Indexed() { boolean result = false; try { result = PropertyUtils.isReadable(wrapDynaBean, "indexedReadOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("indexedReadOnly Threw exception: " + t); } assertTrue("PropertyUtils.isReadable(bean, \"indexedReadOnly\") returned " + result, result); try { result = PropertyUtils.isReadable(wrapDynaBean, "indexedWriteOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("indexedWriteOnly Threw exception: " + t); } assertFalse("PropertyUtils.isReadable(bean, \"indexedWriteOnly\") returned " + result, result); } /** * Test {@link PropertyUtils#isReadable(Object, String)} * for mapped properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_isReadable_Mapped() { boolean result = false; try { result = PropertyUtils.isReadable(wrapDynaBean, "mappedReadOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("mappedReadOnly Threw exception: " + t); } assertTrue("PropertyUtils.isReadable(bean, \"mappedReadOnly\") returned " + result, result); try { result = PropertyUtils.isReadable(wrapDynaBean, "mappedWriteOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("mappedWriteOnly Threw exception: " + t); } assertFalse("PropertyUtils.isReadable(bean, \"mappedWriteOnly\") returned " + result, result); } /** * Test {@link PropertyUtils#isWriteable(Object, String)} * for indexed properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_isWriteable_Indexed() { boolean result = false; try { result = PropertyUtils.isWriteable(wrapDynaBean, "indexedReadOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("indexedReadOnly Threw exception: " + t); } assertFalse("PropertyUtils.isWriteable(bean, \"indexedReadOnly\") returned " + result, result); try { result = PropertyUtils.isWriteable(wrapDynaBean, "indexedWriteOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("indexedWriteOnly Threw exception: " + t); } assertTrue("PropertyUtils.isWriteable(bean, \"indexedWriteOnly\") returned " + result, result); } /** * Test {@link PropertyUtils#isWriteable(Object, String)} * for mapped properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_isWriteable_Mapped() { boolean result = false; try { result = PropertyUtils.isWriteable(wrapDynaBean, "mappedReadOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("mappedReadOnly Threw exception: " + t); } assertFalse("PropertyUtils.isWriteable(bean, \"mappedReadOnly\") returned " + result, result); try { result = PropertyUtils.isWriteable(wrapDynaBean, "mappedWriteOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("mappedWriteOnly Threw exception: " + t); } assertTrue("PropertyUtils.isWriteable(bean, \"mappedWriteOnly\") returned " + result, result); } /** * Test {@link PropertyUtils#getProperty(Object, String)} * for simple properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_getProperty() { boolean threwIllegalArgumentException = false; Object result = null; try { result = PropertyUtils.getProperty(wrapDynaBean, "simpleReadOnly"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("simpleWriteOnly Threw exception: " + t); } assertEquals("simpleReadOnly", testBean.getSimpleReadOnly(), result); try { result = PropertyUtils.getProperty(wrapDynaBean, "simpleWriteOnly"); } catch (IllegalArgumentException ex) { threwIllegalArgumentException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("simpleWriteOnly Threw exception: " + t); } assertTrue("Expected IllegalArgumentException but returned '" + result + "'", threwIllegalArgumentException); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} * for simple properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_setProperty() { boolean threwIllegalArgumentException = false; try { PropertyUtils.setProperty(wrapDynaBean, "simpleReadOnly", "READONLY-SIMPLE-BAR"); } catch (IllegalArgumentException ex) { threwIllegalArgumentException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("simpleReadOnly Threw exception: " + t); } assertTrue("Expected IllegalArgumentException", threwIllegalArgumentException); try { PropertyUtils.setProperty(wrapDynaBean, "simpleWriteOnly", "SIMPLE-BAR"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("simpleWriteOnly Threw exception: " + t); } assertEquals("simpleWriteOnly", testBean.getSimpleReadOnly(), "SIMPLE-BAR"); } /** * Test {@link PropertyUtils#getProperty(Object, String)} * for indexed properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_getProperty_Indexed() { boolean threwIllegalArgumentException = false; Object result = null; try { result = PropertyUtils.getProperty(wrapDynaBean, "indexedReadOnly[0]"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("indexedReadOnly Threw exception: " + t); } assertEquals("indexedReadOnly", testBean.getIndexedReadOnly(0), result); try { result = PropertyUtils.getProperty(wrapDynaBean, "indexedWriteOnly[0]"); } catch (IllegalArgumentException ex) { threwIllegalArgumentException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("indexedWriteOnly Threw exception: " + t); } assertTrue("Expected IllegalArgumentException but returned '" + result + "'", threwIllegalArgumentException); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} * for indexed properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_setProperty_Indexed() { boolean threwIllegalArgumentException = false; try { PropertyUtils.setProperty(wrapDynaBean, "indexedReadOnly[0]", "READONLY-INDEXED-BAR"); } catch (IllegalArgumentException ex) { threwIllegalArgumentException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("indexedReadOnly Threw exception: " + t); } assertTrue("Expected IllegalArgumentException", threwIllegalArgumentException); try { PropertyUtils.setProperty(wrapDynaBean, "indexedWriteOnly[0]", "INDEXED-BAR"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("indexedWriteOnly Threw exception: " + t); } assertEquals("indexedWriteOnly", testBean.getIndexedReadOnly(0), "INDEXED-BAR"); } /** * Test {@link PropertyUtils#getProperty(Object, String)} * for mapped properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_getProperty_Mapped() { boolean threwIllegalArgumentException = false; Object result = null; try { result = PropertyUtils.getProperty(wrapDynaBean, "mappedReadOnly(foo-key)"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("mappedReadOnly Threw exception: " + t); } assertEquals("mappedReadOnly", testBean.getMappedReadOnly("foo-key"), result); try { result = PropertyUtils.getProperty(wrapDynaBean, "mappedWriteOnly(foo-key)"); } catch (IllegalArgumentException ex) { threwIllegalArgumentException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("mappedWriteOnly Threw exception: " + t); } assertTrue("Expected IllegalArgumentException but returned '" + result + "'", threwIllegalArgumentException); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} * for mapped properties. */ public void testIssue_BEANUTILS_61_PropertyUtils_setProperty_Mapped() { boolean threwIllegalArgumentException = false; try { PropertyUtils.setProperty(wrapDynaBean, "mappedReadOnly(foo-key)", "READONLY-MAPPED-BAR"); } catch (IllegalArgumentException ex) { threwIllegalArgumentException = true; // expected result } catch (Throwable t) { log.error("ERROR " + t, t); fail("mappedReadOnly Threw exception: " + t); } assertTrue("Expected IllegalArgumentException", threwIllegalArgumentException); try { PropertyUtils.setProperty(wrapDynaBean, "mappedWriteOnly(foo-key)", "MAPPED-BAR"); } catch (Throwable t) { log.error("ERROR " + t, t); fail("mappedWriteOnly Threw exception: " + t); } assertEquals("mappedWriteOnly", testBean.getMappedReadOnly("foo-key"), "MAPPED-BAR"); } /** * Test {@link PropertyUtils#copyProperties(Object, Object)} * to a read-only WrapDynaBean property. */ public void testIssue_BEANUTILS_61_PropertyUtils_copyProperties_to_WrapDynaBean() { String value = "copied simpleReadOnly"; Map source = new HashMap(); source.put("simpleReadOnly", value); try { PropertyUtils.copyProperties(wrapDynaBean, source); } catch (Throwable t) { log.error("ERROR " + t, t); fail("copyProperties Threw exception: " + t); } assertFalse("Target value='" + value + "'", value.equals(testBean.getSimpleReadOnly())); } /** * Test {@link PropertyUtils#copyProperties(Object, Object)} * to a read-only WrapDynaBean property. */ public void testIssue_BEANUTILS_61_PropertyUtils_copyProperties_from_WrapDynaBean() { String value = "ORIG TARGET VALUE"; TestBean targetBean = Jira61BeanFactory.createBean(); targetBean.setSimpleWriteOnly(value); try { PropertyUtils.copyProperties(targetBean, wrapDynaBean); } catch (Throwable t) { log.error("ERROR " + t, t); fail("copyProperties Threw exception: " + t); } assertTrue("Target value='" + targetBean.getSimpleReadOnly() + "'", value.equals(targetBean.getSimpleReadOnly())); } /** * Test {@link BeanUtils#copyProperties(Object, Object)} * to a read-only WrapDynaBean property. */ public void testIssue_BEANUTILS_61_BeanUtils_copyProperties_to_WrapDynaBean() { String value = "copied simpleReadOnly"; Map source = new HashMap(); source.put("simpleReadOnly", value); try { BeanUtils.copyProperties(wrapDynaBean, source); } catch (Throwable t) { log.error("ERROR " + t, t); fail("copyProperties Threw exception: " + t); } assertFalse("Target value='" + value + "'", value.equals(testBean.getSimpleReadOnly())); } /** * Test {@link BeanUtils#copyProperties(Object, Object)} * to a read-only WrapDynaBean property. */ public void testIssue_BEANUTILS_61_BeanUtils_copyProperties_from_WrapDynaBean() { String value = "ORIG TARGET VALUE"; TestBean targetBean = Jira61BeanFactory.createBean(); targetBean.setSimpleWriteOnly(value); try { BeanUtils.copyProperties(targetBean, wrapDynaBean); } catch (Throwable t) { log.error("ERROR " + t, t); fail("copyProperties Threw exception: " + t); } assertTrue("Target value='" + targetBean.getSimpleReadOnly() + "'", value.equals(targetBean.getSimpleReadOnly())); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira87TestCase.java100644 0 0 6312 12262570610 27543 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.bugs.other.Jira87BeanFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test case for Jiar issue# BEANUTILS-87. * *

          * In BeanUtils 1.7.0 a "package friendly" implementation * of a public interface with defined a "mapped property" * caused an {@link IllegalAccessException} to be thrown by * PropertyUtils's getMappedProperty method. * *

          * This test case demonstrates the issue. * * @version $Id: Jira87TestCase.java 1456817 2013-03-15 09:05:17Z britter $ * @see https://issues.apache.org/jira/browse/BEANUTILS-87 */ public class Jira87TestCase extends TestCase { private final Log log = LogFactory.getLog(Jira87TestCase.class); /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira87TestCase(String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return (new TestSuite(Jira87TestCase.class)); } /** * Set up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Interface definition with a mapped property */ public void testJira87() { Jira87BeanFactory.PublicMappedInterface bean = Jira87BeanFactory.createMappedPropertyBean(); try { // N.B. The test impl. returns the key value assertEquals("foo", PropertyUtils.getMappedProperty(bean, "value(foo)")); } catch (Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/Jira92TestCase.java100644 0 0 4045 12262570610 27540 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs; import junit.framework.TestCase; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.TestBean; /** * Test case for Jira issue# BEANUTILS-92. * * @version $Id: Jira92TestCase.java 1456817 2013-03-15 09:05:17Z britter $ * @see https://issues.apache.org/jira/browse/BEANUTILS-92 */ public class Jira92TestCase extends TestCase { /** * Test copy properties where the target bean only * has an indexed setter. */ public void testIssue_BEANUTILS_92_copyProperties_indexed_only_setter() throws Exception { PropertyUtils.copyProperties(new Jira92TestBean(), new TestBean()); } /** * Test bean which has only indexed setter */ public static class Jira92TestBean { private final java.util.Date[] dateArrayProperty = new java.util.Date[10]; /** * Indexed Setter. * * @param index index * @param date indexed value to set */ public void setDateArrayProperty(int index, java.util.Date date) { this.dateArrayProperty[index] = date; } } } ././@LongLink100644 0 0 151 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/Jira18BeanFactory.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/Jira18BeanFactory.100644 0 0 6477 12262570610 30512 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs.other; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.bugs.Jira18TestCase; /** * Factory which creates package scope beans with * public methods for {@link Jira18TestCase}. * * @version $Id: Jira18BeanFactory.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class Jira18BeanFactory { /** * Factory method which creates package friendly beans. * * @return The a package friendly bean with public methods */ public static Object createBean() { return new PackageFriendlyBean(); } /* =============== Package Friendly Bean =============== */ static class PackageFriendlyBean { private final String[] indexed = new String[] {"one", "two", "three"}; private String simple = "FOO"; private final Map mapped = new HashMap(); /** Default Constructor */ public PackageFriendlyBean() { mapped.put("foo-key", "foo-value"); mapped.put("bar-key", "bar-value"); } /** * Return simple property. * * @return The simple value */ public String getSimple() { return simple; } /** * Set simple property. * * @param simple The simple value */ public void setSimple(String simple) { this.simple = simple; } /** * Return indexed property. * * @param index The index * @return The indexed value */ public String getIndexed(int index) { return indexed[index]; } /** * Set indexed property. * * @param index The index * @param value The indexed value */ public void setIndexed(int index, String value) { this.indexed[index] = value; } /** * Return mapped property. * * @param key The mapped key * @return The mapped value */ public String getMapped(String key) { return (String)mapped.get(key); } /** * Set mapped property. * * @param key The mapped key * @param value The mapped value */ public void setMapped(String key, String value) { mapped.put(key, value); } } } ././@LongLink100644 0 0 152 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/Jira273BeanFactory.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/Jira273BeanFactory100644 0 0 7554 12262570610 30514 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs.other; import org.apache.commons.beanutils.bugs.Jira273TestCase; /** * Factory which creates beans for {@link Jira273TestCase}. * * @version $Id: Jira273BeanFactory.java 1454606 2013-03-08 22:30:51Z britter $ */ public class Jira273BeanFactory { /** * Factory method which creates annonymous * {@link PublicBeanWithMethod} with method NOT overriden. * * @return a new annonymous {@link PublicBeanWithMethod}. */ public static Object createAnnonymousOverriden() { return new PublicBeanWithMethod() { @Override public String getBeanValue() { return "AnnonymousOverriden"; } }; } /** * Factory method which creates annonymous * {@link PublicBeanWithMethod} with method overriden. * * @return a new annonymous {@link PublicBeanWithMethod}. */ public static Object createAnnonymousNotOverriden() { return new PublicBeanWithMethod() { }; } /** * Factory method which creates a PrivatePublicOverriden bean. * * @return a new a PrivatePublicOverriden bean. */ public static Object createPrivatePublicOverriden() { return new PrivatePublicOverriden(); } /** * Factory method which creates a PrivatePrivatePublicOverriden bean. * * @return a new a PrivatePrivatePublicOverriden bean. */ public static Object createPrivatePrivatePublicOverriden() { return new PrivatePrivatePublicOverriden(); } /** * Factory method which creates a PrivatePrivatePublicNotOverriden bean. * * @return a new a PrivatePrivatePublicNotOverriden bean. */ public static Object createPrivatePrivatePublicNotOverriden() { return new PrivatePrivatePublicNotOverriden(); } /** * Factory method which creates a PrivatePublicNotOverriden bean. * * @return a new a PrivatePublicNotOverriden bean. */ public static Object createPrivatePublicNotOverriden() { return new PrivatePublicNotOverriden(); } private static class PrivateBeanWithMethod { public String getBeanValue() { return "PrivateBeanWithMethod"; } } public static class PublicBeanWithMethod { public String getBeanValue() { return "PublicBeanWithMethod"; } } private static class PrivatePublicOverriden extends PublicBeanWithMethod { @Override public String getBeanValue() { return "PrivatePublicOverriden"; } } private static class PrivatePublicNotOverriden extends PublicBeanWithMethod { } private static class PrivatePrivatePublicOverriden extends PrivatePublicNotOverriden { @Override public String getBeanValue() { return "PrivatePrivatePublicOverriden"; } } private static class PrivatePrivatePublicNotOverriden extends PrivatePublicNotOverriden { } } ././@LongLink100644 0 0 152 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/Jira298BeanFactory.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/Jira298BeanFactory100644 0 0 3271 12262570610 30513 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs.other; import org.apache.commons.beanutils.bugs.Jira298TestCase; /** * Factory which creates beans for {@link Jira298TestCase}. * * @version $Id: Jira298BeanFactory.java 1454597 2013-03-08 21:58:12Z britter $ */ public class Jira298BeanFactory { /** * Factory method which creates ImplX. * * @return a new ImplX. */ public static IX createImplX() { return new ImplX(); } public interface IX { public String getName(); public void setName(String name); } static class BaseX { private String name = "BaseX name value"; public String getName() { return name; } public void setName(String name) { this.name = name; } } static class ImplX extends BaseX implements IX { } } ././@LongLink100644 0 0 151 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/Jira61BeanFactory.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/Jira61BeanFactory.100644 0 0 6363 12262570610 30502 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs.other; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.bugs.Jira61TestCase; /** * Factory which creates beans for {@link Jira61TestCase}. * * @version $Id: Jira61BeanFactory.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class Jira61BeanFactory { /** * Factory method which creates a new {@link TestBean}. * * @return a new {@link TestBean}. */ public static TestBean createBean() { return new TestBean(); } /** * Test Bean */ public static class TestBean { private final String[] indexed = new String[] {"one", "two", "three"}; private String simple = "FOO"; private final Map mapped = new HashMap(); /** Default Constructor */ public TestBean() { mapped.put("foo-key", "foo-value"); mapped.put("bar-key", "bar-value"); } /** * Return simpleReadOnly * * @return the simple value */ public String getSimpleReadOnly() { return simple; } /** * Set simpleWriteOnly * * @param simple simple value */ public void setSimpleWriteOnly(String simple) { this.simple = simple; } /** * Return indexed property. * * @param index The index * @return The indexed value */ public String getIndexedReadOnly(int index) { return indexed[index]; } /** * Set indexed property. * * @param index The index * @param value The indexed value */ public void setIndexedWriteOnly(int index, String value) { this.indexed[index] = value; } /** * Return mapped property. * * @param key The mapped key * @return The mapped value */ public String getMappedReadOnly(String key) { return (String)mapped.get(key); } /** * Set mapped property. * * @param key The mapped key * @param value The mapped value */ public void setMappedWriteOnly(String key, String value) { mapped.put(key, value); } } } ././@LongLink100644 0 0 151 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/Jira87BeanFactory.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/bugs/other/Jira87BeanFactory.100644 0 0 4270 12262570610 30505 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.bugs.other; import org.apache.commons.beanutils.bugs.Jira87TestCase; /** * Factory which creates beans for {@link Jira87TestCase}. * * @version $Id: Jira87BeanFactory.java 1454597 2013-03-08 21:58:12Z britter $ */ public class Jira87BeanFactory { /** * Factory method which creates beans bean with mapped method. * * @return The the mapped property bean instance */ public static PublicMappedInterface createMappedPropertyBean() { return new PackageMappedImpl(); } /* =================== Public interface with Mapped Property ========================= */ /** * Public interface with a mapped property. */ public interface PublicMappedInterface { /** * Mapped Property method * @param key The key of the mapped value * @return The value */ Object getValue(String key); } /* =============== Package Friendly implementation of public interface =============== */ static class PackageMappedImpl implements PublicMappedInterface { /** * This implementation returns the key value. * * @param key The key of the mapped value * @return The key value */ public Object getValue(String key) { return key; } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/Child.java100644 0 0 1753 12262570607 25140 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * @version $Id: Child.java 1454597 2013-03-08 21:58:12Z britter $ */ public interface Child { public String getName(); } ././@LongLink100644 0 0 145 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/ConstructorUtilsTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/ConstructorUtilsTestCase.java100644 0 0 24610 12262570607 31134 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** *

          Test case for ConstructorUtils

          * * @version $Id: ConstructorUtilsTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ConstructorUtilsTestCase extends TestCase { // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public ConstructorUtilsTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { super.setUp(); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(ConstructorUtilsTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() throws Exception { super.tearDown(); } // ------------------------------------------------ Individual Test Methods public void testInvokeConstructor() throws Exception { { Object obj = ConstructorUtils.invokeConstructor(TestBean.class,"TEST"); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals("TEST",((TestBean)obj).getStringProperty()); } { Object obj = ConstructorUtils.invokeConstructor(TestBean.class,new Float(17.3f)); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals(17.3f,((TestBean)obj).getFloatProperty(),0.0f); } } public void testInvokeConstructorNull() throws Exception { Object obj = ConstructorUtils.invokeConstructor(TestBean.class, (Object) null); assertNotNull(obj); assertTrue(obj instanceof TestBean); } public void testInvokeConstructorWithArgArray() throws Exception { Object[] args = { new Float(17.3f), "TEST" }; Object obj = ConstructorUtils.invokeConstructor(TestBean.class,args); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals(17.3f,((TestBean)obj).getFloatProperty(),0.0f); assertEquals("TEST",((TestBean)obj).getStringProperty()); } public void testInvokeConstructorWithTypeArray() throws Exception { { Object[] args = { Boolean.TRUE, "TEST" }; Class[] types = { Boolean.TYPE, String.class }; Object obj = ConstructorUtils.invokeConstructor(TestBean.class,args,types); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals(true,((TestBean)obj).getBooleanProperty()); assertEquals("TEST",((TestBean)obj).getStringProperty()); } { Object[] args = { Boolean.TRUE, "TEST" }; Class[] types = { Boolean.class, String.class }; Object obj = ConstructorUtils.invokeConstructor(TestBean.class,args,types); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals(true,((TestBean)obj).isBooleanSecond()); assertEquals("TEST",((TestBean)obj).getStringProperty()); } } public void testInvokeExactConstructor() throws Exception { { Object obj = ConstructorUtils.invokeExactConstructor(TestBean.class,"TEST"); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals("TEST",((TestBean)obj).getStringProperty()); } { try { ConstructorUtils.invokeExactConstructor(TestBean.class,new Float(17.3f)); fail("Expected NoSuchMethodException"); } catch(NoSuchMethodException e) { // expected } } { Object obj = ConstructorUtils.invokeExactConstructor(TestBean.class,Boolean.TRUE); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals(true,((TestBean)obj).isBooleanSecond()); } } public void testInvokeExactConstructorWithNull() throws Exception { Object obj = ConstructorUtils.invokeExactConstructor(TestBean.class, (Object) null); assertNotNull(obj); assertTrue(obj instanceof TestBean); } public void testInvokeExactConstructorWithArgArray() throws Exception { { Object[] args = { new Float(17.3f), "TEST" }; try { ConstructorUtils.invokeExactConstructor(TestBean.class,args); fail("Expected NoSuchMethodException"); } catch(NoSuchMethodException e) { // expected } } { Object[] args = { Boolean.TRUE, "TEST" }; Object obj = ConstructorUtils.invokeExactConstructor(TestBean.class,args); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals(true,((TestBean)obj).isBooleanSecond()); assertEquals("TEST",((TestBean)obj).getStringProperty()); } } public void testInvokeExactConstructorWithTypeArray() throws Exception { { Object[] args = { Boolean.TRUE, "TEST" }; Class[] types = { Boolean.TYPE, String.class }; Object obj = ConstructorUtils.invokeExactConstructor(TestBean.class,args,types); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals(true,((TestBean)obj).getBooleanProperty()); assertEquals("TEST",((TestBean)obj).getStringProperty()); } { Object[] args = { Boolean.TRUE, "TEST" }; Class[] types = { Boolean.class, String.class }; Object obj = ConstructorUtils.invokeExactConstructor(TestBean.class,args,types); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals(true,((TestBean)obj).isBooleanSecond()); assertEquals("TEST",((TestBean)obj).getStringProperty()); } { Object[] args = { new Float(17.3f), "TEST" }; Class[] types = { Float.TYPE, String.class }; Object obj = ConstructorUtils.invokeExactConstructor(TestBean.class,args,types); assertNotNull(obj); assertTrue(obj instanceof TestBean); assertEquals(17.3f,((TestBean)obj).getFloatProperty(),0.0f); assertEquals("TEST",((TestBean)obj).getStringProperty()); } { Object[] args = { new Float(17.3f), "TEST" }; Class[] types = { Float.class, String.class }; try { ConstructorUtils.invokeExactConstructor(TestBean.class,args,types); fail("Expected NoSuchMethodException"); } catch(NoSuchMethodException e) { // expected } } } public void testGetAccessibleConstructor() throws Exception { { Constructor ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,String.class); assertNotNull(ctor); assertTrue(Modifier.isPublic(ctor.getModifiers())); } { Constructor ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,Integer.class); assertNotNull(ctor); assertTrue(Modifier.isPublic(ctor.getModifiers())); } { Constructor ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,Integer.TYPE); assertNull(ctor); } } public void testGetAccessibleConstructorWithTypeArray() throws Exception { { Class[] types = { Boolean.TYPE, String.class }; Constructor ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,types); assertNotNull(ctor); assertTrue(Modifier.isPublic(ctor.getModifiers())); } { Class[] types = { Boolean.TYPE, Boolean.TYPE, String.class }; Constructor ctor = ConstructorUtils.getAccessibleConstructor(TestBean.class,types); assertNull(ctor); } } public void testGetAccessibleConstructorWithConstructorArg() throws Exception { { Class[] types = { Integer.class }; Constructor c1 = TestBean.class.getConstructor(types); Constructor ctor = ConstructorUtils.getAccessibleConstructor(c1); assertNotNull(ctor); assertTrue(Modifier.isPublic(ctor.getModifiers())); } { Class[] types = { Integer.class }; Constructor c1 = TestBean.class.getDeclaredConstructor(types); Constructor ctor = ConstructorUtils.getAccessibleConstructor(c1); assertNotNull(ctor); assertTrue(Modifier.isPublic(ctor.getModifiers())); } { Class[] types = { Integer.TYPE }; Constructor c1 = TestBean.class.getDeclaredConstructor(types); Constructor ctor = ConstructorUtils.getAccessibleConstructor(c1); assertNull(ctor); } } } ././@LongLink100644 0 0 156 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ArrayConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ArrayConverterTest100644 0 0 37723 12262570610 31215 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test Case for the ArrayConverter class. * * @version $Id: ArrayConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ArrayConverterTestCase extends TestCase { /** * Construct a new Array Converter test case. * @param name Test Name */ public ArrayConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ /** * Create Test Suite * @return test suite */ public static TestSuite suite() { return new TestSuite(ArrayConverterTestCase.class); } /** Set Up */ @Override public void setUp() throws Exception { } /** Tear Down */ @Override public void tearDown() throws Exception { } // ------------------------------------------------------------------------ /** * Test Converting using the IntegerConverter as the component Converter */ public void testComponentIntegerConverter() { IntegerConverter intConverter = new IntegerConverter(new Integer(0)); intConverter.setPattern("#,###"); intConverter.setLocale(Locale.US); ArrayConverter arrayConverter = new ArrayConverter(int[].class, intConverter, 0); arrayConverter.setAllowedChars(new char[] {',', '-'}); arrayConverter.setDelimiter(';'); // Expected results int[] intArray = new int[] {1111, 2222, 3333, 4444}; String stringA = "1,111; 2,222; 3,333; 4,444"; String stringB = intArray[0]+ ";" + intArray[1] + ";" + intArray[2] + ";" +intArray[3]; String[] strArray = new String[] {""+intArray[0], ""+intArray[1], ""+intArray[2], ""+intArray[3]}; long[] longArray = new long[] {intArray[0], intArray[1], intArray[2], intArray[3]}; Long[] LONGArray = new Long[] {new Long(intArray[0]), new Long(intArray[1]), new Long(intArray[2]), new Long(intArray[3])}; Integer[] IntegerArray = new Integer[] {new Integer(intArray[0]), new Integer(intArray[1]), new Integer(intArray[2]), new Integer(intArray[3])}; ArrayList strList = new ArrayList(); ArrayList longList = new ArrayList(); for (int i = 0; i < strArray.length; i++) { strList.add(strArray[i]); longList.add(LONGArray[i]); } String msg = null; // String --> int[] try { msg = "String --> int[]"; checkArray(msg, intArray, arrayConverter.convert(int[].class, stringA)); } catch (Exception e) { fail(msg + " failed " + e); } // String --> int[] (with braces) try { msg = "String --> Integer[] (with braces)"; checkArray(msg, IntegerArray, arrayConverter.convert(Integer[].class, "{" + stringA + "}")); } catch (Exception e) { fail(msg + " failed " + e); } // String[] --> int[] try { msg = "String[] --> int[]"; checkArray(msg, intArray, arrayConverter.convert(int[].class, strArray)); } catch (Exception e) { fail(msg + " failed " + e); } // String[] --> Integer[] try { msg = "String[] --> Integer[]"; checkArray(msg, IntegerArray, arrayConverter.convert(Integer[].class, strArray)); } catch (Exception e) { fail(msg + " failed " + e); } // long[] --> int[] try { msg = "long[] --> int[]"; checkArray(msg, intArray, arrayConverter.convert(int[].class, longArray)); } catch (Exception e) { fail(msg + " failed " + e); } // Long --> int[] try { msg = "Long --> int[]"; checkArray(msg, new int[] {LONGArray[0].intValue()}, arrayConverter.convert(int[].class, LONGArray[0])); } catch (Exception e) { fail(msg + " failed " + e); } // LONG[] --> int[] try { msg = "LONG[] --> int[]"; checkArray(msg, intArray, arrayConverter.convert(int[].class, LONGArray)); } catch (Exception e) { fail(msg + " failed " + e); } // Long --> String try { msg = "Long --> String"; assertEquals(msg, LONGArray[0] + "", arrayConverter.convert(String.class, LONGArray[0])); } catch (Exception e) { fail(msg + " failed " + e); } // LONG[] --> String (first) try { msg = "LONG[] --> String (first)"; assertEquals(msg, LONGArray[0] + "", arrayConverter.convert(String.class, LONGArray)); } catch (Exception e) { fail(msg + " failed " + e); } // LONG[] --> String (all) try { msg = "LONG[] --> String (all)"; arrayConverter.setOnlyFirstToString(false); assertEquals(msg, stringB, arrayConverter.convert(String.class, LONGArray)); } catch (Exception e) { fail(msg + " failed " + e); } // Collection of Long --> String try { msg = "Collection of Long --> String"; assertEquals(msg, stringB, arrayConverter.convert(String.class, longList)); } catch (Exception e) { fail(msg + " failed " + e); } // LONG[] --> String[] try { msg = "long[] --> String[]"; checkArray(msg, strArray, arrayConverter.convert(String[].class, LONGArray)); } catch (Exception e) { fail(msg + " failed " + e); } // Collection of String --> Integer[] try { msg = "Collection of String --> Integer[]"; checkArray(msg, IntegerArray, arrayConverter.convert(Integer[].class, strList)); } catch (Exception e) { fail(msg + " failed " + e); } // Collection of Long --> int[] try { msg = "Collection of Long --> int[]"; checkArray(msg, intArray, arrayConverter.convert(int[].class, longList)); } catch (Exception e) { fail(msg + " failed " + e); } } /** * Test Converting a String[] to integer array (with leading/trailing whitespace) */ public void testStringArrayToNumber() { // Configure Converter IntegerConverter intConverter = new IntegerConverter(); ArrayConverter arrayConverter = new ArrayConverter(int[].class, intConverter); // Test Data String[] array = new String[] {"10", " 11", "12 ", " 13 "}; ArrayList list = new ArrayList(); for (int i = 0; i < array.length; i++) { list.add(array[i]); } // Expected results String msg = null; int[] expectedInt = new int[] {10, 11, 12, 13}; Integer[] expectedInteger = new Integer[] {new Integer(expectedInt[0]), new Integer(expectedInt[1]), new Integer(expectedInt[2]), new Integer(expectedInt[3])}; // Test String[] --> int[] try { msg = "String[] --> int[]"; checkArray(msg, expectedInt, arrayConverter.convert(int[].class, array)); } catch (Exception e) { fail(msg + " failed " + e); } // Test String[] --> Integer[] try { msg = "String[] --> Integer[]"; checkArray(msg, expectedInteger, arrayConverter.convert(Integer[].class, array)); } catch (Exception e) { fail(msg + " failed " + e); } // Test List --> int[] try { msg = "List --> int[]"; checkArray(msg, expectedInt, arrayConverter.convert(int[].class, list)); } catch (Exception e) { fail(msg + " failed " + e); } // Test List --> Integer[] try { msg = "List --> Integer[]"; checkArray(msg, expectedInteger, arrayConverter.convert(Integer[].class, list)); } catch (Exception e) { fail(msg + " failed " + e); } } /** * Test the Matrix!!!! (parses a String into a 2 dimensional integer array or matrix) */ public void testTheMatrix() { // Test Date - create the Matrix!! // Following String uses two delimiter: // - comma (",") to separate individual numbers // - semi-colon (";") to separate lists of numbers String matrixString = "11,12,13 ; 21,22,23 ; 31,32,33 ; 41,42,43"; int[][] expected = new int[][] {new int[] {11, 12, 13}, new int[] {21, 22, 23}, new int[] {31, 32, 33}, new int[] {41, 42, 43}}; // Construct an Integer Converter IntegerConverter integerConverter = new IntegerConverter(); // Construct an array Converter for an integer array (i.e. int[]) using // an IntegerConverter as the element converter. // N.B. Uses the default comma (i.e. ",") as the delimiter between individual numbers ArrayConverter arrayConverter = new ArrayConverter(int[].class, integerConverter); // Construct a "Matrix" Converter which converts arrays of integer arrays using // the first (int[]) Converter as the element Converter. // N.B. Uses a semi-colon (i.e. ";") as the delimiter to separate the different sets of numbers. // Also the delimiter for the above array Converter needs to be added to this // array Converter's "allowed characters" ArrayConverter matrixConverter = new ArrayConverter(int[][].class, arrayConverter); matrixConverter.setDelimiter(';'); matrixConverter.setAllowedChars(new char[] {','}); try { // Do the Conversion Object result = matrixConverter.convert(int[][].class, matrixString); // Check it actually worked OK assertEquals("Check int[][].class", int[][].class, result.getClass()); int[][] matrix = (int[][])result; assertEquals("Check int[][] length", expected.length, matrix.length); for (int i = 0; i < expected.length; i++) { assertEquals("Check int[" + i + "] length", expected[i].length, matrix[i].length); for (int j = 0; j < expected[i].length; j++) { String label = "Matrix int[" + i + "," + j + "] element"; assertEquals(label, expected[i][j], matrix[i][j]); // System.out.println(label + " = " + matrix[i][j]); } } } catch (Exception e) { fail("Matrix Conversion threw " + e); } } /** * Test Converting using the IntegerConverter as the component Converter */ public void testInvalidWithDefault() { int[] zeroArray = new int[0]; int[] oneArray = new int[1]; IntegerConverter intConverter = new IntegerConverter(); assertEquals("Null Default", null, new ArrayConverter(int[].class, intConverter, -1).convert(int[].class, null)); checkArray("Zero Length", zeroArray, new ArrayConverter(int[].class, intConverter, 0).convert(int[].class, null)); checkArray("One Length", oneArray, new ArrayConverter(Integer[].class, intConverter, 1).convert(int[].class, null)); } /** * Test Empty String */ public void testEmptyString() { int[] zeroArray = new int[0]; IntegerConverter intConverter = new IntegerConverter(); checkArray("Empty String", zeroArray, new ArrayConverter(int[].class, intConverter, -1).convert(int[].class, "")); assertEquals("Default String", null, new ArrayConverter(int[].class, intConverter).convert(String.class, null)); } /** * Test Errors creating the converter */ public void testErrors() { try { new ArrayConverter(null, new DateConverter()); fail("Default Type missing - expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected result } try { new ArrayConverter(Boolean.class, new DateConverter()); fail("Default Type not an array - expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected result } try { new ArrayConverter(int[].class, null); fail("Component Converter missing - expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected result } } /** * Test for BEANUTILS-302 - throwing a NPE when underscore used */ public void testUnderscore_BEANUTILS_302() { String value = "first_value,second_value"; ArrayConverter converter = new ArrayConverter(String[].class, new StringConverter()); // test underscore not allowed (the default) String[] result = converter.convert(String[].class, value); assertNotNull("result.null", result); assertEquals("result.length", 4, result.length); assertEquals("result[0]", "first", result[0]); assertEquals("result[1]", "value", result[1]); assertEquals("result[2]", "second", result[2]); assertEquals("result[3]", "value", result[3]); // configure the converter to allow underscore converter.setAllowedChars(new char[] {'.', '-', '_'}); // test underscore allowed result = converter.convert(String[].class, value); assertNotNull("result.null", result); assertEquals("result.length", 2, result.length); assertEquals("result[0]", "first_value", result[0]); assertEquals("result[1]", "second_value", result[1]); } /** * Check that two arrays are the same. * @param msg Test prefix msg * @param expected Expected Array value * @param result Result array value */ private void checkArray(String msg, Object expected, Object result) { assertNotNull(msg + " Expected Null", expected); assertNotNull(msg + " Result Null", result); assertTrue(msg + " Result not array", result.getClass().isArray()); assertTrue(msg + " Expected not array", expected.getClass().isArray()); int resultLth = Array.getLength(result); assertEquals(msg + " Size", Array.getLength(expected), resultLth); assertEquals(msg + " Type", expected.getClass(), result.getClass()); for (int i = 0; i < resultLth; i++) { Object expectElement = Array.get(expected, i); Object resultElement = Array.get(result, i); assertEquals(msg + " Element " + i, expectElement, resultElement); } } } ././@LongLink100644 0 0 163 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/BigDecimalConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/BigDecimalConverte100644 0 0 10027 12262570610 31061 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.math.BigDecimal; import junit.framework.TestSuite; import org.apache.commons.beanutils.Converter; /** * Test Case for the DoubleConverter class. * * @version $Id: BigDecimalConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class BigDecimalConverterTestCase extends NumberConverterTestBase { private Converter converter = null; // ------------------------------------------------------------------------ public BigDecimalConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ @Override public void setUp() throws Exception { converter = makeConverter(); numbers[0] = new BigDecimal("-12"); numbers[1] = new BigDecimal("13"); numbers[2] = new BigDecimal("-22"); numbers[3] = new BigDecimal("23"); } public static TestSuite suite() { return new TestSuite(BigDecimalConverterTestCase.class); } @Override public void tearDown() throws Exception { converter = null; } // ------------------------------------------------------------------------ @Override protected NumberConverter makeConverter() { return new BigDecimalConverter(); } @Override protected NumberConverter makeConverter(Object defaultValue) { return new BigDecimalConverter(defaultValue); } @Override protected Class getExpectedType() { return BigDecimal.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { String[] message= { "from String", "from String", "from String", "from String", "from String", "from Byte", "from Short", "from Integer", "from Long", "from Float", "from Double" }; Object[] input = { "-17.2", "-1.1", "0.0", "1.1", "17.2", new Byte((byte)7), new Short((short)8), new Integer(9), new Long(10), new Float("11.1"), new Double("12.2") }; BigDecimal[] expected = { new BigDecimal("-17.2"), new BigDecimal("-1.1"), new BigDecimal("0.0"), new BigDecimal("1.1"), new BigDecimal("17.2"), new BigDecimal("7"), new BigDecimal("8"), new BigDecimal("9"), new BigDecimal("10"), new BigDecimal("11.1"), new BigDecimal("12.2") }; for(int i=0;i getExpectedType() { return BigInteger.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { String[] message= { "from String", "from String", "from String", "from String", "from String", "from String", "from String", "from Byte", "from Short", "from Integer", "from Long", "from Float", "from Double" }; Object[] input = { String.valueOf(Long.MIN_VALUE), "-17", "-1", "0", "1", "17", String.valueOf(Long.MAX_VALUE), new Byte((byte)7), new Short((short)8), new Integer(9), new Long(10), new Float(11.1), new Double(12.2) }; BigInteger[] expected = { BigInteger.valueOf(Long.MIN_VALUE), BigInteger.valueOf(-17), BigInteger.valueOf(-1), BigInteger.valueOf(0), BigInteger.valueOf(1), BigInteger.valueOf(17), BigInteger.valueOf(Long.MAX_VALUE), BigInteger.valueOf(7), BigInteger.valueOf(8), BigInteger.valueOf(9), BigInteger.valueOf(10), BigInteger.valueOf(11), BigInteger.valueOf(12) }; for(int i=0;iboolean[] and String->boolean[]. * *

          Note that the tests here don't rigorously test conversions of individual * strings to booleans, as the BooleanArrayConverter class uses a * BooleanConverter instance to do those conversions, and the BooleanConverter * class has its own unit tests. Here, the tests focus on the array-related * behaviour.

          * * @version $Id: BooleanArrayConverterTestCase.java 1546738 2013-11-30 16:24:19Z oheger $ */ public class BooleanArrayConverterTestCase extends TestCase { public static final String[] STANDARD_TRUES = new String[] { "yes", "y", "true", "on", "1" }; public static final String[] STANDARD_FALSES = new String[] { "no", "n", "false", "off", "0" }; public BooleanArrayConverterTestCase(String name) { super(name); } /** * Check that an object of type String[] with valid boolean string * values gets converted nicely. */ public void testStandardStringArrayConversion() { String[] values = { "true", "false", "yes", "no", "y", "n", "1", "0", }; BooleanArrayConverter converter = new BooleanArrayConverter(); boolean[] results = (boolean[]) converter.convert(null, values); assertNotNull(results); assertEquals(8, results.length); assertTrue(results[0]); assertFalse(results[1]); assertTrue(results[2]); assertFalse(results[3]); assertTrue(results[4]); assertFalse(results[5]); assertTrue(results[6]); assertFalse(results[7]); } /** * Check that an object whose toString method returns a list of boolean * values gets converted nicely. */ public void testStandardStringConversion() { BooleanArrayConverter converter = new BooleanArrayConverter(); StringBuilder input = new StringBuilder(); boolean[] results; // string has {} input.setLength(0); input.append("{true, 'yes', Y, 1, 'FALSE', \"no\", 'n', 0}"); results = (boolean[]) converter.convert(null, input); assertNotNull(results); assertEquals(8, results.length); assertTrue(results[0]); assertTrue(results[1]); assertTrue(results[2]); assertTrue(results[3]); assertFalse(results[4]); assertFalse(results[5]); assertFalse(results[6]); assertFalse(results[7]); // string does not have {} input.setLength(0); input.append("'falsE', 'no', 'N', 0, \"truE\", yeS, 'y', '1'"); results = (boolean[]) converter.convert(null, input); assertNotNull(results); assertEquals(8, results.length); assertFalse(results[0]); assertFalse(results[1]); assertFalse(results[2]); assertFalse(results[3]); assertTrue(results[4]); assertTrue(results[5]); assertTrue(results[6]); assertTrue(results[7]); // string has only one element, non-quoted input.setLength(0); input.append("y"); results = (boolean[]) converter.convert(null, input); assertNotNull(results); assertEquals(1, results.length); assertTrue(results[0]); // string has only one element, quoted with ". input.setLength(0); input.append("\"1\""); results = (boolean[]) converter.convert(null, input); assertNotNull(results); assertEquals(1, results.length); assertTrue(results[0]); // string has only one element, quoted with ' // Here we also pass an object of type String rather than the // StringBuilder results = (boolean[]) converter.convert(null, "'yes'"); assertNotNull(results); assertEquals(1, results.length); assertTrue(results[0]); } /** * Check that the user can specify non-standard true/false values by * providing a customised BooleanConverter. */ public void testAdditionalStrings() { String[] trueStrings = {"sure"}; String[] falseStrings = {"nope"}; BooleanConverter bc = new BooleanConverter( trueStrings, falseStrings, BooleanConverter.NO_DEFAULT); BooleanArrayConverter converter = new BooleanArrayConverter( bc, BooleanArrayConverter.NO_DEFAULT); boolean[] results = (boolean[]) converter.convert(null, "NOPE, sure, sure"); assertNotNull(results); assertEquals(3, results.length); assertFalse(results[0]); assertTrue(results[1]); assertTrue(results[2]); try { // the literal string 'true' should no longer be recognised as // a true value.. converter.convert(null, "true"); fail("Converting invalid string should have generated an exception"); } catch(Exception ex) { // ok, expected } } /** * Check that when the input string cannot be split into a String[], and * there is no default value then an exception is thrown. */ public void testInvalidStringWithoutDefault() { BooleanArrayConverter converter = new BooleanArrayConverter(); try { converter.convert(null, "true!"); fail("Converting invalid string should have generated an exception"); } catch (ConversionException expected) { // Exception is successful test } } /** * Check that when the input string cannot be split into a String[], and * there is a default value then that default is returned. */ public void testInvalidStringWithDefault() { boolean[] defaults = new boolean[1]; BooleanArrayConverter converter = new BooleanArrayConverter(defaults); Object o = converter.convert(null, "true!"); assertSame("Unexpected object returned for failed conversion", o, defaults); } /** * Check that when one of the elements in a comma-separated string is not * a valid boolean, and there is no default value then an exception is thrown. */ public void testInvalidElementWithoutDefault() { BooleanArrayConverter converter = new BooleanArrayConverter(); try { converter.convert(null, "true,bogus"); fail("Converting invalid string should have generated an exception"); } catch (ConversionException expected) { // Exception is successful test } } /** * Check that when one of the elements in a comma-separated string is not * a valid boolean, and there is a default value then the default value * is returned. *

          * Note that the default value is for the complete array object returned, * not for the failed element. */ public void testInvalidElementWithDefault() { boolean[] defaults = new boolean[1]; BooleanArrayConverter converter = new BooleanArrayConverter(defaults); Object o = converter.convert(null, "true,bogus"); assertSame("Unexpected object returned for failed conversion", o, defaults); } /** * Check that when a custom BooleanConverter is used, and that converter * has a (per-element) default, then that element (and just that element) * is assigned the default value. *

          * With the standard BooleanArrayConverter, if any of the elements * in the array are bad, then the array-wide default value is returned. * However by specifying a custom BooleanConverter which has a per-element * default, the unrecognised elements get that per-element default but the * others are converted as expected. */ public void testElementDefault() { boolean[] defaults = new boolean[1]; BooleanConverter bc = new BooleanConverter(Boolean.TRUE); BooleanArrayConverter converter = new BooleanArrayConverter(bc, defaults); boolean[] results = (boolean[]) converter.convert(null, "true,bogus"); assertEquals(2, results.length); assertTrue(results[0]); assertTrue(results[1]); } /** * Check that registration of a custom converter works. */ public void testRegistration() { String[] trueStrings = {"sure"}; String[] falseStrings = {"nope"}; BooleanConverter bc = new BooleanConverter( trueStrings, falseStrings, BooleanConverter.NO_DEFAULT); BooleanArrayConverter converter = new BooleanArrayConverter( bc, BooleanArrayConverter.NO_DEFAULT); ConvertUtils.register(converter, BooleanArrayConverter.MODEL); boolean[] sample = new boolean[0]; boolean[] results = (boolean[]) ConvertUtils.convert("sure,nope", sample.getClass()); assertEquals(2, results.length); assertTrue(results[0]); assertFalse(results[1]); } } ././@LongLink100644 0 0 160 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/BooleanConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/BooleanConverterTe100644 0 0 11163 12262570610 31135 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestCase; import org.apache.commons.beanutils.ConversionException; /** * @version $Id: BooleanConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class BooleanConverterTestCase extends TestCase { public static final String[] STANDARD_TRUES = new String[] { "yes", "y", "true", "on", "1" }; public static final String[] STANDARD_FALSES = new String[] { "no", "n", "false", "off", "0" }; public BooleanConverterTestCase(String name) { super(name); } public void testStandardValues() { BooleanConverter converter = new BooleanConverter(); testConversionValues(converter, STANDARD_TRUES, STANDARD_FALSES); } public void testCaseInsensitivity() { BooleanConverter converter = new BooleanConverter(); testConversionValues( converter, new String[] {"Yes", "TRUE"}, new String[] {"NO", "fAlSe"}); } public void testInvalidString() { BooleanConverter converter = new BooleanConverter(); try { converter.convert(Boolean.class, "bogus"); fail("Converting invalid string should have generated an exception"); } catch (ConversionException expected) { // Exception is successful test } } public void testDefaultValue() { Object defaultValue = Boolean.TRUE; BooleanConverter converter = new BooleanConverter(defaultValue); assertSame(defaultValue, converter.convert(Boolean.class, "bogus")); testConversionValues(converter, STANDARD_TRUES, STANDARD_FALSES); } public void testAdditionalStrings() { String[] trueStrings = {"sure"}; String[] falseStrings = {"nope"}; BooleanConverter converter = new BooleanConverter( trueStrings, falseStrings, BooleanConverter.NO_DEFAULT); testConversionValues( converter, new String[] {"sure", "Sure"}, new String[] {"nope", "nOpE"}); try { converter.convert(Boolean.class, "true"); fail("Converting obsolete true value should have generated an exception"); } catch (ConversionException expected) { // Exception is successful test } try { converter.convert(Boolean.class, "bogus"); fail("Converting invalid string should have generated an exception"); } catch (ConversionException expected) { // Exception is successful test } } /** * Tests a conversion to another target type. This should not be possible. */ public void testConversionToOtherType() { BooleanConverter converter = new BooleanConverter(); try { converter.convert(Integer.class, STANDARD_TRUES[0]); fail("Could convert to unsupported type!"); } catch (ConversionException cex) { // Expected result } } /** * Tests whether a conversion to a primitive boolean is possible. */ public void testPrimitiveTargetClass() { BooleanConverter converter = new BooleanConverter(); assertTrue("Wrong result", converter.convert(Boolean.TYPE, STANDARD_TRUES[0])); } protected void testConversionValues(BooleanConverter converter, String[] trueValues, String[] falseValues) { for (int i = 0; i < trueValues.length; i++) { assertEquals(Boolean.TRUE, converter.convert(Boolean.class, trueValues[i])); } for (int i = 0; i < falseValues.length; i++) { assertEquals(Boolean.FALSE, converter.convert(Boolean.class, falseValues[i])); } } } ././@LongLink100644 0 0 155 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ByteConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ByteConverterTestC100644 0 0 12361 12262570610 31134 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestSuite; import org.apache.commons.beanutils.Converter; /** * Test Case for the ByteConverter class. * * @version $Id: ByteConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ByteConverterTestCase extends NumberConverterTestBase { private Converter converter = null; // ------------------------------------------------------------------------ public ByteConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ @Override public void setUp() throws Exception { converter = makeConverter(); numbers[0] = new Byte("-12"); numbers[1] = new Byte("13"); numbers[2] = new Byte("-22"); numbers[3] = new Byte("23"); } public static TestSuite suite() { return new TestSuite(ByteConverterTestCase.class); } @Override public void tearDown() throws Exception { converter = null; } // ------------------------------------------------------------------------ @Override protected NumberConverter makeConverter() { return new ByteConverter(); } @Override protected NumberConverter makeConverter(Object defaultValue) { return new ByteConverter(defaultValue); } @Override protected Class getExpectedType() { return Byte.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { String[] message= { "from String", "from String", "from String", "from String", "from String", "from String", "from String", "from Byte", "from Short", "from Integer", "from Long", "from Float", "from Double" }; Object[] input = { String.valueOf(Byte.MIN_VALUE), "-17", "-1", "0", "1", "17", String.valueOf(Byte.MAX_VALUE), new Byte((byte)7), new Short((short)8), new Integer(9), new Long(10), new Float(11.1), new Double(12.2) }; Byte[] expected = { new Byte(Byte.MIN_VALUE), new Byte((byte)-17), new Byte((byte)-1), new Byte((byte)0), new Byte((byte)1), new Byte((byte)17), new Byte(Byte.MAX_VALUE), new Byte((byte)7), new Byte((byte)8), new Byte((byte)9), new Byte((byte)10), new Byte((byte)11), new Byte((byte)12) }; for(int i=0;i clazz = Byte.class; Long min = new Long(Byte.MIN_VALUE); Long max = new Long(Byte.MAX_VALUE); Long minMinusOne = new Long(min.longValue() - 1); Long maxPlusOne = new Long(max.longValue() + 1); // Minimum assertEquals("Minimum", new Byte(Byte.MIN_VALUE), converter.convert(clazz, min)); // Maximum assertEquals("Maximum", new Byte(Byte.MAX_VALUE), converter.convert(clazz, max)); // Too Small try { assertEquals("Minimum - 1", null, converter.convert(clazz, minMinusOne)); fail("Less than minimum, expected ConversionException"); } catch (Exception e) { // expected result } // Too Large try { assertEquals("Maximum + 1", null, converter.convert(clazz, maxPlusOne)); fail("More than maximum, expected ConversionException"); } catch (Exception e) { // expected result } } } ././@LongLink100644 0 0 161 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/CalendarConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/CalendarConverterT100644 0 0 5126 12262570610 31104 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.Calendar; import junit.framework.TestSuite; /** * Test Case for the CalendarConverter class. * * @version $Id: CalendarConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class CalendarConverterTestCase extends DateConverterTestBase { /** * Construct a new Calendar test case. * @param name Test Name */ public CalendarConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ /** * Create Test Suite * @return test suite */ public static TestSuite suite() { return new TestSuite(CalendarConverterTestCase.class); } // ------------------------------------------------------------------------ /** * Create the Converter with no default value. * @return A new Converter */ @Override protected DateTimeConverter makeConverter() { return new CalendarConverter(); } /** * Create the Converter with a default value. * @param defaultValue The default value * @return A new Converter */ @Override protected DateTimeConverter makeConverter(Object defaultValue) { return new CalendarConverter(defaultValue); } /** * Return the expected type * @return The expected type */ @Override protected Class getExpectedType() { return Calendar.class; } /** * Convert from a java.util.Date to the Converter's type. * * @param value The Date value to convert * @return The converted value */ @Override protected Object toType(Calendar value) { return value; } }././@LongLink100644 0 0 162 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/CharacterConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/CharacterConverter100644 0 0 10531 12262570610 31157 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.Converter; /** * Test Case for the CharacterConverter class. * * @version $Id: CharacterConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class CharacterConverterTestCase extends TestCase { /** * Construct a new Character Converter test case. * @param name Test Name */ public CharacterConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ /** * Create Test Suite * @return test suite */ public static TestSuite suite() { return new TestSuite(CharacterConverterTestCase.class); } /** Set Up */ @Override public void setUp() throws Exception { } /** Tear Down */ @Override public void tearDown() throws Exception { } // ------------------------------------------------------------------------ /** * Test Conversion to String */ public void testConvertToString() { Converter converter = new CharacterConverter(); assertEquals("Character Test", "N", converter.convert(String.class, new Character('N'))); assertEquals("String Test", "F", converter.convert(String.class, "FOO")); assertEquals("Integer Test", "3", converter.convert(String.class, new Integer(321))); assertEquals("Null Test", null, converter.convert(String.class, null)); } /** * Test Conversion to Character */ public void testConvertToCharacter() { Converter converter = new CharacterConverter(); assertEquals("Character Test", new Character('N'), converter.convert(Character.class, new Character('N'))); assertEquals("String Test", new Character('F'), converter.convert(Character.class, "FOO")); assertEquals("Integer Test", new Character('3'), converter.convert(Character.class, new Integer(321))); } /** * Tests whether the primitive char class can be passed as target type. */ public void testConvertToChar() { Converter converter = new CharacterConverter(); assertEquals("Wrong result", new Character('F'), converter.convert(Character.TYPE, "FOO")); } /** * Tests a conversion to character for null input if no default value is * provided. */ public void testConvertToCharacterNullNoDefault() { Converter converter = new CharacterConverter(); try { converter.convert(Character.class, null); fail("Expected a ConversionException for null value"); } catch (Exception e) { // expected result } } /** * Test Conversion to Character (with default) */ public void testDefault() { Converter converter = new CharacterConverter("C"); assertEquals("Default Test", new Character('C'), converter.convert(Character.class, null)); } /** * Tries a conversion to an unsupported type. */ public void testConvertToUnsupportedType() { Converter converter = new CharacterConverter(); try { converter.convert(Integer.class, "Test"); fail("Could convert to unsupported type!"); } catch (ConversionException cex) { // expected result } } } ././@LongLink100644 0 0 156 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ClassConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ClassConverterTest100644 0 0 12666 12262570610 31203 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.Converter; /** * Test Case for the ClassConverter class. * * @version $Id: ClassConverterTestCase.java 1546738 2013-11-30 16:24:19Z oheger $ */ public class ClassConverterTestCase extends TestCase { /** * Construct a new Class Converter test case. * @param name Test Name */ public ClassConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ /** * Create Test Suite * @return test suite */ public static TestSuite suite() { return new TestSuite(ClassConverterTestCase.class); } /** Set Up */ @Override public void setUp() throws Exception { } /** Tear Down */ @Override public void tearDown() throws Exception { } // ------------------------------------------------------------------------ /** * Test Conversion to String */ public void testConvertToString() { Converter converter = new ClassConverter(); assertEquals("Class Test", "java.lang.Integer", converter.convert(String.class, Integer.class)); assertEquals("Value Test", "foo", converter.convert(String.class, "foo")); assertEquals("Value Test", "bar", converter.convert(String.class, new StringBuilder("bar"))); assertEquals("Null Test", null, converter.convert(String.class, null)); } /** * Test Conversion to Class */ public void testConvertToClass() { Converter converter = new ClassConverter(); assertEquals("Class Test", Integer.class, converter.convert(Class.class, Integer.class)); assertEquals("String Test", Integer.class, converter.convert(Class.class, "java.lang.Integer")); assertEquals("StringBuilder Test", Integer.class, converter.convert(Class.class, new StringBuilder("java.lang.Integer"))); // Invalid Test try { converter.convert(Class.class, new Integer(6)); fail("Expected invalid value to fail"); } catch (ConversionException e) { // expected result } // Test Null try { converter.convert(Class.class, null); fail("Expected null value to fail"); } catch (ConversionException e) { // expected result } } /** * Test Invalid Conversion with default */ public void testConvertToClassDefault() { Converter converter = new ClassConverter(Object.class); assertEquals("Invalid Test", Object.class, converter.convert(Class.class, new Integer(6))); assertEquals("Null Test", Object.class, converter.convert(Class.class, null)); } /** * Test Invalid Conversion with default "null" */ public void testConvertToClassDefaultNull() { Converter converter = new ClassConverter(null); assertEquals("Invalid Test", null, converter.convert(Class.class, new Integer(6))); assertEquals("Null Test", null, converter.convert(Class.class, null)); } /** * Test Array Conversion */ public void testArray() { Converter converter = new ClassConverter(); // Test Array Class to String assertEquals("Array to String", "[Ljava.lang.Boolean;", converter.convert(String.class, Boolean[].class)); // *** N.B. for some reason the following works on m1, but not m2 // Test String to Array Class // assertEquals("String to Array", Boolean[].class, converter.convert(Class.class, "[Ljava.lang.Boolean;")); } /** * Test Invalid */ public void testInvalid() { Converter converter = new ClassConverter(); // Test invalid class name try { converter.convert(Class.class, "foo.bar"); fail("Invalid class name, expected ConversionException"); } catch (ConversionException e) { // expected result } } /** * Tries a conversion to an unsupported target type. */ public void testUnsupportedTargetType() { Converter converter = new ClassConverter(); try { converter.convert(Integer.class, getClass().getName()); fail("Invalid target class not detected!"); } catch (ConversionException cex) { // expected result } } } ././@LongLink100644 0 0 145 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ClassReloader.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ClassReloader.java100644 0 0 6650 12262570610 31025 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * A special classloader useful for testing j2ee-like scenarios. * *

          In some tests we want to be able to emulate "container" frameworks, * where code runs in a hierarchy of classloaders, and certain classes may * be loaded by various classloaders in the hierarchy.

          * *

          Normally this is done by having certain jars or class-file-directories * in the classpath of some classloaders but not others. This is quite * difficult difficult to integrate with the build process for the unit * tests though; compiling certain classes and having the output go into * places that is not in the default classpath for the unit tests would be * a major pain.

          * *

          So this class takes a sneaky alternative approach: it can grab any class * already loaded by a parent classloader and reload that class via this * classloader. The effect is exactly as if a class (or jar file) had been * present in the classpath for a container's "shared" classloader and * been present in the component-specific classpath too, without any messing * about with the way unit test code is compiled or executed. * * @version $Id: ClassReloader.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ClassReloader extends ClassLoader { public ClassReloader(ClassLoader parent) { super(parent); } /** * Given a class already in the classpath of a parent classloader, * reload that class via this classloader. */ public Class reload(Class clazz) throws FileNotFoundException, IOException { String className = clazz.getName(); String classFile = className.replace('.', '/') + ".class"; InputStream classStream = getParent().getResourceAsStream(classFile); if (classStream == null) { throw new FileNotFoundException(classFile); } byte[] buf = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); for(;;) { int bytesRead = classStream.read(buf); if (bytesRead == -1) break; baos.write(buf, 0, bytesRead); } classStream.close(); byte[] classData = baos.toByteArray(); // now we have the raw class data, let's turn it into a class Class newClass = defineClass(className, classData, 0, classData.length); resolveClass(newClass); return newClass; } } ././@LongLink100644 0 0 155 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ClassReloaderTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ClassReloaderTestC100644 0 0 5431 12262570610 31044 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests for the ClassReloader utility class. * * @version $Id: ClassReloaderTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ClassReloaderTestCase extends TestCase { // ------------------------------------------------------------------------ public ClassReloaderTestCase(String name) { super(name); } public static TestSuite suite() { return new TestSuite(ClassReloaderTestCase.class); } // ------------------------------------------------------------------------ public static class DummyClass { } /** * Test basic operation of the ClassReloader. */ public void testBasicOperation() throws Exception { ClassLoader sharedLoader = this.getClass().getClassLoader(); ClassReloader componentLoader = new ClassReloader(sharedLoader); Class sharedClass = DummyClass.class; Class componentClass = componentLoader.reload(sharedClass); // the two Class objects contain the same bytecode, but are not equal assertTrue(sharedClass != componentClass); // the two class objects have different classloaders assertSame(sharedLoader, sharedClass.getClassLoader()); assertSame(componentLoader, componentClass.getClassLoader()); assertTrue(sharedLoader != componentLoader); // verify that objects of these two types are not assignment-compatible Object obj1 = sharedClass.newInstance(); Object obj2 = componentClass.newInstance(); assertTrue("Obj1 class incorrect", sharedClass.isInstance(obj1)); assertFalse("Obj1 class incorrect", componentClass.isInstance(obj1)); assertFalse("Obj2 class incorrect", sharedClass.isInstance(obj2)); assertTrue("Obj2 class incorrect", componentClass.isInstance(obj2)); } } ././@LongLink100644 0 0 152 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ConverterTestSuite.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ConverterTestSuite100644 0 0 5303 12262570610 31175 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.Test; import junit.framework.TestSuite; /** *

          * Created a test suite so that new test cases can be added here without having to * edit the build.xml. *

          * * @version $Id: ConverterTestSuite.java 1454597 2013-03-08 21:58:12Z britter $ */ public class ConverterTestSuite { /** * Return the tests included in this test suite. */ public static Test suite() { TestSuite testSuite = new TestSuite(); testSuite.addTestSuite(ArrayConverterTestCase.class); testSuite.addTestSuite(BigDecimalConverterTestCase.class); testSuite.addTestSuite(BigIntegerConverterTestCase.class); testSuite.addTestSuite(BooleanArrayConverterTestCase.class); testSuite.addTestSuite(BooleanConverterTestCase.class); testSuite.addTestSuite(ByteConverterTestCase.class); testSuite.addTestSuite(CalendarConverterTestCase.class); testSuite.addTestSuite(CharacterConverterTestCase.class); testSuite.addTestSuite(ClassConverterTestCase.class); testSuite.addTestSuite(DateConverterTestCase.class); testSuite.addTestSuite(DoubleConverterTestCase.class); testSuite.addTestSuite(FileConverterTestCase.class); testSuite.addTestSuite(FloatConverterTestCase.class); testSuite.addTestSuite(IntegerConverterTestCase.class); testSuite.addTestSuite(LongConverterTestCase.class); testSuite.addTestSuite(ShortConverterTestCase.class); testSuite.addTestSuite(SqlDateConverterTestCase.class); testSuite.addTestSuite(SqlTimeConverterTestCase.class); testSuite.addTestSuite(SqlTimestampConverterTestCase.class); testSuite.addTestSuite(StringArrayConverterTestCase.class); testSuite.addTestSuite(URLConverterTestCase.class); return testSuite; } } ././@LongLink100644 0 0 155 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestBase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestB100644 0 0 45040 12262570610 31105 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import junit.framework.TestCase; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.Converter; /** * Abstract base for <Date>Converter classes. * * @version $Id: DateConverterTestBase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public abstract class DateConverterTestBase extends TestCase { // ------------------------------------------------------------------------ /** * Construct a new test case. * @param name Name of the test */ public DateConverterTestBase(String name) { super(name); } // ------------------------------------------------------------------------ /** * Create the Converter with no default value. * @return A new Converter */ protected abstract DateTimeConverter makeConverter(); /** * Create the Converter with a default value. * @param defaultValue The default value * @return A new Converter */ protected abstract DateTimeConverter makeConverter(Object defaultValue); /** * Return the expected type * @return The expected type */ protected abstract Class getExpectedType(); /** * Convert from a Calendar to the appropriate Date type * * @param value The Calendar value to convert * @return The converted value */ protected abstract Object toType(Calendar value); // ------------------------------------------------------------------------ /** * Assumes ConversionException in response to covert(getExpectedType(), null). */ public void testConvertNull() { try { makeConverter().convert(getExpectedType(), null); fail("Expected ConversionException"); } catch(ConversionException e) { // expected } } /** * Assumes convert() returns some non-null * instance of getExpectedType(). */ public void testConvertDate() { String[] message= { "from Date", "from Calendar", "from SQL Date", "from SQL Time", "from SQL Timestamp" }; long now = System.currentTimeMillis(); Object[] date = { new Date(now), new java.util.GregorianCalendar(), new java.sql.Date(now), new java.sql.Time(now), new java.sql.Timestamp(now) }; // Initialize calendar also with same ms to avoid a failing test in a new time slice ((GregorianCalendar)date[1]).setTime(new Date(now)); for (int i = 0; i < date.length; i++) { Object val = makeConverter().convert(getExpectedType(), date[i]); assertNotNull("Convert " + message[i] + " should not be null", val); assertTrue("Convert " + message[i] + " should return a " + getExpectedType().getName(), getExpectedType().isInstance(val)); assertEquals("Convert " + message[i] + " should return a " + date[0], now, getTimeInMillis(val)); } } /** * Test Default Type conversion (i.e. don't specify target type) */ public void testDefaultType() { String pattern = "yyyy-MM-dd"; // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setPattern(pattern); // Valid String --> Type Conversion String testString = "2006-10-29"; Calendar calendar = toCalendar(testString, pattern, null); Object expected = toType(calendar); Object result = converter.convert(null, testString); if (getExpectedType().equals(Calendar.class)) { assertTrue("TYPE ", getExpectedType().isAssignableFrom(result.getClass())); } else { assertEquals("TYPE ", getExpectedType(), result.getClass()); } assertEquals("VALUE ", expected, result); } /** * Test default String to type conversion * * N.B. This method is overridden by test case * implementations for java.sql.Date/Time/Timestamp */ public void testDefaultStringToTypeConvert() { // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setUseLocaleFormat(false); try { converter.convert(getExpectedType(), "2006-10-23"); fail("Expected Conversion exception"); } catch (ConversionException e) { // expected result } } /** * Test Conversion to String */ public void testStringConversion() { String pattern = "yyyy-MM-dd"; // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setPattern(pattern); // Create Values String expected = "2006-10-29"; Calendar calendar = toCalendar(expected, pattern, null); // Type --> String Conversion stringConversion(converter, expected, toType(calendar)); // Calendar --> String Conversion stringConversion(converter, expected, calendar); // java.util.Date --> String Conversion stringConversion(converter, expected, toDate(calendar)); // java.sql.Date --> String Conversion stringConversion(converter, expected, toSqlDate(calendar)); // java.sql.Timestamp --> String Conversion stringConversion(converter, expected, toSqlTimestamp(calendar)); // java.sql.Time --> String Conversion stringConversion(converter, expected, toSqlTime(calendar)); stringConversion(converter, null, null); stringConversion(converter, "", ""); } /** * Test Converter with no default value */ public void testPatternNoDefault() { String pattern = "yyyy-MM-dd"; // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setPattern(pattern); // Valid String --> Type Conversion String testString = "2006-10-29"; Calendar calendar = toCalendar(testString, pattern, null); Object expected = toType(calendar); validConversion(converter, expected, testString); // Valid java.util.Date --> Type Conversion validConversion(converter, expected, calendar); // Valid Calendar --> Type Conversion validConversion(converter, expected, toDate(calendar)); // Test java.sql.Date --> Type Conversion validConversion(converter, expected, toSqlDate(calendar)); // java.sql.Timestamp --> String Conversion validConversion(converter, expected, toSqlTimestamp(calendar)); // java.sql.Time --> String Conversion validConversion(converter, expected, toSqlTime(calendar)); // Invalid Conversions invalidConversion(converter, null); invalidConversion(converter, ""); invalidConversion(converter, "2006-10-2X"); invalidConversion(converter, "2006/10/01"); invalidConversion(converter, "02/10/2006"); invalidConversion(converter, "02/10/06"); invalidConversion(converter, new Integer(2)); } /** * Test Converter with no default value */ public void testPatternDefault() { String pattern = "yyyy-MM-dd"; // Create & Configure the Converter Object defaultValue = toType("2000-01-01", pattern, null); assertNotNull("Check default date", defaultValue); DateTimeConverter converter = makeConverter(defaultValue); converter.setPattern(pattern); // Valid String --> Type Conversion String testString = "2006-10-29"; Object expected = toType(testString, pattern, null); validConversion(converter, expected, testString); // Invalid Values, expect default value validConversion(converter, defaultValue, null); validConversion(converter, defaultValue, ""); validConversion(converter, defaultValue, "2006-10-2X"); validConversion(converter, defaultValue, "2006/10/01"); validConversion(converter, defaultValue, "02/10/06"); validConversion(converter, defaultValue, new Integer(2)); } /** * Test Converter with no default value */ public void testPatternNullDefault() { String pattern = "yyyy-MM-dd"; // Create & Configure the Converter Object defaultValue = null; DateTimeConverter converter = makeConverter(defaultValue); converter.setPattern(pattern); // Valid String --> Type Conversion String testString = "2006-10-29"; Object expected = toType(testString, pattern, null); validConversion(converter, expected, testString); // Invalid Values, expect default --> null validConversion(converter, defaultValue, null); validConversion(converter, defaultValue, ""); validConversion(converter, defaultValue, "2006-10-2X"); validConversion(converter, defaultValue, "2006/10/01"); validConversion(converter, defaultValue, "02/10/06"); validConversion(converter, defaultValue, new Integer(2)); } /** * Test Converter with multiple patterns */ public void testMultiplePatterns() { String testString = null; Object expected = null; // Create & Configure the Converter String[] patterns = new String[] {"yyyy-MM-dd", "yyyy/MM/dd"}; DateTimeConverter converter = makeConverter(); converter.setPatterns(patterns); // First Pattern testString = "2006-10-28"; expected = toType(testString, patterns[0], null); validConversion(converter, expected, testString); // Second pattern testString = "2006/10/18"; expected = toType(testString, patterns[1], null); validConversion(converter, expected, testString); // Invalid Conversion invalidConversion(converter, "17/03/2006"); invalidConversion(converter, "17.03.2006"); } /** * Test Date Converter with no default value */ public void testLocale() { // Re-set the default Locale to Locale.US Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); String pattern = "M/d/yy"; // SHORT style date format for US Locale // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setUseLocaleFormat(true); // Valid String --> Type Conversion String testString = "10/28/06"; Object expected = toType(testString, pattern, null); validConversion(converter, expected, testString); // Invalid Conversions invalidConversion(converter, null); invalidConversion(converter, ""); invalidConversion(converter, "2006-10-2X"); invalidConversion(converter, "10.28.06"); invalidConversion(converter, "10-28-06"); invalidConversion(converter, new Integer(2)); // Restore the default Locale Locale.setDefault(defaultLocale); } /** * Test Converter with types it can't handle */ public void testInvalidType() { // Create & Configure the Converter DateTimeConverter converter = makeConverter(); // Invalid Class Type try { converter.convert(Character.class, new Date()); fail("Requested Character.class conversion, expected ConversionException"); } catch (ConversionException e) { // Expected result } } /** * Test Conversion to the required type * @param converter The converter to use * @param expected The expected result * @param value The value to convert */ void validConversion(Converter converter, Object expected, Object value) { String valueType = (value == null ? "null" : value.getClass().getName()); String msg = "Converting '" + valueType + "' value '" + value + "'"; try { Object result = converter.convert(getExpectedType(), value); Class resultType = (result == null ? null : result.getClass()); Class expectType = (expected == null ? null : expected.getClass()); assertEquals("TYPE " + msg, expectType, resultType); assertEquals("VALUE " + msg, expected, result); } catch (Exception ex) { fail(msg + " threw " + ex.toString()); } } /** * Test Conversion to String * @param converter The converter to use * @param expected The expected result * @param value The value to convert */ void stringConversion(Converter converter, String expected, Object value) { String valueType = (value == null ? "null" : value.getClass().getName()); String msg = "Converting '" + valueType + "' value '" + value + "' to String"; try { Object result = converter.convert(String.class, value); Class resultType = (result == null ? null : result.getClass()); Class expectType = (expected == null ? null : expected.getClass()); assertEquals("TYPE " + msg, expectType, resultType); assertEquals("VALUE " + msg, expected, result); } catch (Exception ex) { fail(msg + " threw " + ex.toString()); } } /** * Test Conversion Error * @param converter The converter to use * @param value The value to convert */ void invalidConversion(Converter converter, Object value) { String valueType = (value == null ? "null" : value.getClass().getName()); String msg = "Converting '" + valueType + "' value '" + value + "'"; try { Object result = converter.convert(getExpectedType(), value); fail(msg + ", expected ConversionException, but result = '" + result + "'"); } catch (ConversionException ex) { // Expected Result } } /** * Parse a String value to the required type * @param value The String value to parse * @param pattern The date pattern * @param locale The locale to use (or null) * @return parsed Calendar value */ Object toType(String value, String pattern, Locale locale) { Calendar calendar = toCalendar(value, pattern, locale); return toType(calendar); } /** * Parse a String value to a Calendar * @param value The String value to parse * @param pattern The date pattern * @param locale The locale to use (or null) * @return parsed Calendar value */ Calendar toCalendar(String value, String pattern, Locale locale) { Calendar calendar = null; try { DateFormat format = (locale == null) ? new SimpleDateFormat(pattern) : new SimpleDateFormat(pattern, locale); format.setLenient(false); format.parse(value); calendar = format.getCalendar(); } catch (Exception e) { fail("Error creating Calendar value ='" + value + ", pattern='" + pattern + "' " + e.toString()); } return calendar; } /** * Convert a Calendar to a java.util.Date * @param calendar The calendar object to convert * @return The converted java.util.Date */ Date toDate(Calendar calendar) { return calendar.getTime(); } /** * Convert a Calendar to a java.sql.Date * @param calendar The calendar object to convert * @return The converted java.sql.Date */ java.sql.Date toSqlDate(Calendar calendar) { return new java.sql.Date(getTimeInMillis(calendar)); } /** * Convert a Calendar to a java.sql.Time * @param calendar The calendar object to convert * @return The converted java.sql.Time */ java.sql.Time toSqlTime(Calendar calendar) { return new java.sql.Time(getTimeInMillis(calendar)); } /** * Convert a Calendar to a java.sql.Timestamp * @param calendar The calendar object to convert * @return The converted java.sql.Timestamp */ java.sql.Timestamp toSqlTimestamp(Calendar calendar) { return new java.sql.Timestamp(getTimeInMillis(calendar)); } /** * Convert a Date or Calendar objects to the time in millisconds * @param date The date or calendar object * @return The time in milliseconds */ long getTimeInMillis(Object date) { if (date instanceof java.sql.Timestamp) { // ---------------------- JDK 1.3 Fix ---------------------- // N.B. Prior to JDK 1.4 the Timestamp's getTime() method // didn't include the milliseconds. The following code // ensures it works consistently accross JDK versions java.sql.Timestamp timestamp = (java.sql.Timestamp)date; long timeInMillis = ((timestamp.getTime() / 1000) * 1000); timeInMillis += timestamp.getNanos() / 1000000; return timeInMillis; } if (date instanceof Calendar) { return ((Calendar)date).getTime().getTime(); } else { return ((Date)date).getTime(); } } } ././@LongLink100644 0 0 155 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/DateConverterTestC100644 0 0 5413 12262570610 31066 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.util.Calendar; import java.util.Date; import junit.framework.TestSuite; /** * Test Case for the DateConverter class. * * @version $Id: DateConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class DateConverterTestCase extends DateConverterTestBase { /** * Construct a new Date test case. * @param name Test Name */ public DateConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ /** * Create Test Suite * @return test suite */ public static TestSuite suite() { return new TestSuite(DateConverterTestCase.class); } /** Set Up */ @Override public void setUp() throws Exception { } /** Tear Down */ @Override public void tearDown() throws Exception { } // ------------------------------------------------------------------------ /** * Create the Converter with no default value. * @return A new Converter */ @Override protected DateTimeConverter makeConverter() { return new DateConverter(); } /** * Create the Converter with a default value. * @param defaultValue The default value * @return A new Converter */ @Override protected DateTimeConverter makeConverter(Object defaultValue) { return new DateConverter(defaultValue); } /** * Return the expected type * @return The expected type */ @Override protected Class getExpectedType() { return Date.class; } /** * Convert from a Calendar to the appropriate Date type * * @param value The Calendar value to convert * @return The converted value */ @Override protected Object toType(Calendar value) { return value.getTime(); } }././@LongLink100644 0 0 157 12262571655 10271 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/DoubleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/DoubleConverterTes100644 0 0 10672 12262570610 31157 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestSuite; import org.apache.commons.beanutils.Converter; /** * Test Case for the DoubleConverter class. * * @version $Id: DoubleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class DoubleConverterTestCase extends NumberConverterTestBase { private Converter converter = null; // ------------------------------------------------------------------------ public DoubleConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ @Override public void setUp() throws Exception { converter = makeConverter(); numbers[0] = new Double("-12"); numbers[1] = new Double("13"); numbers[2] = new Double("-22"); numbers[3] = new Double("23"); } public static TestSuite suite() { return new TestSuite(DoubleConverterTestCase.class); } @Override public void tearDown() throws Exception { converter = null; } // ------------------------------------------------------------------------ @Override protected NumberConverter makeConverter() { return new DoubleConverter(); } @Override protected NumberConverter makeConverter(Object defaultValue) { return new DoubleConverter(defaultValue); } @Override protected Class getExpectedType() { return Double.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { String[] message= { "from String", "from String", "from String", "from String", "from String", "from String", "from String", "from Byte", "from Short", "from Integer", "from Long", "from Float", "from Double" }; Object[] input = { String.valueOf(Double.MIN_VALUE), "-17.2", "-1.1", "0.0", "1.1", "17.2", String.valueOf(Double.MAX_VALUE), new Byte((byte)7), new Short((short)8), new Integer(9), new Long(10), new Float(11.1), new Double(12.2) }; Double[] expected = { new Double(Double.MIN_VALUE), new Double(-17.2), new Double(-1.1), new Double(0.0), new Double(1.1), new Double(17.2), new Double(Double.MAX_VALUE), new Double(7), new Double(8), new Double(9), new Double(10), new Double(11.1), new Double(12.2) }; for(int i=0;i getExpectedType() { return File.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { String[] message= { "from String", "from String", "from String" }; Object[] input = { "/tmp", "/tmp/foo.txt", "/tmp/does/not/exist.foo" }; File[] expected = { new File("/tmp"), new File("/tmp/foo.txt"), new File("/tmp/does/not/exist.foo") }; for(int i=0;i getExpectedType() { return Float.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { String[] message= { "from String", "from String", "from String", "from String", "from String", "from String", "from String", "from Byte", "from Short", "from Integer", "from Long", "from Float", "from Double" }; Object[] input = { String.valueOf(Float.MIN_VALUE), "-17.2", "-1.1", "0.0", "1.1", "17.2", String.valueOf(Float.MAX_VALUE), new Byte((byte)7), new Short((short)8), new Integer(9), new Long(10), new Float(11.1), new Double(12.2), }; Float[] expected = { new Float(Float.MIN_VALUE), new Float(-17.2), new Float(-1.1), new Float(0.0), new Float(1.1), new Float(17.2), new Float(Float.MAX_VALUE), new Float(7), new Float(8), new Float(9), new Float(10), new Float(11.1), new Float(12.2) }; for(int i=0;i clazz = Float.class; Double max = new Double(Float.MAX_VALUE); Double tooBig = new Double(Double.MAX_VALUE); // Maximum assertEquals("Maximum", new Float(Float.MAX_VALUE), converter.convert(clazz, max)); // Too Large try { assertEquals("Too Big", null, converter.convert(clazz, tooBig)); fail("More than maximum, expected ConversionException"); } catch (Exception e) { // expected result } } } ././@LongLink100644 0 0 160 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/IntegerConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/IntegerConverterTe100644 0 0 13373 12262570610 31160 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestSuite; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.Converter; /** * Test Case for the IntegerConverter class. * * @version $Id: IntegerConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class IntegerConverterTestCase extends NumberConverterTestBase { private Converter converter = null; // ------------------------------------------------------------------------ public IntegerConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ @Override public void setUp() throws Exception { converter = makeConverter(); numbers[0] = new Integer("-12"); numbers[1] = new Integer("13"); numbers[2] = new Integer("-22"); numbers[3] = new Integer("23"); } public static TestSuite suite() { return new TestSuite(IntegerConverterTestCase.class); } @Override public void tearDown() throws Exception { converter = null; } // ------------------------------------------------------------------------ @Override protected NumberConverter makeConverter() { return new IntegerConverter(); } @Override protected NumberConverter makeConverter(Object defaultValue) { return new IntegerConverter(defaultValue); } @Override protected Class getExpectedType() { return Integer.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { String[] message= { "from String", "from String", "from String", "from String", "from String", "from String", "from String", "from Byte", "from Short", "from Integer", "from Long", "from Float", "from Double" }; Object[] input = { String.valueOf(Integer.MIN_VALUE), "-17", "-1", "0", "1", "17", String.valueOf(Integer.MAX_VALUE), new Byte((byte)7), new Short((short)8), new Integer(9), new Long(10), new Float(11.1), new Double(12.2) }; Integer[] expected = { new Integer(Integer.MIN_VALUE), new Integer(-17), new Integer(-1), new Integer(0), new Integer(1), new Integer(17), new Integer(Integer.MAX_VALUE), new Integer(7), new Integer(8), new Integer(9), new Integer(10), new Integer(11), new Integer(12) }; for(int i=0;i clazz = Integer.class; Long min = new Long(Integer.MIN_VALUE); Long max = new Long(Integer.MAX_VALUE); Long minMinusOne = new Long(min.longValue() - 1); Long maxPlusOne = new Long(max.longValue() + 1); // Minimum assertEquals("Minimum", new Integer(Integer.MIN_VALUE), converter.convert(clazz, min)); // Maximum assertEquals("Maximum", new Integer(Integer.MAX_VALUE), converter.convert(clazz, max)); // Too Small try { assertEquals("Minimum - 1", null, converter.convert(clazz, minMinusOne)); fail("Less than minimum, expected ConversionException"); } catch (Exception e) { // expected result } // Too Large try { assertEquals("Maximum + 1", null, converter.convert(clazz, maxPlusOne)); fail("More than maximum, expected ConversionException"); } catch (Exception e) { // expected result } } /** * Tests whether an invalid default object causes an exception. */ public void testInvalidDefaultObject() { NumberConverter converter = makeConverter(); try { converter.setDefaultValue("notANumber"); fail("Invalid default value not detected!"); } catch (ConversionException cex) { // expected result } } } ././@LongLink100644 0 0 155 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/LongConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/LongConverterTestC100644 0 0 10007 12262570610 31123 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestSuite; import org.apache.commons.beanutils.Converter; /** * Test Case for the LongConverter class. * * @version $Id: LongConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class LongConverterTestCase extends NumberConverterTestBase { private Converter converter = null; // ------------------------------------------------------------------------ public LongConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ @Override public void setUp() throws Exception { converter = makeConverter(); numbers[0] = new Long("-12"); numbers[1] = new Long("13"); numbers[2] = new Long("-22"); numbers[3] = new Long("23"); } public static TestSuite suite() { return new TestSuite(LongConverterTestCase.class); } @Override public void tearDown() throws Exception { converter = null; } // ------------------------------------------------------------------------ @Override protected NumberConverter makeConverter() { return new LongConverter(); } @Override protected NumberConverter makeConverter(Object defaultValue) { return new LongConverter(defaultValue); } @Override protected Class getExpectedType() { return Long.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { String[] message= { "from String", "from String", "from String", "from String", "from String", "from String", "from String", "from Byte", "from Short", "from Integer", "from Long", "from Float", "from Double" }; Object[] input = { String.valueOf(Long.MIN_VALUE), "-17", "-1", "0", "1", "17", String.valueOf(Long.MAX_VALUE), new Byte((byte)7), new Short((short)8), new Integer(9), new Long(10), new Float(11.1), new Double(12.2) }; Long[] expected = { new Long(Long.MIN_VALUE), new Long(-17), new Long(-1), new Long(0), new Long(1), new Long(17), new Long(Long.MAX_VALUE), new Long(7), new Long(8), new Long(9), new Long(10), new Long(11), new Long(12) }; for(int i=0;i ref = new WeakReference(componentLoader); componentLoader = null; forceGarbageCollection(ref); assertNull(ref.get()); } finally { // Restore context classloader that was present before this // test started. It is expected to be the same as the system // classloader, but we handle all cases here.. Thread.currentThread().setContextClassLoader(origContextClassLoader); // and restore all the standard converters ConvertUtils.deregister(); } } /** * Test whether registering a standard Converter instance while * a custom context classloader is set causes a memory leak. * *

          This test emulates a j2ee container where BeanUtils has been * loaded from a "common" lib location that is shared across all * components running within the container. The "component" registers * a converter object, whose class was loaded from the "common" lib * location. The registered converter: *

            *
          • should not be visible to other components; and
          • *
          • should not prevent the component-specific classloader from being * garbage-collected when the container sets its reference to null. *
          * */ public void testComponentRegistersStandardConverter() throws Exception { ClassLoader origContextClassLoader = Thread.currentThread().getContextClassLoader(); try { // sanity check; who's paranoid?? :-) assertEquals(origContextClassLoader, ConvertUtils.class.getClassLoader()); // create a custom classloader for a "component" // just like a container would. ClassLoader componentLoader1 = new ClassLoader() {}; ClassLoader componentLoader2 = new ClassLoader() {}; Converter origFloatConverter = ConvertUtils.lookup(Float.TYPE); Converter floatConverter1 = new FloatConverter(); // Emulate the container invoking a component #1, and the component // registering a custom converter instance whose class is // available via the "shared" classloader. Thread.currentThread().setContextClassLoader(componentLoader1); { // here we pretend we're running inside component #1 // When we first do a ConvertUtils operation inside a custom // classloader, we get a completely fresh copy of the // ConvertUtilsBean, with all-new Converter objects in it.. assertFalse(ConvertUtils.lookup(Float.TYPE) == origFloatConverter); // Now we register a custom converter (but of a standard class). // This should only affect code that runs with exactly the // same context classloader set. ConvertUtils.register(floatConverter1, Float.TYPE); assertTrue(ConvertUtils.lookup(Float.TYPE) == floatConverter1); } Thread.currentThread().setContextClassLoader(origContextClassLoader); // The converter visible outside any custom component should not // have been altered. assertTrue(ConvertUtils.lookup(Float.TYPE) == origFloatConverter); // Emulate the container invoking a component #2. Thread.currentThread().setContextClassLoader(componentLoader2); { // here we pretend we're running inside component #2 // we should get a completely fresh ConvertUtilsBean, with // all-new Converter objects again. assertFalse(ConvertUtils.lookup(Float.TYPE) == origFloatConverter); assertFalse(ConvertUtils.lookup(Float.TYPE) == floatConverter1); } Thread.currentThread().setContextClassLoader(origContextClassLoader); // Emulate a container "undeploying" component #1. This should // make component loader available for garbage collection (we hope) WeakReference weakRefToComponent1 = new WeakReference(componentLoader1); componentLoader1 = null; // force garbage collection and verify that the componentLoader // has been garbage-collected forceGarbageCollection(weakRefToComponent1); assertNull( "Component classloader did not release properly; memory leak present", weakRefToComponent1.get()); } finally { // Restore context classloader that was present before this // test started, so that in case of a test failure we don't stuff // up later tests... Thread.currentThread().setContextClassLoader(origContextClassLoader); // and restore all the standard converters ConvertUtils.deregister(); } } /** * Test whether registering a custom Converter subclass while * a custom context classloader is set causes a memory leak. * *

          This test emulates a j2ee container where BeanUtils has been * loaded from a "common" lib location that is shared across all * components running within the container. The "component" registers * a converter object, whose class was loaded via the component-specific * classloader. The registered converter: *

            *
          • should not be visible to other components; and
          • *
          • should not prevent the component-specific classloader from being * garbage-collected when the container sets its reference to null. *
          * */ public void testComponentRegistersCustomConverter() throws Exception { ClassLoader origContextClassLoader = Thread.currentThread().getContextClassLoader(); try { // sanity check; who's paranoid?? :-) assertEquals(origContextClassLoader, ConvertUtils.class.getClassLoader()); // create a custom classloader for a "component" // just like a container would. ClassReloader componentLoader = new ClassReloader(origContextClassLoader); // Load a custom Converter via component loader. This emulates what // would happen if a user wrote their own FloatConverter subclass // and deployed it via the component-specific classpath. Thread.currentThread().setContextClassLoader(componentLoader); { // Here we pretend we're running inside the component, and that // a class FloatConverter has been loaded from the component's // private classpath. Class newFloatConverterClass = componentLoader.reload(FloatConverter.class); Object newFloatConverter = newFloatConverterClass.newInstance(); assertTrue(newFloatConverter.getClass().getClassLoader() == componentLoader); // verify that this new object does implement the Converter type // despite being loaded via a classloader different from the one // that loaded the Converter class. assertTrue( "Converter loader via child does not implement parent type", Converter.class.isInstance(newFloatConverter)); // this converter registration will only apply to the // componentLoader classloader... ConvertUtils.register((Converter)newFloatConverter, Float.TYPE); // After registering a custom converter, lookup should return // it back to us. We'll try this lookup again with a different // context-classloader set, and shouldn't see it Converter componentConverter = ConvertUtils.lookup(Float.TYPE); assertTrue(componentConverter.getClass().getClassLoader() == componentLoader); newFloatConverter = null; } Thread.currentThread().setContextClassLoader(origContextClassLoader); // Because the context classloader has been reset, we shouldn't // see the custom registered converter here... Converter sharedConverter = ConvertUtils.lookup(Float.TYPE); assertFalse(sharedConverter.getClass().getClassLoader() == componentLoader); // and here we should see it again Thread.currentThread().setContextClassLoader(componentLoader); { Converter componentConverter = ConvertUtils.lookup(Float.TYPE); assertTrue(componentConverter.getClass().getClassLoader() == componentLoader); } Thread.currentThread().setContextClassLoader(origContextClassLoader); // Emulate a container "undeploying" the component. This should // make component loader available for garbage collection (we hope) WeakReference weakRefToComponent = new WeakReference(componentLoader); componentLoader = null; // force garbage collection and verify that the componentLoader // has been garbage-collected forceGarbageCollection(weakRefToComponent); assertNull( "Component classloader did not release properly; memory leak present", weakRefToComponent.get()); } finally { // Restore context classloader that was present before this // test started. It is expected to be the same as the system // classloader, but we handle all cases here.. Thread.currentThread().setContextClassLoader(origContextClassLoader); // and restore all the standard converters ConvertUtils.deregister(); } } /** * Attempt to force garbage collection of the specified target. * *

          Unfortunately there is no way to force a JVM to perform * garbage collection; all we can do is hint to it that * garbage-collection would be a good idea, and to consume * memory in order to trigger it.

          * *

          On return, target.get() will return null if the target has * been garbage collected.

          * *

          If target.get() still returns non-null after this method has returned, * then either there is some reference still being held to the target, or * else we were not able to trigger garbage collection; there is no way * to tell these scenarios apart.

          */ private void forceGarbageCollection(WeakReference target) { int bytes = 2; while(target.get() != null) { System.gc(); // Create increasingly-large amounts of non-referenced memory // in order to persuade the JVM to collect it. We are hoping // here that the JVM is dumb enough to run a full gc pass over // all data (including the target) rather than simply collecting // this easily-reclaimable memory! try { @SuppressWarnings("unused") byte[] b = new byte[bytes]; bytes = bytes * 2; } catch(OutOfMemoryError e) { // well that sure should have forced a garbage collection // run to occur! break; } } // and let's do one more just to clean up any garbage we might have // created on the last pass.. System.gc(); } } ././@LongLink100644 0 0 157 12262571655 10271 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/NumberConverterTestBase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/NumberConverterTes100644 0 0 35763 12262570610 31205 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; import java.util.Locale; import junit.framework.TestCase; import org.apache.commons.beanutils.ConversionException; /** * Abstract base for <Number>Converter classes. * * @version $Id: NumberConverterTestBase.java 1546738 2013-11-30 16:24:19Z oheger $ */ public abstract class NumberConverterTestBase extends TestCase { /** Test Number values */ protected Number[] numbers = new Number[4]; // ------------------------------------------------------------------------ public NumberConverterTestBase(String name) { super(name); } // ------------------------------------------------------------------------ protected abstract NumberConverter makeConverter(); protected abstract NumberConverter makeConverter(Object defaultValue); protected abstract Class getExpectedType(); // ------------------------------------------------------------------------ /** * Assumes ConversionException in response to covert(getExpectedType(),null). */ public void testConvertNull() { try { makeConverter().convert(getExpectedType(),null); fail("Expected ConversionException"); } catch(ConversionException e) { // expected } } /** * Assumes convert(getExpectedType(),Number) returns some non-null * instance of getExpectedType(). */ public void testConvertNumber() { String[] message= { "from Byte", "from Short", "from Integer", "from Long", "from Float", "from Double", "from BigDecimal", "from BigInteger", "from Integer array", }; Object[] number = { new Byte((byte)7), new Short((short)8), new Integer(9), new Long(10), new Float(11.1), new Double(12.2), new BigDecimal("17.2"), new BigInteger("33"), new Integer[] {new Integer(3), new Integer(2), new Integer(1)} }; for(int i=0;i String (using a Pattern, with default and specified Locales) */ public void testNumberToStringPattern() { // Re-set the default Locale to Locale.US Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); NumberConverter converter = makeConverter(); converter.setPattern("[0,0.0];(0,0.0)"); // Default Locale assertEquals("Default Locale " + numbers[0], "(12.0)", converter.convert(String.class, numbers[0])); assertEquals("Default Locale " + numbers[1], "[13.0]", converter.convert(String.class, numbers[1])); // Locale.GERMAN converter.setLocale(Locale.GERMAN); assertEquals("Locale.GERMAN " + numbers[2], "(22,0)", converter.convert(String.class, numbers[2])); assertEquals("Locale.GERMAN " + numbers[3], "[23,0]", converter.convert(String.class, numbers[3])); // Restore the default Locale Locale.setDefault(defaultLocale); } /** * Convert Number --> String (using default and specified Locales) */ public void testNumberToStringLocale() { // Re-set the default Locale to Locale.US Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); NumberConverter converter = makeConverter(); converter.setUseLocaleFormat(true); // Default Locale assertEquals("Default Locale " + numbers[0], "-12", converter.convert(String.class, numbers[0])); assertEquals("Default Locale " + numbers[1], "13", converter.convert(String.class, numbers[1])); // Locale.GERMAN converter.setLocale(Locale.GERMAN); assertEquals("Locale.GERMAN " + numbers[2], "-22", converter.convert(String.class, numbers[2])); assertEquals("Locale.GERMAN " + numbers[3], "23", converter.convert(String.class, numbers[3])); // Restore the default Locale Locale.setDefault(defaultLocale); } /** * Convert Array --> Number */ public void testStringArrayToInteger() { Integer defaultValue = new Integer(-1); NumberConverter converter = makeConverter(defaultValue); // Default Locale assertEquals("Valid First", new Integer(5), converter.convert(Integer.class, new String[] {"5", "4", "3"})); assertEquals("Invalid First", defaultValue, converter.convert(Integer.class, new String[] {"FOO", "1", "2"})); assertEquals("Null First", defaultValue, converter.convert(Integer.class, new String[] {null, "1", "2"})); assertEquals("Long Array", new Integer(9), converter.convert(Integer.class, new long[] {9, 2, 6})); } /** * Convert Number --> String (default conversion) */ public void testNumberToStringDefault() { NumberConverter converter = makeConverter(); // Default Number --> String conversion assertEquals("Default Convert " + numbers[0], numbers[0].toString(), converter.convert(String.class, numbers[0])); assertEquals("Default Convert " + numbers[1], numbers[1].toString(), converter.convert(String.class, numbers[1])); } /** * Convert String --> Number (using a Pattern, with default and specified Locales) */ public void testStringToNumberPattern() { // Re-set the default Locale to Locale.US Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); NumberConverter converter = makeConverter(); converter.setPattern("[0,0];(0,0)"); // Default Locale assertEquals("Default Locale " + numbers[0], numbers[0], converter.convert(getExpectedType(), "(1,2)")); assertEquals("Default Locale " + numbers[1], numbers[1], converter.convert(getExpectedType(), "[1,3]")); // Locale.GERMAN converter.setLocale(Locale.GERMAN); assertEquals("Locale.GERMAN " + numbers[2], numbers[2], converter.convert(getExpectedType(), "(2.2)")); assertEquals("Locale.GERMAN " + numbers[3], numbers[3], converter.convert(getExpectedType(), "[2.3]")); // Invalid Value try { converter.convert(getExpectedType(), "1,2"); fail("Expected invalid value to cause ConversionException"); } catch (Exception e) { // expected result } // Invalid Type (will try via String) Object obj = new Object() { @Override public String toString() { return "dsdgsdsdg"; } }; try { converter.convert(getExpectedType(), obj); fail("Expected invalid value to cause ConversionException"); } catch (Exception e) { // expected result } // Restore the default Locale Locale.setDefault(defaultLocale); } /** * Convert String --> Number (using default and specified Locales) */ public void testStringToNumberLocale() { // Re-set the default Locale to Locale.US Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); NumberConverter converter = makeConverter(); converter.setUseLocaleFormat(true); // Default Locale assertEquals("Default Locale " + numbers[0], numbers[0], converter.convert(getExpectedType(), "-0,012")); assertEquals("Default Locale " + numbers[1], numbers[1], converter.convert(getExpectedType(), "0,013")); // Invalid Value try { converter.convert(getExpectedType(), "0,02x"); fail("Expected invalid value to cause ConversionException"); } catch (Exception e) { // expected result } // Locale.GERMAN converter.setLocale(Locale.GERMAN); assertEquals("Locale.GERMAN " + numbers[2], numbers[2], converter.convert(getExpectedType(), "-0.022")); assertEquals("Locale.GERMAN " + numbers[3], numbers[3], converter.convert(getExpectedType(), "0.023")); // Invalid Value try { converter.convert(getExpectedType(), "0.02x"); fail("Expected invalid value to cause ConversionException"); } catch (Exception e) { // expected result } // Restore the default Locale Locale.setDefault(defaultLocale); } /** * Convert String --> Number (default conversion) */ public void testStringToNumberDefault() { NumberConverter converter = makeConverter(); converter.setUseLocaleFormat(false); // Default String --> Number conversion assertEquals("Default Convert " + numbers[0], numbers[0], converter.convert(getExpectedType(), numbers[0].toString())); // Invalid try { converter.convert(getExpectedType(), "12x"); fail("Expected invalid value to cause ConversionException"); } catch (Exception e) { // expected result } } /** * Convert String --> Number if the target type is not defined. Then the * default type should be used. */ public void testStringToNumberDefaultType() { NumberConverter converter = makeConverter(); converter.setUseLocaleFormat(false); assertEquals("Default Convert " + numbers[0], numbers[0], converter.convert(null, numbers[0].toString())); } /** * Convert Boolean --> Number (default conversion) */ public void testBooleanToNumberDefault() { NumberConverter converter = makeConverter(); // Other type --> String conversion assertEquals("Boolean.FALSE to Number ", 0, ((Number)converter.convert(getExpectedType(), Boolean.FALSE)).intValue()); assertEquals("Boolean.TRUE to Number ", 1, ((Number)converter.convert(getExpectedType(), Boolean.TRUE)).intValue()); } /** * Convert Date --> Long */ public void testDateToNumber() { NumberConverter converter = makeConverter(); Date dateValue = new Date(); long longValue = dateValue.getTime(); // Date --> Long conversion assertEquals("Date to Long", new Long(longValue), converter.convert(Long.class, dateValue)); // Date --> Integer try { converter.convert(Integer.class, dateValue); fail("Date to Integer - expected a ConversionException"); } catch (ConversionException e) { // expected result - too large for Integer } } /** * Convert Calendar --> Long */ public void testCalendarToNumber() { NumberConverter converter = makeConverter(); Calendar calendarValue = Calendar.getInstance(); long longValue = calendarValue.getTime().getTime(); // Calendar --> Long conversion assertEquals("Calendar to Long", new Long(longValue), converter.convert(Long.class, calendarValue)); // Calendar --> Integer try { converter.convert(Integer.class, calendarValue); fail("Calendar to Integer - expected a ConversionException"); } catch (ConversionException e) { // expected result - too large for Integer } } /** * Convert Other --> String (default conversion) */ public void testOtherToStringDefault() { NumberConverter converter = makeConverter(); // Other type --> String conversion assertEquals("Default Convert ", "ABC", converter.convert(String.class, new StringBuilder("ABC"))); } /** * Convert Number --> String (using default and specified Locales) */ public void testInvalidDefault() { Object defaultvalue = numbers[0]; NumberConverter converter = makeConverter(defaultvalue); // Default String --> Number conversion assertEquals("Invalid null ", defaultvalue, converter.convert(getExpectedType(), null)); assertEquals("Default XXXX ", defaultvalue, converter.convert(getExpectedType(), "XXXX")); } /** * Convert Number --> String (using default and specified Locales) */ public void testInvalidException() { NumberConverter converter = makeConverter(); try { converter.convert(getExpectedType(), null); fail("Null test, expected ConversionException"); } catch (ConversionException e) { // expected result } try { converter.convert(getExpectedType(), "XXXX"); fail("Invalid test, expected ConversionException"); } catch (ConversionException e) { // expected result } } /** * Test specifying an invalid type. */ public void testInvalidType() { NumberConverter converter = makeConverter(); try { converter.convert(Object.class, numbers[0]); fail("Invalid type test, expected ConversionException"); } catch (ConversionException e) { // expected result } } /** * Tests a conversion to an unsupported type if a default value is set. */ public void testInvalidTypeWithDefault() { NumberConverter converter = makeConverter(42); try { converter.convert(Object.class, numbers[0]); fail("Invalid type with default test, expected ConversionException"); } catch(ConversionException e) { // expected result } } } ././@LongLink100644 0 0 156 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ShortConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/ShortConverterTest100644 0 0 12445 12262570610 31230 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestSuite; import org.apache.commons.beanutils.Converter; /** * Test Case for the ShortConverter class. * * @version $Id: ShortConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ShortConverterTestCase extends NumberConverterTestBase { private Converter converter = null; // ------------------------------------------------------------------------ public ShortConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ @Override public void setUp() throws Exception { converter = makeConverter(); numbers[0] = new Short("-12"); numbers[1] = new Short("13"); numbers[2] = new Short("-22"); numbers[3] = new Short("23"); } public static TestSuite suite() { return new TestSuite(ShortConverterTestCase.class); } @Override public void tearDown() throws Exception { converter = null; } // ------------------------------------------------------------------------ @Override protected NumberConverter makeConverter() { return new ShortConverter(); } @Override protected NumberConverter makeConverter(Object defaultValue) { return new ShortConverter(defaultValue); } @Override protected Class getExpectedType() { return Short.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { String[] message= { "from String", "from String", "from String", "from String", "from String", "from String", "from String", "from Byte", "from Short", "from Integer", "from Long", "from Float", "from Double" }; Object[] input = { String.valueOf(Short.MIN_VALUE), "-17", "-1", "0", "1", "17", String.valueOf(Short.MAX_VALUE), new Byte((byte)7), new Short((short)8), new Integer(9), new Long(10), new Float(11.1), new Double(12.2) }; Short[] expected = { new Short(Short.MIN_VALUE), new Short((short)-17), new Short((short)-1), new Short((short)0), new Short((short)1), new Short((short)17), new Short(Short.MAX_VALUE), new Short((short)7), new Short((short)8), new Short((short)9), new Short((short)10), new Short((short)11), new Short((short)12) }; for(int i=0;i clazz = Short.class; Long min = new Long(Short.MIN_VALUE); Long max = new Long(Short.MAX_VALUE); Long minMinusOne = new Long(min.longValue() - 1); Long maxPlusOne = new Long(max.longValue() + 1); // Minimum assertEquals("Minimum", new Short(Short.MIN_VALUE), converter.convert(clazz, min)); // Maximum assertEquals("Maximum", new Short(Short.MAX_VALUE), converter.convert(clazz, max)); // Too Small try { assertEquals("Minimum - 1", null, converter.convert(clazz, minMinusOne)); fail("Less than minimum, expected ConversionException"); } catch (Exception e) { // expected result } // Too Large try { assertEquals("Maximum + 1", null, converter.convert(clazz, maxPlusOne)); fail("More than maximum, expected ConversionException"); } catch (Exception e) { // expected result } } } ././@LongLink100644 0 0 160 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/SqlDateConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/SqlDateConverterTe100644 0 0 7617 12262570610 31104 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.sql.Date; import java.util.Calendar; import junit.framework.TestSuite; /** * Test Case for the {@link SqlDateConverter} class. * * @version $Id: SqlDateConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class SqlDateConverterTestCase extends DateConverterTestBase { /** * Construct a new Date test case. * @param name Test Name */ public SqlDateConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ /** * Create Test Suite * @return test suite */ public static TestSuite suite() { return new TestSuite(SqlDateConverterTestCase.class); } // ------------------------------------------------------------------------ /** * Test default String to java.sql.Date conversion */ @Override public void testDefaultStringToTypeConvert() { // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setUseLocaleFormat(false); // Valid String --> java.sql.Date Conversion String testString = "2006-05-16"; Object expected = toType(testString, "yyyy-MM-dd", null); validConversion(converter, expected, testString); // Invalid String --> java.sql.Date Conversion invalidConversion(converter, "01/01/2006"); } /** * Test default java.sql.Date to String conversion */ public void testDefaultTypeToStringConvert() { // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setUseLocaleFormat(false); // Valid String --> java.sql.Date Conversion String expected = "2006-05-16"; Object testVal = toType(expected, "yyyy-MM-dd", null); stringConversion(converter, expected, testVal); Object result = converter.convert(String.class, new Integer(2)); assertEquals("Default toString()", "2", result); } /** * Create the Converter with no default value. * @return A new Converter */ @Override protected DateTimeConverter makeConverter() { return new SqlDateConverter(); } /** * Create the Converter with a default value. * @param defaultValue The default value * @return A new Converter */ @Override protected DateTimeConverter makeConverter(Object defaultValue) { return new SqlDateConverter(defaultValue); } /** * Return the expected type * @return The expected type */ @Override protected Class getExpectedType() { return Date.class; } /** * Convert from a Calendar to the appropriate Date type * * @param value The Calendar value to convert * @return The converted value */ @Override protected Object toType(Calendar value) { return new java.sql.Date(getTimeInMillis(value)); } } ././@LongLink100644 0 0 160 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/SqlTimeConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/SqlTimeConverterTe100644 0 0 11157 12262570610 31137 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.sql.Time; import java.util.Calendar; import java.util.Locale; import junit.framework.TestSuite; /** * Test Case for the {@link SqlTimeConverter} class. * * @version $Id: SqlTimeConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class SqlTimeConverterTestCase extends DateConverterTestBase { /** * Construct a new Date test case. * @param name Test Name */ public SqlTimeConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ /** * Create Test Suite * @return test suite */ public static TestSuite suite() { return new TestSuite(SqlTimeConverterTestCase.class); } // ------------------------------------------------------------------------ /** * Test Date Converter with no default value */ @Override public void testLocale() { // Re-set the default Locale to Locale.US Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); String pattern = "h:mm a"; // SHORT style time format for US Locale // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setUseLocaleFormat(true); // Valid String --> Type Conversion String testString = "3:06 pm"; Object expected = toType(testString, pattern, null); validConversion(converter, expected, testString); // Invalid Conversions invalidConversion(converter, null); invalidConversion(converter, ""); invalidConversion(converter, "13:05"); invalidConversion(converter, "11:05 p"); invalidConversion(converter, "11.05 pm"); invalidConversion(converter, new Integer(2)); // Test specified Locale converter.setLocale(Locale.UK); invalidConversion(converter, testString); // Test previous value now fails validConversion(converter, expected, "15:06"); // UK Short style is "HH:mm" // Restore the default Locale Locale.setDefault(defaultLocale); } /** * Test default String to java.sql.Time conversion */ @Override public void testDefaultStringToTypeConvert() { // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setUseLocaleFormat(false); // Valid String --> java.sql.Time Conversion String testString = "15:36:21"; Object expected = toType(testString, "HH:mm:ss", null); validConversion(converter, expected, testString); // Invalid String --> java.sql.Time Conversion invalidConversion(converter, "15:36"); } /** * Create the Converter with no default value. * @return A new Converter */ @Override protected DateTimeConverter makeConverter() { return new SqlTimeConverter(); } /** * Create the Converter with a default value. * @param defaultValue The default value * @return A new Converter */ @Override protected DateTimeConverter makeConverter(Object defaultValue) { return new SqlTimeConverter(defaultValue); } /** * Return the expected type * @return The expected type */ @Override protected Class getExpectedType() { return Time.class; } /** * Convert from a Calendar to the appropriate Date type * * @param value The Calendar value to convert * @return The converted value */ @Override protected Object toType(Calendar value) { return new Time(getTimeInMillis(value)); } }././@LongLink100644 0 0 165 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/SqlTimestampConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/SqlTimestampConver100644 0 0 11140 12262570610 31170 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.sql.Timestamp; import java.util.Calendar; import java.util.Locale; import junit.framework.TestSuite; /** * Test Case for the {@link SqlTimestampConverter} class. * * @version $Id: SqlTimestampConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class SqlTimestampConverterTestCase extends DateConverterTestBase { /** * Construct a new Date test case. * @param name Test Name */ public SqlTimestampConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ /** * Create Test Suite * @return test suite */ public static TestSuite suite() { return new TestSuite(SqlTimestampConverterTestCase.class); } // ------------------------------------------------------------------------ /** * Test Date Converter with no default value */ @Override public void testLocale() { // Re-set the default Locale to Locale.US Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); String pattern = "M/d/yy h:mm a"; // SHORT style Date & Time format for US Locale // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setUseLocaleFormat(true); // Valid String --> Type Conversion String testString = "3/21/06 3:06 pm"; Object expected = toType(testString, pattern, null); validConversion(converter, expected, testString); // Invalid Conversions invalidConversion(converter, null); invalidConversion(converter, ""); invalidConversion(converter, "13:05 pm"); invalidConversion(converter, "11:05 p"); invalidConversion(converter, "11.05 pm"); invalidConversion(converter, new Integer(2)); // Restore the default Locale Locale.setDefault(defaultLocale); } /** * Test default String to java.sql.Timestamp conversion */ @Override public void testDefaultStringToTypeConvert() { // Create & Configure the Converter DateTimeConverter converter = makeConverter(); converter.setUseLocaleFormat(false); // Valid String --> java.sql.Timestamp Conversion String testString = "2006-10-23 15:36:01.0"; Object expected = toType(testString, "yyyy-MM-dd HH:mm:ss.S", null); validConversion(converter, expected, testString); // Invalid String --> java.sql.Timestamp Conversion invalidConversion(converter, "2006/09/21 15:36:01.0"); invalidConversion(converter, "2006-10-22"); invalidConversion(converter, "15:36:01"); } /** * Create the Converter with no default value. * @return A new Converter */ @Override protected DateTimeConverter makeConverter() { return new SqlTimestampConverter(); } /** * Create the Converter with a default value. * @param defaultValue The default value * @return A new Converter */ @Override protected DateTimeConverter makeConverter(Object defaultValue) { return new SqlTimestampConverter(defaultValue); } /** * Return the expected type * @return The expected type */ @Override protected Class getExpectedType() { return Timestamp.class; } /** * Convert from a Calendar to the appropriate Date type * * @param value The Calendar value to convert * @return The converted value */ @Override protected Object toType(Calendar value) { return new Timestamp(getTimeInMillis(value)); } }././@LongLink100644 0 0 164 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/StringArrayConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/StringArrayConvert100644 0 0 3372 12262570610 31166 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestCase; /** * Test Case for StringArrayConverter * * @version $Id: StringArrayConverterTestCase.java 1454597 2013-03-08 21:58:12Z britter $ */ public class StringArrayConverterTestCase extends TestCase { public StringArrayConverterTestCase(String name) { super(name); } public void testIntToString() { int[] testArray = {1, 2, 3, 4, 5}; String[] results = (String []) new StringArrayConverter().convert(String.class, testArray); assertEquals("Incorrect results size", 5, results.length); assertEquals("Entry one is wrong", "1", results[0]); assertEquals("Entry two is wrong", "2", results[1]); assertEquals("Entry three is wrong", "3", results[2]); assertEquals("Entry four is wrong", "4", results[3]); assertEquals("Entry five is wrong", "5", results[4]); } } ././@LongLink100644 0 0 157 12262571655 10271 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/StringConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/StringConverterTes100644 0 0 4310 12262570610 31163 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import junit.framework.TestCase; import org.apache.commons.beanutils.ConversionException; /** * Test case for {@code StringConverter}. * * @version $Id: StringConverterTestCase.java 1540332 2013-11-09 15:29:18Z oheger $ */ public class StringConverterTestCase extends TestCase { /** The converter to be tested. */ private StringConverter converter; @Override protected void setUp() throws Exception { super.setUp(); converter = new StringConverter(); } /** * Tests whether the correct default type is returned. */ public void testDefaultType() { assertEquals("Wrong default type", String.class, converter.getDefaultType()); } /** * Tests a conversion to a string type. */ public void testConvertToTypeString() { Object value = new Object(); String strVal = converter.convert(String.class, value); assertEquals("Wrong conversion result", value.toString(), strVal); } /** * Tries to convert an object to an unsupported type. */ public void testConvertToUnsupportedType() { try { converter.convert(Integer.class, new Object()); fail("No conversion exception thrown!"); } catch(ConversionException cex) { // expected result } } } ././@LongLink100644 0 0 154 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/URLConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/converters/URLConverterTestCa100644 0 0 10122 12262570610 31025 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.converters; import java.net.URL; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.Converter; /** * Test Case for the URLConverter class. * * @version $Id: URLConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class URLConverterTestCase extends TestCase { private Converter converter = null; // ------------------------------------------------------------------------ public URLConverterTestCase(String name) { super(name); } // ------------------------------------------------------------------------ @Override public void setUp() throws Exception { converter = makeConverter(); } public static TestSuite suite() { return new TestSuite(URLConverterTestCase.class); } @Override public void tearDown() throws Exception { converter = null; } // ------------------------------------------------------------------------ protected Converter makeConverter() { return new URLConverter(); } protected Class getExpectedType() { return URL.class; } // ------------------------------------------------------------------------ public void testSimpleConversion() throws Exception { String[] message= { "from String", "from String", "from String", "from String", "from String", "from String", "from String", "from String", }; Object[] input = { "http://www.apache.org", "http://www.apache.org/", "ftp://cvs.apache.org", "file://project.xml", "http://208.185.179.12", "http://www.apache.org:9999/test/thing", "http://user:admin@www.apache.org:50/one/two.three", "http://notreal.apache.org", }; URL[] expected = { new URL("http://www.apache.org"), new URL("http://www.apache.org/"), new URL("ftp://cvs.apache.org"), new URL("file://project.xml"), new URL("http://208.185.179.12"), new URL("http://www.apache.org:9999/test/thing"), new URL("http://user:admin@www.apache.org:50/one/two.three"), new URL("http://notreal.apache.org") }; for(int i=0;i * Test Case for the ConvertUtils class. *

          * * @version $Id: ConvertUtilsTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ConvertUtilsTestCase extends TestCase { // ---------------------------------------------------- Instance Variables // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public ConvertUtilsTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { ConvertUtils.deregister(); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(ConvertUtilsTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { // No action required } // ------------------------------------------------ Individual Test Methods /** * Negative String to primitive integer array tests. */ public void testNegativeIntegerArray() { Object value = null; int intArray[] = new int[0]; value = ConvertUtils.convert((String) null, intArray.getClass()); checkIntegerArray(value, intArray); value = ConvertUtils.convert("a", intArray.getClass()); checkIntegerArray(value, intArray); value = ConvertUtils.convert("{ a }", intArray.getClass()); checkIntegerArray(value, intArray); value = ConvertUtils.convert("1a3", intArray.getClass()); checkIntegerArray(value, intArray); value = ConvertUtils.convert("{ 1a3 }", intArray.getClass()); checkIntegerArray(value, intArray); value = ConvertUtils.convert("0,1a3", intArray.getClass()); checkIntegerArray(value, intArray); value = ConvertUtils.convert("{ 0, 1a3 }", intArray.getClass()); checkIntegerArray(value, intArray); } /** * Negative scalar conversion tests. These rely on the standard * default value conversions in ConvertUtils. */ public void testNegativeScalar() { Object value = null; value = ConvertUtils.convert("foo", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = ConvertUtils.convert("foo", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = ConvertUtils.convert("foo", Byte.TYPE); assertTrue(value instanceof Byte); assertEquals(((Byte) value).byteValue(), (byte) 0); value = ConvertUtils.convert("foo", Byte.class); assertTrue(value instanceof Byte); assertEquals(((Byte) value).byteValue(), (byte) 0); try { value = ConvertUtils.convert ("org.apache.commons.beanutils.Undefined", Class.class); fail("Should have thrown conversion exception"); } catch (ConversionException e) { // Expected result } value = ConvertUtils.convert("foo", Double.TYPE); assertTrue(value instanceof Double); assertEquals(((Double) value).doubleValue(), 0.0, 0.005); value = ConvertUtils.convert("foo", Double.class); assertTrue(value instanceof Double); assertEquals(((Double) value).doubleValue(), 0.0, 0.005); value = ConvertUtils.convert("foo", Float.TYPE); assertTrue(value instanceof Float); assertEquals(((Float) value).floatValue(), (float) 0.0, (float) 0.005); value = ConvertUtils.convert("foo", Float.class); assertTrue(value instanceof Float); assertEquals(((Float) value).floatValue(), (float) 0.0, (float) 0.005); value = ConvertUtils.convert("foo", Integer.TYPE); assertTrue(value instanceof Integer); assertEquals(((Integer) value).intValue(), 0); value = ConvertUtils.convert("foo", Integer.class); assertTrue(value instanceof Integer); assertEquals(((Integer) value).intValue(), 0); value = ConvertUtils.convert("foo", Byte.TYPE); assertTrue(value instanceof Byte); assertEquals(((Byte) value).byteValue(), (byte) 0); value = ConvertUtils.convert("foo", Long.class); assertTrue(value instanceof Long); assertEquals(((Long) value).longValue(), 0); value = ConvertUtils.convert("foo", Short.TYPE); assertTrue(value instanceof Short); assertEquals(((Short) value).shortValue(), (short) 0); value = ConvertUtils.convert("foo", Short.class); assertTrue(value instanceof Short); assertEquals(((Short) value).shortValue(), (short) 0); } /** * Negative String to String array tests. */ public void testNegativeStringArray() { Object value = null; String stringArray[] = new String[0]; value = ConvertUtils.convert((String) null, stringArray.getClass()); checkStringArray(value, stringArray); } /** * Test conversion of object to string for arrays. */ public void testObjectToStringArray() { int intArray0[] = new int[0]; int intArray1[] = { 123 }; int intArray2[] = { 123, 456 }; String stringArray0[] = new String[0]; String stringArray1[] = { "abc" }; String stringArray2[] = { "abc", "def" }; assertEquals("intArray0", null, ConvertUtils.convert(intArray0)); assertEquals("intArray1", "123", ConvertUtils.convert(intArray1)); assertEquals("intArray2", "123", ConvertUtils.convert(intArray2)); assertEquals("stringArray0", null, ConvertUtils.convert(stringArray0)); assertEquals("stringArray1", "abc", ConvertUtils.convert(stringArray1)); assertEquals("stringArray2", "abc", ConvertUtils.convert(stringArray2)); } /** * Test conversion of object to string for scalars. */ public void testObjectToStringScalar() { assertEquals("Boolean->String", "false", ConvertUtils.convert(Boolean.FALSE)); assertEquals("Boolean->String", "true", ConvertUtils.convert(Boolean.TRUE)); assertEquals("Byte->String", "123", ConvertUtils.convert(new Byte((byte) 123))); assertEquals("Character->String", "a", ConvertUtils.convert(new Character('a'))); assertEquals("Double->String", "123.0", ConvertUtils.convert(new Double(123.0))); assertEquals("Float->String", "123.0", ConvertUtils.convert(new Float((float) 123.0))); assertEquals("Integer->String", "123", ConvertUtils.convert(new Integer(123))); assertEquals("Long->String", "123", ConvertUtils.convert(new Long(123))); assertEquals("Short->String", "123", ConvertUtils.convert(new Short((short) 123))); assertEquals("String->String", "abc", ConvertUtils.convert("abc")); assertEquals("String->String null", null, ConvertUtils.convert(null)); } /** * Positive array conversion tests. */ public void testPositiveArray() { String values1[] = { "10", "20", "30" }; Object value = ConvertUtils.convert(values1, Integer.TYPE); int shape[] = new int[0]; assertEquals(shape.getClass(), value.getClass()); int results1[] = (int[]) value; assertEquals(results1[0], 10); assertEquals(results1[1], 20); assertEquals(results1[2], 30); String values2[] = { "100", "200", "300" }; value = ConvertUtils.convert(values2, shape.getClass()); assertEquals(shape.getClass(), value.getClass()); int results2[] = (int[]) value; assertEquals(results2[0], 100); assertEquals(results2[1], 200); assertEquals(results2[2], 300); } /** * Positive String to primitive integer array tests. */ public void testPositiveIntegerArray() { Object value = null; int intArray[] = new int[0]; int intArray1[] = new int[] { 0 }; int intArray2[] = new int[] { 0, 10 }; value = ConvertUtils.convert("{ }", intArray.getClass()); checkIntegerArray(value, intArray); value = ConvertUtils.convert("0", intArray.getClass()); checkIntegerArray(value, intArray1); value = ConvertUtils.convert(" 0 ", intArray.getClass()); checkIntegerArray(value, intArray1); value = ConvertUtils.convert("{ 0 }", intArray.getClass()); checkIntegerArray(value, intArray1); value = ConvertUtils.convert("0,10", intArray.getClass()); checkIntegerArray(value, intArray2); value = ConvertUtils.convert("0 10", intArray.getClass()); checkIntegerArray(value, intArray2); value = ConvertUtils.convert("{0,10}", intArray.getClass()); checkIntegerArray(value, intArray2); value = ConvertUtils.convert("{0 10}", intArray.getClass()); checkIntegerArray(value, intArray2); value = ConvertUtils.convert("{ 0, 10 }", intArray.getClass()); checkIntegerArray(value, intArray2); value = ConvertUtils.convert("{ 0 10 }", intArray.getClass()); checkIntegerArray(value, intArray2); } /** * Positive scalar conversion tests. */ public void testPositiveScalar() { Object value = null; value = ConvertUtils.convert("true", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = ConvertUtils.convert("true", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = ConvertUtils.convert("yes", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = ConvertUtils.convert("yes", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = ConvertUtils.convert("y", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = ConvertUtils.convert("y", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = ConvertUtils.convert("on", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = ConvertUtils.convert("on", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = ConvertUtils.convert("false", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = ConvertUtils.convert("false", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = ConvertUtils.convert("no", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = ConvertUtils.convert("no", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = ConvertUtils.convert("n", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = ConvertUtils.convert("n", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = ConvertUtils.convert("off", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = ConvertUtils.convert("off", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = ConvertUtils.convert("123", Byte.TYPE); assertTrue(value instanceof Byte); assertEquals(((Byte) value).byteValue(), (byte) 123); value = ConvertUtils.convert("123", Byte.class); assertTrue(value instanceof Byte); assertEquals(((Byte) value).byteValue(), (byte) 123); value = ConvertUtils.convert("a", Character.TYPE); assertTrue(value instanceof Character); assertEquals(((Character) value).charValue(), 'a'); value = ConvertUtils.convert("a", Character.class); assertTrue(value instanceof Character); assertEquals(((Character) value).charValue(), 'a'); value = ConvertUtils.convert("java.lang.String", Class.class); assertTrue(value instanceof Class); assertEquals(String.class, value); value = ConvertUtils.convert("123.456", Double.TYPE); assertTrue(value instanceof Double); assertEquals(((Double) value).doubleValue(), 123.456, 0.005); value = ConvertUtils.convert("123.456", Double.class); assertTrue(value instanceof Double); assertEquals(((Double) value).doubleValue(), 123.456, 0.005); value = ConvertUtils.convert("123.456", Float.TYPE); assertTrue(value instanceof Float); assertEquals(((Float) value).floatValue(), (float) 123.456, (float) 0.005); value = ConvertUtils.convert("123.456", Float.class); assertTrue(value instanceof Float); assertEquals(((Float) value).floatValue(), (float) 123.456, (float) 0.005); value = ConvertUtils.convert("123", Integer.TYPE); assertTrue(value instanceof Integer); assertEquals(((Integer) value).intValue(), 123); value = ConvertUtils.convert("123", Integer.class); assertTrue(value instanceof Integer); assertEquals(((Integer) value).intValue(), 123); value = ConvertUtils.convert("123", Long.TYPE); assertTrue(value instanceof Long); assertEquals(((Long) value).longValue(), 123); value = ConvertUtils.convert("123", Long.class); assertTrue(value instanceof Long); assertEquals(((Long) value).longValue(), 123); value = ConvertUtils.convert("123", Short.TYPE); assertTrue(value instanceof Short); assertEquals(((Short) value).shortValue(), (short) 123); value = ConvertUtils.convert("123", Short.class); assertTrue(value instanceof Short); assertEquals(((Short) value).shortValue(), (short) 123); String input = null; input = "2002-03-17"; value = ConvertUtils.convert(input, Date.class); assertTrue(value instanceof Date); assertEquals(input, value.toString()); input = "20:30:40"; value = ConvertUtils.convert(input, Time.class); assertTrue(value instanceof Time); assertEquals(input, value.toString()); input = "2002-03-17 20:30:40.0"; value = ConvertUtils.convert(input, Timestamp.class); assertTrue(value instanceof Timestamp); assertEquals(input, value.toString()); } /** * Positive String to String array tests. */ public void testPositiveStringArray() { Object value = null; String stringArray[] = new String[0]; String stringArray1[] = new String[] { "abc" }; String stringArray2[] = new String[] { "abc", "de,f" }; value = ConvertUtils.convert("", stringArray.getClass()); checkStringArray(value, stringArray); value = ConvertUtils.convert(" ", stringArray.getClass()); checkStringArray(value, stringArray); value = ConvertUtils.convert("{}", stringArray.getClass()); checkStringArray(value, stringArray); value = ConvertUtils.convert("{ }", stringArray.getClass()); checkStringArray(value, stringArray); value = ConvertUtils.convert("abc", stringArray.getClass()); checkStringArray(value, stringArray1); value = ConvertUtils.convert("{abc}", stringArray.getClass()); checkStringArray(value, stringArray1); value = ConvertUtils.convert("\"abc\"", stringArray.getClass()); checkStringArray(value, stringArray1); value = ConvertUtils.convert("{\"abc\"}", stringArray.getClass()); checkStringArray(value, stringArray1); value = ConvertUtils.convert("'abc'", stringArray.getClass()); checkStringArray(value, stringArray1); value = ConvertUtils.convert("{'abc'}", stringArray.getClass()); checkStringArray(value, stringArray1); value = ConvertUtils.convert("abc 'de,f'", stringArray.getClass()); checkStringArray(value, stringArray2); value = ConvertUtils.convert("{abc, 'de,f'}", stringArray.getClass()); checkStringArray(value, stringArray2); value = ConvertUtils.convert("\"abc\",\"de,f\"", stringArray.getClass()); checkStringArray(value, stringArray2); value = ConvertUtils.convert("{\"abc\" 'de,f'}", stringArray.getClass()); checkStringArray(value, stringArray2); value = ConvertUtils.convert("'abc' 'de,f'", stringArray.getClass()); checkStringArray(value, stringArray2); value = ConvertUtils.convert("{'abc', \"de,f\"}", stringArray.getClass()); checkStringArray(value, stringArray2); } public void testSeparateConvertInstances() throws Exception { ConvertUtilsBean utilsOne = new ConvertUtilsBean(); ConvertUtilsBean utilsTwo = new ConvertUtilsBean(); // make sure that the test work ok before anything's changed Object value = utilsOne.convert("true", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals( "Standard conversion failed (1)", ((Boolean) value).booleanValue(), true); value = utilsTwo.convert("true", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals( "Standard conversion failed (2)", ((Boolean) value).booleanValue(), true); // now register a test utilsOne.register(new ThrowExceptionConverter(), Boolean.TYPE); try { utilsOne.convert("true", Boolean.TYPE); fail("Register converter failed."); } catch (PassTestException e) { /* This shows that the registration has worked */ } try { // nothing should have changed value = utilsTwo.convert("true", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals( "Standard conversion failed (3)", ((Boolean) value).booleanValue(), true); } catch (PassTestException e) { // This is a failure since utilsTwo should still have // standard converters registered fail("Registering a converter for an instance should not effect another instance."); } // nothing we'll test deregister utilsOne.deregister(); value = utilsOne.convert("true", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals("Instance deregister failed.", ((Boolean) value).booleanValue(), true); value = utilsTwo.convert("true", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals( "Standard conversion failed (4)", ((Boolean) value).booleanValue(), true); } public void testDeregisteringSingleConverter() throws Exception { // make sure that the test work ok before anything's changed Object value = ConvertUtils.convert("true", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals( "Standard conversion failed (1)", ((Boolean) value).booleanValue(), true); // we'll test deregister ConvertUtils.deregister(Boolean.TYPE); assertNull("Converter should be null",ConvertUtils.lookup(Boolean.TYPE)); } @SuppressWarnings({ "unchecked", "rawtypes" }) // We need to use raw types in order to test legacy converters public void testConvertToString() throws Exception { Converter dummyConverter = new Converter() { public Object convert(Class type, Object value) { return value; } }; Converter fooConverter = new Converter() { public Object convert(Class type, Object value) { return "Foo-Converter"; } }; DateConverter dateConverter = new DateConverter(); dateConverter.setLocale(Locale.US); ConvertUtilsBean utils = new ConvertUtilsBean(); utils.register(dateConverter, java.util.Date.class); utils.register(fooConverter, String.class); // Convert using registerd DateConverter java.util.Date today = new java.util.Date(); DateFormat fmt = new SimpleDateFormat("M/d/yy"); /* US Short Format */ String expected = fmt.format(today); assertEquals("DateConverter M/d/yy", expected, utils.convert(today, String.class)); // Date converter doesn't do String conversion - use String Converter utils.register(dummyConverter, java.util.Date.class); assertEquals("Date Converter doesn't do String conversion", "Foo-Converter", utils.convert(today, String.class)); // No registered Date converter - use String Converter utils.deregister(java.util.Date.class); assertEquals("No registered Date converter", "Foo-Converter", utils.convert(today, String.class)); // String Converter doesn't do Strings!!! utils.register(dummyConverter, String.class); assertEquals("String Converter doesn't do Strings!!!", today.toString(), utils.convert(today, String.class)); // No registered Date or String converter - use Object's toString() utils.deregister(String.class); assertEquals("Object's toString()", today.toString(), utils.convert(today, String.class)); } /** * Tests a conversion to an unsupported target type. */ public void testConvertUnsupportedTargetType() { ConvertUtilsBean utils = new ConvertUtilsBean(); Object value = "A test value"; assertSame("Got different object", value, utils.convert(value, getClass())); } // -------------------------------------------------------- Private Methods private void checkIntegerArray(Object value, int intArray[]) { assertNotNull("Returned value is not null", value); assertEquals("Returned value is int[]", intArray.getClass(), value.getClass()); int results[] = (int[]) value; assertEquals("Returned array length", intArray.length, results.length); for (int i = 0; i < intArray.length; i++) { assertEquals("Returned array value " + i, intArray[i], results[i]); } } private void checkStringArray(Object value, String stringArray[]) { assertNotNull("Returned value is not null", value); assertEquals("Returned value is String[]", stringArray.getClass(), value.getClass()); String results[] = (String[]) value; assertEquals("Returned array length", stringArray.length, results.length); for (int i = 0; i < stringArray.length; i++) { assertEquals("Returned array value " + i, stringArray[i], results[i]); } } } ././@LongLink100644 0 0 160 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/DefaultIntrospectionContextTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/DefaultIntrospectionContextTe100644 0 0 14311 12262570607 31212 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.util.HashSet; import java.util.Set; import junit.framework.TestCase; /** * Test class for {@code IntrospectionContext}. * * @version $Id: DefaultIntrospectionContextTestCase.java 1540359 2013-11-09 18:10:52Z oheger $ */ public class DefaultIntrospectionContextTestCase extends TestCase { /** Constant for the name of a property. */ private static final String PROP = "foo"; /** The context to be tested. */ private DefaultIntrospectionContext context; @Override protected void setUp() throws Exception { super.setUp(); context = new DefaultIntrospectionContext(getClass()); } /** * Creates a property descriptor object for a property with the given name. * * @param propName the property name * @return the descriptor for this property */ private static PropertyDescriptor createDescriptor(String propName) { try { return new PropertyDescriptor(propName, DefaultIntrospectionContextTestCase.class, null, null); } catch (IntrospectionException e) { throw new IllegalStateException("Unexpected exception: " + e); } } /** * Tests a newly created instance. */ public void testInit() { assertEquals("Wrong current class", getClass(), context.getTargetClass()); assertTrue("Got property names", context.propertyNames().isEmpty()); } /** * Tests whether a property descriptor can be added. */ public void testAddPropertyDescriptor() { PropertyDescriptor desc = createDescriptor(PROP); context.addPropertyDescriptor(desc); assertTrue("Property not found", context.hasProperty(PROP)); assertSame("Wrong descriptor", desc, context.getPropertyDescriptor(PROP)); } /** * Tries to add a null descriptor. */ public void testAddPropertyDescriptorNull() { try { context.addPropertyDescriptor(null); fail("Could add null descriptor!"); } catch (IllegalArgumentException iex) { // ok } } /** * Tests whether multiple descriptors can be added. */ public void testAddPropertyDescriptors() { final int count = 4; PropertyDescriptor[] descs = new PropertyDescriptor[count]; Set descSet = new HashSet(); for (int i = 0; i < count; i++) { descs[i] = createDescriptor(PROP + i); descSet.add(descs[i]); } context.addPropertyDescriptors(descs); PropertyDescriptor d = createDescriptor(PROP); context.addPropertyDescriptor(d); descSet.add(d); Set names = context.propertyNames(); assertEquals("Wrong number of property names", count + 1, names.size()); assertTrue("Property not found: " + PROP, names.contains(PROP)); for (int i = 0; i < count; i++) { assertTrue("Property not found: " + (PROP + i), names.contains(PROP + i)); } PropertyDescriptor[] addedDescs = context.getPropertyDescriptors(); assertEquals("Wrong number of added descriptors", count + 1, addedDescs.length); for (PropertyDescriptor pd : addedDescs) { assertTrue("Unexpected descriptor: " + pd, descSet.remove(pd)); } } /** * Tries to add a null array with property descriptors. */ public void testAddPropertyDescriptorsNull() { try { context.addPropertyDescriptors(null); fail("Could add a null array with descriptors!"); } catch (IllegalArgumentException iex) { // ok } } /** * Tests hasProperty() if the expected result is false. */ public void testHasPropertyFalse() { assertFalse("Wrong result (1)", context.hasProperty(PROP)); context.addPropertyDescriptor(createDescriptor(PROP)); assertFalse("Wrong result (2)", context.hasProperty("other")); } /** * Tests getPropertyDescriptor() if the property name is unknown. */ public void testGetPropertyDescriptorUnknown() { assertNull("Got a property (1)", context.getPropertyDescriptor(PROP)); context.addPropertyDescriptor(createDescriptor(PROP)); assertNull("Got a property (2)", context.getPropertyDescriptor("other")); } /** * Tests that the set with property names cannot be changed. */ public void testPropertyNamesModify() { Set names = context.propertyNames(); try { names.add(PROP); fail("Could modify property names set!"); } catch (UnsupportedOperationException uex) { // ok } } /** * Tests whether a descriptor can be removed. */ public void testRemovePropertyDescriptor() { context.addPropertyDescriptor(createDescriptor(PROP)); context.removePropertyDescriptor(PROP); assertTrue("Got property names", context.propertyNames().isEmpty()); assertEquals("Got descriptors", 0, context.getPropertyDescriptors().length); } } ././@LongLink100644 0 0 151 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/DynaBeanMapDecoratorTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/DynaBeanMapDecoratorTestCase.100644 0 0 30220 12262570610 30672 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** *

          Test Case for the DynaBeanMapDecorator implementation class.

          * * @version $Id: DynaBeanMapDecoratorTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ @SuppressWarnings("deprecation") public class DynaBeanMapDecoratorTestCase extends TestCase { private static final DynaProperty stringProp = new DynaProperty("stringProp", String.class); private static final DynaProperty nullProp = new DynaProperty("nullProp", String.class); private static final DynaProperty intProp = new DynaProperty("intProp", Integer.class); private static final DynaProperty dateProp = new DynaProperty("dateProp", Date.class); private static final DynaProperty mapProp = new DynaProperty("mapProp", Map.class); private static final DynaProperty[] properties = new DynaProperty[] { stringProp, nullProp, intProp, dateProp, mapProp}; private static final DynaClass dynaClass = new BasicDynaClass("testDynaClass", BasicDynaBean.class, properties); private static String stringVal = "somevalue"; private static Integer intVal = new Integer(5); private static Date dateVal = new Date(); private final Map mapVal = new HashMap(); private final Object[] values = new Object[] {stringVal, null, intVal, dateVal, mapVal}; private BasicDynaBean dynaBean; private Map decoratedMap; private Map modifiableMap; private static final Map emptyMap = new DynaBeanMapDecorator(new BasicDynaBean(new BasicDynaClass())); // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public DynaBeanMapDecoratorTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Run thus Test */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(DynaBeanMapDecoratorTestCase.class)); } /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { mapVal.clear(); mapVal.put("key1", "key1Value"); mapVal.put("key2", "key2Value"); // Initialize DynaBean and properties dynaBean = new BasicDynaBean(dynaClass); for (int i = 0; i < properties.length; i++) { dynaBean.set(properties[i].getName(), values[i]); } // Create decorated Maps decoratedMap = new DynaBeanMapDecorator(dynaBean); modifiableMap = new DynaBeanMapDecorator(dynaBean, false); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { dynaBean = null; decoratedMap = null; modifiableMap = null; } // ------------------------------------------------ Individual Test Methods /** * Test isReadOnly() method */ public void testIsReadOnly() { assertTrue("decoratedMap true", ((DynaBeanMapDecorator)decoratedMap).isReadOnly()); assertFalse("modifiableMap false", ((DynaBeanMapDecorator)modifiableMap).isReadOnly()); } /** * Test clear() method */ public void testClear() { try { decoratedMap.clear(); fail("decoratedMap.clear()"); } catch(UnsupportedOperationException ignore) { // expected result } try { modifiableMap.clear(); fail("modifiableMap.clear()"); } catch(UnsupportedOperationException ignore) { // expected result } } /** * Test containsKey() method */ public void testContainsKey() { assertTrue("decoratedMap true", decoratedMap.containsKey(stringProp.getName())); assertFalse("decoratedMap false", decoratedMap.containsKey("xyz")); } /** * Test containsValue() method */ public void testContainsValue() { assertTrue("decoratedMap true", decoratedMap.containsValue(stringVal)); assertFalse("decoratedMap false", decoratedMap.containsValue("xyz")); } /** * Test entrySet() method */ public void testEntrySet() { Set> set = modifiableMap.entrySet(); // Check the Set can't be modified Map m = new HashMap(); m.put("key", "value"); checkUnmodifiable("entrySet()", set, m.entrySet().iterator().next()); assertEquals("entrySet size", properties.length, set.size()); Iterator> iterator = set.iterator(); List namesList = new ArrayList(); int i = 0; while (iterator.hasNext()) { Map.Entry entry = iterator.next(); String name = (String)entry.getKey(); namesList.add(name); Object expectValue = decoratedMap.get(name); assertEquals("entrySet("+i+") val", expectValue, entry.getValue()); i++; } for (int j = 0; j < properties.length; j++) { String name = properties[j].getName(); assertTrue("Check property[" + j + "]", namesList.contains(name)); } } /** * Test get() method */ public void testGet() { // valid property name assertEquals("decoratedMap valid", stringVal, decoratedMap.get(stringProp.getName())); // invalid property name try { decoratedMap.get("xyz"); fail("decoratedMap invalid"); } catch(IllegalArgumentException ignore) { // expected result } } /** * Test isEmpty() method */ public void testIsEmpty() { assertTrue("Empty", emptyMap.isEmpty()); assertFalse("Not Empty", decoratedMap.isEmpty()); } /** * Test keySet() method */ public void testKeySet() { Set set = modifiableMap.keySet(); // Check the Set can't be modified checkUnmodifiable("keySet()", set, "xyz"); assertEquals("keySet size", properties.length, set.size()); for (int i = 0; i < properties.length; i++) { String name = properties[i].getName(); assertTrue("Check property[" + i + "]", set.contains(name)); } } /** * Test put() method */ public void testPut() { String newValue = "ABC"; // Test read only try { decoratedMap.put(stringProp.getName(), newValue); fail("Not read only"); } catch(UnsupportedOperationException ignore) { // expected result } // Test Writable assertEquals("modifiableMap put", stringVal, modifiableMap.put(stringProp.getName(), newValue)); assertEquals("dynaBean get", newValue, dynaBean.get(stringProp.getName())); assertEquals("modifiableMap get", newValue, modifiableMap.get(stringProp.getName())); } /** * Test putAll() method */ public void testPutAll() { String newValue = "ABC"; Map newMap = new HashMap(); newMap.put(stringProp.getName(), newValue); // Test read only try { decoratedMap.putAll(newMap); fail("Not read only"); } catch(UnsupportedOperationException ignore) { // expected result } // Test Writable assertEquals("before putAll", stringVal, dynaBean.get(stringProp.getName())); modifiableMap.putAll(newMap); assertEquals("after putAll", newValue, dynaBean.get(stringProp.getName())); } /** * Test remove() method */ public void testRemove() { try { decoratedMap.remove(stringProp.getName()); fail("decoratedMap.remove()"); } catch(UnsupportedOperationException ignore) { // expected result } try { modifiableMap.remove(stringProp.getName()); fail("modifiableMap.remove()"); } catch(UnsupportedOperationException ignore) { // expected result } } /** * Test size() method */ public void testSize() { assertEquals("Empty", 0, emptyMap.size()); assertEquals("Not Empty", properties.length, decoratedMap.size()); } /** * Test values() method */ public void testValues() { Collection collection = modifiableMap.values(); // Check the Collection can't be modified checkUnmodifiable("values()", collection, "xyz"); assertEquals("values size", values.length, collection.size()); // Collection should be ordered in same sequence as properties Iterator iterator = collection.iterator(); int i = 0; while (iterator.hasNext()) { assertEquals("values("+i+")", values[i], iterator.next()); i++; } } /** * Check that a Collection is not modifiable */ private void checkUnmodifiable(String desc, Collection collection, E addElem) { // Check can't add() try { collection.add(addElem); fail(desc + ".add()"); } catch(UnsupportedOperationException ignore) { // expected result } // Check can't addAll() List list = new ArrayList(1); list.add(addElem); try { collection.addAll(list); fail(desc + ".addAll()"); } catch(UnsupportedOperationException ignore) { // expected result } // Check can't clear() try { collection.clear(); fail(desc + ".clear()"); } catch(UnsupportedOperationException ignore) { // expected result } // Check can't remove() try { collection.remove("abc"); fail(desc + ".remove()"); } catch(UnsupportedOperationException ignore) { // expected result } // Check can't removeAll() try { collection.removeAll(list); fail(desc + ".removeAll()"); } catch(UnsupportedOperationException ignore) { // expected result } // Check can't retainAll() try { collection.retainAll(list); fail(desc + ".retainAll()"); } catch(UnsupportedOperationException ignore) { // expected result } } }commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/DynaBeanUtilsTestCase.java100644 0 0 144666 12262570610 30320 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test case for BeanUtils when the underlying bean is actually a DynaBean. * * @version $Id: DynaBeanUtilsTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class DynaBeanUtilsTestCase extends TestCase { // ----------------------------------------------------- Instance Variables /** * The basic test bean for each test. */ protected DynaBean bean = null; /** * The nested bean pointed at by the "nested" property. */ protected TestBean nested = null; /** * The set of properties that should be described. */ protected String describes[] = { "booleanProperty", "booleanSecond", "byteProperty", "doubleProperty", "dupProperty", "floatProperty", "intArray", "intIndexed", "intProperty", "listIndexed", "longProperty", "mapProperty", "mappedProperty", "mappedIntProperty", "nested", "nullProperty", // "readOnlyProperty", "shortProperty", "stringArray", "stringIndexed", "stringProperty" }; // ----------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public DynaBeanUtilsTestCase(String name) { super(name); } // --------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { ConvertUtils.deregister(); // Instantiate a new DynaBean instance DynaClass dynaClass = createDynaClass(); bean = dynaClass.newInstance(); // Initialize the DynaBean's property values (like TestBean) bean.set("booleanProperty", new Boolean(true)); bean.set("booleanSecond", new Boolean(true)); bean.set("byteProperty", new Byte((byte) 121)); bean.set("doubleProperty", new Double(321.0)); bean.set("floatProperty", new Float((float) 123.0)); String dupProperty[] = { "Dup 0", "Dup 1", "Dup 2", "Dup 3", "Dup 4"}; bean.set("dupProperty", dupProperty); int intArray[] = { 0, 10, 20, 30, 40 }; bean.set("intArray", intArray); int intIndexed[] = { 0, 10, 20, 30, 40 }; bean.set("intIndexed", intIndexed); bean.set("intProperty", new Integer(123)); List listIndexed = new ArrayList(); listIndexed.add("String 0"); listIndexed.add("String 1"); listIndexed.add("String 2"); listIndexed.add("String 3"); listIndexed.add("String 4"); bean.set("listIndexed", listIndexed); bean.set("longProperty", new Long(321)); HashMap mapProperty = new HashMap(); mapProperty.put("First Key", "First Value"); mapProperty.put("Second Key", "Second Value"); bean.set("mapProperty", mapProperty); HashMap mappedProperty = new HashMap(); mappedProperty.put("First Key", "First Value"); mappedProperty.put("Second Key", "Second Value"); bean.set("mappedProperty", mappedProperty); HashMap mappedIntProperty = new HashMap(); mappedIntProperty.put("One", new Integer(1)); mappedIntProperty.put("Two", new Integer(2)); bean.set("mappedIntProperty", mappedIntProperty); nested = new TestBean(); bean.set("nested", nested); // Property "nullProperty" is not initialized, so it should return null bean.set("shortProperty", new Short((short) 987)); String stringArray[] = { "String 0", "String 1", "String 2", "String 3", "String 4" }; bean.set("stringArray", stringArray); String stringIndexed[] = { "String 0", "String 1", "String 2", "String 3", "String 4" }; bean.set("stringIndexed", stringIndexed); bean.set("stringProperty", "This is a string"); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(DynaBeanUtilsTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { bean = null; nested = null; } // ------------------------------------------------ Individual Test Methods /** * Test the cloneBean() method from a DynaBean. */ public void testCloneDynaBean() { // Set up an origin bean with customized properties DynaClass dynaClass = DynaBeanUtilsTestCase.createDynaClass(); DynaBean orig = null; try { orig = dynaClass.newInstance(); } catch (Exception e) { fail("newInstance(): " + e); } orig.set("booleanProperty", Boolean.FALSE); orig.set("byteProperty", new Byte((byte)111)); orig.set("doubleProperty", new Double(333.33)); orig.set("dupProperty", new String[] { "New 0", "New 1", "New 2" }); orig.set("intArray", new int[] { 100, 200, 300 }); orig.set("intProperty", new Integer(333)); orig.set("longProperty", new Long(3333)); orig.set("shortProperty", new Short((short) 33)); orig.set("stringArray", new String[] { "New 0", "New 1" }); orig.set("stringProperty", "Custom string"); // Copy the origin bean to our destination test bean DynaBean clonedBean = null; try { clonedBean = (DynaBean) BeanUtils.cloneBean(orig); } catch (Exception e) { fail("Threw exception: " + e); } // Validate the results for scalar properties assertEquals("Cloned boolean property", false, ((Boolean) clonedBean.get("booleanProperty")).booleanValue()); assertEquals("Cloned byte property", (byte) 111, ((Byte) clonedBean.get("byteProperty")).byteValue()); assertEquals("Cloned double property", 333.33, ((Double) clonedBean.get("doubleProperty")).doubleValue(), 0.005); assertEquals("Cloned int property", 333, ((Integer) clonedBean.get("intProperty")).intValue()); assertEquals("Cloned long property", 3333, ((Long) clonedBean.get("longProperty")).longValue()); assertEquals("Cloned short property", (short) 33, ((Short) clonedBean.get("shortProperty")).shortValue()); assertEquals("Cloned string property", "Custom string", (String) clonedBean.get("stringProperty")); // Validate the results for array properties String dupProperty[] = (String[]) clonedBean.get("dupProperty"); assertNotNull("dupProperty present", dupProperty); assertEquals("dupProperty length", 3, dupProperty.length); assertEquals("dupProperty[0]", "New 0", dupProperty[0]); assertEquals("dupProperty[1]", "New 1", dupProperty[1]); assertEquals("dupProperty[2]", "New 2", dupProperty[2]); int intArray[] = (int[]) clonedBean.get("intArray"); assertNotNull("intArray present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 100, intArray[0]); assertEquals("intArray[1]", 200, intArray[1]); assertEquals("intArray[2]", 300, intArray[2]); String stringArray[] = (String[]) clonedBean.get("stringArray"); assertNotNull("stringArray present", stringArray); assertEquals("stringArray length", 2, stringArray.length); assertEquals("stringArray[0]", "New 0", stringArray[0]); assertEquals("stringArray[1]", "New 1", stringArray[1]); } /** * Test the copyProperties() method from a DynaBean. */ public void testCopyPropertiesDynaBean() { // Set up an origin bean with customized properties DynaClass dynaClass = DynaBeanUtilsTestCase.createDynaClass(); DynaBean orig = null; try { orig = dynaClass.newInstance(); } catch (Exception e) { fail("newInstance(): " + e); } orig.set("booleanProperty", Boolean.FALSE); orig.set("byteProperty", new Byte((byte)111)); orig.set("doubleProperty", new Double(333.33)); orig.set("dupProperty", new String[] { "New 0", "New 1", "New 2" }); orig.set("intArray", new int[] { 100, 200, 300 }); orig.set("intProperty", new Integer(333)); orig.set("longProperty", new Long(3333)); orig.set("shortProperty", new Short((short) 33)); orig.set("stringArray", new String[] { "New 0", "New 1" }); orig.set("stringProperty", "Custom string"); // Copy the origin bean to our destination test bean try { BeanUtils.copyProperties(bean, orig); } catch (Exception e) { fail("Threw exception: " + e); } // Validate the results for scalar properties assertEquals("Copied boolean property", false, ((Boolean) bean.get("booleanProperty")).booleanValue()); assertEquals("Copied byte property", (byte) 111, ((Byte) bean.get("byteProperty")).byteValue()); assertEquals("Copied double property", 333.33, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); assertEquals("Copied int property", 333, ((Integer) bean.get("intProperty")).intValue()); assertEquals("Copied long property", 3333, ((Long) bean.get("longProperty")).longValue()); assertEquals("Copied short property", (short) 33, ((Short) bean.get("shortProperty")).shortValue()); assertEquals("Copied string property", "Custom string", (String) bean.get("stringProperty")); // Validate the results for array properties String dupProperty[] = (String[]) bean.get("dupProperty"); assertNotNull("dupProperty present", dupProperty); assertEquals("dupProperty length", 3, dupProperty.length); assertEquals("dupProperty[0]", "New 0", dupProperty[0]); assertEquals("dupProperty[1]", "New 1", dupProperty[1]); assertEquals("dupProperty[2]", "New 2", dupProperty[2]); int intArray[] = (int[]) bean.get("intArray"); assertNotNull("intArray present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 100, intArray[0]); assertEquals("intArray[1]", 200, intArray[1]); assertEquals("intArray[2]", 300, intArray[2]); String stringArray[] = (String[]) bean.get("stringArray"); assertNotNull("stringArray present", stringArray); assertEquals("stringArray length", 2, stringArray.length); assertEquals("stringArray[0]", "New 0", stringArray[0]); assertEquals("stringArray[1]", "New 1", stringArray[1]); } /** * Test copyProperties() when the origin is a a Map. */ public void testCopyPropertiesMap() { Map map = new HashMap(); map.put("booleanProperty", "false"); map.put("byteProperty", "111"); map.put("doubleProperty", "333.0"); map.put("dupProperty", new String[] { "New 0", "New 1", "New 2" }); map.put("floatProperty", "222.0"); map.put("intArray", new String[] { "0", "100", "200" }); map.put("intProperty", "111"); map.put("longProperty", "444"); map.put("shortProperty", "555"); map.put("stringProperty", "New String Property"); try { BeanUtils.copyProperties(bean, map); } catch (Throwable t) { fail("Threw " + t.toString()); } // Scalar properties assertEquals("booleanProperty", false, ((Boolean) bean.get("booleanProperty")).booleanValue()); assertEquals("byteProperty", (byte) 111, ((Byte) bean.get("byteProperty")).byteValue()); assertEquals("doubleProperty", 333.0, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); assertEquals("floatProperty", (float) 222.0, ((Float) bean.get("floatProperty")).floatValue(), (float) 0.005); assertEquals("intProperty", 111, ((Integer) bean.get("intProperty")).intValue()); assertEquals("longProperty", 444, ((Long) bean.get("longProperty")).longValue()); assertEquals("shortProperty", (short) 555, ((Short) bean.get("shortProperty")).shortValue()); assertEquals("stringProperty", "New String Property", (String) bean.get("stringProperty")); // Indexed Properties String dupProperty[] = (String[]) bean.get("dupProperty"); assertNotNull("dupProperty present", dupProperty); assertEquals("dupProperty length", 3, dupProperty.length); assertEquals("dupProperty[0]", "New 0", dupProperty[0]); assertEquals("dupProperty[1]", "New 1", dupProperty[1]); assertEquals("dupProperty[2]", "New 2", dupProperty[2]); int intArray[] = (int[]) bean.get("intArray"); assertNotNull("intArray present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 0, intArray[0]); assertEquals("intArray[1]", 100, intArray[1]); assertEquals("intArray[2]", 200, intArray[2]); } /** * Test the copyProperties() method from a standard JavaBean. */ public void testCopyPropertiesStandard() { // Set up an origin bean with customized properties TestBean orig = new TestBean(); orig.setBooleanProperty(false); orig.setByteProperty((byte) 111); orig.setDoubleProperty(333.33); orig.setDupProperty(new String[] { "New 0", "New 1", "New 2" }); orig.setIntArray(new int[] { 100, 200, 300 }); orig.setIntProperty(333); orig.setLongProperty(3333); orig.setShortProperty((short) 33); orig.setStringArray(new String[] { "New 0", "New 1" }); orig.setStringProperty("Custom string"); // Copy the origin bean to our destination test bean try { BeanUtils.copyProperties(bean, orig); } catch (Exception e) { fail("Threw exception: " + e); } // Validate the results for scalar properties assertEquals("Copied boolean property", false, ((Boolean) bean.get("booleanProperty")).booleanValue()); assertEquals("Copied byte property", (byte) 111, ((Byte) bean.get("byteProperty")).byteValue()); assertEquals("Copied double property", 333.33, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); assertEquals("Copied int property", 333, ((Integer) bean.get("intProperty")).intValue()); assertEquals("Copied long property", 3333, ((Long) bean.get("longProperty")).longValue()); assertEquals("Copied short property", (short) 33, ((Short) bean.get("shortProperty")).shortValue()); assertEquals("Copied string property", "Custom string", (String) bean.get("stringProperty")); // Validate the results for array properties String dupProperty[] = (String[]) bean.get("dupProperty"); assertNotNull("dupProperty present", dupProperty); assertEquals("dupProperty length", 3, dupProperty.length); assertEquals("dupProperty[0]", "New 0", dupProperty[0]); assertEquals("dupProperty[1]", "New 1", dupProperty[1]); assertEquals("dupProperty[2]", "New 2", dupProperty[2]); int intArray[] = (int[]) bean.get("intArray"); assertNotNull("intArray present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 100, intArray[0]); assertEquals("intArray[1]", 200, intArray[1]); assertEquals("intArray[2]", 300, intArray[2]); String stringArray[] = (String[]) bean.get("stringArray"); assertNotNull("stringArray present", stringArray); assertEquals("stringArray length", 2, stringArray.length); assertEquals("stringArray[0]", "New 0", stringArray[0]); assertEquals("stringArray[1]", "New 1", stringArray[1]); } /** * Test the describe() method. */ public void testDescribe() { Map map = null; try { map = PropertyUtils.describe(bean); } catch (Exception e) { fail("Threw exception " + e); } // Verify existence of all the properties that should be present for (int i = 0; i < describes.length; i++) { assertTrue("Property '" + describes[i] + "' is present", map.containsKey(describes[i])); } assertTrue("Property 'writeOnlyProperty' is not present", !map.containsKey("writeOnlyProperty")); // Verify the values of scalar properties assertEquals("Value of 'booleanProperty'", Boolean.TRUE, map.get("booleanProperty")); assertEquals("Value of 'byteProperty'", new Byte((byte) 121), map.get("byteProperty")); assertEquals("Value of 'doubleProperty'", new Double(321.0), map.get("doubleProperty")); assertEquals("Value of 'floatProperty'", new Float((float) 123.0), map.get("floatProperty")); assertEquals("Value of 'intProperty'", new Integer(123), map.get("intProperty")); assertEquals("Value of 'longProperty'", new Long(321), map.get("longProperty")); assertEquals("Value of 'shortProperty'", new Short((short) 987), map.get("shortProperty")); assertEquals("Value of 'stringProperty'", "This is a string", (String) map.get("stringProperty")); } /** * Test populate() method on array properties as a whole. */ public void testPopulateArrayProperties() { try { HashMap map = new HashMap(); // int intArray[] = new int[] { 123, 456, 789 }; String intArrayIn[] = new String[] { "123", "456", "789" }; map.put("intArray", intArrayIn); String stringArray[] = new String[] { "New String 0", "New String 1" }; map.put("stringArray", stringArray); BeanUtils.populate(bean, map); int intArray[] = (int[]) bean.get("intArray"); assertNotNull("intArray is present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 123, intArray[0]); assertEquals("intArray[1]", 456, intArray[1]); assertEquals("intArray[2]", 789, intArray[2]); stringArray = (String[]) bean.get("stringArray"); assertNotNull("stringArray is present", stringArray); assertEquals("stringArray length", 2, stringArray.length); assertEquals("stringArray[0]", "New String 0", stringArray[0]); assertEquals("stringArray[1]", "New String 1", stringArray[1]); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } } /** * tests the string and int arrays of TestBean */ public void testGetArrayProperty() { try { String arr[] = BeanUtils.getArrayProperty(bean, "stringArray"); String comp[] = (String[]) bean.get("stringArray"); assertTrue("String array length = " + comp.length, (comp.length == arr.length)); arr = BeanUtils.getArrayProperty(bean, "intArray"); int iarr[] = (int[]) bean.get("intArray"); assertTrue("String array length = " + iarr.length, (iarr.length == arr.length)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * tests getting an indexed property */ public void testGetIndexedProperty1() { try { String val = BeanUtils.getIndexedProperty(bean, "intIndexed[3]"); String comp = String.valueOf(bean.get("intIndexed", 3)); assertTrue("intIndexed[3] == " + comp, val.equals(comp)); val = BeanUtils.getIndexedProperty(bean, "stringIndexed[3]"); comp = (String) bean.get("stringIndexed", 3); assertTrue("stringIndexed[3] == " + comp, val.equals(comp)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * tests getting an indexed property */ public void testGetIndexedProperty2() { try { String val = BeanUtils.getIndexedProperty(bean, "intIndexed", 3); String comp = String.valueOf(bean.get("intIndexed", 3)); assertTrue("intIndexed,3 == " + comp, val.equals(comp)); val = BeanUtils.getIndexedProperty(bean, "stringIndexed", 3); comp = (String) bean.get("stringIndexed", 3); assertTrue("stringIndexed,3 == " + comp, val.equals(comp)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * tests getting a nested property */ public void testGetNestedProperty() { try { String val = BeanUtils.getNestedProperty(bean, "nested.stringProperty"); String comp = nested.getStringProperty(); assertTrue("nested.StringProperty == " + comp, val.equals(comp)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * tests getting a 'whatever' property */ public void testGetGeneralProperty() { try { String val = BeanUtils.getProperty(bean, "nested.intIndexed[2]"); String comp = String.valueOf(bean.get("intIndexed", 2)); assertTrue("nested.intIndexed[2] == " + comp, val.equals(comp)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * tests getting a 'whatever' property */ public void testGetSimpleProperty() { try { String val = BeanUtils.getSimpleProperty(bean, "shortProperty"); String comp = String.valueOf(bean.get("shortProperty")); assertTrue("shortProperty == " + comp, val.equals(comp)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test populate() method on individual array elements. */ public void testPopulateArrayElements() { try { HashMap map = new HashMap(); map.put("intIndexed[0]", "100"); map.put("intIndexed[2]", "120"); map.put("intIndexed[4]", "140"); BeanUtils.populate(bean, map); Integer intIndexed0 = (Integer) bean.get("intIndexed", 0); assertEquals("intIndexed[0] is 100", 100, intIndexed0.intValue()); Integer intIndexed1 = (Integer) bean.get("intIndexed", 1); assertEquals("intIndexed[1] is 10", 10, intIndexed1.intValue()); Integer intIndexed2 = (Integer) bean.get("intIndexed", 2); assertEquals("intIndexed[2] is 120", 120, intIndexed2.intValue()); Integer intIndexed3 = (Integer) bean.get("intIndexed", 3); assertEquals("intIndexed[3] is 30", 30, intIndexed3.intValue()); Integer intIndexed4 = (Integer) bean.get("intIndexed", 4); assertEquals("intIndexed[4] is 140", 140, intIndexed4.intValue()); map.clear(); map.put("stringIndexed[1]", "New String 1"); map.put("stringIndexed[3]", "New String 3"); BeanUtils.populate(bean, map); assertEquals("stringIndexed[0] is \"String 0\"", "String 0", (String) bean.get("stringIndexed", 0)); assertEquals("stringIndexed[1] is \"New String 1\"", "New String 1", (String) bean.get("stringIndexed", 1)); assertEquals("stringIndexed[2] is \"String 2\"", "String 2", (String) bean.get("stringIndexed", 2)); assertEquals("stringIndexed[3] is \"New String 3\"", "New String 3", (String) bean.get("stringIndexed", 3)); assertEquals("stringIndexed[4] is \"String 4\"", "String 4", (String) bean.get("stringIndexed", 4)); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } } /** * Test populate() on mapped properties. */ public void testPopulateMapped() { try { HashMap map = new HashMap(); map.put("mappedProperty(First Key)", "New First Value"); map.put("mappedProperty(Third Key)", "New Third Value"); BeanUtils.populate(bean, map); assertEquals("mappedProperty(First Key)", "New First Value", (String) bean.get("mappedProperty", "First Key")); assertEquals("mappedProperty(Second Key)", "Second Value", (String) bean.get("mappedProperty", "Second Key")); assertEquals("mappedProperty(Third Key)", "New Third Value", (String) bean.get("mappedProperty", "Third Key")); assertNull("mappedProperty(Fourth Key", bean.get("mappedProperty", "Fourth Key")); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } } /** * Test populate() method on nested properties. */ public void testPopulateNested() { try { HashMap map = new HashMap(); map.put("nested.booleanProperty", "false"); // booleanSecond is left at true map.put("nested.doubleProperty", "432.0"); // floatProperty is left at 123.0 map.put("nested.intProperty", "543"); // longProperty is left at 321 map.put("nested.shortProperty", "654"); // stringProperty is left at "This is a string" BeanUtils.populate(bean, map); TestBean nested = (TestBean) bean.get("nested"); assertTrue("booleanProperty is false", !nested.getBooleanProperty()); assertTrue("booleanSecond is true", nested.isBooleanSecond()); assertEquals("doubleProperty is 432.0", 432.0, nested.getDoubleProperty(), 0.005); assertEquals("floatProperty is 123.0", (float) 123.0, nested.getFloatProperty(), (float) 0.005); assertEquals("intProperty is 543", 543, nested.getIntProperty()); assertEquals("longProperty is 321", 321, nested.getLongProperty()); assertEquals("shortProperty is 654", (short) 654, nested.getShortProperty()); assertEquals("stringProperty is \"This is a string\"", "This is a string", nested.getStringProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } } /** * Test populate() method on scalar properties. */ public void testPopulateScalar() { try { bean.set("nullProperty", "non-null value"); HashMap map = new HashMap(); map.put("booleanProperty", "false"); // booleanSecond is left at true map.put("doubleProperty", "432.0"); // floatProperty is left at 123.0 map.put("intProperty", "543"); // longProperty is left at 321 map.put("nullProperty", null); map.put("shortProperty", "654"); // stringProperty is left at "This is a string" BeanUtils.populate(bean, map); Boolean booleanProperty = (Boolean) bean.get("booleanProperty"); assertTrue("booleanProperty is false", !booleanProperty.booleanValue()); Boolean booleanSecond = (Boolean) bean.get("booleanSecond"); assertTrue("booleanSecond is true", booleanSecond.booleanValue()); Double doubleProperty = (Double) bean.get("doubleProperty"); assertEquals("doubleProperty is 432.0", 432.0, doubleProperty.doubleValue(), 0.005); Float floatProperty = (Float) bean.get("floatProperty"); assertEquals("floatProperty is 123.0", (float) 123.0, floatProperty.floatValue(), (float) 0.005); Integer intProperty = (Integer) bean.get("intProperty"); assertEquals("intProperty is 543", 543, intProperty.intValue()); Long longProperty = (Long) bean.get("longProperty"); assertEquals("longProperty is 321", 321, longProperty.longValue()); assertNull("nullProperty is null", bean.get("nullProperty")); Short shortProperty = (Short) bean.get("shortProperty"); assertEquals("shortProperty is 654", (short) 654, shortProperty.shortValue()); assertEquals("stringProperty is \"This is a string\"", "This is a string", (String) bean.get("stringProperty")); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } } /** * Test calling setProperty() with null property values. */ public void testSetPropertyNullValues() throws Exception { Object oldValue = null; Object newValue = null; // Scalar value into array oldValue = PropertyUtils.getSimpleProperty(bean, "stringArray"); BeanUtils.setProperty(bean, "stringArray", (String) null); newValue = PropertyUtils.getSimpleProperty(bean, "stringArray"); assertNotNull("stringArray is not null", newValue); assertTrue("stringArray of correct type", newValue instanceof String[]); assertEquals("stringArray length", 1, ((String[]) newValue).length); PropertyUtils.setProperty(bean, "stringArray", oldValue); // Indexed value into array oldValue = PropertyUtils.getSimpleProperty(bean, "stringArray"); BeanUtils.setProperty(bean, "stringArray[2]", (String) null); newValue = PropertyUtils.getSimpleProperty(bean, "stringArray"); assertNotNull("stringArray is not null", newValue); assertTrue("stringArray of correct type", newValue instanceof String[]); assertEquals("stringArray length", 5, ((String[]) newValue).length); assertTrue("stringArray[2] is null", ((String[]) newValue)[2] == null); PropertyUtils.setProperty(bean, "stringArray", oldValue); // Value into scalar BeanUtils.setProperty(bean, "stringProperty", null); assertTrue("stringProperty is now null", BeanUtils.getProperty(bean, "stringProperty") == null); } /** * Test converting to and from primitive wrapper types. */ public void testSetPropertyOnPrimitiveWrappers() throws Exception { BeanUtils.setProperty(bean,"intProperty", new Integer(1)); assertEquals(1,((Integer) bean.get("intProperty")).intValue()); BeanUtils.setProperty(bean,"stringProperty", new Integer(1)); assertEquals(1, Integer.parseInt((String) bean.get("stringProperty"))); } /** * Test setting a null property value. */ public void testSetPropertyNull() throws Exception { bean.set("nullProperty", "non-null value"); BeanUtils.setProperty(bean, "nullProperty", null); assertNull("nullProperty is null", bean.get("nullProperty")); } /** * Test narrowing and widening conversions on byte. */ public void testCopyPropertyByte() throws Exception { BeanUtils.setProperty(bean, "byteProperty", new Byte((byte) 123)); assertEquals((byte) 123, ((Byte) bean.get("byteProperty")).byteValue()); /* BeanUtils.setProperty(bean, "byteProperty", new Double((double) 123)); assertEquals((byte) 123, ((Byte) bean.get("byteProperty")).byteValue()); BeanUtils.setProperty(bean, "byteProperty", new Float((float) 123)); assertEquals((byte) 123, ((Byte) bean.get("byteProperty")).byteValue()); */ BeanUtils.setProperty(bean, "byteProperty", new Integer(123)); assertEquals((byte) 123, ((Byte) bean.get("byteProperty")).byteValue()); BeanUtils.setProperty(bean, "byteProperty", new Long(123)); assertEquals((byte) 123, ((Byte) bean.get("byteProperty")).byteValue()); BeanUtils.setProperty(bean, "byteProperty", new Short((short) 123)); assertEquals((byte) 123, ((Byte) bean.get("byteProperty")).byteValue()); } /** * Test narrowing and widening conversions on double. */ public void testCopyPropertyDouble() throws Exception { BeanUtils.setProperty(bean, "doubleProperty", new Byte((byte) 123)); assertEquals(123, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); BeanUtils.setProperty(bean, "doubleProperty", new Double(123)); assertEquals(123, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); BeanUtils.setProperty(bean, "doubleProperty", new Float(123)); assertEquals(123, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); BeanUtils.setProperty(bean, "doubleProperty", new Integer(123)); assertEquals(123, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); BeanUtils.setProperty(bean, "doubleProperty", new Long(123)); assertEquals(123, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); BeanUtils.setProperty(bean, "doubleProperty", new Short((short) 123)); assertEquals(123, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); } /** * Test narrowing and widening conversions on float. */ public void testCopyPropertyFloat() throws Exception { BeanUtils.setProperty(bean, "floatProperty", new Byte((byte) 123)); assertEquals(123, ((Float) bean.get("floatProperty")).floatValue(), 0.005); BeanUtils.setProperty(bean, "floatProperty", new Double(123)); assertEquals(123, ((Float) bean.get("floatProperty")).floatValue(), 0.005); BeanUtils.setProperty(bean, "floatProperty", new Float(123)); assertEquals(123, ((Float) bean.get("floatProperty")).floatValue(), 0.005); BeanUtils.setProperty(bean, "floatProperty", new Integer(123)); assertEquals(123, ((Float) bean.get("floatProperty")).floatValue(), 0.005); BeanUtils.setProperty(bean, "floatProperty", new Long(123)); assertEquals(123, ((Float) bean.get("floatProperty")).floatValue(), 0.005); BeanUtils.setProperty(bean, "floatProperty", new Short((short) 123)); assertEquals(123, ((Float) bean.get("floatProperty")).floatValue(), 0.005); } /** * Test narrowing and widening conversions on int. */ public void testCopyPropertyInteger() throws Exception { BeanUtils.setProperty(bean, "longProperty", new Byte((byte) 123)); assertEquals(123, ((Integer) bean.get("intProperty")).intValue()); /* BeanUtils.setProperty(bean, "longProperty", new Double((double) 123)); assertEquals((int) 123, ((Integer) bean.get("intProperty")).intValue()); BeanUtils.setProperty(bean, "longProperty", new Float((float) 123)); assertEquals((int) 123, ((Integer) bean.get("intProperty")).intValue()); */ BeanUtils.setProperty(bean, "longProperty", new Integer(123)); assertEquals(123, ((Integer) bean.get("intProperty")).intValue()); BeanUtils.setProperty(bean, "longProperty", new Long(123)); assertEquals(123, ((Integer) bean.get("intProperty")).intValue()); BeanUtils.setProperty(bean, "longProperty", new Short((short) 123)); assertEquals(123, ((Integer) bean.get("intProperty")).intValue()); } /** * Test narrowing and widening conversions on long. */ public void testCopyPropertyLong() throws Exception { BeanUtils.setProperty(bean, "longProperty", new Byte((byte) 123)); assertEquals(123, ((Long) bean.get("longProperty")).longValue()); /* BeanUtils.setProperty(bean, "longProperty", new Double((double) 123)); assertEquals((long) 123, ((Long) bean.get("longProperty")).longValue()); BeanUtils.setProperty(bean, "longProperty", new Float((float) 123)); assertEquals((long) 123, ((Long) bean.get("longProperty")).longValue()); */ BeanUtils.setProperty(bean, "longProperty", new Integer(123)); assertEquals(123, ((Long) bean.get("longProperty")).longValue()); BeanUtils.setProperty(bean, "longProperty", new Long(123)); assertEquals(123, ((Long) bean.get("longProperty")).longValue()); BeanUtils.setProperty(bean, "longProperty", new Short((short) 123)); assertEquals(123, ((Long) bean.get("longProperty")).longValue()); } /** * Test copying a null property value. */ public void testCopyPropertyNull() throws Exception { bean.set("nullProperty", "non-null value"); BeanUtils.copyProperty(bean, "nullProperty", null); assertNull("nullProperty is null", bean.get("nullProperty")); } /** * Test narrowing and widening conversions on short. */ public void testCopyPropertyShort() throws Exception { BeanUtils.setProperty(bean, "shortProperty", new Byte((byte) 123)); assertEquals((short) 123, ((Short) bean.get("shortProperty")).shortValue()); /* BeanUtils.setProperty(bean, "shortProperty", new Double((double) 123)); assertEquals((short) 123, ((Short) bean.get("shortProperty")).shortValue()); BeanUtils.setProperty(bean, "shortProperty", new Float((float) 123)); assertEquals((short) 123, ((Short) bean.get("shortProperty")).shortValue()); */ BeanUtils.setProperty(bean, "shortProperty", new Integer(123)); assertEquals((short) 123, ((Short) bean.get("shortProperty")).shortValue()); BeanUtils.setProperty(bean, "shortProperty", new Long(123)); assertEquals((short) 123, ((Short) bean.get("shortProperty")).shortValue()); BeanUtils.setProperty(bean, "shortProperty", new Short((short) 123)); assertEquals((short) 123, ((Short) bean.get("shortProperty")).shortValue()); } /** * Test copying a property using a nested indexed array expression, * with and without conversions. */ public void testCopyPropertyNestedIndexedArray() throws Exception { int origArray[] = { 0, 10, 20, 30, 40}; int intArray[] = { 0, 0, 0 }; ((TestBean) bean.get("nested")).setIntArray(intArray); int intChanged[] = { 0, 0, 0 }; // No conversion required BeanUtils.copyProperty(bean, "nested.intArray[1]", new Integer(1)); checkIntArray((int[]) bean.get("intArray"), origArray); intChanged[1] = 1; checkIntArray(((TestBean) bean.get("nested")).getIntArray(), intChanged); // Widening conversion required BeanUtils.copyProperty(bean, "nested.intArray[1]", new Byte((byte) 2)); checkIntArray((int[]) bean.get("intArray"), origArray); intChanged[1] = 2; checkIntArray(((TestBean) bean.get("nested")).getIntArray(), intChanged); // Narrowing conversion required BeanUtils.copyProperty(bean, "nested.intArray[1]", new Long(3)); checkIntArray((int[]) bean.get("intArray"), origArray); intChanged[1] = 3; checkIntArray(((TestBean) bean.get("nested")).getIntArray(), intChanged); // String conversion required BeanUtils.copyProperty(bean, "nested.intArray[1]", "4"); checkIntArray((int[]) bean.get("intArray"), origArray); intChanged[1] = 4; checkIntArray(((TestBean) bean.get("nested")).getIntArray(), intChanged); } /** * Test copying a property using a nested mapped map property. */ public void testCopyPropertyNestedMappedMap() throws Exception { Map origMap = new HashMap(); origMap.put("First Key", "First Value"); origMap.put("Second Key", "Second Value"); Map changedMap = new HashMap(); changedMap.put("First Key", "First Value"); changedMap.put("Second Key", "Second Value"); // No conversion required BeanUtils.copyProperty(bean, "nested.mapProperty(Second Key)", "New Second Value"); checkMap((Map) bean.get("mapProperty"), origMap); changedMap.put("Second Key", "New Second Value"); checkMap(((TestBean) bean.get("nested")).getMapProperty(), changedMap); } /** * Test copying a property using a nested simple expression, with and * without conversions. */ public void testCopyPropertyNestedSimple() throws Exception { bean.set("intProperty", new Integer(0)); nested.setIntProperty(0); // No conversion required BeanUtils.copyProperty(bean, "nested.intProperty", new Integer(1)); assertEquals(0, ((Integer) bean.get("intProperty")).intValue()); assertEquals(1, nested.getIntProperty()); // Widening conversion required BeanUtils.copyProperty(bean, "nested.intProperty", new Byte((byte) 2)); assertEquals(0, ((Integer) bean.get("intProperty")).intValue()); assertEquals(2, nested.getIntProperty()); // Narrowing conversion required BeanUtils.copyProperty(bean, "nested.intProperty", new Long(3)); assertEquals(0, ((Integer) bean.get("intProperty")).intValue()); assertEquals(3, nested.getIntProperty()); // String conversion required BeanUtils.copyProperty(bean, "nested.intProperty", "4"); assertEquals(0, ((Integer) bean.get("intProperty")).intValue()); assertEquals(4, nested.getIntProperty()); } // ------------------------------------------------------ Protected Methods // Ensure that the nested intArray matches the specified values protected void checkIntArray(int actual[], int expected[]) { assertNotNull("actual array not null", actual); assertEquals("actual array length", expected.length, actual.length); for (int i = 0; i < actual.length; i++) { assertEquals("actual array value[" + i + "]", expected[i], actual[i]); } } // Ensure that the actual Map matches the expected Map protected void checkMap(Map actual, Map expected) { assertNotNull("actual map not null", actual); assertEquals("actual map size", expected.size(), actual.size()); Iterator keys = expected.keySet().iterator(); while (keys.hasNext()) { Object key = keys.next(); assertEquals("actual map value(" + key + ")", expected.get(key), actual.get(key)); } } /** * Create and return a DynaClass instance for our test * DynaBean. */ protected static DynaClass createDynaClass() { int intArray[] = new int[0]; String stringArray[] = new String[0]; DynaClass dynaClass = new BasicDynaClass ("TestDynaClass", null, new DynaProperty[]{ new DynaProperty("booleanProperty", Boolean.TYPE), new DynaProperty("booleanSecond", Boolean.TYPE), new DynaProperty("byteProperty", Byte.TYPE), new DynaProperty("doubleProperty", Double.TYPE), new DynaProperty("dupProperty", stringArray.getClass()), new DynaProperty("floatProperty", Float.TYPE), new DynaProperty("intArray", intArray.getClass()), new DynaProperty("intIndexed", intArray.getClass()), new DynaProperty("intProperty", Integer.TYPE), new DynaProperty("listIndexed", List.class), new DynaProperty("longProperty", Long.TYPE), new DynaProperty("mapProperty", Map.class), new DynaProperty("mappedProperty", Map.class), new DynaProperty("mappedIntProperty", Map.class), new DynaProperty("nested", TestBean.class), new DynaProperty("nullProperty", String.class), new DynaProperty("shortProperty", Short.TYPE), new DynaProperty("stringArray", stringArray.getClass()), new DynaProperty("stringIndexed", stringArray.getClass()), new DynaProperty("stringProperty", String.class), }); return (dynaClass); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/DynaPropertyTestCase.java100644 0 0 10122 12262570610 30211 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.util.Collection; /** * Test case for {@link DynaProperty}. * * @version $Id: DynaPropertyTestCase.java 1454606 2013-03-08 22:30:51Z britter $ */ public class DynaPropertyTestCase extends TestCase { private DynaProperty testPropertyWithName; private DynaProperty testProperty1Duplicate; private DynaProperty testPropertyWithNameAndType; private DynaProperty testProperty2Duplicate; private DynaProperty testPropertyWithNameAndTypeAndContentType; private DynaProperty testProperty3Duplicate; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public DynaPropertyTestCase(String name) { super(name); } /** * Return the tests included in this test suite. * @return a test suite */ public static Test suite() { return (new TestSuite(DynaPropertyTestCase.class)); } /** * Set up instance variables required by this test case. */ @Override protected void setUp() throws Exception { super.setUp(); testPropertyWithName = new DynaProperty("test1"); testProperty1Duplicate = new DynaProperty("test1"); testPropertyWithNameAndType = new DynaProperty("test2", Integer.class); testProperty2Duplicate = new DynaProperty("test2", Integer.class); testPropertyWithNameAndTypeAndContentType = new DynaProperty("test3", Collection.class, Short.class); testProperty3Duplicate = new DynaProperty("test3", Collection.class, Short.class); } /** * Tear down instance variables required by this test case. */ @Override protected void tearDown() throws Exception { testPropertyWithName = testProperty1Duplicate = null; testPropertyWithNameAndType = testProperty2Duplicate = null; testPropertyWithNameAndTypeAndContentType = testProperty3Duplicate = null; super.tearDown(); } /** * Class under test for int hashCode(Object) */ public void testHashCode() { final int initialHashCode = testPropertyWithNameAndTypeAndContentType.hashCode(); assertEquals(testPropertyWithName.hashCode(), testProperty1Duplicate.hashCode()); assertEquals(testPropertyWithNameAndType.hashCode(), testProperty2Duplicate.hashCode()); assertEquals(testPropertyWithNameAndTypeAndContentType.hashCode(), testProperty3Duplicate.hashCode()); assertEquals(initialHashCode, testPropertyWithNameAndTypeAndContentType.hashCode()); } /** * Class under test for boolean equals(Object) */ public void testEqualsObject() { assertEquals(testPropertyWithName, testProperty1Duplicate); assertEquals(testPropertyWithNameAndType, testProperty2Duplicate); assertEquals(testPropertyWithNameAndTypeAndContentType, testProperty3Duplicate); assertFalse(testPropertyWithName.equals(testPropertyWithNameAndType)); assertFalse(testPropertyWithNameAndType.equals(testPropertyWithNameAndTypeAndContentType)); assertFalse(testPropertyWithName.equals(null)); } } ././@LongLink100644 0 0 146 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/DynaPropertyUtilsTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/DynaPropertyUtilsTestCase.jav100644 0 0 267415 12262570610 31134 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test accessing DynaBeans transparently via PropertyUtils. * * @version $Id: DynaPropertyUtilsTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class DynaPropertyUtilsTestCase extends TestCase { // ----------------------------------------------------- Instance Variables /** * The basic test bean for each test. */ protected DynaBean bean = null; /** * The set of properties that should be described. */ protected String describes[] = { "booleanProperty", "booleanSecond", "doubleProperty", "floatProperty", "intArray", "intIndexed", "intProperty", "listIndexed", "longProperty", "mappedObjects", "mappedProperty", "mappedIntProperty", "nested", "nullProperty", // "readOnlyProperty", "shortProperty", "stringArray", "stringIndexed", "stringProperty" }; /** * The nested bean pointed at by the "nested" property. */ protected TestBean nested = null; // ----------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public DynaPropertyUtilsTestCase(String name) { super(name); } // --------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { // Instantiate a new DynaBean instance DynaClass dynaClass = createDynaClass(); bean = dynaClass.newInstance(); // Initialize the DynaBean's property values (like TestBean) bean.set("booleanProperty", new Boolean(true)); bean.set("booleanSecond", new Boolean(true)); bean.set("doubleProperty", new Double(321.0)); bean.set("floatProperty", new Float((float) 123.0)); int intArray[] = { 0, 10, 20, 30, 40 }; bean.set("intArray", intArray); int intIndexed[] = { 0, 10, 20, 30, 40 }; bean.set("intIndexed", intIndexed); bean.set("intProperty", new Integer(123)); List listIndexed = new ArrayList(); listIndexed.add("String 0"); listIndexed.add("String 1"); listIndexed.add("String 2"); listIndexed.add("String 3"); listIndexed.add("String 4"); bean.set("listIndexed", listIndexed); bean.set("longProperty", new Long(321)); HashMap mapProperty = new HashMap(); mapProperty.put("First Key", "First Value"); mapProperty.put("Second Key", "Second Value"); bean.set("mapProperty", mapProperty); HashMap mappedObjects = new HashMap(); mappedObjects.put("First Key", "First Value"); mappedObjects.put("Second Key", "Second Value"); bean.set("mappedObjects", mappedObjects); HashMap mappedProperty = new HashMap(); mappedProperty.put("First Key", "First Value"); mappedProperty.put("Second Key", "Second Value"); bean.set("mappedProperty", mappedProperty); HashMap mappedIntProperty = new HashMap(); mappedIntProperty.put("One", new Integer(1)); mappedIntProperty.put("Two", new Integer(2)); bean.set("mappedIntProperty", mappedIntProperty); nested = new TestBean(); bean.set("nested", nested); // Property "nullProperty" is not initialized, so it should return null bean.set("shortProperty", new Short((short) 987)); String stringArray[] = { "String 0", "String 1", "String 2", "String 3", "String 4" }; bean.set("stringArray", stringArray); String stringIndexed[] = { "String 0", "String 1", "String 2", "String 3", "String 4" }; bean.set("stringIndexed", stringIndexed); bean.set("stringProperty", "This is a string"); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(DynaPropertyUtilsTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { bean = null; nested = null; } // ------------------------------------------------ Individual Test Methods /** * Test copyProperties() when the origin is a a Map. */ public void testCopyPropertiesMap() { Map map = new HashMap(); map.put("booleanProperty", Boolean.FALSE); map.put("doubleProperty", new Double(333.0)); map.put("dupProperty", new String[] { "New 0", "New 1", "New 2" }); map.put("floatProperty", new Float((float) 222.0)); map.put("intArray", new int[] { 0, 100, 200 }); map.put("intProperty", new Integer(111)); map.put("longProperty", new Long(444)); map.put("shortProperty", new Short((short) 555)); map.put("stringProperty", "New String Property"); try { PropertyUtils.copyProperties(bean, map); } catch (Throwable t) { fail("Threw " + t.toString()); } // Scalar properties assertEquals("booleanProperty", false, ((Boolean) bean.get("booleanProperty")).booleanValue()); assertEquals("doubleProperty", 333.0, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); assertEquals("floatProperty", (float) 222.0, ((Float) bean.get("floatProperty")).floatValue(), (float) 0.005); assertEquals("intProperty", 111, ((Integer) bean.get("intProperty")).intValue()); assertEquals("longProperty", 444, ((Long) bean.get("longProperty")).longValue()); assertEquals("shortProperty", (short) 555, ((Short) bean.get("shortProperty")).shortValue()); assertEquals("stringProperty", "New String Property", (String) bean.get("stringProperty")); // Indexed Properties String dupProperty[] = (String[]) bean.get("dupProperty"); assertNotNull("dupProperty present", dupProperty); assertEquals("dupProperty length", 3, dupProperty.length); assertEquals("dupProperty[0]", "New 0", dupProperty[0]); assertEquals("dupProperty[1]", "New 1", dupProperty[1]); assertEquals("dupProperty[2]", "New 2", dupProperty[2]); int intArray[] = (int[]) bean.get("intArray"); assertNotNull("intArray present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 0, intArray[0]); assertEquals("intArray[1]", 100, intArray[1]); assertEquals("intArray[2]", 200, intArray[2]); } /** * Test the describe() method. */ public void testDescribe() { Map map = null; try { map = PropertyUtils.describe(bean); } catch (Exception e) { fail("Threw exception " + e); } // Verify existence of all the properties that should be present for (int i = 0; i < describes.length; i++) { assertTrue("Property '" + describes[i] + "' is present", map.containsKey(describes[i])); } assertTrue("Property 'writeOnlyProperty' is not present", !map.containsKey("writeOnlyProperty")); // Verify the values of scalar properties assertEquals("Value of 'booleanProperty'", Boolean.TRUE, map.get("booleanProperty")); assertEquals("Value of 'doubleProperty'", new Double(321.0), map.get("doubleProperty")); assertEquals("Value of 'floatProperty'", new Float((float) 123.0), map.get("floatProperty")); assertEquals("Value of 'intProperty'", new Integer(123), map.get("intProperty")); assertEquals("Value of 'longProperty'", new Long(321), map.get("longProperty")); assertEquals("Value of 'shortProperty'", new Short((short) 987), map.get("shortProperty")); assertEquals("Value of 'stringProperty'", "This is a string", (String) map.get("stringProperty")); } /** * Corner cases on getIndexedProperty invalid arguments. */ public void testGetIndexedArguments() { // Use explicit index argument try { PropertyUtils.getIndexedProperty(null, "intArray", 0); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getIndexedProperty(bean, null, 0); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } // Use index expression try { PropertyUtils.getIndexedProperty(null, "intArray[0]"); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } try { PropertyUtils.getIndexedProperty(bean, "[0]"); fail("Should throw NoSuchMethodException 4"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 4"); } try { PropertyUtils.getIndexedProperty(bean, "intArray"); fail("Should throw IllegalArgumentException 5"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 5"); } // Use explicit index argument try { PropertyUtils.getIndexedProperty(null, "intIndexed", 0); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getIndexedProperty(bean, null, 0); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } // Use index expression try { PropertyUtils.getIndexedProperty(null, "intIndexed[0]"); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } try { PropertyUtils.getIndexedProperty(bean, "[0]"); fail("Should throw NoSuchMethodException 4"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 4"); } try { PropertyUtils.getIndexedProperty(bean, "intIndexed"); fail("Should throw IllegalArgumentException 5"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 5"); } } /** * Positive and negative tests on getIndexedProperty valid arguments. */ public void testGetIndexedValues() { Object value = null; // Use explicit key argument for (int i = 0; i < 5; i++) { try { value = PropertyUtils.getIndexedProperty(bean, "intArray", i); assertNotNull("intArray returned value " + i, value); assertTrue("intArray returned Integer " + i, value instanceof Integer); assertEquals("intArray returned correct " + i, i * 10, ((Integer) value).intValue()); } catch (Throwable t) { fail("intArray " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "intIndexed", i); assertNotNull("intIndexed returned value " + i, value); assertTrue("intIndexed returned Integer " + i, value instanceof Integer); assertEquals("intIndexed returned correct " + i, i * 10, ((Integer) value).intValue()); } catch (Throwable t) { fail("intIndexed " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "listIndexed", i); assertNotNull("listIndexed returned value " + i, value); assertTrue("list returned String " + i, value instanceof String); assertEquals("listIndexed returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("listIndexed " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "stringArray", i); assertNotNull("stringArray returned value " + i, value); assertTrue("stringArray returned String " + i, value instanceof String); assertEquals("stringArray returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("stringArray " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "stringIndexed", i); assertNotNull("stringIndexed returned value " + i, value); assertTrue("stringIndexed returned String " + i, value instanceof String); assertEquals("stringIndexed returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("stringIndexed " + i + " threw " + t); } } // Use key expression for (int i = 0; i < 5; i++) { try { value = PropertyUtils.getIndexedProperty(bean, "intArray[" + i + "]"); assertNotNull("intArray returned value " + i, value); assertTrue("intArray returned Integer " + i, value instanceof Integer); assertEquals("intArray returned correct " + i, i * 10, ((Integer) value).intValue()); } catch (Throwable t) { fail("intArray " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "intIndexed[" + i + "]"); assertNotNull("intIndexed returned value " + i, value); assertTrue("intIndexed returned Integer " + i, value instanceof Integer); assertEquals("intIndexed returned correct " + i, i * 10, ((Integer) value).intValue()); } catch (Throwable t) { fail("intIndexed " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "listIndexed[" + i + "]"); assertNotNull("listIndexed returned value " + i, value); assertTrue("listIndexed returned String " + i, value instanceof String); assertEquals("listIndexed returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("listIndexed " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "stringArray[" + i + "]"); assertNotNull("stringArray returned value " + i, value); assertTrue("stringArray returned String " + i, value instanceof String); assertEquals("stringArray returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("stringArray " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "stringIndexed[" + i + "]"); assertNotNull("stringIndexed returned value " + i, value); assertTrue("stringIndexed returned String " + i, value instanceof String); assertEquals("stringIndexed returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("stringIndexed " + i + " threw " + t); } } // Index out of bounds tests try { value = PropertyUtils.getIndexedProperty(bean, "intArray", -1); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "intArray", 5); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "intIndexed", -1); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "intIndexed", 5); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "listIndexed", -1); fail("Should have thrown IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of IndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "listIndexed", 5); fail("Should have thrown IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of IndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "stringArray", -1); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "stringArray", 5); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "stringIndexed", -1); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "stringIndexed", 5); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } } /** * Corner cases on getMappedProperty invalid arguments. */ public void testGetMappedArguments() { // Use explicit key argument try { PropertyUtils.getMappedProperty(null, "mappedProperty", "First Key"); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getMappedProperty(bean, null, "First Key"); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } try { PropertyUtils.getMappedProperty(bean, "mappedProperty", null); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } // Use key expression try { PropertyUtils.getMappedProperty(null, "mappedProperty(First Key)"); fail("Should throw IllegalArgumentException 4"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 4"); } try { PropertyUtils.getMappedProperty(bean, "(Second Key)"); fail("Should throw IllegalArgumentException 5"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 5"); } try { PropertyUtils.getMappedProperty(bean, "mappedProperty"); fail("Should throw IllegalArgumentException 6"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 6"); } } /** * Test getting mapped values with periods in the key. */ public void testGetMappedPeriods() { bean.set("mappedProperty", "key.with.a.dot", "Special Value"); assertEquals("Can retrieve directly", "Special Value", (String) bean.get("mappedProperty", "key.with.a.dot")); try { assertEquals("Can retrieve via getMappedProperty", "Special Value", PropertyUtils.getMappedProperty (bean, "mappedProperty", "key.with.a.dot")); } catch (Exception e) { fail("Thew exception: " + e); } try { assertEquals("Can retrieve via getNestedProperty", "Special Value", PropertyUtils.getNestedProperty (bean, "mappedProperty(key.with.a.dot)")); } catch (Exception e) { fail("Thew exception: " + e); } bean.set("mappedObjects", "nested.property", new TestBean()); assertNotNull("Can retrieve directly", bean.get("mappedObjects", "nested.property")); try { assertEquals("Can retrieve nested", "This is a string", PropertyUtils.getNestedProperty (bean, "mappedObjects(nested.property).stringProperty")); } catch (Exception e) { fail("Thew exception: " + e); } } /** * Test getting mapped values with slashes in the key. This is different * from periods because slashes are not syntactically significant. */ public void testGetMappedSlashes() { bean.set("mappedProperty", "key/with/a/slash", "Special Value"); assertEquals("Can retrieve directly", "Special Value", bean.get("mappedProperty", "key/with/a/slash")); try { assertEquals("Can retrieve via getMappedProperty", "Special Value", PropertyUtils.getMappedProperty (bean, "mappedProperty", "key/with/a/slash")); } catch (Exception e) { fail("Thew exception: " + e); } try { assertEquals("Can retrieve via getNestedProperty", "Special Value", PropertyUtils.getNestedProperty (bean, "mappedProperty(key/with/a/slash)")); } catch (Exception e) { fail("Thew exception: " + e); } bean.set("mappedObjects", "nested/property", new TestBean()); assertNotNull("Can retrieve directly", bean.get("mappedObjects", "nested/property")); try { assertEquals("Can retrieve nested", "This is a string", PropertyUtils.getNestedProperty (bean, "mappedObjects(nested/property).stringProperty")); } catch (Exception e) { fail("Thew exception: " + e); } } /** * Positive and negative tests on getMappedProperty valid arguments. */ public void testGetMappedValues() { Object value = null; // Use explicit key argument try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty", "First Key"); assertEquals("Can find first value", "First Value", value); } catch (Throwable t) { fail("Finding first value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty", "Second Key"); assertEquals("Can find second value", "Second Value", value); } catch (Throwable t) { fail("Finding second value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty", "Third Key"); assertNull("Can not find third value", value); } catch (Throwable t) { fail("Finding third value threw " + t); } // Use key expression with parentheses try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty(First Key)"); assertEquals("Can find first value", "First Value", value); } catch (Throwable t) { fail("Finding first value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty(Second Key)"); assertEquals("Can find second value", "Second Value", value); } catch (Throwable t) { fail("Finding second value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty(Third Key)"); assertNull("Can not find third value", value); } catch (Throwable t) { fail("Finding third value threw " + t); } // Use key expression with dotted syntax try { value = PropertyUtils.getNestedProperty(bean, "mapProperty.First Key"); assertEquals("Can find first value", "First Value", value); } catch (Throwable t) { fail("Finding first value threw " + t); } try { value = PropertyUtils.getNestedProperty(bean, "mapProperty.Second Key"); assertEquals("Can find second value", "Second Value", value); } catch (Throwable t) { fail("Finding second value threw " + t); } try { value = PropertyUtils.getNestedProperty(bean, "mapProperty.Third Key"); assertNull("Can not find third value", value); } catch (Throwable t) { fail("Finding third value threw " + t); } } /** * Corner cases on getNestedProperty invalid arguments. */ public void testGetNestedArguments() { try { PropertyUtils.getNestedProperty(null, "stringProperty"); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getNestedProperty(bean, null); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } } /** * Test getNestedProperty on a boolean property. */ public void testGetNestedBoolean() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.booleanProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Boolean)); TestBean nested = (TestBean) bean.get("nested"); assertTrue("Got correct value", ((Boolean) value).booleanValue() == nested.getBooleanProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a double property. */ public void testGetNestedDouble() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.doubleProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Double)); TestBean nested = (TestBean) bean.get("nested"); assertEquals("Got correct value", ((Double) value).doubleValue(), nested.getDoubleProperty(), 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a float property. */ public void testGetNestedFloat() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.floatProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Float)); TestBean nested = (TestBean) bean.get("nested"); assertEquals("Got correct value", ((Float) value).floatValue(), nested.getFloatProperty(), (float) 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on an int property. */ public void testGetNestedInt() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.intProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Integer)); TestBean nested = (TestBean) bean.get("nested"); assertEquals("Got correct value", ((Integer) value).intValue(), nested.getIntProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a long property. */ public void testGetNestedLong() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.longProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Long)); TestBean nested = (TestBean) bean.get("nested"); assertEquals("Got correct value", ((Long) value).longValue(), nested.getLongProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a read-only String property. */ public void testGetNestedReadOnly() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.readOnlyProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof String)); TestBean nested = (TestBean) bean.get("nested"); assertEquals("Got correct value", (String) value, nested.getReadOnlyProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a short property. */ public void testGetNestedShort() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.shortProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Short)); TestBean nested = (TestBean) bean.get("nested"); assertEquals("Got correct value", ((Short) value).shortValue(), nested.getShortProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a String property. */ public void testGetNestedString() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.stringProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof String)); TestBean nested = (TestBean) bean.get("nested"); assertEquals("Got correct value", ((String) value), nested.getStringProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test getNestedProperty on an unknown property. */ public void testGetNestedUnknown() { try { PropertyUtils.getNestedProperty(bean, "nested.unknown"); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test } } /** * Corner cases on getSimpleProperty invalid arguments. */ public void testGetSimpleArguments() { try { PropertyUtils.getSimpleProperty(null, "stringProperty"); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getSimpleProperty(bean, null); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } } /** * Test getSimpleProperty on a boolean property. */ public void testGetSimpleBoolean() { try { Object value = PropertyUtils.getSimpleProperty(bean, "booleanProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Boolean)); assertTrue("Got correct value", ((Boolean) value).booleanValue() == true); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a double property. */ public void testGetSimpleDouble() { try { Object value = PropertyUtils.getSimpleProperty(bean, "doubleProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Double)); assertEquals("Got correct value", ((Double) value).doubleValue(), 321.0, 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a float property. */ public void testGetSimpleFloat() { try { Object value = PropertyUtils.getSimpleProperty(bean, "floatProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Float)); assertEquals("Got correct value", ((Float) value).floatValue(), (float) 123.0, (float) 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test getSimpleProperty on an indexed property. */ public void testGetSimpleIndexed() { try { PropertyUtils.getSimpleProperty(bean, "intIndexed[0]"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { // Correct result for this test } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on an int property. */ public void testGetSimpleInt() { try { Object value = PropertyUtils.getSimpleProperty(bean, "intProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Integer)); assertEquals("Got correct value", ((Integer) value).intValue(), 123); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a long property. */ public void testGetSimpleLong() { try { Object value = PropertyUtils.getSimpleProperty(bean, "longProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Long)); assertEquals("Got correct value", ((Long) value).longValue(), 321); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test getSimpleProperty on a nested property. */ public void testGetSimpleNested() { try { PropertyUtils.getSimpleProperty(bean, "nested.stringProperty"); fail("Should have thrown IllegaArgumentException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { // Correct result for this test } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a short property. */ public void testGetSimpleShort() { try { Object value = PropertyUtils.getSimpleProperty(bean, "shortProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Short)); assertEquals("Got correct value", ((Short) value).shortValue(), (short) 987); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a String property. */ public void testGetSimpleString() { try { Object value = PropertyUtils.getSimpleProperty(bean, "stringProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof String)); assertEquals("Got correct value", (String) value, "This is a string"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test getSimpleProperty on an unknown property. */ public void testGetSimpleUnknown() { try { PropertyUtils.getSimpleProperty(bean, "unknown"); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test assertEquals("Unknown property 'unknown' on dynaclass '" + bean.getDynaClass() + "'", e.getMessage() ); } } /** * Corner cases on setIndexedProperty invalid arguments. */ public void testSetIndexedArguments() { // Use explicit index argument try { PropertyUtils.setIndexedProperty(null, "intArray", 0, new Integer(1)); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.setIndexedProperty(bean, null, 0, new Integer(1)); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } // Use index expression try { PropertyUtils.setIndexedProperty(null, "intArray[0]", new Integer(1)); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } try { PropertyUtils.setIndexedProperty(bean, "[0]", new Integer(1)); fail("Should throw NoSuchMethodException 4"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 4"); } try { PropertyUtils.setIndexedProperty(bean, "intArray", new Integer(1)); fail("Should throw IllegalArgumentException 5"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 5"); } // Use explicit index argument try { PropertyUtils.setIndexedProperty(null, "intIndexed", 0, new Integer(1)); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.setIndexedProperty(bean, null, 0, new Integer(1)); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } // Use index expression try { PropertyUtils.setIndexedProperty(null, "intIndexed[0]", new Integer(1)); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } try { PropertyUtils.setIndexedProperty(bean, "[0]", new Integer(1)); fail("Should throw NoSuchMethodException 4"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 4"); } try { PropertyUtils.setIndexedProperty(bean, "intIndexed", new Integer(1)); fail("Should throw IllegalArgumentException 5"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 5"); } } /** * Positive and negative tests on setIndexedProperty valid arguments. */ public void testSetIndexedValues() { Object value = null; // Use explicit index argument try { PropertyUtils.setIndexedProperty(bean, "intArray", 0, new Integer(1)); value = PropertyUtils.getIndexedProperty(bean, "intArray", 0); assertNotNull("Returned new value 0", value); assertTrue("Returned Integer new value 0", value instanceof Integer); assertEquals("Returned correct new value 0", 1, ((Integer) value).intValue()); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "intIndexed", 1, new Integer(11)); value = PropertyUtils.getIndexedProperty(bean, "intIndexed", 1); assertNotNull("Returned new value 1", value); assertTrue("Returned Integer new value 1", value instanceof Integer); assertEquals("Returned correct new value 1", 11, ((Integer) value).intValue()); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "listIndexed", 2, "New Value 2"); value = PropertyUtils.getIndexedProperty(bean, "listIndexed", 2); assertNotNull("Returned new value 2", value); assertTrue("Returned String new value 2", value instanceof String); assertEquals("Returned correct new value 2", "New Value 2", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "stringArray", 2, "New Value 2"); value = PropertyUtils.getIndexedProperty(bean, "stringArray", 2); assertNotNull("Returned new value 2", value); assertTrue("Returned String new value 2", value instanceof String); assertEquals("Returned correct new value 2", "New Value 2", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "stringArray", 3, "New Value 3"); value = PropertyUtils.getIndexedProperty(bean, "stringArray", 3); assertNotNull("Returned new value 3", value); assertTrue("Returned String new value 3", value instanceof String); assertEquals("Returned correct new value 3", "New Value 3", (String) value); } catch (Throwable t) { fail("Threw " + t); } // Use index expression try { PropertyUtils.setIndexedProperty(bean, "intArray[4]", new Integer(1)); value = PropertyUtils.getIndexedProperty(bean, "intArray[4]"); assertNotNull("Returned new value 4", value); assertTrue("Returned Integer new value 4", value instanceof Integer); assertEquals("Returned correct new value 4", 1, ((Integer) value).intValue()); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "intIndexed[3]", new Integer(11)); value = PropertyUtils.getIndexedProperty(bean, "intIndexed[3]"); assertNotNull("Returned new value 5", value); assertTrue("Returned Integer new value 5", value instanceof Integer); assertEquals("Returned correct new value 5", 11, ((Integer) value).intValue()); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "listIndexed[1]", "New Value 2"); value = PropertyUtils.getIndexedProperty(bean, "listIndexed[1]"); assertNotNull("Returned new value 6", value); assertTrue("Returned String new value 6", value instanceof String); assertEquals("Returned correct new value 6", "New Value 2", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "stringArray[1]", "New Value 2"); value = PropertyUtils.getIndexedProperty(bean, "stringArray[2]"); assertNotNull("Returned new value 6", value); assertTrue("Returned String new value 6", value instanceof String); assertEquals("Returned correct new value 6", "New Value 2", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "stringArray[0]", "New Value 3"); value = PropertyUtils.getIndexedProperty(bean, "stringArray[0]"); assertNotNull("Returned new value 7", value); assertTrue("Returned String new value 7", value instanceof String); assertEquals("Returned correct new value 7", "New Value 3", (String) value); } catch (Throwable t) { fail("Threw " + t); } // Index out of bounds tests try { PropertyUtils.setIndexedProperty(bean, "intArray", -1, new Integer(0)); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "intArray", 5, new Integer(0)); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "intIndexed", -1, new Integer(0)); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "intIndexed", 5, new Integer(0)); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "listIndexed", 5, "New String"); fail("Should have thrown IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of IndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "listIndexed", -1, "New String"); fail("Should have thrown IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of IndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "stringArray", -1, "New String"); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "stringArray", 5, "New String"); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "stringIndexed", -1, "New String"); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "stringIndexed", 5, "New String"); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } } /** * Corner cases on getMappedProperty invalid arguments. */ public void testSetMappedArguments() { // Use explicit key argument try { PropertyUtils.setMappedProperty(null, "mappedProperty", "First Key", "First Value"); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.setMappedProperty(bean, null, "First Key", "First Value"); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } try { PropertyUtils.setMappedProperty(bean, "mappedProperty", null, "First Value"); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } // Use key expression try { PropertyUtils.setMappedProperty(null, "mappedProperty(First Key)", "First Value"); fail("Should throw IllegalArgumentException 4"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 4"); } try { PropertyUtils.setMappedProperty(bean, "(Second Key)", "Second Value"); fail("Should throw IllegalArgumentException 5"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 5"); } try { PropertyUtils.setMappedProperty(bean, "mappedProperty", "Third Value"); fail("Should throw IllegalArgumentException 6"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 6"); } } /** * Positive and negative tests on setMappedProperty valid arguments. */ public void testSetMappedValues() { Object value = null; // Use explicit key argument try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty", "Fourth Key"); assertNull("Can not find fourth value", value); } catch (Throwable t) { fail("Finding fourth value threw " + t); } try { PropertyUtils.setMappedProperty(bean, "mappedProperty", "Fourth Key", "Fourth Value"); } catch (Throwable t) { fail("Setting fourth value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty", "Fourth Key"); assertEquals("Can find fourth value", "Fourth Value", value); } catch (Throwable t) { fail("Finding fourth value threw " + t); } // Use key expression with parentheses try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty(Fifth Key)"); assertNull("Can not find fifth value", value); } catch (Throwable t) { fail("Finding fifth value threw " + t); } try { PropertyUtils.setMappedProperty(bean, "mappedProperty(Fifth Key)", "Fifth Value"); } catch (Throwable t) { fail("Setting fifth value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty(Fifth Key)"); assertEquals("Can find fifth value", "Fifth Value", value); } catch (Throwable t) { fail("Finding fifth value threw " + t); } // Use key expression with dotted expression try { value = PropertyUtils.getNestedProperty(bean, "mapProperty.Sixth Key"); assertNull("Can not find sixth value", value); } catch (Throwable t) { fail("Finding fifth value threw " + t); } try { PropertyUtils.setNestedProperty(bean, "mapProperty.Sixth Key", "Sixth Value"); } catch (Throwable t) { fail("Setting sixth value threw " + t); } try { value = PropertyUtils.getNestedProperty(bean, "mapProperty.Sixth Key"); assertEquals("Can find sixth value", "Sixth Value", value); } catch (Throwable t) { fail("Finding sixth value threw " + t); } } /** * Corner cases on setNestedProperty invalid arguments. */ public void testSetNestedArguments() { try { PropertyUtils.setNestedProperty(null, "stringProperty", ""); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.setNestedProperty(bean, null, ""); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } } /** * Test setNextedProperty on a boolean property. */ public void testSetNestedBoolean() { try { boolean oldValue = nested.getBooleanProperty(); boolean newValue = !oldValue; PropertyUtils.setNestedProperty(bean, "nested.booleanProperty", new Boolean(newValue)); assertTrue("Matched new value", newValue == nested.getBooleanProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a double property. */ public void testSetNestedDouble() { try { double oldValue = nested.getDoubleProperty(); double newValue = oldValue + 1.0; PropertyUtils.setNestedProperty(bean, "nested.doubleProperty", new Double(newValue)); assertEquals("Matched new value", newValue, nested.getDoubleProperty(), 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a float property. */ public void testSetNestedFloat() { try { float oldValue = nested.getFloatProperty(); float newValue = oldValue + (float) 1.0; PropertyUtils.setNestedProperty(bean, "nested.floatProperty", new Float(newValue)); assertEquals("Matched new value", newValue, nested.getFloatProperty(), (float) 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a int property. */ public void testSetNestedInt() { try { int oldValue = nested.getIntProperty(); int newValue = oldValue + 1; PropertyUtils.setNestedProperty(bean, "nested.intProperty", new Integer(newValue)); assertEquals("Matched new value", newValue, nested.getIntProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a long property. */ public void testSetNestedLong() { try { long oldValue = nested.getLongProperty(); long newValue = oldValue + 1; PropertyUtils.setNestedProperty(bean, "nested.longProperty", new Long(newValue)); assertEquals("Matched new value", newValue, nested.getLongProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a read-only String property. */ public void testSetNestedReadOnly() { try { String oldValue = nested.getWriteOnlyPropertyValue(); String newValue = oldValue + " Extra Value"; PropertyUtils.setNestedProperty(bean, "nested.readOnlyProperty", newValue); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test } } /** * Test setNestedProperty on a short property. */ public void testSetNestedShort() { try { short oldValue = nested.getShortProperty(); short newValue = oldValue; newValue++; PropertyUtils.setNestedProperty(bean, "nested.shortProperty", new Short(newValue)); assertEquals("Matched new value", newValue, nested.getShortProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a String property. */ public void testSetNestedString() { try { String oldValue = nested.getStringProperty(); String newValue = oldValue + " Extra Value"; PropertyUtils.setNestedProperty(bean, "nested.stringProperty", newValue); assertEquals("Matched new value", newValue, nested.getStringProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on an unknown property name. */ public void testSetNestedUnknown() { try { String newValue = "New String Value"; PropertyUtils.setNestedProperty(bean, "nested.unknown", newValue); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test } } /** * Test setNestedProperty on a write-only String property. */ public void testSetNestedWriteOnly() { try { String oldValue = nested.getWriteOnlyPropertyValue(); String newValue = oldValue + " Extra Value"; PropertyUtils.setNestedProperty(bean, "nested.writeOnlyProperty", newValue); assertEquals("Matched new value", newValue, nested.getWriteOnlyPropertyValue()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Corner cases on setSimpleProperty invalid arguments. */ public void testSetSimpleArguments() { try { PropertyUtils.setSimpleProperty(null, "stringProperty", ""); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.setSimpleProperty(bean, null, ""); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } } /** * Test setSimpleProperty on a boolean property. */ public void testSetSimpleBoolean() { try { boolean oldValue = ((Boolean) bean.get("booleanProperty")).booleanValue(); boolean newValue = !oldValue; PropertyUtils.setSimpleProperty(bean, "booleanProperty", new Boolean(newValue)); assertTrue("Matched new value", newValue == ((Boolean) bean.get("booleanProperty")).booleanValue()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a double property. */ public void testSetSimpleDouble() { try { double oldValue = ((Double) bean.get("doubleProperty")).doubleValue(); double newValue = oldValue + 1.0; PropertyUtils.setSimpleProperty(bean, "doubleProperty", new Double(newValue)); assertEquals("Matched new value", newValue, ((Double) bean.get("doubleProperty")).doubleValue(), 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a float property. */ public void testSetSimpleFloat() { try { float oldValue = ((Float) bean.get("floatProperty")).floatValue(); float newValue = oldValue + (float) 1.0; PropertyUtils.setSimpleProperty(bean, "floatProperty", new Float(newValue)); assertEquals("Matched new value", newValue, ((Float) bean.get("floatProperty")).floatValue(), (float) 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test setSimpleProperty on an indexed property. */ public void testSetSimpleIndexed() { try { PropertyUtils.setSimpleProperty(bean, "stringIndexed[0]", "New String Value"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { // Correct result for this test } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a int property. */ public void testSetSimpleInt() { try { int oldValue = ((Integer) bean.get("intProperty")).intValue(); int newValue = oldValue + 1; PropertyUtils.setSimpleProperty(bean, "intProperty", new Integer(newValue)); assertEquals("Matched new value", newValue, ((Integer) bean.get("intProperty")).intValue()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a long property. */ public void testSetSimpleLong() { try { long oldValue = ((Long) bean.get("longProperty")).longValue(); long newValue = oldValue + 1; PropertyUtils.setSimpleProperty(bean, "longProperty", new Long(newValue)); assertEquals("Matched new value", newValue, ((Long) bean.get("longProperty")).longValue()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test setSimpleProperty on a nested property. */ public void testSetSimpleNested() { try { PropertyUtils.setSimpleProperty(bean, "nested.stringProperty", "New String Value"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { // Correct result for this test } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a short property. */ public void testSetSimpleShort() { try { short oldValue = ((Short) bean.get("shortProperty")).shortValue(); short newValue = oldValue; newValue++; PropertyUtils.setSimpleProperty(bean, "shortProperty", new Short(newValue)); assertEquals("Matched new value", newValue, ((Short) bean.get("shortProperty")).shortValue()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a String property. */ public void testSetSimpleString() { try { String oldValue = (String) bean.get("stringProperty"); String newValue = oldValue + " Extra Value"; PropertyUtils.setSimpleProperty(bean, "stringProperty", newValue); assertEquals("Matched new value", newValue, (String) bean.get("stringProperty")); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on an unknown property name. */ public void testSetSimpleUnknown() { try { String newValue = "New String Value"; PropertyUtils.setSimpleProperty(bean, "unknown", newValue); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test assertEquals("Unknown property 'unknown' on dynaclass '" + bean.getDynaClass() + "'", e.getMessage() ); } } // ------------------------------------------------------ Protected Methods /** * Create and return a DynaClass instance for our test * DynaBean. */ protected DynaClass createDynaClass() { int intArray[] = new int[0]; String stringArray[] = new String[0]; DynaClass dynaClass = new BasicDynaClass ("TestDynaClass", null, new DynaProperty[]{ new DynaProperty("booleanProperty", Boolean.TYPE), new DynaProperty("booleanSecond", Boolean.TYPE), new DynaProperty("doubleProperty", Double.TYPE), new DynaProperty("dupProperty", stringArray.getClass()), new DynaProperty("floatProperty", Float.TYPE), new DynaProperty("intArray", intArray.getClass()), new DynaProperty("intIndexed", intArray.getClass()), new DynaProperty("intProperty", Integer.TYPE), new DynaProperty("listIndexed", List.class), new DynaProperty("longProperty", Long.TYPE), new DynaProperty("mapProperty", Map.class), new DynaProperty("mappedObjects", Map.class), new DynaProperty("mappedProperty", Map.class), new DynaProperty("mappedIntProperty", Map.class), new DynaProperty("nested", TestBean.class), new DynaProperty("nullProperty", String.class), new DynaProperty("shortProperty", Short.TYPE), new DynaProperty("stringArray", stringArray.getClass()), new DynaProperty("stringIndexed", stringArray.getClass()), new DynaProperty("stringProperty", String.class), }); return (dynaClass); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/DynaResultSetTestCase.java100644 0 0 21631 12262570607 30334 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.math.BigDecimal; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test accessing ResultSets via DynaBeans. * * @version $Id: DynaResultSetTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class DynaResultSetTestCase extends TestCase { // ----------------------------------------------------- Instance Variables /** * The mock result set DynaClass to be tested. */ protected ResultSetDynaClass dynaClass = null; /** * Names of the columns for this test. Must match the order they are * defined in {@link TestResultSetMetaData}, and must be all lower case. */ protected String columns[] = { "bigdecimalproperty", "booleanproperty", "byteproperty", "dateproperty", "doubleproperty", "floatproperty", "intproperty", "longproperty", "nullproperty", "shortproperty", "stringproperty", "timeproperty", "timestampproperty" }; // ----------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public DynaResultSetTestCase(String name) { super(name); } // --------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { dynaClass = new ResultSetDynaClass(TestResultSet.createProxy()); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(DynaResultSetTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { dynaClass = null; } // ------------------------------------------------ Individual Test Methods public void testGetName() { assertEquals("DynaClass name", "org.apache.commons.beanutils.ResultSetDynaClass", dynaClass.getName()); } public void testGetDynaProperty() { // Invalid argument test try { dynaClass.getDynaProperty(null); fail("Did not throw IllegaArgumentException"); } catch (IllegalArgumentException e) { // Expected result } // Negative test DynaProperty dynaProp = dynaClass.getDynaProperty("unknownProperty"); assertTrue("unknown property returns null", (dynaProp == null)); // Positive test dynaProp = dynaClass.getDynaProperty("stringproperty"); assertNotNull("string property exists", dynaProp); assertEquals("string property name", "stringproperty", dynaProp.getName()); assertEquals("string property class", String.class, dynaProp.getType()); } public void testGetDynaProperties() { DynaProperty dynaProps[] = dynaClass.getDynaProperties(); assertNotNull("dynaProps exists", dynaProps); assertEquals("dynaProps length", columns.length, dynaProps.length); for (int i = 0; i < columns.length; i++) { assertEquals("Property " + columns[i], columns[i], dynaProps[i].getName()); } } public void testNewInstance() { try { dynaClass.newInstance(); fail("Did not throw UnsupportedOperationException()"); } catch (UnsupportedOperationException e) { // Expected result } catch (Exception e) { fail("Threw exception " + e); } } public void testIteratorCount() { Iterator rows = dynaClass.iterator(); assertNotNull("iterator exists", rows); int n = 0; while (rows.hasNext()) { rows.next(); n++; if (n > 10) { fail("Returned too many rows"); } } assertEquals("iterator rows", 5, n); } public void testIteratorResults() { // Grab the third row Iterator rows = dynaClass.iterator(); rows.next(); rows.next(); DynaBean row = (DynaBean) rows.next(); // Invalid argument test try { row.get("unknownProperty"); fail("Did not throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected result } // Verify property values Object bigDecimalProperty = row.get("bigdecimalproperty"); assertNotNull("bigDecimalProperty exists", bigDecimalProperty); assertTrue("bigDecimalProperty type", bigDecimalProperty instanceof BigDecimal); assertEquals("bigDecimalProperty value", 123.45, ((BigDecimal) bigDecimalProperty).doubleValue(), 0.005); Object intProperty = row.get("intproperty"); assertNotNull("intProperty exists", intProperty); assertTrue("intProperty type", intProperty instanceof Integer); assertEquals("intProperty value", 103, ((Integer) intProperty).intValue()); Object nullProperty = row.get("nullproperty"); assertNull("nullProperty null", nullProperty); Object stringProperty = row.get("stringproperty"); assertNotNull("stringProperty exists", stringProperty); assertTrue("stringProperty type", stringProperty instanceof String); assertEquals("stringProperty value", "This is a string", (String) stringProperty); } /** * Test normal case column names (i.e. not converted to lower case) */ public void testIteratorResultsNormalCase() { ResultSetDynaClass dynaClass = null; try { dynaClass = new ResultSetDynaClass(TestResultSet.createProxy(), false); } catch (Exception e) { fail("Error creating ResultSetDynaClass: " + e); } // Grab the third row Iterator rows = dynaClass.iterator(); rows.next(); rows.next(); DynaBean row = (DynaBean) rows.next(); // Invalid argument test try { row.get("unknownProperty"); fail("Did not throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected result } // Verify property values Object bigDecimalProperty = row.get("bigDecimalProperty"); assertNotNull("bigDecimalProperty exists", bigDecimalProperty); assertTrue("bigDecimalProperty type", bigDecimalProperty instanceof BigDecimal); assertEquals("bigDecimalProperty value", 123.45, ((BigDecimal) bigDecimalProperty).doubleValue(), 0.005); Object intProperty = row.get("intProperty"); assertNotNull("intProperty exists", intProperty); assertTrue("intProperty type", intProperty instanceof Integer); assertEquals("intProperty value", 103, ((Integer) intProperty).intValue()); Object nullProperty = row.get("nullProperty"); assertNull("nullProperty null", nullProperty); Object stringProperty = row.get("stringProperty"); assertNotNull("stringProperty exists", stringProperty); assertTrue("stringProperty type", stringProperty instanceof String); assertEquals("stringProperty value", "This is a string", (String) stringProperty); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/DynaRowSetTestCase.java100644 0 0 33564 12262570610 27627 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test accessing RowSets via DynaBeans. * * @version $Id: DynaRowSetTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class DynaRowSetTestCase extends TestCase { // ----------------------------------------------------- Instance Variables /** * The mock result set DynaClass to be tested. */ protected RowSetDynaClass dynaClass = null; /** * Names of the columns for this test. Must match the order they are * defined in {@link TestResultSetMetaData}, and must be all lower case. */ protected String columns[] = { "bigdecimalproperty", "booleanproperty", "byteproperty", "dateproperty", "doubleproperty", "floatproperty", "intproperty", "longproperty", "nullproperty", "shortproperty", "stringproperty", "timeproperty", "timestampproperty" }; // ----------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public DynaRowSetTestCase(String name) { super(name); } // --------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { dynaClass = new RowSetDynaClass(TestResultSet.createProxy()); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(DynaRowSetTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { dynaClass = null; } // ------------------------------------------------ Individual Test Methods public void testGetName() { assertEquals("DynaClass name", "org.apache.commons.beanutils.RowSetDynaClass", dynaClass.getName()); } public void testGetDynaProperty() { // Invalid argument test try { dynaClass.getDynaProperty(null); fail("Did not throw IllegaArgumentException"); } catch (IllegalArgumentException e) { // Expected result } // Negative test DynaProperty dynaProp = dynaClass.getDynaProperty("unknownProperty"); assertTrue("unknown property returns null", (dynaProp == null)); // Positive test dynaProp = dynaClass.getDynaProperty("stringproperty"); assertNotNull("string property exists", dynaProp); assertEquals("string property name", "stringproperty", dynaProp.getName()); assertEquals("string property class", String.class, dynaProp.getType()); } public void testGetDynaProperties() { DynaProperty dynaProps[] = dynaClass.getDynaProperties(); assertNotNull("dynaProps exists", dynaProps); assertEquals("dynaProps length", columns.length, dynaProps.length); for (int i = 0; i < columns.length; i++) { assertEquals("Property " + columns[i], columns[i], dynaProps[i].getName()); } } public void testNewInstance() { try { dynaClass.newInstance(); fail("Did not throw UnsupportedOperationException()"); } catch (UnsupportedOperationException e) { // Expected result } catch (Exception e) { fail("Threw exception " + e); } } public void testListCount() { List rows = dynaClass.getRows(); assertNotNull("list exists", rows); assertEquals("list row count", 5, rows.size()); } public void testListResults() { // Grab the third row List rows = dynaClass.getRows(); DynaBean row = rows.get(2); // Invalid argument test try { row.get("unknownProperty"); fail("Did not throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected result } // Verify property values Object bigDecimalProperty = row.get("bigdecimalproperty"); assertNotNull("bigDecimalProperty exists", bigDecimalProperty); assertTrue("bigDecimalProperty type", bigDecimalProperty instanceof BigDecimal); assertEquals("bigDecimalProperty value", 123.45, ((BigDecimal) bigDecimalProperty).doubleValue(), 0.005); Object intProperty = row.get("intproperty"); assertNotNull("intProperty exists", intProperty); assertTrue("intProperty type", intProperty instanceof Integer); assertEquals("intProperty value", 103, ((Integer) intProperty).intValue()); Object nullProperty = row.get("nullproperty"); assertNull("nullProperty null", nullProperty); Object stringProperty = row.get("stringproperty"); assertNotNull("stringProperty exists", stringProperty); assertTrue("stringProperty type", stringProperty instanceof String); assertEquals("stringProperty value", "This is a string", (String) stringProperty); } /** * Test normal case column names (i.e. not converted to lower case) */ public void testListResultsNormalCase() { RowSetDynaClass dynaClass = null; try { dynaClass = new RowSetDynaClass(TestResultSet.createProxy(), false); } catch (Exception e) { fail("Error creating RowSetDynaClass: " + e); } // Grab the third row List rows = dynaClass.getRows(); DynaBean row = rows.get(2); // Invalid argument test try { row.get("unknownProperty"); fail("Did not throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected result } // Verify property values Object bigDecimalProperty = row.get("bigDecimalProperty"); assertNotNull("bigDecimalProperty exists", bigDecimalProperty); assertTrue("bigDecimalProperty type", bigDecimalProperty instanceof BigDecimal); assertEquals("bigDecimalProperty value", 123.45, ((BigDecimal) bigDecimalProperty).doubleValue(), 0.005); Object intProperty = row.get("intProperty"); assertNotNull("intProperty exists", intProperty); assertTrue("intProperty type", intProperty instanceof Integer); assertEquals("intProperty value", 103, ((Integer) intProperty).intValue()); Object nullProperty = row.get("nullProperty"); assertNull("nullProperty null", nullProperty); Object stringProperty = row.get("stringProperty"); assertNotNull("stringProperty exists", stringProperty); assertTrue("stringProperty type", stringProperty instanceof String); assertEquals("stringProperty value", "This is a string", (String) stringProperty); } public void testLimitedRows() throws Exception { // created one with low limit RowSetDynaClass limitedDynaClass = new RowSetDynaClass(TestResultSet.createProxy(), 3); List rows = limitedDynaClass.getRows(); assertNotNull("list exists", rows); assertEquals("limited row count", 3, rows.size()); } /** * Test issues associated with Oracle JDBC driver. * * See issue# https://issues.apache.org/jira/browse/BEANUTILS-142 * * @throws Exception if an error occurs */ public void testInconsistentOracleDriver() throws Exception { ResultSetMetaData metaData = TestResultSetMetaData.createProxy(new TestResultSetMetaDataInconsistent()); ResultSet resultSet = TestResultSet.createProxy(new TestResultSetInconsistent(metaData)); // Date Column returns "java.sql.Timestamp" for the column class name but ResultSet getObject // returns a java.sql.Date value int dateColIdx = 4; assertEquals("Date Meta Name", "dateProperty", metaData.getColumnName(dateColIdx)); assertEquals("Date Meta Class", "java.sql.Timestamp", metaData.getColumnClassName(dateColIdx)); assertEquals("Date Meta Type", java.sql.Types.DATE, metaData.getColumnType(dateColIdx)); assertEquals("Date ResultSet Value", java.sql.Date.class, resultSet.getObject("dateProperty").getClass()); // Timestamp column class returns a custom Timestamp impl for the column class name and ResultSet getObject int timestampColIdx = 13; assertEquals("Timestamp Meta Name", "timestampProperty", metaData.getColumnName(timestampColIdx)); assertEquals("Timestamp Meta Class", CustomTimestamp.class.getName(), metaData.getColumnClassName(timestampColIdx)); assertEquals("Timestamp Meta Type", java.sql.Types.TIMESTAMP, metaData.getColumnType(timestampColIdx)); assertEquals("Timestamp ResultSet Value", CustomTimestamp.class, resultSet.getObject("timestampProperty").getClass()); RowSetDynaClass inconsistentDynaClass = new RowSetDynaClass(resultSet); DynaBean firstRow = inconsistentDynaClass.getRows().get(0); Class expectedType = null; DynaProperty property = null; // Test Date property = firstRow.getDynaClass().getDynaProperty("dateproperty"); expectedType = java.sql.Date.class; assertEquals("Date Class", expectedType, property.getType()); assertEquals("Date Value", expectedType, firstRow.get(property.getName()).getClass()); // Test Timestamp property = firstRow.getDynaClass().getDynaProperty("timestampproperty"); expectedType = java.sql.Timestamp.class; assertEquals("Timestamp Class", expectedType, property.getType()); assertEquals("Timestamp Value", expectedType, firstRow.get(property.getName()).getClass()); } /** * A proxy ResultSet implementation that returns Timstamp for a date column. * * See issue# https://issues.apache.org/jira/browse/BEANUTILS-142 */ private static class TestResultSetInconsistent extends TestResultSet { public TestResultSetInconsistent(ResultSetMetaData metaData) { super(metaData); } /** * Get an columns's value * @param columnName Name of the column * @return the column value * @throws SQLException if an error occurs */ @Override public Object getObject(String columnName) throws SQLException { if ("timestampProperty".equals(columnName)) { return new CustomTimestamp(); } else { return super.getObject(columnName); } } } /** * A proxy ResultSetMetaData implementation that returns a class name that * is inconsistent with the type returned by the ResultSet.getObject() method. * * See issue# https://issues.apache.org/jira/browse/BEANUTILS-142 */ private static class TestResultSetMetaDataInconsistent extends TestResultSetMetaData { /** * This method substitues class names of "java.sql.Timestamp" with * "java.sql.Date" to test inconsistent JDBC drivers. * * @param columnIndex The column index * @return The column class name * @throws SQLException if an error occurs */ @Override public String getColumnClassName(int columnIndex) throws SQLException { String columnName = getColumnName(columnIndex); if (columnName.equals("dateProperty")) { return java.sql.Timestamp.class.getName(); } else if (columnName.equals("timestampProperty")) { return CustomTimestamp.class.getName(); } else { return super.getColumnClassName(columnIndex); } } } private static class CustomTimestamp { private final long timestamp = new java.util.Date().getTime(); @Override public String toString() { return "CustomTimestamp[" + timestamp + "]"; } } } ././@LongLink100644 0 0 157 12262571655 10271 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/expression/DefaultResolverTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/expression/DefaultResolverTes100644 0 0 31070 12262570607 31171 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.expression; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Junit Test for BasicResolver. * * @version $Id: DefaultResolverTestCase.java 1454606 2013-03-08 22:30:51Z britter $ */ public class DefaultResolverTestCase extends TestCase { private final DefaultResolver resolver = new DefaultResolver(); // Simple Properties Test Data private final String[] validProperties = new String[] {null, "", "a", "bc", "def", "g.h", "ij.k", "lm.no", "pqr.stu"}; private final String[] validNames = new String[] {null, "", "a", "bc", "def", "g", "ij", "lm", "pqr"}; // Indexed Properties Test Data private final String[] validIndexProperties = new String[] {"a[1]", "b[12]", "cd[3]", "ef[45]", "ghi[6]", "jkl[789]", }; private final String[] validIndexNames = new String[] {"a", "b", "cd", "ef", "ghi", "jkl"}; private final int[] validIndexValues = new int[] {1, 12, 3, 45, 6, 789}; // Mapped Properties Test Data private final String[] validMapProperties = new String[] {"a(b)", "c(de)", "fg(h)", "ij(kl)", "mno(pqr.s)", "tuv(wx).yz[1]"}; private final String[] validMapNames = new String[] {"a", "c", "fg", "ij", "mno", "tuv"}; private final String[] validMapKeys = new String[] {"b", "de", "h", "kl", "pqr.s", "wx"}; private final String[] nextExpressions = new String[] {"a", "bc", "d.e", "fg.h", "ij.kl", "m(12)", "no(3.4)", "pq(r).s", "t[12]", "uv[34].wx"}; private final String[] nextProperties = new String[] {"a", "bc", "d", "fg", "ij", "m(12)", "no(3.4)", "pq(r)", "t[12]", "uv[34]"}; private final String[] removeProperties = new String[] {null, null, "e", "h", "kl", null, null, "s", null, "wx"}; /** * Construct a DefaultResolver Test Case. * @param name The name of the test */ public DefaultResolverTestCase(String name) { super(name); } // ------------------------------------------------------------------------ /** * Create Test Suite * @return test suite */ public static TestSuite suite() { return new TestSuite(DefaultResolverTestCase.class); } /** * Set Up */ @Override protected void setUp() { } /** * Tear Down */ @Override protected void tearDown() { } // ------------------------------------------------------------------------ /** * Test getIndex() method. */ public void testGetIndex() { String label = null; // Simple Properties (expect -1) for (int i = 0; i < validProperties.length; i++) { try { label = "Simple " + label(validProperties[i], i); assertEquals(label, -1, resolver.getIndex(validProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Indexed Properties (expect correct index value) for (int i = 0; i < validIndexProperties.length; i++) { try { label = "Indexed " + label(validIndexProperties[i], i); assertEquals(label, validIndexValues[i], resolver.getIndex(validIndexProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Mapped Properties (expect -1) for (int i = 0; i < validMapProperties.length; i++) { try { label = "Mapped " + label(validMapProperties[i], i); assertEquals(label, -1, resolver.getIndex(validMapProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Missing Index Value label = "Missing Index"; try { int index = resolver.getIndex("foo[]"); fail(label + " expected IllegalArgumentException: " + index); } catch (IllegalArgumentException e) { assertEquals(label + " Error Message", "No Index Value", e.getMessage()); } catch (Throwable t) { fail(label + " expected IllegalArgumentException: " + t); } // Malformed label = "Malformed"; try { int index = resolver.getIndex("foo[12"); fail(label + " expected IllegalArgumentException: " + index); } catch (IllegalArgumentException e) { assertEquals(label + " Error Message", "Missing End Delimiter", e.getMessage()); } catch (Throwable t) { fail(label + " expected IllegalArgumentException: " + t); } // Non-numeric label = "Malformed"; try { int index = resolver.getIndex("foo[BAR]"); fail(label + " expected IllegalArgumentException: " + index); } catch (IllegalArgumentException e) { assertEquals(label + " Error Message", "Invalid index value 'BAR'", e.getMessage()); } catch (Throwable t) { fail(label + " expected IllegalArgumentException: " + t); } } /** * Test getMapKey() method. */ public void testGetMapKey() { String label = null; // Simple Properties (expect null) for (int i = 0; i < validProperties.length; i++) { try { label = "Simple " + label(validProperties[i], i); assertEquals(label, null, resolver.getKey(validProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Indexed Properties (expect null) for (int i = 0; i < validIndexProperties.length; i++) { try { label = "Indexed " + label(validIndexProperties[i], i); assertEquals(label, null, resolver.getKey(validIndexProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Mapped Properties (expect correct map key) for (int i = 0; i < validMapProperties.length; i++) { try { label = "Mapped " + label(validMapProperties[i], i); assertEquals(label, validMapKeys[i], resolver.getKey(validMapProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Malformed label = "Malformed"; try { String key = resolver.getKey("foo(bar"); fail(label + " expected IllegalArgumentException: " + key); } catch (IllegalArgumentException e) { assertEquals(label + " Error Message", "Missing End Delimiter", e.getMessage()); } catch (Throwable t) { fail(label + " expected IllegalArgumentException: " + t); } } /** * Test isIndexed() method. */ public void testIsIndexed() { String label = null; // Simple Properties (expect -1) for (int i = 0; i < validProperties.length; i++) { try { label = "Simple " + label(validProperties[i], i); assertFalse(label, resolver.isIndexed(validProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Indexed Properties (expect correct index value) for (int i = 0; i < validIndexProperties.length; i++) { try { label = "Indexed " + label(validIndexProperties[i], i); assertTrue(label, resolver.isIndexed(validIndexProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Mapped Properties (expect -1) for (int i = 0; i < validMapProperties.length; i++) { try { label = "Mapped " + label(validMapProperties[i], i); assertFalse(label, resolver.isIndexed(validMapProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } } /** * Test isMapped() method. */ public void testIsMapped() { String label = null; // Simple Properties (expect null) for (int i = 0; i < validProperties.length; i++) { try { label = "Simple " + label(validProperties[i], i); assertFalse(label, resolver.isMapped(validProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Indexed Properties (expect null) for (int i = 0; i < validIndexProperties.length; i++) { try { label = "Indexed " + label(validIndexProperties[i], i); assertFalse(label, resolver.isMapped(validIndexProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Mapped Properties (expect correct map key) for (int i = 0; i < validMapProperties.length; i++) { try { label = "Mapped " + label(validMapProperties[i], i); assertTrue(label, resolver.isMapped(validMapProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } } /** * Test getName() method. */ public void testGetName() { String label = null; // Simple Properties for (int i = 0; i < validProperties.length; i++) { try { label = "Simple " + label(validProperties[i], i); assertEquals(label, validNames[i], resolver.getProperty(validProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Indexed Properties for (int i = 0; i < validIndexProperties.length; i++) { try { label = "Indexed " + label(validIndexProperties[i], i); assertEquals(label, validIndexNames[i], resolver.getProperty(validIndexProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } // Mapped Properties for (int i = 0; i < validMapProperties.length; i++) { try { label = "Mapped " + label(validMapProperties[i], i); assertEquals(label, validMapNames[i], resolver.getProperty(validMapProperties[i])); } catch (Throwable t) { fail(label + " threw " + t); } } } /** * Test next() method. */ public void testNext() { String label = null; for (int i = 0; i < nextExpressions.length; i++) { try { label = label(nextExpressions[i], i); assertEquals(label, nextProperties[i], resolver.next(nextExpressions[i])); } catch (Throwable t) { fail(label + " threw " + t); } } } /** * Test remove() method. */ public void testRemove() { String label = null; for (int i = 0; i < nextExpressions.length; i++) { try { label = label(nextExpressions[i], i); assertEquals(label, removeProperties[i], resolver.remove(nextExpressions[i])); } catch (Throwable t) { fail(label + " threw " + t); } } } private String label(String expression, int i) { return "Expression[" + i + "]=\"" + expression + "\""; } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/ExtendMapBean.java100644 0 0 2473 12262570606 26567 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.Hashtable; /** * Used to test * * @version $Id: ExtendMapBean.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ExtendMapBean extends Hashtable { private String dbName = "[UNSET]"; public ExtendMapBean() {} public String getUnusuallyNamedProperty() { return dbName; } public void setUnusuallyNamedProperty(String dbName) { this.dbName = dbName; } } ././@LongLink100644 0 0 150 12262571655 10262 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/FluentIntrospectionTestBean.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/FluentIntrospectionTestBean.j100644 0 0 3350 12262570610 31056 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * A bean class used for tests of introspection. * * @version $Id: FluentIntrospectionTestBean.java 1540359 2013-11-09 18:10:52Z oheger $ */ public class FluentIntrospectionTestBean extends AlphaBean { private String stringProperty; private String fluentGetProperty; public String getStringProperty() { return stringProperty; } public void setStringProperty(String stringProperty) { this.stringProperty = stringProperty; } public FluentIntrospectionTestBean setFluentProperty(String value) { setStringProperty(value); return this; } public String getFluentGetProperty() { return fluentGetProperty; } public FluentIntrospectionTestBean setFluentGetProperty( String fluentGetProperty) { this.fluentGetProperty = fluentGetProperty; return this; } } ././@LongLink100644 0 0 163 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/FluentPropertyBeanIntrospectorTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/FluentPropertyBeanIntrospecto100644 0 0 7605 12262570610 31213 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * Test class for {@code FluentPropertyBeanIntrospector}. * * @version $Id: FluentPropertyBeanIntrospectorTestCase.java 1540359 2013-11-09 18:10:52Z oheger $ */ public class FluentPropertyBeanIntrospectorTestCase extends TestCase { /** * Puts all property descriptors into a map so that they can be accessed by * property name. * * @param descs the array with descriptors * @return a map with property names as keys */ private static Map createDescriptorMap( PropertyDescriptor[] descs) { Map map = new HashMap(); for (PropertyDescriptor pd : descs) { map.put(pd.getName(), pd); } return map; } /** * Convenience method for obtaining a specific property descriptor and * checking whether it exists. * * @param props the map with property descriptors * @param name the name of the desired descriptor * @return the descriptor from the map */ private static PropertyDescriptor fetchDescriptor( Map props, String name) { assertTrue("Property not found: " + name, props.containsKey(name)); return props.get(name); } /** * Tries to create an instance without a prefix for write methods. */ public void testInitNoPrefix() { try { new FluentPropertyBeanIntrospector(null); fail("Missing prefix for write methods not detected!"); } catch (IllegalArgumentException iex) { // ok } } /** * Tests whether correct property descriptors are detected. */ public void testIntrospection() throws IntrospectionException { PropertyUtilsBean pu = new PropertyUtilsBean(); FluentPropertyBeanIntrospector introspector = new FluentPropertyBeanIntrospector(); pu.addBeanIntrospector(introspector); Map props = createDescriptorMap(pu .getPropertyDescriptors(FluentIntrospectionTestBean.class)); PropertyDescriptor pd = fetchDescriptor(props, "name"); assertNotNull("No read method for name", pd.getReadMethod()); assertNotNull("No write method for name", pd.getWriteMethod()); fetchDescriptor(props, "stringProperty"); pd = fetchDescriptor(props, "fluentProperty"); assertNull("Read method for fluentProperty", pd.getReadMethod()); assertNotNull("No write method for fluentProperty", pd.getWriteMethod()); pd = fetchDescriptor(props, "fluentGetProperty"); assertNotNull("No read method for fluentGetProperty", pd.getReadMethod()); assertNotNull("No write method for fluentGetProperty", pd.getWriteMethod()); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/IndexedPropertyTestCase.java100644 0 0 45721 12262570607 30721 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IndexedPropertyDescriptor; import java.beans.PropertyDescriptor; import java.util.ArrayList; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

          Test Case for the Indexed Properties.

          * * @version $Id: IndexedPropertyTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class IndexedPropertyTestCase extends TestCase { private static final Log log = LogFactory.getLog(IndexedPropertyTestCase.class); // ---------------------------------------------------- Instance Variables /** * The test bean for each test. */ private IndexedTestBean bean = null; private BeanUtilsBean beanUtilsBean; private PropertyUtilsBean propertyUtilsBean; private String[] testArray; private String[] newArray; private List testList; private List newList; private ArrayList arrayList; // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public IndexedPropertyTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { // BeanUtils beanUtilsBean = new BeanUtilsBean(); propertyUtilsBean = beanUtilsBean.getPropertyUtils(); // initialize Arrays and Lists testArray= new String[] {"array-0", "array-1", "array-2"}; newArray = new String[] {"newArray-0", "newArray-1", "newArray-2"}; testList = new ArrayList(); testList.add("list-0"); testList.add("list-1"); testList.add("list-2"); newList = new ArrayList(); newList.add("newList-0"); newList.add("newList-1"); newList.add("newList-2"); arrayList = new ArrayList(); arrayList.add("arrayList-0"); arrayList.add("arrayList-1"); arrayList.add("arrayList-2"); // initialize Test Bean properties bean = new IndexedTestBean(); bean.setStringArray(testArray); bean.setStringList(testList); bean.setArrayList(arrayList); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(IndexedPropertyTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { bean = null; } // ------------------------------------------------ Individual Test Methods /** * Test IndexedPropertyDescriptor for an Array */ public void testArrayIndexedPropertyDescriptor() { try { PropertyDescriptor descriptor = propertyUtilsBean.getPropertyDescriptor(bean, "stringArray"); assertNotNull("No Array Descriptor", descriptor); assertEquals("Not IndexedPropertyDescriptor", IndexedPropertyDescriptor.class, descriptor.getClass()); assertEquals("PropertDescriptor Type invalid", testArray.getClass(), descriptor.getPropertyType()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test IndexedPropertyDescriptor for a List */ public void testListIndexedPropertyDescriptor() { try { PropertyDescriptor descriptor = propertyUtilsBean.getPropertyDescriptor(bean, "stringList"); assertNotNull("No List Descriptor", descriptor); assertEquals("Not IndexedPropertyDescriptor", IndexedPropertyDescriptor.class, descriptor.getClass()); assertEquals("PropertDescriptor Type invalid", List.class, descriptor.getPropertyType()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test IndexedPropertyDescriptor for an ArrayList */ public void testArrayListIndexedPropertyDescriptor() { try { PropertyDescriptor descriptor = propertyUtilsBean.getPropertyDescriptor(bean, "arrayList"); assertNotNull("No ArrayList Descriptor", descriptor); assertEquals("Not IndexedPropertyDescriptor", IndexedPropertyDescriptor.class, descriptor.getClass()); assertEquals("PropertDescriptor Type invalid", ArrayList.class, descriptor.getPropertyType()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test Read Method for an Array */ public void testArrayReadMethod() { try { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)propertyUtilsBean.getPropertyDescriptor(bean, "stringArray"); assertNotNull("No Array Read Method", descriptor.getReadMethod()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test Write Method for an Array */ public void testArrayWriteMethod() { try { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)propertyUtilsBean.getPropertyDescriptor(bean, "stringArray"); assertNotNull("No Array Write Method", descriptor.getWriteMethod()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test Indexed Read Method for an Array */ public void testArrayIndexedReadMethod() { try { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)propertyUtilsBean.getPropertyDescriptor(bean, "stringArray"); assertNotNull("No Array Indexed Read Method", descriptor.getIndexedReadMethod()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test Indexed Write Method for an Array */ public void testArrayIndexedWriteMethod() { try { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)propertyUtilsBean.getPropertyDescriptor(bean, "stringArray"); assertNotNull("No Array Indexed Write Method", descriptor.getIndexedWriteMethod()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test Read Method for a List * * JDK 1.3.1_04: Test Passes * JDK 1.4.2_05: Test Fails - getter which returns java.util.List not returned * by IndexedPropertyDescriptor.getReadMethod(); */ public void testListReadMethod() { try { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)propertyUtilsBean.getPropertyDescriptor(bean, "stringList"); assertNotNull("No List Read Method", descriptor.getReadMethod()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test Write Method for a List * * JDK 1.3.1_04: Test Passes * JDK 1.4.2_05: Test Fails - setter whith java.util.List argument not returned * by IndexedPropertyDescriptor.getWriteMethod(); */ public void testListWriteMethod() { try { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)propertyUtilsBean.getPropertyDescriptor(bean, "stringList"); assertNotNull("No List Write Method", descriptor.getWriteMethod()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test Indexed Read Method for a List */ public void testListIndexedReadMethod() { try { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)propertyUtilsBean.getPropertyDescriptor(bean, "stringList"); assertNotNull("No List Indexed Read Method", descriptor.getIndexedReadMethod()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test Indexed Write Method for a List */ public void testListIndexedWriteMethod() { try { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)propertyUtilsBean.getPropertyDescriptor(bean, "stringList"); assertNotNull("No List Indexed Write Method", descriptor.getIndexedWriteMethod()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test Read Method for an ArrayList */ public void testArrayListReadMethod() { try { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)propertyUtilsBean.getPropertyDescriptor(bean, "arrayList"); assertNotNull("No ArrayList Read Method", descriptor.getReadMethod()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test Write Method for an ArrayList */ public void testArrayListWriteMethod() { try { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)propertyUtilsBean.getPropertyDescriptor(bean, "arrayList"); assertNotNull("No ArrayList Write Method", descriptor.getWriteMethod()); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test getting an array property */ public void testGetArray() { try { assertEquals(testArray, propertyUtilsBean.getProperty(bean, "stringArray")); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test getting an array property as a String * * NOTE: Why does retrieving array just return the first element in the array, whereas * retrieveing a List returns a comma separated list of all the elements? */ public void testGetArrayAsString() { try { assertEquals("array-0", beanUtilsBean.getProperty(bean, "stringArray")); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test getting an indexed item of an Array using getProperty("name[x]") */ public void testGetArrayItemA() { try { assertEquals("array-1", beanUtilsBean.getProperty(bean, "stringArray[1]")); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test getting an indexed item of an Array using getIndexedProperty("name") */ public void testGetArrayItemB() { try { assertEquals("array-1", beanUtilsBean.getIndexedProperty(bean, "stringArray", 1)); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test getting a List * * JDK 1.3.1_04: Test Passes * JDK 1.4.2_05: Test Fails - fails NoSuchMethodException, i.e. reason as testListReadMethod() * failed. */ public void testGetList() { try { assertEquals(testList, propertyUtilsBean.getProperty(bean, "stringList")); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test getting a List property as a String * * JDK 1.3.1_04: Test Passes * JDK 1.4.2_05: Test Fails - fails NoSuchMethodException, i.e. reason as testListReadMethod() * failed. */ public void testGetListAsString() { try { assertEquals("list-0", beanUtilsBean.getProperty(bean, "stringList")); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test getting an indexed item of a List using getProperty("name[x]") */ public void testGetListItemA() { try { assertEquals("list-1", beanUtilsBean.getProperty(bean, "stringList[1]")); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test getting an indexed item of a List using getIndexedProperty("name") */ public void testGetListItemB() { try { assertEquals("list-1", beanUtilsBean.getIndexedProperty(bean, "stringList", 1)); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test setting an Array property * * JDK 1.3.1_04 and 1.4.2_05: Test Fails - IllegalArgumentException can't invoke setter, argument type mismatch * * Fails because of a bug in BeanUtilsBean.setProperty() method. Value is always converted to the array's component * type which in this case is a String. Then it calls the setStringArray(String[]) passing a String rather than * String[] causing this exception. If there isn't an "index" value then the PropertyType (rather than * IndexedPropertyType) should be used. * */ public void testSetArray() { try { beanUtilsBean.setProperty(bean, "stringArray", newArray); Object value = bean.getStringArray(); assertEquals("Type is different", newArray.getClass(), value.getClass()); String[] array = (String[])value; assertEquals("Array Length is different", newArray.length, array.length); for (int i = 0; i < array.length; i++) { assertEquals("Element " + i + " is different", newArray[i], array[i]); } } catch(Exception e) { log.error("testSetArray()", e); fail("Threw exception " + e); } } /** * Test setting an indexed item of an Array using setProperty("name[x]", value) */ public void testSetArrayItemA() { try { beanUtilsBean.setProperty(bean, "stringArray[1]", "modified-1"); assertEquals("modified-1", bean.getStringArray(1)); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test setting an indexed item of an Array using setIndexedProperty("name", value) */ public void testSetArrayItemB() { try { propertyUtilsBean.setIndexedProperty(bean, "stringArray", 1, "modified-1"); assertEquals("modified-1", bean.getStringArray(1)); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test setting a List property * * JDK 1.3.1_04: Test Passes * JDK 1.4.2_05: Test Fails - setter which returns java.util.List not returned * by IndexedPropertyDescriptor.getWriteMethod() - therefore * setProperty does nothing and values remain unchanged. */ public void testSetList() { try { beanUtilsBean.setProperty(bean, "stringList", newList); Object value = bean.getStringList(); assertEquals("Type is different", newList.getClass(), value.getClass()); List list = (List)value; assertEquals("List size is different", newList.size(), list.size()); for (int i = 0; i < list.size(); i++) { assertEquals("Element " + i + " is different", newList.get(i), list.get(i)); } } catch(Exception e) { log.error("testSetList()", e); fail("Threw exception " + e); } } /** * Test setting an indexed item of a List using setProperty("name[x]", value) */ public void testSetListItemA() { try { beanUtilsBean.setProperty(bean, "stringList[1]", "modified-1"); assertEquals("modified-1", bean.getStringList(1)); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test setting an indexed item of a List using setIndexedProperty("name", value) */ public void testSetListItemB() { try { propertyUtilsBean.setIndexedProperty(bean, "stringList", 1, "modified-1"); assertEquals("modified-1", bean.getStringList(1)); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test getting an ArrayList */ public void testGetArrayList() { try { assertEquals(arrayList, propertyUtilsBean.getProperty(bean, "arrayList")); } catch(Exception e) { fail("Threw exception " + e); } } /** * Test setting an ArrayList property */ public void testSetArrayList() { try { beanUtilsBean.setProperty(bean, "arrayList", newList); Object value = bean.getArrayList(); assertEquals("Type is different", newList.getClass(), value.getClass()); List list = (List)value; assertEquals("List size is different", newList.size(), list.size()); for (int i = 0; i < list.size(); i++) { assertEquals("Element " + i + " is different", newList.get(i), list.get(i)); } } catch(Exception e) { log.error("testSetList()", e); fail("Threw exception " + e); } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/IndexedTestBean.java100644 0 0 6514 12262570610 27115 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.ArrayList; import java.util.List; /** * Indexed Properties Test bean for JUnit tests for the "beanutils" component. * * @version $Id: IndexedTestBean.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class IndexedTestBean { private String[] stringArray; private List stringList; private ArrayList arrayList; // ----------------------------------------------------------- Constructors /** * Default Constructor. */ public IndexedTestBean() { } /** * Getter for the String[] property. */ public String[] getStringArray() { return stringArray; } /** * Setter for the String[] property. */ public void setStringArray(String[] stringArray) { this.stringArray = stringArray; } /** * Indexed Getter for the String[] property. */ public String getStringArray(int index) { return stringArray[index]; } /** * Indexed Setter for the String[] property. */ public void setStringArray(int index, String value) { stringArray[index] = value; } /** * Getter for the java.util.List property. */ public List getStringList() { return stringList; } /** * Setter for the java.util.List property. */ public void setStringList(List stringList) { this.stringList = stringList; } /** * Indexed Getter for the java.util.List property. */ public String getStringList(int index) { return stringList.get(index); } /** * Indexed Setter for the java.util.List property. */ public void setStringList(int index, String value) { stringList.add(index, value); } /** * Getter for the java.util.ArrayList property. */ public ArrayList getArrayList() { return arrayList; } /** * Setter for the java.util.ArrayList property. */ public void setArrayList(ArrayList arrayList) { this.arrayList = arrayList; } /** * Indexed Getter for the java.util.ArrayList property. */ public Object getArrayList(int index) { return arrayList.get(index); } /** * Indexed Setter for the java.util.ArrayList property. */ public void setArrayList(int index, Object value) { arrayList.add(index, value); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/LazyDynaBeanTestCase.java100644 0 0 55412 12262570607 30113 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.TreeMap; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** *

          Test Case for the LazyDynaBean implementation class.

          * * @version $Id: LazyDynaBeanTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class LazyDynaBeanTestCase extends TestCase { protected LazyDynaBean bean = null; protected LazyDynaClass dynaClass = null; protected String testProperty = "myProperty"; protected String testPropertyA = "myProperty-A"; protected String testPropertyB = "myProperty-B"; protected String testString1 = "myStringValue-1"; protected String testString2 = "myStringValue-2"; protected Integer testInteger1 = new Integer(30); protected Integer testInteger2 = new Integer(40); protected String testKey = "myKey"; // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public LazyDynaBeanTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Run thus Test */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(LazyDynaBeanTestCase.class)); } /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { bean = new LazyDynaBean(); dynaClass = (LazyDynaClass)bean.getDynaClass(); dynaClass.setReturnNull(true); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { bean = null; } // ------------------------------------------------ Individual Test Methods /** * Test Getting/Setting a Simple Property */ public void testSimpleProperty() { // Check the property & value doesn't exist assertNull("Check Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Value is null", bean.get(testProperty)); // Set a new property - should add new property and set value bean.set(testProperty, testInteger1); assertEquals("Check First Value is correct", testInteger1, bean.get(testProperty)); assertEquals("Check Property type is correct", Integer.class, dynaClass.getDynaProperty(testProperty).getType()); // Set the property again - should set the new value bean.set(testProperty, testInteger2); assertEquals("Check Second Value is correct", testInteger2, bean.get(testProperty)); // Set the property again - with a different type, should fail try { bean.set(testProperty, testString1); fail("expected ConversionException trying to set an Integer property to a String"); } catch (ConversionException expected) { // expected result } } /** * Test Getting/Setting a 'null' Property */ public void testNullProperty() { // Check the property & value doesn't exist assertNull("Check Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Value is null", bean.get(testProperty)); // Set a new property to null bean.set(testProperty, null); assertNull("Check Value is still null", bean.get(testProperty)); } /** * Test Setting a Simple Property when MutableDynaClass is set to restricted */ public void testSimplePropertyRestricted() { // Set the MutableDyanClass to 'restricted' (i.e. no new properties cab be added dynaClass.setRestricted(true); assertTrue("Check MutableDynaClass is restricted", dynaClass.isRestricted()); // Check the property & value doesn't exist assertNull("Check Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Value is null", bean.get(testProperty)); // Set the property - should fail because property doesn't exist and MutableDynaClass is restricted try { bean.set(testProperty, testString1); fail("expected IllegalArgumentException trying to add new property to restricted DynaClass"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test Getting/Setting a 'Mapped' Property - default HashMap property */ public void testMappedPropertyDefault() { // Check the property & value doesn't exist assertNull("Check Mapped Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Map is null", bean.get(testProperty)); assertNull("Check Mapped Value is null", bean.get(testProperty, testKey)); // Set a new mapped property - should add new HashMap property and set the mapped value bean.set(testProperty, testKey, testInteger1); assertEquals("Check Mapped Property exists", HashMap.class, bean.get(testProperty).getClass()); assertEquals("Check First Mapped Value is correct(a)", testInteger1, bean.get(testProperty, testKey)); assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((HashMap)bean.get(testProperty)).get(testKey)); // Set the property again - should set the new value bean.set(testProperty, testKey, testInteger2); assertEquals("Check Second Mapped Value is correct(a)", testInteger2, bean.get(testProperty, testKey)); assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((HashMap)bean.get(testProperty)).get(testKey)); } /** * Test Getting/Setting a 'Mapped' Property - use TreeMap property */ public void testMappedPropertyTreeMap() { // Check the property & value doesn't exist assertNull("Check Mapped Property doesn't exist", dynaClass.getDynaProperty(testProperty)); // Add a 'TreeMap' property to the DynaClass dynaClass.add(testProperty, TreeMap.class); assertTrue("Check Property is mapped", dynaClass.getDynaProperty(testProperty).isMapped()); assertEquals("Check Property is correct type", TreeMap.class, dynaClass.getDynaProperty(testProperty).getType()); assertEquals("Check Mapped Property exists", TreeMap.class, bean.get(testProperty).getClass()); // assertNull("Check mapped property is null", bean.get(testProperty)); // Set a new mapped property - should instatiate a new TreeMap property and set the mapped value bean.set(testProperty, testKey, testInteger1); assertEquals("Check Mapped Property exists", TreeMap.class, bean.get(testProperty).getClass()); assertEquals("Check First Mapped Value is correct(a)", testInteger1, bean.get(testProperty, testKey)); assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((TreeMap)bean.get(testProperty)).get(testKey)); // Set the property again - should set the new value bean.set(testProperty, testKey, testInteger2); assertEquals("Check Second Mapped Value is correct(a)", testInteger2, bean.get(testProperty, testKey)); assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((TreeMap)bean.get(testProperty)).get(testKey)); } /** * Test Setting a 'Mapped' Property using PropertyUtils */ public void testMappedPropertyUtils() { dynaClass.setReturnNull(false); // Check the property & value doesn't exist assertFalse("Check Mapped Property doesn't exist", dynaClass.isDynaProperty(testProperty)); assertNull("Check Map is null", bean.get(testProperty)); assertNull("Check Mapped Value is null", bean.get(testProperty, testKey)); // Set the mapped property using PropertyUtils try { PropertyUtils.setProperty(bean, testProperty+"("+testKey+")", testString1); } catch (NoSuchMethodException ex) { fail("testIndexedPropertyUtils threw "+ex); } catch (InvocationTargetException ex) { fail("testIndexedPropertyUtils threw "+ex); } catch (IllegalAccessException ex) { fail("testIndexedPropertyUtils threw "+ex); } // Check property value correctly set assertEquals("Check Mapped Bean Value is correct", testString1, bean.get(testProperty, testKey)); } /** * Test Setting a Mapped Property when MutableDynaClass is set to restricted */ public void testMappedPropertyRestricted() { // Set the MutableDyanClass to 'restricted' (i.e. no new properties cab be added dynaClass.setRestricted(true); assertTrue("Check MutableDynaClass is restricted", dynaClass.isRestricted()); // Check the property & value doesn't exist assertNull("Check Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Value is null", bean.get(testProperty)); // Set the property - should fail because property doesn't exist and MutableDynaClass is restricted try { bean.set(testProperty, testKey, testInteger1); fail("expected IllegalArgumentException trying to add new property to restricted MutableDynaClass"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test setting mapped property for type which is not Map */ public void testMappedInvalidType() { dynaClass.add(testProperty, String.class); assertFalse("Check Property is not mapped", dynaClass.getDynaProperty(testProperty).isMapped()); try { bean.set(testProperty, testKey, testInteger1); fail("set(property, key, value) should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test Getting/Setting an 'Indexed' Property - default ArrayList property */ public void testIndexedPropertyDefault() { int index = 3; // Check the property & value doesn't exist assertNull("Check Indexed Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Indexed Property is null", bean.get(testProperty)); assertNull("Check Indexed value is null", bean.get(testProperty, index)); // Set the property, should create new ArrayList and set appropriate indexed value bean.set(testProperty, index, testInteger1); assertNotNull("Check Indexed Property is not null", bean.get(testProperty)); assertEquals("Check Indexed Property is correct type", ArrayList.class, bean.get(testProperty).getClass()); assertEquals("Check First Indexed Value is correct", testInteger1, bean.get(testProperty, index)); assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((ArrayList)bean.get(testProperty)).size())); // Set a second indexed value, should automatically grow the ArrayList and set appropriate indexed value index = index + 2; bean.set(testProperty, index, testString1); assertEquals("Check Second Indexed Value is correct", testString1, bean.get(testProperty, index)); assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((ArrayList)bean.get(testProperty)).size())); } /** * Test Getting/Setting a List 'Indexed' Property - use alternative List (LinkedList) */ public void testIndexedLinkedList() { int index = 3; // Check the property & value doesn't exist assertNull("Check Indexed Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Indexed Property is null", bean.get(testProperty)); // Add a 'LinkedList' property to the DynaClass dynaClass.add(testProperty, LinkedList.class); assertTrue("Check Property is indexed", dynaClass.getDynaProperty(testProperty).isIndexed()); assertEquals("Check Property is correct type", LinkedList.class, dynaClass.getDynaProperty(testProperty).getType()); assertEquals("Check Property type is correct", LinkedList.class, bean.get(testProperty).getClass()); // Set the property, should instantiate a new LinkedList and set appropriate indexed value bean.set(testProperty, index, testString1); assertEquals("Check Property type is correct", LinkedList.class, bean.get(testProperty).getClass()); assertEquals("Check First Indexed Value is correct", testString1, bean.get(testProperty, index)); assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((LinkedList)bean.get(testProperty)).size())); // Set a second indexed value, should automatically grow the LinkedList and set appropriate indexed value index = index + 2; bean.set(testProperty, index, testInteger1); assertEquals("Check Second Indexed Value is correct", testInteger1, bean.get(testProperty, index)); assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((LinkedList)bean.get(testProperty)).size())); } /** * Test Getting/Setting a primitive array 'Indexed' Property - use int[] */ public void testIndexedPrimitiveArray() { int index = 3; int[] primitiveArray = new int[0]; // Check the property & value doesn't exist assertNull("Check Indexed Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Indexed Property is null", bean.get(testProperty)); // Add a DynaProperty of type int[] dynaClass.add(testProperty, primitiveArray.getClass()); assertEquals("Check Indexed Property exists", primitiveArray.getClass(), dynaClass.getDynaProperty(testProperty).getType()); assertEquals("Check Indexed Property is correct type", primitiveArray.getClass(), bean.get(testProperty).getClass()); // Set an indexed value bean.set(testProperty, index, testInteger1); assertNotNull("Check Indexed Property is not null", bean.get(testProperty)); assertEquals("Check Indexed Property is correct type", primitiveArray.getClass(), bean.get(testProperty).getClass()); assertEquals("Check First Indexed Value is correct(a)", testInteger1, bean.get(testProperty, index)); assertEquals("Check First Indexed Value is correct(b)", testInteger1, new Integer(((int[])bean.get(testProperty))[index])); assertEquals("Check Array length is correct", new Integer(index+1), new Integer(((int[])bean.get(testProperty)).length)); // Set a second indexed value, should automatically grow the int[] and set appropriate indexed value index = index + 2; bean.set(testProperty, index, testInteger2); assertEquals("Check Second Indexed Value is correct(a)", testInteger2, bean.get(testProperty, index)); assertEquals("Check Second Indexed Value is correct(b)", testInteger2, new Integer(((int[])bean.get(testProperty))[index])); assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((int[])bean.get(testProperty)).length)); } /** * Test Getting/Setting an Object array 'Indexed' Property - use String[] */ public void testIndexedObjectArray() { int index = 3; Object objectArray = new String[0]; // Check the property & value doesn't exist assertNull("Check Indexed Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Indexed Property is null", bean.get(testProperty)); // Add a DynaProperty of type String[] dynaClass.add(testProperty, objectArray.getClass()); assertEquals("Check Indexed Property exists", objectArray.getClass(), dynaClass.getDynaProperty(testProperty).getType()); assertEquals("Check Indexed Property is correct type", objectArray.getClass(), bean.get(testProperty).getClass()); // Set an indexed value bean.set(testProperty, index, testString1); assertNotNull("Check Indexed Property is not null", bean.get(testProperty)); assertEquals("Check Indexed Property is correct type", objectArray.getClass(), bean.get(testProperty).getClass()); assertEquals("Check First Indexed Value is correct(a)", testString1, bean.get(testProperty, index)); assertEquals("Check First Indexed Value is correct(b)", testString1, ((String[])bean.get(testProperty))[index]); assertEquals("Check Array length is correct", new Integer(index+1), new Integer(((String[])bean.get(testProperty)).length)); // Set a second indexed value, should automatically grow the String[] and set appropriate indexed value index = index + 2; bean.set(testProperty, index, testString2); assertEquals("Check Second Indexed Value is correct(a)", testString2, bean.get(testProperty, index)); assertEquals("Check Second Indexed Value is correct(b)", testString2, ((String[])bean.get(testProperty))[index]); assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((String[])bean.get(testProperty)).length)); } /** * Test Getting/Setting an DynaBean[] array */ public void testIndexedDynaBeanArray() { int index = 3; Object objectArray = new LazyDynaMap[0]; // Check the property & value doesn't exist assertNull("Check Indexed Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Indexed Property is null", bean.get(testProperty)); // Add a DynaProperty of type String[] dynaClass.add(testProperty, objectArray.getClass()); assertEquals("Check Indexed Property exists", objectArray.getClass(), dynaClass.getDynaProperty(testProperty).getType()); assertEquals("Check Indexed Property is correct type", objectArray.getClass(), bean.get(testProperty).getClass()); // Retrieving from Array should initialize DynaBean for (int i = index; i >= 0; i--) { assertEquals("Check Array Components initialized", LazyDynaMap.class, bean.get(testProperty, index).getClass()); } dynaClass.add(testPropertyB, objectArray.getClass()); LazyDynaMap newMap = new LazyDynaMap(); newMap.set(testPropertyB, testString2); bean.set(testPropertyA, index, newMap); assertEquals("Check Indexed Value is correct(a)", testString2, ((DynaBean)bean.get(testPropertyA, index)).get(testPropertyB)); } /** * Test Setting an 'Indexed' Property using PropertyUtils */ public void testIndexedPropertyUtils() { int index = 3; dynaClass.setReturnNull(false); // Check the property & value doesn't exist assertFalse("Check Indexed Property doesn't exist", dynaClass.isDynaProperty(testProperty)); assertNull("Check Indexed Property is null", bean.get(testProperty)); assertNull("Check Indexed value is null", bean.get(testProperty, index)); // Use PropertyUtils to set the indexed value try { PropertyUtils.setProperty(bean, testProperty+"["+index+"]", testString1); } catch (NoSuchMethodException ex) { fail("testIndexedPropertyUtils threw "+ex); } catch (InvocationTargetException ex) { fail("testIndexedPropertyUtils threw "+ex); } catch (IllegalAccessException ex) { fail("testIndexedPropertyUtils threw "+ex); } // Check property value correctly set assertEquals("Check Indexed Bean Value is correct", testString1, bean.get(testProperty, index)); } /** * Test Setting an Indexed Property when MutableDynaClass is set to restricted */ public void testIndexedPropertyRestricted() { int index = 3; // Set the MutableDyanClass to 'restricted' (i.e. no new properties cab be added dynaClass.setRestricted(true); assertTrue("Check MutableDynaClass is restricted", dynaClass.isRestricted()); // Check the property & value doesn't exist assertNull("Check Property doesn't exist", dynaClass.getDynaProperty(testProperty)); assertNull("Check Value is null", bean.get(testProperty)); // Set the property - should fail because property doesn't exist and MutableDynaClass is restricted try { bean.set(testProperty, index, testInteger1); fail("expected IllegalArgumentException trying to add new property to restricted MutableDynaClass"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test setting indexed property for type which is not List or Array */ public void testIndexedInvalidType() { int index = 3; dynaClass.add(testProperty, String.class); assertFalse("Check Property is not indexed", dynaClass.getDynaProperty(testProperty).isIndexed()); try { bean.set(testProperty, index, testString1); fail("set(property, index, value) should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected result } } }commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/LazyDynaClassTestCase.java100644 0 0 21561 12262570610 30303 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; /** *

          Test Case for the LazyDynaClass implementation class.

          * * @version $Id: LazyDynaClassTestCase.java 1454606 2013-03-08 22:30:51Z britter $ */ public class LazyDynaClassTestCase extends TestCase { protected LazyDynaClass dynaClass = null; protected String testProperty = "myProperty"; // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public LazyDynaClassTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Run this Test */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { dynaClass = new LazyDynaClass(); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(LazyDynaClassTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { dynaClass = null; } // ------------------------------------------------ Individual Test Methods /** * Test add(name) method */ public void testAddProperty1() { dynaClass.add(testProperty); DynaProperty dynaProperty = dynaClass.getDynaProperty(testProperty); assertEquals("name is correct", testProperty, dynaProperty.getName()); assertEquals("type is correct", Object.class, dynaProperty.getType()); } /** * Test add(name, type) method */ public void testAddProperty2() { dynaClass.add(testProperty, String.class); DynaProperty dynaProperty = dynaClass.getDynaProperty(testProperty); assertEquals("name is correct", testProperty, dynaProperty.getName()); assertEquals("type is correct", String.class, dynaProperty.getType()); } /** * Test add(name, type, readable, writable) method */ public void testAddProperty3() { try { dynaClass.add(testProperty, String.class, true, true); fail("add(name, type, readable, writable) did not throw UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { // expected result } } /** * Test add(name) method with 'null' name */ public void testAddPropertyNullName1() { try { dynaClass.add((String)null); fail("null property name not prevented"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test add(name, type) method with 'null' name */ public void testAddPropertyNullName2() { try { dynaClass.add(null, String.class); fail("null property name not prevented"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test add(name, type, readable, writable) method with 'null' name */ public void testAddPropertyNullName3() { try { dynaClass.add(null, String.class, true, true); fail("add(name, type, readable, writable) did not throw UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { // expected result } } /** * Test add(name) method when restricted is set to 'true' */ public void testAddPropertyRestricted1() { dynaClass.setRestricted(true); assertTrue("MutableDynaClass is restricted", dynaClass.isRestricted()); try { dynaClass.add(testProperty); fail("add(name) did not throw IllegalStateException"); } catch (IllegalStateException expected) { // expected result } } /** * Test add(name, type) method when restricted is set to 'true' */ public void testAddPropertyRestricted2() { dynaClass.setRestricted(true); assertTrue("MutableDynaClass is restricted", dynaClass.isRestricted()); try { dynaClass.add(testProperty, String.class); fail("add(name, type) did not throw IllegalStateException"); } catch (IllegalStateException expected) { // expected result } } /** * Test add(name, type, readable, writable) method when restricted is set to 'true' */ public void testAddPropertyRestricted3() { dynaClass.setRestricted(true); assertTrue("MutableDynaClass is restricted", dynaClass.isRestricted()); try { dynaClass.add(testProperty, String.class, true, true); fail("add(name, type, readable, writable) did not throw UnsupportedOperationException"); } catch (UnsupportedOperationException t) { // expected result } } /** * Test retrieving a property which doesn't exist (returnNull is 'false') */ public void testGetPropertyDoesntExist1() { dynaClass.setReturnNull(false); assertFalse("returnNull is 'false'", dynaClass.isReturnNull()); DynaProperty dynaProperty = dynaClass.getDynaProperty(testProperty); assertEquals("name is correct", testProperty, dynaProperty.getName()); assertEquals("type is correct", Object.class, dynaProperty.getType()); assertFalse("property doesnt exist", dynaClass.isDynaProperty(testProperty)); } /** * Test retrieving a property which doesn't exist (returnNull is 'true') */ public void testGetPropertyDoesntExist2() { dynaClass.setReturnNull(true); assertTrue("returnNull is 'true'", dynaClass.isReturnNull()); assertNull("property is null", dynaClass.getDynaProperty(testProperty)); } /** * Test removing a property */ public void testRemoveProperty() { dynaClass.setReturnNull(true); dynaClass.add(testProperty); assertTrue("Property exists", dynaClass.isDynaProperty(testProperty)); assertNotNull("property is Not null", dynaClass.getDynaProperty(testProperty)); dynaClass.remove(testProperty); assertFalse("Property doesn't exist", dynaClass.isDynaProperty(testProperty)); assertNull("property is null", dynaClass.getDynaProperty(testProperty)); } /** * Test removing a property, name is null */ public void testRemovePropertyNullName() { try { dynaClass.remove(null); fail("remove(null) did not throw IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test removing a property, DynaClass is restricted */ public void testRemovePropertyRestricted() { dynaClass.add(testProperty); assertTrue("Property exists", dynaClass.isDynaProperty(testProperty)); dynaClass.setRestricted(true); assertTrue("MutableDynaClass is restricted", dynaClass.isRestricted()); try { dynaClass.remove(testProperty); fail("remove property when MutableDynaClassis restricted did not throw IllegalStateException"); } catch (IllegalStateException expected) { // expected result } } /** * Test removing a property which doesn't exist */ public void testRemovePropertyDoesntExist() { assertFalse("property doesn't exist", dynaClass.isDynaProperty(testProperty)); dynaClass.remove(testProperty); assertFalse("property still doesn't exist", dynaClass.isDynaProperty(testProperty)); } }commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/LazyDynaListTestCase.java100644 0 0 53357 12262570607 30167 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** *

          Test Case for the LazyDynaListclass.

          * * @version $Id: LazyDynaListTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class LazyDynaListTestCase extends TestCase { private static final String BASIC_PROP1 = "BasicDynaClass_Property1"; private static final String BASIC_PROP2 = "BasicDynaClass_Property2"; protected DynaProperty[] properties = new DynaProperty[] { new DynaProperty(BASIC_PROP1, String.class), new DynaProperty(BASIC_PROP2, HashMap.class)}; protected DynaClass treeMapDynaClass = new LazyDynaMap(new TreeMap()); protected DynaClass hashMapDynaClass = new LazyDynaMap(new HashMap()); protected DynaClass pojoDynaClass = new WrapDynaBean(new TestBean()).getDynaClass(); protected DynaClass basicDynaClass = new BasicDynaClass("test", BasicDynaBean.class, properties); // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public LazyDynaListTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Run thus Test */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(LazyDynaListTestCase.class)); } /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { } // ------------------------------------------------ Individual Test Methods /** * Test DynaBean Create */ public void testDynaBeanDynaClass() { // Create LazyArrayList for DynaBeans LazyDynaList list = new LazyDynaList(basicDynaClass); // test dynaBeanTest(list, BasicDynaBean.class, basicDynaClass, new BenchBean()); } /** * Test DynaBean Create */ public void testDynaBeanType() { // Create LazyArrayList for DynaBeans LazyDynaList list = new LazyDynaList(LazyDynaBean.class); LazyDynaBean bean = new LazyDynaBean(); bean.set("prop1", "val"); // test dynaBeanTest(list, LazyDynaBean.class, bean.getDynaClass(), new BenchBean()); } /** * Test Map Create */ public void testMapDynaClass() { // Create LazyArrayList for TreeMap's LazyDynaList list = new LazyDynaList(treeMapDynaClass); // test mapTest(list, TreeMap.class, new BenchBean()); } /** * Test Map Create */ public void testMapType() { // Create LazyArrayList for HashMap's LazyDynaList list = new LazyDynaList(HashMap.class); // test mapTest(list, HashMap.class, new BenchBean()); } /** * Test Pojo Create */ public void testPojoDynaClass() { // Create LazyArrayList for POJO's LazyDynaList list = new LazyDynaList(pojoDynaClass); // test pojoTest(list, TestBean.class, new BenchBean()); } /** * Test Pojo Create */ public void testPojoType() { // Create LazyArrayList for POJO's LazyDynaList list = new LazyDynaList(TestBean.class); // test pojoTest(list, TestBean.class, new BenchBean()); } /** * Test Collection */ public void testCollection(LazyDynaList list, Class testClass, DynaClass testDynaClass, Object wrongBean) { // ----- Create Collection & Array of Maps ----- int size = 5; List testList = new ArrayList(size); TreeMap[] testArray = new TreeMap[size]; for (int i = 0; i < size; i++) { TreeMap map = new TreeMap(); map.put("prop"+i, "val"+i); testArray[i] = map; testList.add(testArray[i]); } // ----- Create LazyArrayList from Collection ----- LazyDynaList lazyList = new LazyDynaList(testList); assertEquals("1. check size", size, lazyList.size()); DynaBean[] dynaArray = lazyList.toDynaBeanArray(); TreeMap[] mapArray = (TreeMap[])lazyList.toArray(); // Check values assertEquals("2. check size", size, dynaArray.length); assertEquals("3. check size", size, mapArray.length); for (int i = 0; i < size; i++) { assertEquals("4."+i+" DynaBean error ", "val"+i, dynaArray[i].get("prop"+i)); assertEquals("5."+i+" Map error ", "val"+i, mapArray[i].get("prop"+i)); } // ----- Create LazyArrayList from Array ----- lazyList = new LazyDynaList(testArray); assertEquals("6. check size", size, lazyList.size()); dynaArray = lazyList.toDynaBeanArray(); mapArray = (TreeMap[])lazyList.toArray(); // Check values assertEquals("7. check size", size, dynaArray.length); assertEquals("8. check size", size, mapArray.length); for (int i = 0; i < size; i++) { assertEquals("9."+i+" DynaBean error ", "val"+i, dynaArray[i].get("prop"+i)); assertEquals("10."+i+" Map error ", "val"+i, mapArray[i].get("prop"+i)); } } /** * Test adding a map to List with no type set. */ public void testNullType() { LazyDynaList lazyList = new LazyDynaList(); lazyList.add(new HashMap()); } /** * Test DynaBean Create */ private void dynaBeanTest(LazyDynaList list, Class testClass, DynaClass testDynaClass, Object wrongBean) { // Test get(index) created correct DynaBean - Second Object dynaBean = list.get(1); assertNotNull("1. DynaBean Not Created", dynaBean); assertEquals("2. Wrong Type", testClass, dynaBean.getClass()); // Test toArray() creates correct Array - Second Object array = list.toArray(); assertNotNull("3. Array Not Created", array); assertEquals("4. Not DynaBean[]", testClass, array.getClass().getComponentType()); DynaBean[] dynaArray = (DynaBean[])array; assertEquals("5. Array Size Wrong", 2, dynaArray.length); // Test get(index) created correct DynaBean - Fourth dynaBean = list.get(3); assertNotNull("6. DynaBean Not Created", dynaBean); assertEquals("7. Wrong type", testClass, dynaBean.getClass()); // Test toArray() creates correct Array - Fourth array = list.toArray(); assertNotNull("8. Array Not Created", array); assertEquals("9. Not DynaBean[]", testClass, array.getClass().getComponentType()); dynaArray = (DynaBean[])array; assertEquals("10. Array Size Wrong", 4, dynaArray.length); // Test fail if different type added try { list.add(2, wrongBean); fail("Expected IllegalArgumentException"); } catch(IllegalArgumentException ignore) { // expected result } // find a String property to set String testProperty = findStringProperty(testDynaClass); assertNotNull("Test Property Not Found", testProperty); dynaArray = list.toDynaBeanArray(); for (int i = 0; i < dynaArray.length; i++) { dynaArray[i].set(testProperty, "orig_pos"+i); } // Create Collection List collection = new ArrayList(); try { collection.add(testDynaClass.newInstance()); collection.add(testDynaClass.newInstance()); collection.add(testDynaClass.newInstance()); } catch(Exception ex) { fail("1. FAILED: " + ex); } int expectedSize = dynaArray.length + collection.size(); String origValue = (String)((DynaBean)collection.get(0)).get(testProperty); ((DynaBean)collection.get(0)).set(testProperty, origValue+"_updated_"+0); ((DynaBean)collection.get(1)).set(testProperty, origValue+"_updated_"+1); ((DynaBean)collection.get(2)).set(testProperty, origValue+"_updated_"+2); // Test Insert - addAll(index, Collection) list.addAll(1, collection); dynaArray = list.toDynaBeanArray(); // Check array after insert dynaArray = list.toDynaBeanArray(); assertEquals("11. Array Size Wrong", expectedSize, dynaArray.length); // Check Beans have inserted correctly - by checking the property values assertEquals("12. Wrong Value", "orig_pos0", dynaArray[0].get(testProperty)); assertEquals("13. Wrong Value", origValue+"_updated_"+0, dynaArray[1].get(testProperty)); assertEquals("14. Wrong Value", origValue+"_updated_"+1, dynaArray[2].get(testProperty)); assertEquals("15. Wrong Value", origValue+"_updated_"+2, dynaArray[3].get(testProperty)); assertEquals("16. Wrong Value", "orig_pos1", dynaArray[4].get(testProperty)); // Test Insert - add(index, Object) try { DynaBean extraElement = testDynaClass.newInstance(); extraElement.set(testProperty, "extraOne"); list.add(2, extraElement); dynaArray = list.toDynaBeanArray(); assertEquals("17. Wrong Value", origValue+"_updated_"+0, dynaArray[1].get(testProperty)); assertEquals("18. Wrong Value", "extraOne", dynaArray[2].get(testProperty)); assertEquals("19. Wrong Value", origValue+"_updated_"+1, dynaArray[3].get(testProperty)); } catch(Exception ex) { fail("2. FAILED: " + ex); } } /** * Test Map Create */ private String findStringProperty(DynaClass dynaClass) { DynaProperty[] properties = dynaClass.getDynaProperties(); for (int i = 0; i < properties.length; i++) { if (properties[i].getType() == String.class) { return properties[i].getName(); } } return null; } /** * Test Map Create */ private void mapTest(LazyDynaList list, Class testClass, Object wrongBean) { // Test get(index) created correct DynaBean - First Object dynaBean = list.get(0); assertNotNull("1. DynaBean Not Created", dynaBean); assertEquals("2. Not LazyDynaMap", LazyDynaMap.class, dynaBean.getClass()); // Test get(index) created correct Map - First Object map = ((LazyDynaMap)dynaBean).getMap(); assertNotNull("3. Map Not Created", map); assertEquals("4. Wrong Map", testClass, map.getClass()); // Test toArray() creates correct Array - First Object array = list.toArray(); assertNotNull("5. Array Not Created", array); assertEquals("6. Not Map[]", testClass, array.getClass().getComponentType()); Map[] mapArray = (Map[])array; assertEquals("7. Array Size Wrong", 1, mapArray.length); // Test get(index) created correct DynaBean - Third dynaBean = list.get(2); assertNotNull("8. DynaBean Not Created", dynaBean); assertEquals("9. Not LazyDynaMap", LazyDynaMap.class, dynaBean.getClass()); // Test get(index) created correct Map - Third map = ((LazyDynaMap)dynaBean).getMap(); assertNotNull("10. Map Not Created", map); assertEquals("11. Wrong Map", testClass, map.getClass()); // Test toArray() creates correct Array - Third array = list.toArray(); assertNotNull("12. Array Not Created", array); assertEquals("13. Not Map[]", testClass, array.getClass().getComponentType()); mapArray = (Map[])array; assertEquals("14. Array Size Wrong", 3, mapArray.length); // Test fail if different type added try { list.add(2, wrongBean); fail("Expected IllegalArgumentException"); } catch(IllegalArgumentException ignore) { // expected result } } /** * Test Pojo Create */ private void pojoTest(LazyDynaList list, Class testClass, Object wrongBean) { // Test get(index) created correct DynaBean - First Object dynaBean = list.get(0); assertNotNull("1. DynaBean Not Created", dynaBean); assertEquals("2. Not WrapDynaBean", WrapDynaBean.class, dynaBean.getClass()); // Test get(index) created correct POJO - First Object pojoBean = ((WrapDynaBean)dynaBean).getInstance(); assertNotNull("3. POJO Not Created", pojoBean); assertEquals("4. Not WrapDynaBean", testClass, pojoBean.getClass()); // Test toArray() creates correct Array - First Object array = list.toArray(); assertNotNull("5. Array Not Created", array); assertEquals("6. Wrong array", testClass, array.getClass().getComponentType()); Object[] pojoArray = (Object[])array; assertEquals("7. Array Size Wrong", 1, pojoArray.length); // Test get(index) created correct DynaBean - Second dynaBean = list.get(1); assertNotNull("8. DynaBean Not Created", dynaBean); assertEquals("9. Not WrapDynaBean", WrapDynaBean.class, dynaBean.getClass()); // Test get(index) created correct POJO - Second pojoBean = ((WrapDynaBean)dynaBean).getInstance(); assertNotNull("10. POJO Not Created", pojoBean); assertEquals("11. Not WrapDynaBean", testClass, pojoBean.getClass()); // Test toArray() creates correct Array - Second array = list.toArray(); assertNotNull("12. Array Not Created", array); assertEquals("13. Wrong array", testClass, array.getClass().getComponentType()); pojoArray = (Object[])array; assertEquals("14. Array Size Wrong", 2, pojoArray.length); // Test fail if different type added try { list.add(2, wrongBean); fail("Expected IllegalArgumentException"); } catch(IllegalArgumentException ignore) { // expected result } } /** * Test DynaBean serialization. */ public void testSerializationDynaBean() { // Create LazyArrayList for DynaBeans LazyDynaList target = new LazyDynaList(basicDynaClass); BasicDynaBean bean = (BasicDynaBean)target.get(0); // Set a Property assertNull("pre-set check", bean.get(BASIC_PROP1)); bean.set(BASIC_PROP1, "value1"); assertEquals("post-set check", "value1", bean.get(BASIC_PROP1)); // Serialize/Deserialize LazyDynaList result = (LazyDynaList)serializeDeserialize(target, "DynaBean"); target = null; bean = null; // Confirm property value bean = (BasicDynaBean)result.get(0); assertEquals("post-serialize check", "value1", bean.get(BASIC_PROP1)); } /** * Test DynaBean serialization. */ public void testSerializationLazyDynaBean() { // Create LazyArrayList for DynaBeans LazyDynaList target = new LazyDynaList(); LazyDynaBean bean = (LazyDynaBean)target.get(0); // Set a Property assertNull("pre-set check", bean.get(BASIC_PROP1)); bean.set(BASIC_PROP1, "value1"); assertEquals("post-set check", "value1", bean.get(BASIC_PROP1)); // Serialize/Deserialize LazyDynaList result = (LazyDynaList)serializeDeserialize(target, "DynaBean"); target = null; bean = null; // Confirm property value bean = (LazyDynaBean)result.get(0); assertEquals("post-serialize check", "value1", bean.get(BASIC_PROP1)); } /** * Test Map serialization. */ public void testSerializationMap() { // Create LazyArrayList for DynaBeans LazyDynaList target = new LazyDynaList(treeMapDynaClass); LazyDynaMap bean = (LazyDynaMap)target.get(0); // Set a Property assertNull("pre-set check", bean.get(BASIC_PROP1)); bean.set(BASIC_PROP1, "value1"); assertEquals("post-set check", "value1", bean.get(BASIC_PROP1)); // Serialize/Deserialize LazyDynaList result = (LazyDynaList)serializeDeserialize(target, "Map"); target = null; bean = null; // Confirm property value bean = (LazyDynaMap)result.get(0); assertEquals("post-serialize check", "value1", bean.get(BASIC_PROP1)); } /** * Test POJO (WrapDynaBean) serialization. */ public void testSerializationPojo() { // Create LazyArrayList for DynaBeans LazyDynaList target = new LazyDynaList(pojoDynaClass); WrapDynaBean bean = (WrapDynaBean)target.get(0); // Set a Property assertEquals("pre-set check", "This is a string", bean.get("stringProperty")); bean.set("stringProperty", "value1"); assertEquals("post-set check", "value1", bean.get("stringProperty")); // Serialize/Deserialize LazyDynaList result = (LazyDynaList)serializeDeserialize(target, "POJO"); target = null; bean = null; // Test BEANUTILS-300 result.add(null); // Confirm property value bean = (WrapDynaBean)result.get(0); assertEquals("post-serialize check", "value1", bean.get("stringProperty")); } /** * Do serialization and deserialization. */ private Object serializeDeserialize(Object target, String text) { // Serialize the test object ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(target); oos.flush(); oos.close(); } catch (Exception e) { fail(text + ": Exception during serialization: " + e); } // Deserialize the test object Object result = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = ois.readObject(); bais.close(); } catch (Exception e) { fail(text + ": Exception during deserialization: " + e); } return result; } /** * Tests toArray() if the list contains DynaBean objects. */ public void testToArrayDynaBeans() { LazyDynaList list = new LazyDynaList(LazyDynaBean.class); LazyDynaBean elem = new LazyDynaBean(); list.add(elem); LazyDynaBean[] beans = new LazyDynaBean[1]; assertSame("Wrong array", beans, list.toArray(beans)); assertSame("Wrong element", elem, beans[0]); } /** * Tests toArray() if the list contains maps. */ public void testToArrayMapType() { LazyDynaList list = new LazyDynaList(HashMap.class); HashMap elem = new HashMap(); list.add(elem); Map[] array = new Map[1]; assertSame("Wrong array", array, list.toArray(array)); assertEquals("Wrong element", elem, array[0]); } /** * Tests toArray() for other bean elements. */ public void testToArrayOtherType() { LazyDynaList list = new LazyDynaList(TestBean.class); TestBean elem = new TestBean(); list.add(elem); TestBean[] array = new TestBean[1]; assertSame("Wrong array", array, list.toArray(array)); assertEquals("Wrong element", elem, array[0]); } /** * Tests toArray() if the array's size does not fit the collection size. */ public void testToArrayUnsufficientSize() { LazyDynaList list = new LazyDynaList(LazyDynaBean.class); LazyDynaBean elem = new LazyDynaBean(); list.add(elem); LazyDynaBean[] array = (LazyDynaBean[]) list.toArray(new LazyDynaBean[0]); assertEquals("Wrong array size", 1, array.length); assertEquals("Wrong element", elem, array[0]); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/LazyDynaMapTestCase.java100644 0 0 56570 12262570610 27763 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** *

          Test Case for the LazyDynaMap implementation class.

          * * @version $Id: LazyDynaMapTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class LazyDynaMapTestCase extends TestCase { protected LazyDynaMap dynaMap = null; protected String testProperty = "myProperty"; protected String testPropertyA = "myProperty-A"; protected String testPropertyB = "myProperty-B"; protected String testString1 = "myStringValue-1"; protected String testString2 = "myStringValue-2"; protected Integer testInteger1 = new Integer(30); protected Integer testInteger2 = new Integer(40); protected String testKey = "myKey"; // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public LazyDynaMapTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Run thus Test */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(LazyDynaMapTestCase.class)); } /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { dynaMap = new LazyDynaMap(); dynaMap.setReturnNull(true); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { dynaMap = null; } // ------------------------------------------------ Individual Test Methods /** * General Tests */ public void testGeneral() { // LazyDynaMap bean = new LazyDynaMap("TestBean"); assertEquals("Check DynaClass name", "TestBean", new LazyDynaMap("TestBean").getName()); } /** * Test Getting/Setting a Simple Property */ public void testSimpleProperty() { // Check the property & value doesn't exist assertNull("Check Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Value is null", dynaMap.get(testProperty)); // Set a new property - should add new property and set value dynaMap.set(testProperty, testInteger1); assertEquals("Check First Value is correct", testInteger1, dynaMap.get(testProperty)); assertEquals("Check Property type is correct", Integer.class, dynaMap.getDynaProperty(testProperty).getType()); // Set the property again - should set the new value dynaMap.set(testProperty, testInteger2); assertEquals("Check Second Value is correct", testInteger2, dynaMap.get(testProperty)); // Set the property again - with a different type, should succeed dynaMap.set(testProperty, testString1); assertEquals("Check Third Value is correct", testString1, dynaMap.get(testProperty)); } /** * Test Setting a Simple Property when MutableDynaClass is set to restricted */ public void testSimplePropertyRestricted() { // Set the MutableDyanClass to 'restricted' (i.e. no new properties cab be added dynaMap.setRestricted(true); assertTrue("Check MutableDynaClass is restricted", dynaMap.isRestricted()); // Check the property & value doesn't exist assertNull("Check Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Value is null", dynaMap.get(testProperty)); // Set the property - should fail because property doesn't exist and MutableDynaClass is restricted try { dynaMap.set(testProperty, testString1); fail("expected IllegalArgumentException trying to add new property to restricted DynaClass"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test Getting/Setting a 'Mapped' Property - default HashMap property */ public void testMappedPropertyDefault() { // Check the property & value doesn't exist assertNull("Check Mapped Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Map is null", dynaMap.get(testProperty)); assertNull("Check Mapped Value is null", dynaMap.get(testProperty, testKey)); // Set a new mapped property - should add new HashMap property and set the mapped value dynaMap.set(testProperty, testKey, testInteger1); assertEquals("Check Mapped Property exists", HashMap.class, dynaMap.get(testProperty).getClass()); assertEquals("Check First Mapped Value is correct(a)", testInteger1, dynaMap.get(testProperty, testKey)); assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((HashMap)dynaMap.get(testProperty)).get(testKey)); // Set the property again - should set the new value dynaMap.set(testProperty, testKey, testInteger2); assertEquals("Check Second Mapped Value is correct(a)", testInteger2, dynaMap.get(testProperty, testKey)); assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((HashMap)dynaMap.get(testProperty)).get(testKey)); } /** * Test Getting/Setting a 'Mapped' Property - use TreeMap property */ public void testMappedPropertyTreeMap() { // Check the property & value doesn't exist assertNull("Check Mapped Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Map is null", dynaMap.get(testProperty)); // Add a 'TreeMap' property to the DynaClass dynaMap.add(testProperty, TreeMap.class); assertTrue("Check Property is mapped", dynaMap.getDynaProperty(testProperty).isMapped()); assertEquals("Check Property is correct type", TreeMap.class, dynaMap.getDynaProperty(testProperty).getType()); assertEquals("Check Mapped Property now exists", TreeMap.class, dynaMap.get(testProperty).getClass()); // Set a new mapped property - should instatiate a new TreeMap property and set the mapped value dynaMap.set(testProperty, testKey, testInteger1); assertEquals("Check Mapped Property exists", TreeMap.class, dynaMap.get(testProperty).getClass()); assertEquals("Check First Mapped Value is correct(a)", testInteger1, dynaMap.get(testProperty, testKey)); assertEquals("Check First Mapped Value is correct(b)", testInteger1, ((TreeMap)dynaMap.get(testProperty)).get(testKey)); // Set the property again - should set the new value dynaMap.set(testProperty, testKey, testInteger2); assertEquals("Check Second Mapped Value is correct(a)", testInteger2, dynaMap.get(testProperty, testKey)); assertEquals("Check Second Mapped Value is correct(b)", testInteger2, ((TreeMap)dynaMap.get(testProperty)).get(testKey)); } /** * Test Setting a 'Mapped' Property using PropertyUtils */ public void testMappedPropertyUtils() { dynaMap.setReturnNull(false); // Check the property & value doesn't exist assertFalse("Check Mapped Property doesn't exist", dynaMap.isDynaProperty(testProperty)); assertNull("Check Map is null", dynaMap.get(testProperty)); assertNull("Check Mapped Value is null", dynaMap.get(testProperty, testKey)); // Set the mapped property using PropertyUtils try { PropertyUtils.setProperty(dynaMap, testProperty+"("+testKey+")", testString1); } catch (NoSuchMethodException ex) { fail("testIndexedPropertyUtils threw "+ex); } catch (InvocationTargetException ex) { fail("testIndexedPropertyUtils threw "+ex); } catch (IllegalAccessException ex) { fail("testIndexedPropertyUtils threw "+ex); } // Check property value correctly set assertEquals("Check Mapped Bean Value is correct", testString1, dynaMap.get(testProperty, testKey)); } /** * Test Setting a Mapped Property when MutableDynaClass is set to restricted */ public void testMappedPropertyRestricted() { // Set the MutableDyanClass to 'restricted' (i.e. no new properties cab be added dynaMap.setRestricted(true); assertTrue("Check MutableDynaClass is restricted", dynaMap.isRestricted()); // Check the property & value doesn't exist assertNull("Check Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Value is null", dynaMap.get(testProperty)); // Set the property - should fail because property doesn't exist and MutableDynaClass is restricted try { dynaMap.set(testProperty, testKey, testInteger1); fail("expected IllegalArgumentException trying to add new property to restricted MutableDynaClass"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test setting mapped property for type which is not Map */ public void testMappedInvalidType() { dynaMap.set(testProperty, new Integer(1)); assertFalse("Check Property is not mapped", dynaMap.getDynaProperty(testProperty).isMapped()); try { dynaMap.set(testProperty, testKey, testInteger1); fail("set(property, key, value) should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test Getting/Setting an 'Indexed' Property - default ArrayList property */ public void testIndexedPropertyDefault() { int index = 3; // Check the property & value doesn't exist assertNull("Check Indexed Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Indexed Property is null", dynaMap.get(testProperty)); assertNull("Check Indexed value is null", dynaMap.get(testProperty, index)); // Set the property, should create new ArrayList and set appropriate indexed value dynaMap.set(testProperty, index, testInteger1); assertNotNull("Check Indexed Property is not null", dynaMap.get(testProperty)); assertEquals("Check Indexed Property is correct type", ArrayList.class, dynaMap.get(testProperty).getClass()); assertEquals("Check First Indexed Value is correct", testInteger1, dynaMap.get(testProperty, index)); assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((ArrayList)dynaMap.get(testProperty)).size())); // Set a second indexed value, should automatically grow the ArrayList and set appropriate indexed value index = index + 2; dynaMap.set(testProperty, index, testString1); assertEquals("Check Second Indexed Value is correct", testString1, dynaMap.get(testProperty, index)); assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((ArrayList)dynaMap.get(testProperty)).size())); } /** * Test Getting/Setting a List 'Indexed' Property - use alternative List (LinkedList) */ public void testIndexedLinkedList() { int index = 3; // Check the property & value doesn't exist assertNull("Check Indexed Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Indexed Property is null", dynaMap.get(testProperty)); // Add a 'LinkedList' property to the DynaClass - should instantiate a new LinkedList dynaMap.add(testProperty, LinkedList.class); assertTrue("Check Property is indexed", dynaMap.getDynaProperty(testProperty).isIndexed()); assertEquals("Check Property is correct type", LinkedList.class, dynaMap.getDynaProperty(testProperty).getType()); assertEquals("Check Indexed Property now exists", LinkedList.class, dynaMap.get(testProperty).getClass()); // Set the Indexed property, should grow the list to the correct size dynaMap.set(testProperty, index, testString1); assertEquals("Check Property type is correct", LinkedList.class, dynaMap.get(testProperty).getClass()); assertEquals("Check First Indexed Value is correct", testString1, dynaMap.get(testProperty, index)); assertEquals("Check First Array length is correct", new Integer(index+1), new Integer(((LinkedList)dynaMap.get(testProperty)).size())); // Set a second indexed value, should automatically grow the LinkedList and set appropriate indexed value index = index + 2; dynaMap.set(testProperty, index, testInteger1); assertEquals("Check Second Indexed Value is correct", testInteger1, dynaMap.get(testProperty, index)); assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((LinkedList)dynaMap.get(testProperty)).size())); } /** * Test Getting/Setting a primitive array 'Indexed' Property - use int[] */ public void testIndexedPrimitiveArray() { int index = 3; int[] primitiveArray = new int[0]; // Check the property & value doesn't exist assertNull("Check Indexed Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Indexed Property is null", dynaMap.get(testProperty)); // Add a DynaProperty of type int[] dynaMap.add(testProperty, primitiveArray.getClass()); assertEquals("Check Indexed Property exists", primitiveArray.getClass(), dynaMap.getDynaProperty(testProperty).getType()); assertTrue("Check Indexed Property exists", dynaMap.get(testProperty).getClass().isInstance(primitiveArray)); // Set an indexed value dynaMap.set(testProperty, index, testInteger1); assertNotNull("Check Indexed Property is not null", dynaMap.get(testProperty)); assertEquals("Check Indexed Property is correct type", primitiveArray.getClass(), dynaMap.get(testProperty).getClass()); assertEquals("Check First Indexed Value is correct(a)", testInteger1, dynaMap.get(testProperty, index)); assertEquals("Check First Indexed Value is correct(b)", testInteger1, new Integer(((int[])dynaMap.get(testProperty))[index])); assertEquals("Check Array length is correct", new Integer(index+1), new Integer(((int[])dynaMap.get(testProperty)).length)); // Set a second indexed value, should automatically grow the int[] and set appropriate indexed value index = index + 2; dynaMap.set(testProperty, index, testInteger2); assertEquals("Check Second Indexed Value is correct(a)", testInteger2, dynaMap.get(testProperty, index)); assertEquals("Check Second Indexed Value is correct(b)", testInteger2, new Integer(((int[])dynaMap.get(testProperty))[index])); assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((int[])dynaMap.get(testProperty)).length)); } /** * Test Getting/Setting an Object array 'Indexed' Property - use String[] */ public void testIndexedObjectArray() { int index = 3; Object objectArray = new String[0]; // Check the property & value doesn't exist assertNull("Check Indexed Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Indexed Property is null", dynaMap.get(testProperty)); // Add a DynaProperty of type String[] dynaMap.add(testProperty, objectArray.getClass()); assertEquals("Check Indexed Property exists", objectArray.getClass(), dynaMap.getDynaProperty(testProperty).getType()); assertTrue("Check Indexed Property exists", dynaMap.get(testProperty).getClass().isInstance(objectArray)); // Set an indexed value dynaMap.set(testProperty, index, testString1); assertNotNull("Check Indexed Property is not null", dynaMap.get(testProperty)); assertEquals("Check Indexed Property is correct type", objectArray.getClass(), dynaMap.get(testProperty).getClass()); assertEquals("Check First Indexed Value is correct(a)", testString1, dynaMap.get(testProperty, index)); assertEquals("Check First Indexed Value is correct(b)", testString1, ((String[])dynaMap.get(testProperty))[index]); assertEquals("Check Array length is correct", new Integer(index+1), new Integer(((String[])dynaMap.get(testProperty)).length)); // Set a second indexed value, should automatically grow the String[] and set appropriate indexed value index = index + 2; dynaMap.set(testProperty, index, testString2); assertEquals("Check Second Indexed Value is correct(a)", testString2, dynaMap.get(testProperty, index)); assertEquals("Check Second Indexed Value is correct(b)", testString2, ((String[])dynaMap.get(testProperty))[index]); assertEquals("Check Second Array length is correct", new Integer(index+1), new Integer(((String[])dynaMap.get(testProperty)).length)); } /** * Test Getting/Setting an DynaBean[] array */ public void testIndexedDynaBeanArray() { int index = 3; Object objectArray = new LazyDynaBean[0]; // Check the property & value doesn't exist assertNull("Check Indexed Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Indexed Property is null", dynaMap.get(testProperty)); // Add a DynaProperty of type String[] dynaMap.add(testProperty, objectArray.getClass()); assertEquals("Check Indexed Property exists", objectArray.getClass(), dynaMap.getDynaProperty(testProperty).getType()); assertEquals("Check Indexed Property is correct type", objectArray.getClass(), dynaMap.get(testProperty).getClass()); // Retrieving from Array should initialize DynaBean for (int i = index; i >= 0; i--) { assertEquals("Check Array Components initialized", LazyDynaBean.class, dynaMap.get(testProperty, index).getClass()); } dynaMap.add(testPropertyB, objectArray.getClass()); LazyDynaBean newBean = new LazyDynaBean(); newBean.set(testPropertyB, testString2); dynaMap.set(testPropertyA, index, newBean); assertEquals("Check Indexed Value is correct(a)", testString2, ((DynaBean)dynaMap.get(testPropertyA, index)).get(testPropertyB)); } /** * Test Setting an 'Indexed' Property using PropertyUtils */ public void testIndexedPropertyUtils() { int index = 3; dynaMap.setReturnNull(false); // Check the property & value doesn't exist assertFalse("Check Indexed Property doesn't exist", dynaMap.isDynaProperty(testProperty)); assertNull("Check Indexed Property is null", dynaMap.get(testProperty)); assertNull("Check Indexed value is null", dynaMap.get(testProperty, index)); // Use PropertyUtils to set the indexed value try { PropertyUtils.setProperty(dynaMap, testProperty+"["+index+"]", testString1); } catch (NoSuchMethodException ex) { fail("testIndexedPropertyUtils threw "+ex); } catch (InvocationTargetException ex) { fail("testIndexedPropertyUtils threw "+ex); } catch (IllegalAccessException ex) { fail("testIndexedPropertyUtils threw "+ex); } // Check property value correctly set assertEquals("Check Indexed Bean Value is correct", testString1, dynaMap.get(testProperty, index)); } /** * Test Setting an Indexed Property when MutableDynaClass is set to restricted */ public void testIndexedPropertyRestricted() { int index = 3; // Set the MutableDyanClass to 'restricted' (i.e. no new properties cab be added dynaMap.setRestricted(true); assertTrue("Check MutableDynaClass is restricted", dynaMap.isRestricted()); // Check the property & value doesn't exist assertNull("Check Property doesn't exist", dynaMap.getDynaProperty(testProperty)); assertNull("Check Value is null", dynaMap.get(testProperty)); // Set the property - should fail because property doesn't exist and MutableDynaClass is restricted try { dynaMap.set(testProperty, index, testInteger1); fail("expected IllegalArgumentException trying to add new property to restricted MutableDynaClass"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test setting indexed property for type which is not List or Array */ public void testIndexedInvalidType() { int index = 3; dynaMap.set(testProperty, "Test String"); assertFalse("Check Property is not indexed", dynaMap.getDynaProperty(testProperty).isIndexed()); try { dynaMap.set(testProperty, index, testString1); fail("set(property, index, value) should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected result } } /** * Test creating using DynaClass.newInstance() */ public void testNewInstance() { // Create LazyDynaMap using TreeMap // containing some properties LazyDynaMap orig = new LazyDynaMap(new TreeMap()); orig.set("indexProp", 0, "indexVal0"); orig.set("indexProp", 1, "indexVal1"); assertEquals("Index prop size", 2, ((List)orig.get("indexProp")).size()); LazyDynaMap newOne = (LazyDynaMap)orig.newInstance(); Map newMap = newOne.getMap(); assertEquals("Check Map type", TreeMap.class, newMap.getClass()); ArrayList indexProp = (ArrayList)newMap.get("indexProp"); assertNotNull("Indexed Prop missing", indexProp); assertEquals("Index prop size", 0, indexProp.size()); } }././@LongLink100644 0 0 172 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/BaseLocaleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/BaseLocaleC100644 0 0 21375 12262570607 30745 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.util.Locale; import junit.framework.TestCase; import org.apache.commons.beanutils.locale.BaseLocaleConverter; /** * Base Test Case for the DecimalLocaleConverter classes. This class doesn't * define any real tests; it just provides useful methods for the real * test case classes to inherit. * * @version $Id: BaseLocaleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class BaseLocaleConverterTestCase extends TestCase { // Original Default Locale protected Locale origLocale; // Converter protected BaseLocaleConverter converter; protected Object result; protected Object defaultValue; protected Object expectedValue; // Localized values protected Locale localizedLocale; protected String localizedDecimalPattern; protected String localizedIntegerPattern; protected String localizedDecimalValue; protected String localizedIntegerValue; // Locale values protected Locale defaultLocale; protected String defaultDecimalPattern; protected String defaultIntegerPattern; protected String defaultDecimalValue; protected String defaultIntegerValue; // Expected values protected String expectedDecimalValue; protected String expectedIntegerValue; // ---------------------------------------------------------- Constructors public BaseLocaleConverterTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { // Default Locale (Use US) defaultLocale = Locale.US; defaultDecimalPattern = "#,###.00"; defaultIntegerPattern = "#,###"; defaultDecimalValue = "1,234.56"; defaultIntegerValue = "1,234"; // Use German Locale (uses different separators to US) localizedLocale = Locale.GERMAN; localizedDecimalPattern = "#.###,00"; localizedIntegerPattern = "#.###"; localizedDecimalValue = "1.234,56"; localizedIntegerValue = "1.234"; // Expected Values expectedDecimalValue = "1234.56"; expectedIntegerValue = "1234"; // Reset default to the one specified origLocale = Locale.getDefault(); // Initialize converter = null; result = null; defaultValue = null; expectedValue= null; if (defaultLocale.equals(origLocale)) { origLocale = null; } else { // System.out.println("Changing default locale from " + origLocale + " to " + defaultLocale); Locale.setDefault(defaultLocale); } } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { converter = null; result = null; defaultValue = null; expectedValue= null; // Set the Default Locale back to the original value if (origLocale != null) { // System.out.println("Restoring default locale to " + origLocale); Locale.setDefault(origLocale); } } // -------------------------------------------------- Generic Test Methods /** * Test Converting Value WITH a pattern */ protected void convertValueWithPattern(BaseLocaleConverter converter, Object value, String pattern, Object expectedValue) { convertValueWithPattern(converter, "", value, pattern, expectedValue); } /** * Test Converting Value WITH a pattern */ protected void convertValueWithPattern(BaseLocaleConverter converter, String msgId, Object value, String pattern, Object expectedValue) { // Convert value with no pattern try { result = converter.convert(value, pattern); } catch (Exception e) { fail("Pattern conversion threw " + msgId + " threw " + e); } assertEquals("Check conversion value with pattern " + msgId, expectedValue, result); } /** * Test Converting Value WITHOUT a pattern */ protected void convertValueNoPattern(BaseLocaleConverter converter, Object value, Object expectedValue) { convertValueNoPattern(converter, "", value, expectedValue); } /** * Test Converting Value WITHOUT a pattern */ protected void convertValueNoPattern(BaseLocaleConverter converter, String msgId, Object value, Object expectedValue) { // Convert value with no pattern try { result = converter.convert(value); } catch (Exception e) { fail("No Pattern conversion threw " + msgId + " threw " + e); } assertEquals("Check conversion value without pattern " + msgId, expectedValue, result); } /** * Test Converting Value To a specified Type */ protected void convertValueToType(BaseLocaleConverter converter, Class clazz, Object value, String pattern, Object expectedValue) { convertValueToType(converter, "", clazz, value, pattern, expectedValue); } /** * Test Converting Value To a specified Type */ protected void convertValueToType(BaseLocaleConverter converter, String msgId, Class clazz, Object value, String pattern, Object expectedValue) { // Convert value with no pattern try { result = converter.convert(clazz, value, pattern); } catch (Exception e) { fail("Type conversion threw " + msgId + " threw " + e); } assertEquals("Check conversion value to type " + msgId, expectedValue, result); } /** * Test Converting Null value. */ protected void convertNull(BaseLocaleConverter converter, Object expectedValue) { convertNull(converter, "", expectedValue); } /** * Test Converting Null value. */ protected void convertNull(BaseLocaleConverter converter, String msgId, Object expectedValue) { // Convert value with no pattern try { result = converter.convert(null); } catch (Exception e) { fail("Null conversion " + msgId + " threw " + e); } if (expectedValue == null) { assertNull("Check null conversion is null " + msgId + " result="+result, result); } else { assertEquals("Check null conversion is default " + msgId, expectedValue, result); } } /** * Test Converting an invalid value. */ protected void convertInvalid(BaseLocaleConverter converter, Object expectedValue) { convertInvalid(converter, "", expectedValue); } /** * Test Converting an invalid value. */ protected void convertInvalid(BaseLocaleConverter converter, String msgId, Object expectedValue) { // Convert value with no pattern try { result = converter.convert("xyz"); if (expectedValue == null) { fail("Expected ConversionException if no default value " + msgId); } } catch (Exception e) { if (expectedValue != null) { fail("Expected default value " + msgId + " threw " + e); } } if (expectedValue != null) { assertEquals("Check invalid conversion is default " + msgId, expectedValue, result); } } /** * This class isn't intended to perform any real tests; it just provides * methods for the real test cases to inherit. However junit complains * if a class named ..TestCase contains no test methods, so here we * define a dummy one to keep it happy. */ public void testNothing() { } } ././@LongLink100644 0 0 200 12262571655 10256 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/BigDecimalLocaleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/BigDecimalL100644 0 0 23217 12262570607 30741 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.math.BigDecimal; /** * Test Case for the BigDecimalLocaleConverter class. * * @version $Id: BigDecimalLocaleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class BigDecimalLocaleConverterTestCase extends BaseLocaleConverterTestCase { // ---------------------------------------------------------- Constructors public BigDecimalLocaleConverterTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { super.setUp(); defaultValue = new BigDecimal("9.99"); expectedValue = new BigDecimal(expectedDecimalValue); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------------------ /** * Test Converter(defaultValue, locale, pattern, localizedPattern) constructor */ public void testConstructorMain() { // ------------- Construct with localized pattern ------------ converter = new BigDecimalLocaleConverter(defaultValue, localizedLocale, localizedDecimalPattern, true); convertValueNoPattern(converter, "(A)", localizedDecimalValue, expectedValue); convertValueWithPattern(converter, "(A)", localizedDecimalValue, localizedDecimalPattern, expectedValue); convertInvalid(converter, "(A)", defaultValue); convertNull(converter, "(A)", defaultValue); // ************************************************************************** // Convert value in the wrong format - maybe you would expect it to throw an // exception and return the default - it doesn't, DecimalFormat parses it // quite happily turning "1,234.56" into "1.234" // I guess this is one of the limitations of DecimalFormat // ************************************************************************** convertValueNoPattern(converter, "(B)", defaultDecimalValue, new BigDecimal("1.234")); // ************************************************************************** // Convert with non-localized pattern - this causes an exception in parse() // but it gets swallowed in convert() method and returns default. // **** IS THIS THE EXPECTED BEHAVIOUR? **** // Maybe if the pattern is no good, we should use a default pattern rather // than just returning the default value. // ************************************************************************** convertValueWithPattern(converter, "(B)", localizedDecimalValue, defaultDecimalPattern, defaultValue); // ************************************************************************** // Convert with specified type // // BaseLocaleConverter completely ignores the type - so even if we specify // Double.class here it still returns a BigDecimal. // **** This has been changed due to BEANUTILS-449 **** // ************************************************************************** //convertValueToType(converter, "(B)", Double.class, localizedDecimalValue, localizedDecimalPattern, expectedValue); // ------------- Construct with non-localized pattern ------------ converter = new BigDecimalLocaleConverter(defaultValue, localizedLocale, defaultDecimalPattern, false); convertValueNoPattern(converter, "(C)", localizedDecimalValue, expectedValue); convertValueWithPattern(converter, "(C)", localizedDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, "(C)", defaultValue); convertNull(converter, "(C)", defaultValue); } /** * Test Converter() constructor * * Uses the default locale, no default value * */ public void testConstructor_2() { // ------------- Construct using default locale ------------ converter = new BigDecimalLocaleConverter(); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(locPattern) constructor * * Uses the default locale, no default value * */ public void testConstructor_3() { // ------------- Construct using localized pattern (default locale) -------- converter = new BigDecimalLocaleConverter(true); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale) constructor */ public void testConstructor_4() { // ------------- Construct using specified Locale -------- converter = new BigDecimalLocaleConverter(localizedLocale); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, locPattern) constructor */ public void testConstructor_5() { // ------------- Construct using specified Locale -------- converter = new BigDecimalLocaleConverter(localizedLocale, true); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, localizedDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern) constructor */ public void testConstructor_6() { // ------------- Construct using specified Locale -------- converter = new BigDecimalLocaleConverter(localizedLocale, defaultDecimalPattern); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern, locPattern) constructor */ public void testConstructor_7() { // ------------- Construct using specified Locale -------- converter = new BigDecimalLocaleConverter(localizedLocale, localizedDecimalPattern, true); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, localizedDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(defaultValue) constructor */ public void testConstructor_8() { // ------------- Construct using specified Locale -------- converter = new BigDecimalLocaleConverter(defaultValue); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Converter(defaultValue, locPattern) constructor */ public void testConstructor_9() { // ------------- Construct using specified Locale -------- converter = new BigDecimalLocaleConverter(defaultValue, true); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } } ././@LongLink100644 0 0 200 12262571655 10256 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/BigIntegerLocaleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/BigIntegerL100644 0 0 24151 12262570607 30776 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.math.BigInteger; import org.apache.commons.beanutils.ConversionException; /** * Test Case for the BigIntegerLocaleConverter class. * * @version $Id: BigIntegerLocaleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class BigIntegerLocaleConverterTestCase extends BaseLocaleConverterTestCase { // ---------------------------------------------------------- Constructors public BigIntegerLocaleConverterTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { super.setUp(); defaultValue = new BigInteger("999"); expectedValue = new BigInteger(expectedIntegerValue); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------------------ /** * Test Converter(defaultValue, locale, pattern, localizedPattern) constructor */ public void testConstructorMain() { // ------------- Construct with localized pattern ------------ converter = new BigIntegerLocaleConverter(defaultValue, localizedLocale, localizedIntegerPattern, true); convertValueNoPattern(converter, "(A)", localizedIntegerValue, expectedValue); convertValueWithPattern(converter, "(A)", localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, "(A)", defaultValue); convertNull(converter, "(A)", defaultValue); // ************************************************************************** // Convert value in the wrong format - maybe you would expect it to throw an // exception and return the default - it doesn't, DecimalFormat parses it // quite happily turning "1,234" into "1" // I guess this is one of the limitations of DecimalFormat // ************************************************************************** convertValueNoPattern(converter, "(B)", defaultIntegerValue, new BigInteger("1")); // ************************************************************************** // Convert with non-localized pattern - unlike the equivalent BigDecimal Test Case // it doesn't causes an exception in parse() - DecimalFormat parses it // quite happily turning "1,234" into "1" // Again this is one of the limitations of DecimalFormat // ************************************************************************** convertValueWithPattern(converter, "(B)", localizedIntegerValue, defaultIntegerPattern, new BigInteger("1")); // ************************************************************************** // Convert with specified type // // BaseLocaleConverter completely ignores the type - so even if we specify // Double.class here it still returns a BigInteger. // **** This has been changed due to BEANUTILS-449 **** // ************************************************************************** //convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue); // ------------- Construct with non-localized pattern ------------ converter = new BigIntegerLocaleConverter(defaultValue, localizedLocale, defaultIntegerPattern, false); convertValueNoPattern(converter, "(C)", localizedIntegerValue, expectedValue); convertValueWithPattern(converter, "(C)", localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, "(C)", defaultValue); convertNull(converter, "(C)", defaultValue); } /** * Test Converter() constructor * * Uses the default locale, no default value * */ public void testConstructor_2() { // ------------- Construct using default locale ------------ converter = new BigIntegerLocaleConverter(); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(locPattern) constructor * * Uses the default locale, no default value * */ public void testConstructor_3() { // ------------- Construct using localized pattern (default locale) -------- converter = new BigIntegerLocaleConverter(true); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale) constructor */ public void testConstructor_4() { // ------------- Construct using specified Locale -------- converter = new BigIntegerLocaleConverter(localizedLocale); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, locPattern) constructor */ public void testConstructor_5() { // ------------- Construct using specified Locale -------- converter = new BigIntegerLocaleConverter(localizedLocale, true); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern) constructor */ public void testConstructor_6() { // ------------- Construct using specified Locale -------- converter = new BigIntegerLocaleConverter(localizedLocale, defaultIntegerPattern); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern, locPattern) constructor */ public void testConstructor_7() { // ------------- Construct using specified Locale -------- converter = new BigIntegerLocaleConverter(localizedLocale, localizedIntegerPattern, true); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(defaultValue) constructor */ public void testConstructor_8() { // ------------- Construct using specified Locale -------- converter = new BigIntegerLocaleConverter(defaultValue); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Converter(defaultValue, locPattern) constructor */ public void testConstructor_9() { // ------------- Construct using specified Locale -------- converter = new BigIntegerLocaleConverter(defaultValue, true); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Tries to convert to an unsupported type. This tests behavior of the base * class. All locale converters should react in the same way. */ public void testUnsupportedType() { converter = new BigIntegerLocaleConverter(); try { converter.convert(getClass(), "test", null); fail("Unsupported type not detected!"); } catch (ConversionException cex) { // expected result } } } ././@LongLink100644 0 0 172 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/ByteLocaleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/ByteLocaleC100644 0 0 23122 12262570607 30766 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; /** * Test Case for the ByteLocaleConverter class. * * @version $Id: ByteLocaleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ByteLocaleConverterTestCase extends BaseLocaleConverterTestCase { // ---------------------------------------------------------- Constructors public ByteLocaleConverterTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { super.setUp(); defaultIntegerPattern = "#,###"; defaultIntegerValue = ",123"; localizedIntegerPattern = "#.###"; localizedIntegerValue = ".123"; // Expected Values expectedDecimalValue = "123.56"; expectedIntegerValue = "123"; defaultValue = new Byte("99"); expectedValue = new Byte(expectedIntegerValue); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------------------ /** * Test Converter(defaultValue, locale, pattern, localizedPattern) constructor */ public void testConstructorMain() { // ------------- Construct with localized pattern ------------ converter = new ByteLocaleConverter(defaultValue, localizedLocale, localizedIntegerPattern, true); convertValueNoPattern(converter, "(A)", localizedIntegerValue, expectedValue); convertValueWithPattern(converter, "(A)", localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, "(A)", defaultValue); convertNull(converter, "(A)", defaultValue); // ************************************************************************** // Convert value in the wrong format - maybe you would expect it to throw an // exception and return the default - it doesn't, DecimalFormat parses it // quite happily turning ",123" into "0" // I guess this is one of the limitations of DecimalFormat // ************************************************************************** convertValueNoPattern(converter, "(B)", defaultIntegerValue, new Byte("0")); // ************************************************************************** // Convert with non-localized pattern // ************************************************************************** convertValueWithPattern(converter, "(B)", "123", defaultIntegerPattern, new Byte("123")); convertValueWithPattern(converter, "(B-2)", localizedIntegerValue, defaultIntegerPattern, defaultValue); // ************************************************************************** // Convert with specified type // // BaseLocaleConverter completely ignores the type - so even if we specify // Double.class here it still returns a Byte. // **** This has been changed due to BEANUTILS-449 **** // ************************************************************************** //convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue); // ------------- Construct with non-localized pattern ------------ converter = new ByteLocaleConverter(defaultValue, localizedLocale, defaultIntegerPattern, false); convertValueNoPattern(converter, "(C)", localizedIntegerValue, expectedValue); convertValueWithPattern(converter, "(C)", localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, "(C)", defaultValue); convertNull(converter, "(C)", defaultValue); } /** * Test Converter() constructor * * Uses the default locale, no default value * */ public void testConstructor_2() { // ------------- Construct using default locale ------------ converter = new ByteLocaleConverter(); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(locPattern) constructor * * Uses the default locale, no default value * */ public void testConstructor_3() { // ------------- Construct using localized pattern (default locale) -------- converter = new ByteLocaleConverter(true); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale) constructor */ public void testConstructor_4() { // ------------- Construct using specified Locale -------- converter = new ByteLocaleConverter(localizedLocale); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, locPattern) constructor */ public void testConstructor_5() { // ------------- Construct using specified Locale -------- converter = new ByteLocaleConverter(localizedLocale, true); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern) constructor */ public void testConstructor_6() { // ------------- Construct using specified Locale -------- converter = new ByteLocaleConverter(localizedLocale, defaultIntegerPattern); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern, locPattern) constructor */ public void testConstructor_7() { // ------------- Construct using specified Locale -------- converter = new ByteLocaleConverter(localizedLocale, localizedIntegerPattern, true); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(defaultValue) constructor */ public void testConstructor_8() { // ------------- Construct using specified Locale -------- converter = new ByteLocaleConverter(defaultValue); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Converter(defaultValue, locPattern) constructor */ public void testConstructor_9() { // ------------- Construct using specified Locale -------- converter = new ByteLocaleConverter(defaultValue, true); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } } ././@LongLink100644 0 0 172 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/DateLocaleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/DateLocaleC100644 0 0 36572 12262570607 30755 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.text.DateFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Locale; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Test Case for the DateLocaleConverter class. * * @version $Id: DateLocaleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class DateLocaleConverterTestCase extends BaseLocaleConverterTestCase { /** All logging goes through this logger */ private final Log log = LogFactory.getLog(DateLocaleConverterTestCase.class); protected String localizedDatePattern; protected String localizedDateValue; protected String localizedShortDateValue; protected String defaultDatePattern; protected String defaultDateValue; protected String defaultShortDateValue; protected boolean validLocalDateSymbols; // ------------------------------------------------------------------------ public DateLocaleConverterTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { super.setUp(); String version = System.getProperty("java.specification.version"); log.debug("JDK Version "+version); try { SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); expectedValue = format.parse("20041001"); defaultValue = format.parse("19670316"); } catch (Exception ex) { log.error("Error creating expected/default dates", ex); } // Default Locale (Use US) defaultLocale = Locale.US; defaultDatePattern = "d MMMM yyyy"; defaultDateValue = "1 October 2004"; defaultShortDateValue = "10/01/04"; // Use German Locale // localizedLocale = Locale.GERMAN; // N.B. doesn't work for dates // localizedLocale = Locale.GERMANY; // N.B. doesn't work for dates localizedLocale = new Locale("de", "AT"); // Austria/German works localizedDatePattern = "t MMMM uuuu"; localizedDateValue = "1 Oktober 2004"; localizedShortDateValue = "01.10.04"; // Test whether the "local pattern characters" are what we // are expecting - Locale.GERMAN and Locale.GERMANY, Locale.FRENCH all // returned the standard "English" pattern characters on my machine // for JDK 1.4 (JDK 1.3 was OK). The Austria/German locale was OK though String expectedChars = "GuMtkHmsSEDFwWahKzZ"; DateFormatSymbols localizedSymbols = new DateFormatSymbols(localizedLocale); String localChars = localizedSymbols.getLocalPatternChars(); // different JDK versions seem to have different numbers of pattern characters int lth = localChars.length() > expectedChars.length() ? expectedChars.length() : localChars.length() < expectedChars.length() ? localChars.length() : expectedChars.length(); validLocalDateSymbols = expectedChars.substring(0, lth).equals(localChars.substring(0, lth)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------------------ public void testSetLenient() { // make sure that date format works as expected SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.UK); // test with no leniency dateFormat.setLenient(false); try { dateFormat.parse("Feb 10, 2001"); } catch (ParseException e) { fail("Could not parse date (1) - " + e.getMessage()); } try { dateFormat.parse("Feb 31, 2001"); fail("Parsed illegal date (1)"); } catch (ParseException e) { // that's what we expected } // test with leniency dateFormat.setLenient(true); try { dateFormat.parse("Feb 10, 2001"); } catch (ParseException e) { fail("Could not parse date (2) - " + e.getMessage()); } try { dateFormat.parse("Feb 31, 2001"); } catch (ParseException e) { fail("Could not parse date (3) - " + e.getMessage()); } // now repeat tests for converter DateLocaleConverter converter = new DateLocaleConverter(Locale.UK, "MMM dd, yyyy"); // test with no leniency converter.setLenient(false); assertEquals("Set lenient failed", converter.isLenient(), false); try { converter.convert("Feb 10, 2001"); } catch (ConversionException e) { fail("Could not parse date (4) - " + e.getMessage()); } try { converter.convert("Feb 31, 2001"); assertEquals("Set lenient failed", converter.isLenient(), false); fail("Parsed illegal date (2)"); } catch (ConversionException e) { // that's what we expected } // test with leniency converter.setLenient(true); assertEquals("Set lenient failed", converter.isLenient(), true); try { converter.convert("Feb 10, 2001"); } catch (ConversionException e) { fail("Could not parse date (5) - " + e.getMessage()); } try { converter.convert("Feb 31, 2001"); } catch (ConversionException e) { fail("Could not parse date (6) - " + e.getMessage()); } } /** * Test Converter(defaultValue, locale, pattern, localizedPattern) constructor */ public void testConstructorMain() { // Skip this test if no valid symbols for the locale if (!validLocalDateSymbols) { log.error("Invalid locale symbols *** skipping testConstructorMain() **"); return; } // ------------- Construct with localized pattern ------------ converter = new DateLocaleConverter(defaultValue, localizedLocale, localizedDatePattern, true); convertValueNoPattern(converter, "(A)", localizedDateValue, expectedValue); convertValueWithPattern(converter, "(A)", localizedDateValue, localizedDatePattern, expectedValue); convertInvalid(converter, "(A)", defaultValue); convertNull(converter, "(A)", defaultValue); // Convert value in the wrong format - should return default value convertValueNoPattern(converter, "(B)", defaultDateValue, defaultValue); // Convert with non-localized pattern - should return default value convertValueWithPattern(converter, "(B)", localizedDateValue, defaultDatePattern, defaultValue); // ************************************************************************** // Convert with specified type // // BaseLocaleConverter completely ignores the type - so even if we specify // Double.class here it still returns a Date. // **** This has been changed due to BEANUTILS-449 **** // ************************************************************************** //convertValueToType(converter, "(B)", String.class, localizedDateValue, localizedDatePattern, expectedValue); // ------------- Construct with non-localized pattern ------------ converter = new DateLocaleConverter(defaultValue, localizedLocale, defaultDatePattern, false); convertValueNoPattern(converter, "(C)", localizedDateValue, expectedValue); convertValueWithPattern(converter, "(C)", localizedDateValue, defaultDatePattern, expectedValue); convertInvalid(converter, "(C)", defaultValue); convertNull(converter, "(C)", defaultValue); } /** * Test Converter() constructor * * Uses the default locale, no default value * */ public void testConstructor_2() { // ------------- Construct using default pattern & default locale ------------ converter = new DateLocaleConverter(); // Perform Tests convertValueNoPattern(converter, defaultShortDateValue, expectedValue); convertValueWithPattern(converter, defaultDateValue, defaultDatePattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(locPattern) constructor * * Uses the default locale, no default value * */ public void testConstructor_3() { // ------------- Construct using default pattern & default locale -------- converter = new DateLocaleConverter(true); // Perform Tests convertValueNoPattern(converter, defaultShortDateValue, expectedValue); convertValueWithPattern(converter, defaultDateValue, defaultDatePattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale) constructor */ public void testConstructor_4() { // ------------- Construct using specified Locale -------- converter = new DateLocaleConverter(localizedLocale); // Perform Tests convertValueNoPattern(converter, localizedShortDateValue, expectedValue); convertValueWithPattern(converter, localizedDateValue, defaultDatePattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, locPattern) constructor */ public void testConstructor_5() { // Skip this test if no valid symbols for the locale if (!validLocalDateSymbols) { log.error("Invalid locale symbols *** skipping testConstructor_5() **"); return; } // ------------- Construct using specified Locale -------- converter = new DateLocaleConverter(localizedLocale, true); // Perform Tests convertValueNoPattern(converter, localizedShortDateValue, expectedValue); convertValueWithPattern(converter, localizedDateValue, localizedDatePattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern) constructor */ public void testConstructor_6() { // ------------- Construct using specified Locale -------- converter = new DateLocaleConverter(localizedLocale, defaultDatePattern); // Perform Tests convertValueNoPattern(converter, localizedDateValue, expectedValue); convertValueWithPattern(converter, localizedDateValue, defaultDatePattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern, locPattern) constructor */ public void testConstructor_7() { // Skip this test if no valid symbols for the locale if (!validLocalDateSymbols) { log.error("Invalid locale symbols *** skipping testConstructor_7() **"); return; } // ------------- Construct using specified Locale -------- converter = new DateLocaleConverter(localizedLocale, localizedDatePattern, true); // Perform Tests convertValueNoPattern(converter, localizedDateValue, expectedValue); convertValueWithPattern(converter, localizedDateValue, localizedDatePattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(defaultValue) constructor */ public void testConstructor_8() { // ------------- Construct using specified Locale -------- converter = new DateLocaleConverter(defaultValue); // Perform Tests convertValueNoPattern(converter, defaultShortDateValue, expectedValue); convertValueWithPattern(converter, defaultDateValue, defaultDatePattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Converter(defaultValue, locPattern) constructor */ public void testConstructor_9() { // ------------- Construct using specified Locale -------- converter = new DateLocaleConverter(defaultValue, true); // Perform Tests convertValueNoPattern(converter, defaultShortDateValue, expectedValue); convertValueWithPattern(converter, defaultDateValue, defaultDatePattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test invalid date */ public void testInvalidDate() { converter = new DateLocaleConverter(defaultLocale); try { converter.convert("01/10/2004", "dd-MM-yyyy"); } catch (ConversionException e) { assertEquals("Parse Error", "Error parsing date '01/10/2004' at position=2", e.getMessage()); } try { converter.convert("01-10-2004X", "dd-MM-yyyy"); } catch (ConversionException e) { assertEquals("Parse Length", "Date '01-10-2004X' contains unparsed characters from position=10", e.getMessage()); } } /** * Test java.util.Date */ public void testDateObject() { converter = new DateLocaleConverter(defaultLocale); assertEquals("java.util.Date", expectedValue, converter.convert(expectedValue)); } /** * Test Calendar */ public void testCalendarObject() { converter = new DateLocaleConverter(defaultLocale); java.util.Calendar calendar = java.util.Calendar.getInstance(); calendar.setTime((java.util.Date)expectedValue); assertEquals("java.util.Calendar", expectedValue, converter.convert(calendar)); } } ././@LongLink100644 0 0 174 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/DoubleLocaleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/DoubleLocal100644 0 0 23052 12262570607 31027 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; /** * Test Case for the DoubleLocaleConverter class. * * @version $Id: DoubleLocaleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class DoubleLocaleConverterTestCase extends BaseLocaleConverterTestCase { // ---------------------------------------------------------- Constructors public DoubleLocaleConverterTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { super.setUp(); defaultValue = new Double("9.99"); expectedValue = new Double(expectedDecimalValue); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------------------ /** * Test Converter(defaultValue, locale, pattern, localizedPattern) constructor */ public void testConstructorMain() { // ------------- Construct with localized pattern ------------ converter = new DoubleLocaleConverter(defaultValue, localizedLocale, localizedDecimalPattern, true); convertValueNoPattern(converter, "(A)", localizedDecimalValue, expectedValue); convertValueWithPattern(converter, "(A)", localizedDecimalValue, localizedDecimalPattern, expectedValue); convertInvalid(converter, "(A)", defaultValue); convertNull(converter, "(A)", defaultValue); // ************************************************************************** // Convert value in the wrong format - maybe you would expect it to throw an // exception and return the default - it doesn't, DecimalFormat parses it // quite happily turning "1,234.56" into "1.234" // I guess this is one of the limitations of DecimalFormat // ************************************************************************** convertValueNoPattern(converter, "(B)", defaultDecimalValue, new Double("1.234")); // ************************************************************************** // Convert with non-localized pattern - this causes an exception in parse() // but it gets swallowed in convert() method and returns default. // **** IS THIS THE EXPECTED BEHAVIOUR? **** // Maybe if the pattern is no good, we should use a default pattern rather // than just returning the default value. // ************************************************************************** convertValueWithPattern(converter, "(B)", localizedDecimalValue, defaultDecimalPattern, defaultValue); // ************************************************************************** // Convert with specified type // // BaseLocaleConverter completely ignores the type - so even if we specify // Double.class here it still returns a Double. // **** This has been changed due to BEANUTILS-449 **** // ************************************************************************** //convertValueToType(converter, "(B)", Integer.class, localizedDecimalValue, localizedDecimalPattern, expectedValue); // ------------- Construct with non-localized pattern ------------ converter = new DoubleLocaleConverter(defaultValue, localizedLocale, defaultDecimalPattern, false); convertValueNoPattern(converter, "(C)", localizedDecimalValue, expectedValue); convertValueWithPattern(converter, "(C)", localizedDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, "(C)", defaultValue); convertNull(converter, "(C)", defaultValue); } /** * Test Converter() constructor * * Uses the default locale, no default value * */ public void testConstructor_2() { // ------------- Construct using default locale ------------ converter = new DoubleLocaleConverter(); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(locPattern) constructor * * Uses the default locale, no default value * */ public void testConstructor_3() { // ------------- Construct using localized pattern (default locale) -------- converter = new DoubleLocaleConverter(true); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale) constructor */ public void testConstructor_4() { // ------------- Construct using specified Locale -------- converter = new DoubleLocaleConverter(localizedLocale); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, locPattern) constructor */ public void testConstructor_5() { // ------------- Construct using specified Locale -------- converter = new DoubleLocaleConverter(localizedLocale, true); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, localizedDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern) constructor */ public void testConstructor_6() { // ------------- Construct using specified Locale -------- converter = new DoubleLocaleConverter(localizedLocale, defaultDecimalPattern); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern, locPattern) constructor */ public void testConstructor_7() { // ------------- Construct using specified Locale -------- converter = new DoubleLocaleConverter(localizedLocale, localizedDecimalPattern, true); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, localizedDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(defaultValue) constructor */ public void testConstructor_8() { // ------------- Construct using specified Locale -------- converter = new DoubleLocaleConverter(defaultValue); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Converter(defaultValue, locPattern) constructor */ public void testConstructor_9() { // ------------- Construct using specified Locale -------- converter = new DoubleLocaleConverter(defaultValue, true); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } } ././@LongLink100644 0 0 173 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/FloatLocaleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/FloatLocale100644 0 0 27720 12262570607 31035 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; import java.text.DecimalFormat; import java.util.Locale; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.locale.LocaleConvertUtils; /** * Test Case for the FloatLocaleConverter class. * * @version $Id: FloatLocaleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class FloatLocaleConverterTestCase extends BaseLocaleConverterTestCase { // ---------------------------------------------------------- Constructors public FloatLocaleConverterTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { super.setUp(); defaultValue = new Float("9.99"); expectedValue = new Float(expectedDecimalValue); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------------------ /** * Test Converter(defaultValue, locale, pattern, localizedPattern) constructor */ public void testConstructorMain() { // ------------- Construct with localized pattern ------------ converter = new FloatLocaleConverter(defaultValue, localizedLocale, localizedDecimalPattern, true); convertValueNoPattern(converter, "(A)", localizedDecimalValue, expectedValue); convertValueWithPattern(converter, "(A)", localizedDecimalValue, localizedDecimalPattern, expectedValue); convertInvalid(converter, "(A)", defaultValue); convertNull(converter, "(A)", defaultValue); // ************************************************************************** // Convert value in the wrong format - maybe you would expect it to throw an // exception and return the default - it doesn't, DecimalFormat parses it // quite happily turning "1,234.56" into "1.234" // I guess this is one of the limitations of DecimalFormat // ************************************************************************** convertValueNoPattern(converter, "(B)", defaultDecimalValue, new Float("1.234")); // ************************************************************************** // Convert with non-localized pattern - this causes an exception in parse() // but it gets swallowed in convert() method and returns default. // **** IS THIS THE EXPECTED BEHAVIOUR? **** // Maybe if the pattern is no good, we should use a default pattern rather // than just returning the default value. // ************************************************************************** convertValueWithPattern(converter, "(B)", localizedDecimalValue, defaultDecimalPattern, defaultValue); // ************************************************************************** // Convert with specified type // // BaseLocaleConverter completely ignores the type - so even if we specify // Float.class here it still returns a Float. // **** This has been changed due to BEANUTILS-449 **** // ************************************************************************** //convertValueToType(converter, "(B)", Integer.class, localizedDecimalValue, localizedDecimalPattern, expectedValue); // ------------- Construct with non-localized pattern ------------ converter = new FloatLocaleConverter(defaultValue, localizedLocale, defaultDecimalPattern, false); convertValueNoPattern(converter, "(C)", localizedDecimalValue, expectedValue); convertValueWithPattern(converter, "(C)", localizedDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, "(C)", defaultValue); convertNull(converter, "(C)", defaultValue); } /** * Test Converter() constructor * * Uses the default locale, no default value * */ public void testConstructor_2() { // ------------- Construct using default locale ------------ converter = new FloatLocaleConverter(); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(locPattern) constructor * * Uses the default locale, no default value * */ public void testConstructor_3() { // ------------- Construct using localized pattern (default locale) -------- converter = new FloatLocaleConverter(true); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale) constructor */ public void testConstructor_4() { // ------------- Construct using specified Locale -------- converter = new FloatLocaleConverter(localizedLocale); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, locPattern) constructor */ public void testConstructor_5() { // ------------- Construct using specified Locale -------- converter = new FloatLocaleConverter(localizedLocale, true); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, localizedDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern) constructor */ public void testConstructor_6() { // ------------- Construct using specified Locale -------- converter = new FloatLocaleConverter(localizedLocale, defaultDecimalPattern); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern, locPattern) constructor */ public void testConstructor_7() { // ------------- Construct using specified Locale -------- converter = new FloatLocaleConverter(localizedLocale, localizedDecimalPattern, true); // Perform Tests convertValueNoPattern(converter, localizedDecimalValue, expectedValue); convertValueWithPattern(converter, localizedDecimalValue, localizedDecimalPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(defaultValue) constructor */ public void testConstructor_8() { // ------------- Construct using specified Locale -------- converter = new FloatLocaleConverter(defaultValue); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Converter(defaultValue, locPattern) constructor */ public void testConstructor_9() { // ------------- Construct using specified Locale -------- converter = new FloatLocaleConverter(defaultValue, true); // Perform Tests convertValueNoPattern(converter, defaultDecimalValue, expectedValue); convertValueWithPattern(converter, defaultDecimalValue, defaultDecimalPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Float limits */ public void testFloatLimits() { converter = new FloatLocaleConverter(defaultLocale, defaultDecimalPattern); DecimalFormat fmt = new DecimalFormat("#.#############################################################"); assertEquals(new Float(-0.12), converter.convert("-0.12")); assertEquals("Positive Float.MAX_VALUE", new Float(Float.MAX_VALUE), converter.convert(fmt.format(Float.MAX_VALUE))); assertEquals("Positive Float.MIN_VALUE", new Float(Float.MIN_VALUE), converter.convert(fmt.format(Float.MIN_VALUE))); assertEquals("Negative Float.MAX_VALUE", new Float(Float.MAX_VALUE * -1), converter.convert(fmt.format(Float.MAX_VALUE * -1))); assertEquals("Negative Float.MIN_VALUE", new Float(Float.MIN_VALUE * -1), converter.convert(fmt.format(Float.MIN_VALUE * -1))); try { converter.convert(fmt.format((double)Float.MAX_VALUE * (double)10)); fail("Positive Too Large should throw ConversionException"); } catch (ConversionException e) { // expected result } try { converter.convert(fmt.format((double)Float.MAX_VALUE * (double)-10)); fail("Negative Too Large should throw ConversionException"); } catch (ConversionException e) { // expected result } try { converter.convert(fmt.format((double)Float.MIN_VALUE / (double)10)); fail("Positive Too Small should throw ConversionException"); } catch (ConversionException e) { // expected result } try { converter.convert(fmt.format((double)Float.MIN_VALUE / (double)-10)); fail("Negative Too Small should throw ConversionException"); } catch (ConversionException e) { // expected result } } /** * Test parsing zero - see BEANUTILS-351 */ public void testParseZero() { try { Object result = LocaleConvertUtils.convert("0", Float.class, Locale.US, null); assertEquals(new Float(0), result); } catch (ConversionException e) { fail("Zero threw ConversionException: " + e); } } } ././@LongLink100644 0 0 175 12262571655 10271 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/IntegerLocaleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/IntegerLoca100644 0 0 24516 12262570607 31044 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; /** * Test Case for the IntegerLocaleConverter class. * * @version $Id: IntegerLocaleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class IntegerLocaleConverterTestCase extends BaseLocaleConverterTestCase { // ---------------------------------------------------------- Constructors public IntegerLocaleConverterTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { super.setUp(); defaultValue = new Integer("999"); expectedValue = new Integer(expectedIntegerValue); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------------------ /** * Test Converter(defaultValue, locale, pattern, localizedPattern) constructor */ public void testConstructorMain() { // ------------- Construct with localized pattern ------------ converter = new IntegerLocaleConverter(defaultValue, localizedLocale, localizedIntegerPattern, true); convertValueNoPattern(converter, "(A)", localizedIntegerValue, expectedValue); convertValueWithPattern(converter, "(A)", localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, "(A)", defaultValue); convertNull(converter, "(A)", defaultValue); // ************************************************************************** // Convert value in the wrong format - maybe you would expect it to throw an // exception and return the default - it doesn't, DecimalFormat parses it // quite happily turning "1,234" into "1" // I guess this is one of the limitations of DecimalFormat // ************************************************************************** convertValueNoPattern(converter, "(B)", defaultIntegerValue, new Integer("1")); // ************************************************************************** // Convert with non-localized pattern - unlike the equivalent BigDecimal Test Case // it doesn't causes an exception in parse() - DecimalFormat parses it // quite happily turning "1,234" into "1" // Again this is one of the limitations of DecimalFormat // ************************************************************************** convertValueWithPattern(converter, "(B)", localizedIntegerValue, defaultIntegerPattern, new Integer("1")); // ************************************************************************** // Convert with specified type // // BaseLocaleConverter completely ignores the type - so even if we specify // Double.class here it still returns a Integer. // **** This has been changed due to BEANUTILS-449 **** // ************************************************************************** //convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue); // ------------- Construct with non-localized pattern ------------ converter = new IntegerLocaleConverter(defaultValue, localizedLocale, defaultIntegerPattern, false); convertValueNoPattern(converter, "(C)", localizedIntegerValue, expectedValue); convertValueWithPattern(converter, "(C)", localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, "(C)", defaultValue); convertNull(converter, "(C)", defaultValue); } /** * Test Converter() constructor * * Uses the default locale, no default value * */ public void testConstructor_2() { // ------------- Construct using default locale ------------ converter = new IntegerLocaleConverter(); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(locPattern) constructor * * Uses the default locale, no default value * */ public void testConstructor_3() { // ------------- Construct using localized pattern (default locale) -------- converter = new IntegerLocaleConverter(true); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale) constructor */ public void testConstructor_4() { // ------------- Construct using specified Locale -------- converter = new IntegerLocaleConverter(localizedLocale); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, locPattern) constructor */ public void testConstructor_5() { // ------------- Construct using specified Locale -------- converter = new IntegerLocaleConverter(localizedLocale, true); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern) constructor */ public void testConstructor_6() { // ------------- Construct using specified Locale -------- converter = new IntegerLocaleConverter(localizedLocale, defaultIntegerPattern); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern, locPattern) constructor */ public void testConstructor_7() { // ------------- Construct using specified Locale -------- converter = new IntegerLocaleConverter(localizedLocale, localizedIntegerPattern, true); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(defaultValue) constructor */ public void testConstructor_8() { // ------------- Construct using specified Locale -------- converter = new IntegerLocaleConverter(defaultValue); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Converter(defaultValue, locPattern) constructor */ public void testConstructor_9() { // ------------- Construct using specified Locale -------- converter = new IntegerLocaleConverter(defaultValue, true); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Converting a number */ public void testNumber() { // ------------- Construct using specified Locale -------- converter = new IntegerLocaleConverter(localizedLocale); Integer value = new Integer(1234); assertEquals("Convert Integer", value, converter.convert(value)); assertEquals("Convert Long", value, converter.convert(new Long(value.intValue()))); } /** * Tests whether a conversion to a primitive type can be performed. */ public void testToPrimitiveType() { converter = new IntegerLocaleConverter(); Integer value = 20131028; Class target = Integer.TYPE; int result = converter.convert(target, (Object) value.toString()); assertEquals("Wrong result", value.intValue(), result); } } ././@LongLink100644 0 0 172 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/LongLocaleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/LongLocaleC100644 0 0 22675 12262570607 30776 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; /** * Test Case for the LongLocaleConverter class. * * @version $Id: LongLocaleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class LongLocaleConverterTestCase extends BaseLocaleConverterTestCase { // ---------------------------------------------------------- Constructors public LongLocaleConverterTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { super.setUp(); defaultValue = new Long("999"); expectedValue = new Long(expectedIntegerValue); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------------------ /** * Test Converter(defaultValue, locale, pattern, localizedPattern) constructor */ public void testConstructorMain() { // ------------- Construct with localized pattern ------------ converter = new LongLocaleConverter(defaultValue, localizedLocale, localizedIntegerPattern, true); convertValueNoPattern(converter, "(A)", localizedIntegerValue, expectedValue); convertValueWithPattern(converter, "(A)", localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, "(A)", defaultValue); convertNull(converter, "(A)", defaultValue); // ************************************************************************** // Convert value in the wrong format - maybe you would expect it to throw an // exception and return the default - it doesn't, DecimalFormat parses it // quite happily turning "1,234" into "1" // I guess this is one of the limitations of DecimalFormat // ************************************************************************** convertValueNoPattern(converter, "(B)", defaultIntegerValue, new Long("1")); // ************************************************************************** // Convert with non-localized pattern - unlike the equivalent BigDecimal Test Case // it doesn't causes an exception in parse() - DecimalFormat parses it // quite happily turning "1,234" into "1" // Again this is one of the limitations of DecimalFormat // ************************************************************************** convertValueWithPattern(converter, "(B)", localizedIntegerValue, defaultIntegerPattern, new Long("1")); // ************************************************************************** // Convert with specified type // // BaseLocaleConverter completely ignores the type - so even if we specify // Double.class here it still returns a Long. // **** This has been changed due to BEANUTILS-449 **** // ************************************************************************** //convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue); // ------------- Construct with non-localized pattern ------------ converter = new LongLocaleConverter(defaultValue, localizedLocale, defaultIntegerPattern, false); convertValueNoPattern(converter, "(C)", localizedIntegerValue, expectedValue); convertValueWithPattern(converter, "(C)", localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, "(C)", defaultValue); convertNull(converter, "(C)", defaultValue); } /** * Test Converter() constructor * * Uses the default locale, no default value * */ public void testConstructor_2() { // ------------- Construct using default locale ------------ converter = new LongLocaleConverter(); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(locPattern) constructor * * Uses the default locale, no default value * */ public void testConstructor_3() { // ------------- Construct using localized pattern (default locale) -------- converter = new LongLocaleConverter(true); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale) constructor */ public void testConstructor_4() { // ------------- Construct using specified Locale -------- converter = new LongLocaleConverter(localizedLocale); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, locPattern) constructor */ public void testConstructor_5() { // ------------- Construct using specified Locale -------- converter = new LongLocaleConverter(localizedLocale, true); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern) constructor */ public void testConstructor_6() { // ------------- Construct using specified Locale -------- converter = new LongLocaleConverter(localizedLocale, defaultIntegerPattern); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern, locPattern) constructor */ public void testConstructor_7() { // ------------- Construct using specified Locale -------- converter = new LongLocaleConverter(localizedLocale, localizedIntegerPattern, true); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(defaultValue) constructor */ public void testConstructor_8() { // ------------- Construct using specified Locale -------- converter = new LongLocaleConverter(defaultValue); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Converter(defaultValue, locPattern) constructor */ public void testConstructor_9() { // ------------- Construct using specified Locale -------- converter = new LongLocaleConverter(defaultValue, true); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } } ././@LongLink100644 0 0 173 12262571655 10267 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/ShortLocaleConverterTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/converters/ShortLocale100644 0 0 22720 12262570607 31062 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale.converters; /** * Test Case for the ShortLocaleConverter class. * * @version $Id: ShortLocaleConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ShortLocaleConverterTestCase extends BaseLocaleConverterTestCase { // ---------------------------------------------------------- Constructors public ShortLocaleConverterTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { super.setUp(); defaultValue = new Short("999"); expectedValue = new Short(expectedIntegerValue); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------------------ /** * Test Converter(defaultValue, locale, pattern, localizedPattern) constructor */ public void testConstructorMain() { // ------------- Construct with localized pattern ------------ converter = new ShortLocaleConverter(defaultValue, localizedLocale, localizedIntegerPattern, true); convertValueNoPattern(converter, "(A)", localizedIntegerValue, expectedValue); convertValueWithPattern(converter, "(A)", localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, "(A)", defaultValue); convertNull(converter, "(A)", defaultValue); // ************************************************************************** // Convert value in the wrong format - maybe you would expect it to throw an // exception and return the default - it doesn't, DecimalFormat parses it // quite happily turning "1,234" into "1" // I guess this is one of the limitations of DecimalFormat // ************************************************************************** convertValueNoPattern(converter, "(B)", defaultIntegerValue, new Short("1")); // ************************************************************************** // Convert with non-localized pattern - unlike the equivalent BigDecimal Test Case // it doesn't causes an exception in parse() - DecimalFormat parses it // quite happily turning "1,234" into "1" // Again this is one of the limitations of DecimalFormat // ************************************************************************** convertValueWithPattern(converter, "(B)", localizedIntegerValue, defaultIntegerPattern, new Short("1")); // ************************************************************************** // Convert with specified type // // BaseLocaleConverter completely ignores the type - so even if we specify // Double.class here it still returns a Short. // **** This has been changed due to BEANUTILS-449 **** // ************************************************************************** //convertValueToType(converter, "(B)", Double.class, localizedIntegerValue, localizedIntegerPattern, expectedValue); // ------------- Construct with non-localized pattern ------------ converter = new ShortLocaleConverter(defaultValue, localizedLocale, defaultIntegerPattern, false); convertValueNoPattern(converter, "(C)", localizedIntegerValue, expectedValue); convertValueWithPattern(converter, "(C)", localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, "(C)", defaultValue); convertNull(converter, "(C)", defaultValue); } /** * Test Converter() constructor * * Uses the default locale, no default value * */ public void testConstructor_2() { // ------------- Construct using default locale ------------ converter = new ShortLocaleConverter(); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(locPattern) constructor * * Uses the default locale, no default value * */ public void testConstructor_3() { // ------------- Construct using localized pattern (default locale) -------- converter = new ShortLocaleConverter(true); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale) constructor */ public void testConstructor_4() { // ------------- Construct using specified Locale -------- converter = new ShortLocaleConverter(localizedLocale); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, locPattern) constructor */ public void testConstructor_5() { // ------------- Construct using specified Locale -------- converter = new ShortLocaleConverter(localizedLocale, true); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern) constructor */ public void testConstructor_6() { // ------------- Construct using specified Locale -------- converter = new ShortLocaleConverter(localizedLocale, defaultIntegerPattern); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(Locale, pattern, locPattern) constructor */ public void testConstructor_7() { // ------------- Construct using specified Locale -------- converter = new ShortLocaleConverter(localizedLocale, localizedIntegerPattern, true); // Perform Tests convertValueNoPattern(converter, localizedIntegerValue, expectedValue); convertValueWithPattern(converter, localizedIntegerValue, localizedIntegerPattern, expectedValue); convertInvalid(converter, null); convertNull(converter, null); } /** * Test Converter(defaultValue) constructor */ public void testConstructor_8() { // ------------- Construct using specified Locale -------- converter = new ShortLocaleConverter(defaultValue); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } /** * Test Converter(defaultValue, locPattern) constructor */ public void testConstructor_9() { // ------------- Construct using specified Locale -------- converter = new ShortLocaleConverter(defaultValue, true); // Perform Tests convertValueNoPattern(converter, defaultIntegerValue, expectedValue); convertValueWithPattern(converter, defaultIntegerValue, defaultIntegerPattern, expectedValue); convertInvalid(converter, defaultValue); convertNull(converter, defaultValue); } } ././@LongLink100644 0 0 157 12262571655 10271 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/LocaleBeanificationTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/LocaleBeanificationTes100644 0 0 51041 12262570607 30776 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.Locale; import java.util.Map; import java.util.WeakHashMap; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.BeanUtilsTestCase; import org.apache.commons.beanutils.ContextClassLoaderLocal; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.PrimitiveBean; import org.apache.commons.beanutils.locale.converters.LongLocaleConverter; import org.apache.commons.logging.LogFactory; /** *

          * Test Case for changes made during LocaleBeanutils Beanification. * This is basically a cut-and-correct version of the beanutils beanifications tests. *

          * * @version $Id: LocaleBeanificationTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class LocaleBeanificationTestCase extends TestCase { // ---------------------------------------------------- Constants /** Maximum number of iterations before our test fails */ public static final int MAX_GC_ITERATIONS = 50; // ---------------------------------------------------- Instance Variables // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public LocaleBeanificationTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { LocaleConvertUtils.deregister(); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(LocaleBeanificationTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { // No action required } // ------------------------------------------------ Individual Test Methods /** Test of the methodology we'll use for some of the later tests */ public void testMemoryTestMethodology() throws Exception { // test methodology // many thanks to Juozas Baliuka for suggesting this method ClassLoader loader = new ClassLoader(this.getClass().getClassLoader()) {}; WeakReference reference = new WeakReference(loader); Class myClass = loader.loadClass("org.apache.commons.beanutils.BetaBean"); assertNotNull("Weak reference released early", reference.get()); // dereference class loader and class: loader = null; myClass = null; int iterations = 0; int bytz = 2; while(true) { System.gc(); if(iterations++ > MAX_GC_ITERATIONS){ fail("Max iterations reached before resource released."); } if( reference.get() == null ) { break; } else { // create garbage: byte[] b = new byte[bytz]; bytz = bytz * 2; } } } /** Tests whether classloaders and beans are released from memory by the map used by beanutils */ public void testMemoryLeak2() throws Exception { // tests when the map used by beanutils has the right behaviour if (BeanUtilsTestCase.isPre14JVM()) { System.out.println("WARNING: CANNOT TEST MEMORY LEAK ON PRE1.4 JVM"); return; } // many thanks to Juozas Baliuka for suggesting this methodology TestClassLoader loader = new TestClassLoader(); ReferenceQueue queue = new ReferenceQueue(); WeakReference loaderReference = new WeakReference(loader, queue); Integer test = new Integer(1); WeakReference testReference = new WeakReference(test, queue); //Map map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.HARD, true); Map map = new WeakHashMap(); map.put(loader, test); assertEquals("In map", test, map.get(loader)); assertNotNull("Weak reference released early (1)", loaderReference.get()); assertNotNull("Weak reference released early (2)", testReference.get()); // dereference strong references loader = null; test = null; int iterations = 0; int bytz = 2; while(true) { System.gc(); if(iterations++ > MAX_GC_ITERATIONS){ fail("Max iterations reached before resource released."); } map.isEmpty(); if( loaderReference.get() == null && testReference.get() == null) { break; } else { // create garbage: byte[] b = new byte[bytz]; bytz = bytz * 2; } } } /** Tests whether classloaders and beans are released from memory */ public void testMemoryLeak() throws Exception { if (BeanUtilsTestCase.isPre14JVM()) { System.out.println("WARNING: CANNOT TEST MEMORY LEAK ON PRE1.4 JVM"); return; } // many thanks to Juozas Baliuka for suggesting this methodology TestClassLoader loader = new TestClassLoader(); WeakReference loaderReference = new WeakReference(loader); LocaleBeanUtilsBean.getLocaleBeanUtilsInstance(); class GetBeanUtilsBeanThread extends Thread { LocaleBeanUtilsBean beanUtils; LocaleConvertUtilsBean convertUtils; GetBeanUtilsBeanThread() {} @Override public void run() { beanUtils = LocaleBeanUtilsBean.getLocaleBeanUtilsInstance(); convertUtils = LocaleConvertUtilsBean.getInstance(); // XXX Log keeps a reference around! LogFactory.releaseAll(); } @Override public String toString() { return "GetBeanUtilsBeanThread"; } } GetBeanUtilsBeanThread thread = new GetBeanUtilsBeanThread(); WeakReference threadWeakReference = new WeakReference(thread); thread.setContextClassLoader(loader); thread.start(); thread.join(); WeakReference beanUtilsReference = new WeakReference(thread.beanUtils); WeakReference convertUtilsReference = new WeakReference(thread.convertUtils); assertNotNull("Weak reference released early (1)", loaderReference.get()); assertNotNull("Weak reference released early (2)", beanUtilsReference.get()); assertNotNull("Weak reference released early (4)", convertUtilsReference.get()); // dereference strong references loader = null; thread.setContextClassLoader(null); thread = null; int iterations = 0; int bytz = 2; while(true) { LocaleBeanUtilsBean.getLocaleBeanUtilsInstance(); System.gc(); if(iterations++ > MAX_GC_ITERATIONS){ fail("Max iterations reached before resource released."); } if( loaderReference.get() == null && beanUtilsReference.get() == null && convertUtilsReference.get() == null) { break; } else { // create garbage: byte[] b = new byte[bytz]; bytz = bytz * 2; } } } /** * Tests whether difference instances are loaded by different * context classloaders. */ public void testGetByContextClassLoader() throws Exception { class GetBeanUtilsBeanThread extends Thread { private final Signal signal; GetBeanUtilsBeanThread(Signal signal) { this.signal = signal; } @Override public void run() { signal.setSignal(2); signal.setBean(LocaleBeanUtilsBean.getLocaleBeanUtilsInstance()); signal.setConvertUtils(LocaleConvertUtilsBean.getInstance()); } @Override public String toString() { return "GetBeanUtilsBeanThread"; } } Signal signal = new Signal(); signal.setSignal(1); GetBeanUtilsBeanThread thread = new GetBeanUtilsBeanThread(signal); thread.setContextClassLoader(new TestClassLoader()); thread.start(); thread.join(); assertEquals("Signal not set by test thread", 2, signal.getSignal()); assertTrue( "Different LocaleBeanUtilsBean instances per context classloader", LocaleBeanUtilsBean.getInstance() != signal.getBean()); assertTrue( "Different LocaleConvertUtilsBean instances per context classloader", LocaleConvertUtilsBean.getInstance() != signal.getConvertUtils()); } /** * Tests whether difference instances are loaded by different * context classloaders. */ public void testContextClassLoaderLocal() throws Exception { class CCLLTesterThread extends Thread { private final Signal signal; private final ContextClassLoaderLocal ccll; CCLLTesterThread(Signal signal, ContextClassLoaderLocal ccll) { this.signal = signal; this.ccll = ccll; } @Override public void run() { ccll.set(new Integer(1789)); signal.setSignal(2); signal.setMarkerObject(ccll.get()); } @Override public String toString() { return "CCLLTesterThread"; } } ContextClassLoaderLocal ccll = new ContextClassLoaderLocal(); ccll.set(1776); assertEquals("Start thread sets value", new Integer(1776), ccll.get()); Signal signal = new Signal(); signal.setSignal(1); CCLLTesterThread thread = new CCLLTesterThread(signal, ccll); thread.setContextClassLoader(new TestClassLoader()); thread.start(); thread.join(); assertEquals("Signal not set by test thread", 2, signal.getSignal()); assertEquals("Second thread preserves value", new Integer(1776), ccll.get()); assertEquals("Second thread gets value it set", new Integer(1789), signal.getMarkerObject()); } /** Tests whether calls are independent for different classloaders */ public void testContextClassloaderIndependence() throws Exception { class TestIndependenceThread extends Thread { private final Signal signal; private final PrimitiveBean bean; TestIndependenceThread(Signal signal, PrimitiveBean bean) { this.signal = signal; this.bean = bean; } @Override public void run() { try { signal.setSignal(3); LocaleConvertUtils.register(new LocaleConverter() { public T convert(Class type, Object value) { return ConvertUtils.primitiveToWrapper(type).cast(9); } public T convert(Class type, Object value, String pattern) { return ConvertUtils.primitiveToWrapper(type).cast(9); } }, Integer.TYPE, Locale.getDefault()); LocaleBeanUtils.setProperty(bean, "int", "1"); } catch (Exception e) { e.printStackTrace(); signal.setException(e); } } @Override public String toString() { return "TestIndependenceThread"; } } PrimitiveBean bean = new PrimitiveBean(); LocaleBeanUtils.setProperty(bean, "int", new Integer(1)); assertEquals("Wrong property value (1)", 1, bean.getInt()); LocaleConvertUtils.register(new LocaleConverter() { public T convert(Class type, Object value) { return ConvertUtils.primitiveToWrapper(type).cast(5); } public T convert(Class type, Object value, String pattern) { return ConvertUtils.primitiveToWrapper(type).cast(5); } }, Integer.TYPE, Locale.getDefault()); LocaleBeanUtils.setProperty(bean, "int", "1"); assertEquals("Wrong property value(2)", 5, bean.getInt()); Signal signal = new Signal(); signal.setSignal(1); TestIndependenceThread thread = new TestIndependenceThread(signal, bean); thread.setContextClassLoader(new TestClassLoader()); thread.start(); thread.join(); assertNull("Exception thrown by test thread:" + signal.getException(), signal.getException()); assertEquals("Signal not set by test thread", 3, signal.getSignal()); assertEquals("Wrong property value(3)", 9, bean.getInt()); } /** Tests whether different threads can set beanutils instances correctly */ public void testBeanUtilsBeanSetInstance() throws Exception { class SetInstanceTesterThread extends Thread { private final Signal signal; private final LocaleBeanUtilsBean bean; SetInstanceTesterThread(Signal signal, LocaleBeanUtilsBean bean) { this.signal = signal; this.bean = bean; } @Override public void run() { LocaleBeanUtilsBean.setInstance(bean); signal.setSignal(21); signal.setBean(LocaleBeanUtilsBean.getLocaleBeanUtilsInstance()); } @Override public String toString() { return "SetInstanceTesterThread"; } } Signal signal = new Signal(); signal.setSignal(1); LocaleBeanUtilsBean beanOne = new LocaleBeanUtilsBean(); LocaleBeanUtilsBean beanTwo = new LocaleBeanUtilsBean(); SetInstanceTesterThread thread = new SetInstanceTesterThread(signal, beanTwo); thread.setContextClassLoader(new TestClassLoader()); LocaleBeanUtilsBean.setInstance(beanOne); assertEquals("Start thread gets right instance", beanOne, LocaleBeanUtilsBean.getLocaleBeanUtilsInstance()); thread.start(); thread.join(); assertEquals("Signal not set by test thread", 21, signal.getSignal()); assertEquals("Second thread preserves value", beanOne, LocaleBeanUtilsBean.getLocaleBeanUtilsInstance()); assertEquals("Second thread gets value it set", beanTwo, signal.getBean()); } /** Tests whether the unset method works*/ public void testContextClassLoaderUnset() throws Exception { LocaleBeanUtilsBean beanOne = new LocaleBeanUtilsBean(); ContextClassLoaderLocal ccll = new ContextClassLoaderLocal(); ccll.set(beanOne); assertEquals("Start thread gets right instance", beanOne, ccll.get()); ccll.unset(); assertTrue("Unset works", !beanOne.equals(ccll.get())); } /** * Test registering a locale-aware converter with the standard ConvertUtils. */ public void testLocaleAwareConverterInConvertUtils() throws Exception { try { // first use the default non-locale-aware converter try { Long data = (Long) ConvertUtils.convert("777", Long.class); assertEquals("Standard format long converted ok", 777, data.longValue()); } catch(ConversionException ex) { fail("Unable to convert non-locale-aware number 777"); } // now try default converter with special delimiters try { // This conversion will cause an error. But the default // Long converter is set up to return a default value of // zero on error. Long data = (Long) ConvertUtils.convert("1.000.000", Long.class); assertEquals("Standard format behaved as expected", 0, data.longValue()); } catch(ConversionException ex) { fail("Unexpected exception from standard Long converter."); } // Now try using a locale-aware converter together with // locale-specific input string. Note that in the german locale, // large numbers can be split up into groups of three digits // using a dot character (and comma is the decimal-point indicator). try { Locale germanLocale = Locale.GERMAN; LongLocaleConverter longLocaleConverter = new LongLocaleConverter(germanLocale); ConvertUtils.register(longLocaleConverter, Long.class); Long data = (Long) ConvertUtils.convert("1.000.000", Long.class); assertEquals("German-format long converted ok", 1000000, data.longValue()); } catch(ConversionException ex) { fail("Unable to convert german-format number"); } } finally { ConvertUtils.deregister(); } } // ---- Auxillary classes class TestClassLoader extends ClassLoader { @Override public String toString() { return "TestClassLoader"; } } class Signal { private Exception e; private int signal = 0; private LocaleBeanUtilsBean bean; private LocaleConvertUtilsBean convertUtils; private Object marker; public Exception getException() { return e; } public void setException(Exception e) { this.e = e; } public int getSignal() { return signal; } public void setSignal(int signal) { this.signal = signal; } public Object getMarkerObject() { return marker; } public void setMarkerObject(Object marker) { this.marker = marker; } public LocaleBeanUtilsBean getBean() { return bean; } public void setBean(LocaleBeanUtilsBean bean) { this.bean = bean; } public LocaleConvertUtilsBean getConvertUtils() { return convertUtils; } public void setConvertUtils(LocaleConvertUtilsBean convertUtils) { this.convertUtils = convertUtils; } } } ././@LongLink100644 0 0 153 12262571655 10265 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/LocaleBeanUtilsTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/LocaleBeanUtilsTestCas100644 0 0 6506 12262570607 30732 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.beanutils.TestBean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Test Case for {@link LocaleBeanUtils}. * * @version $Id: LocaleBeanUtilsTestCase.java 1454606 2013-03-08 22:30:51Z britter $ */ public class LocaleBeanUtilsTestCase extends TestCase { private static Log log = LogFactory.getLog(LocaleBeanUtilsTestCase.class); /** * Construct a new instance of this test case. * * @param name Name of the test case */ public LocaleBeanUtilsTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { } /** * Return the tests included in this test suite. * @return Test Suite */ public static Test suite() { return (new TestSuite(LocaleBeanUtilsTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { } // ------------------------------------------------ Individual Test Methods /** * Test setting a nested simple property */ public void testSetNestedPropertySimple() { TestBean bean = new TestBean(); bean.getNested().setIntProperty(5); assertEquals("Initial value 5", 5, bean.getNested().getIntProperty()); try { LocaleBeanUtils.setProperty(bean, "nested.intProperty", "123", null); } catch (Throwable t) { log.error(t); fail("Threw " + t); } assertEquals("Check Set Value", 123, bean.getNested().getIntProperty()); } /** * Test setting a nested indexed property */ public void testSetNestedPropertyIndexed() { TestBean bean = new TestBean(); bean.getNested().setIntIndexed(1, 51); assertEquals("Initial value[1] 51", 51, bean.getNested().getIntIndexed(1)); try { LocaleBeanUtils.setProperty(bean, "nested.intIndexed[1]", "123", null); } catch (Throwable t) { log.error(t); fail("Threw " + t); } assertEquals("Check Set Value", 123, bean.getNested().getIntIndexed(1)); } } ././@LongLink100644 0 0 152 12262571655 10264 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/LocaleConvertTestSuite.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/LocaleConvertTestSuite100644 0 0 5573 12262570607 31052 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.beanutils.locale.converters.BigDecimalLocaleConverterTestCase; import org.apache.commons.beanutils.locale.converters.BigIntegerLocaleConverterTestCase; import org.apache.commons.beanutils.locale.converters.ByteLocaleConverterTestCase; import org.apache.commons.beanutils.locale.converters.DateLocaleConverterTestCase; import org.apache.commons.beanutils.locale.converters.DoubleLocaleConverterTestCase; import org.apache.commons.beanutils.locale.converters.FloatLocaleConverterTestCase; import org.apache.commons.beanutils.locale.converters.IntegerLocaleConverterTestCase; import org.apache.commons.beanutils.locale.converters.LongLocaleConverterTestCase; import org.apache.commons.beanutils.locale.converters.ShortLocaleConverterTestCase; /** *

          * Created a test suite so that new test cases can be added here without having to * edit the build.xml. *

          * * @version $Id: LocaleConvertTestSuite.java 1454597 2013-03-08 21:58:12Z britter $ */ public class LocaleConvertTestSuite { /** * Return the tests included in this test suite. */ public static Test suite() { TestSuite testSuite = new TestSuite(); testSuite.addTestSuite(LocaleConvertUtilsTestCase.class); testSuite.addTestSuite(LocaleBeanificationTestCase.class); testSuite.addTestSuite(BigDecimalLocaleConverterTestCase.class); testSuite.addTestSuite(BigIntegerLocaleConverterTestCase.class); testSuite.addTestSuite(ByteLocaleConverterTestCase.class); testSuite.addTestSuite(DateLocaleConverterTestCase.class); testSuite.addTestSuite(DoubleLocaleConverterTestCase.class); testSuite.addTestSuite(FloatLocaleConverterTestCase.class); testSuite.addTestSuite(IntegerLocaleConverterTestCase.class); testSuite.addTestSuite(LongLocaleConverterTestCase.class); testSuite.addTestSuite(ShortLocaleConverterTestCase.class); return testSuite; } } ././@LongLink100644 0 0 156 12262571655 10270 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/locale/LocaleConvertUtilsTest100644 0 0 61251 12262570607 31074 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.locale; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.ConversionException; /** *

          * Test Case for the LocaleConvertUtils class. * See unimplemented functionality of the convert utils in the method begining with fixme *

          * * @version $Id: LocaleConvertUtilsTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class LocaleConvertUtilsTestCase extends TestCase { // ---------------------------------------------------- Instance Variables private char m_decimalSeparator; // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public LocaleConvertUtilsTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { LocaleConvertUtils.deregister(); NumberFormat nf = DecimalFormat.getNumberInstance(); String result = nf.format(1.1); // could be commas instead of stops in Europe. m_decimalSeparator = result.charAt(1); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(LocaleConvertUtilsTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { // No action required } // ------------------------------------------------ Individual Test Methods /** * Negative String to primitive integer array tests. */ public void fixmetestNegativeIntegerArray() { fail("Array conversions not implemented yet."); Object value = null; int intArray[] = new int[0]; value = LocaleConvertUtils.convert((String) null, intArray.getClass()); checkIntegerArray(value, intArray); value = LocaleConvertUtils.convert("a", intArray.getClass()); checkIntegerArray(value, intArray); value = LocaleConvertUtils.convert("{ a }", intArray.getClass()); checkIntegerArray(value, intArray); value = LocaleConvertUtils.convert("1a3", intArray.getClass()); checkIntegerArray(value, intArray); value = LocaleConvertUtils.convert("{ 1a3 }", intArray.getClass()); checkIntegerArray(value, intArray); value = LocaleConvertUtils.convert("0,1a3", intArray.getClass()); checkIntegerArray(value, intArray); value = LocaleConvertUtils.convert("{ 0, 1a3 }", intArray.getClass()); checkIntegerArray(value, intArray); } /** * Negative scalar conversion tests. These rely on the standard * default value conversions in LocaleConvertUtils. */ public void testNegativeScalar() { /* fixme Boolean converters not implemented at this point value = LocaleConvertUtils.convert("foo", Boolean.TYPE); ... value = LocaleConvertUtils.convert("foo", Boolean.class); ... */ try { LocaleConvertUtils.convert("foo", Byte.TYPE); fail("Should have thrown conversion exception (1)"); } catch (ConversionException e) { // Expected result } try { LocaleConvertUtils.convert("foo", Byte.class); fail("Should have thrown conversion exception (2)"); } catch (ConversionException e) { // Expected result } /* fixme - not implemented try { value = LocaleConvertUtils.convert("org.apache.commons.beanutils.Undefined", Class.class); fail("Should have thrown conversion exception"); } catch (ConversionException e) { ; // Expected result } */ try { LocaleConvertUtils.convert("foo", Double.TYPE); fail("Should have thrown conversion exception (3)"); } catch (ConversionException e) { // Expected result } try { LocaleConvertUtils.convert("foo", Double.class); fail("Should have thrown conversion exception (4)"); } catch (ConversionException e) { // Expected result } try { LocaleConvertUtils.convert("foo", Float.TYPE); fail("Should have thrown conversion exception (5)"); } catch (ConversionException e) { // Expected result } try { LocaleConvertUtils.convert("foo", Float.class); fail("Should have thrown conversion exception (6)"); } catch (ConversionException e) { // Expected result } try { LocaleConvertUtils.convert("foo", Integer.TYPE); fail("Should have thrown conversion exception (7)"); } catch (ConversionException e) { // Expected result } try { LocaleConvertUtils.convert("foo", Integer.class); fail("Should have thrown conversion exception (8)"); } catch (ConversionException e) { // Expected result } try { LocaleConvertUtils.convert("foo", Byte.TYPE); fail("Should have thrown conversion exception (9)"); } catch (ConversionException e) { // Expected result } try { LocaleConvertUtils.convert("foo", Long.class); fail("Should have thrown conversion exception (10)"); } catch (ConversionException e) { // Expected result } try { LocaleConvertUtils.convert("foo", Short.TYPE); fail("Should have thrown conversion exception (11)"); } catch (ConversionException e) { // Expected result } try { LocaleConvertUtils.convert("foo", Short.class); fail("Should have thrown conversion exception (12)"); } catch (ConversionException e) { // Expected result } } /** * Negative String to String array tests. */ public void fixmetestNegativeStringArray() { fail("Array conversions not implemented yet."); Object value = null; String stringArray[] = new String[0]; value = LocaleConvertUtils.convert((String) null, stringArray.getClass()); checkStringArray(value, stringArray); } /** * Test conversion of object to string for arrays - . */ public void fixmetestObjectToStringArray() { fail("Array conversions not implemented yet."); int intArray0[] = new int[0]; int intArray1[] = {123}; int intArray2[] = {123, 456}; String stringArray0[] = new String[0]; String stringArray1[] = {"abc"}; String stringArray2[] = {"abc", "def"}; assertEquals("intArray0", null, LocaleConvertUtils.convert(intArray0)); assertEquals("intArray1", "123", LocaleConvertUtils.convert(intArray1)); assertEquals("intArray2", "123", LocaleConvertUtils.convert(intArray2)); assertEquals("stringArray0", null, LocaleConvertUtils.convert(stringArray0)); assertEquals("stringArray1", "abc", LocaleConvertUtils.convert(stringArray1)); assertEquals("stringArray2", "abc", LocaleConvertUtils.convert(stringArray2)); } /** * Test conversion of object to string for scalars. */ public void testObjectToStringScalar() { assertEquals("Boolean->String", "false", LocaleConvertUtils.convert(Boolean.FALSE)); assertEquals("Boolean->String", "true", LocaleConvertUtils.convert(Boolean.TRUE)); assertEquals("Byte->String", "123", LocaleConvertUtils.convert(new Byte((byte) 123))); assertEquals("Character->String", "a", LocaleConvertUtils.convert(new Character('a'))); assertEquals("Double->String", "123" + m_decimalSeparator + "4", LocaleConvertUtils.convert(new Double(123.4))); assertEquals("Float->String", "123" + m_decimalSeparator + "4", LocaleConvertUtils.convert(new Float((float) 123.4))); assertEquals("Integer->String", "123", LocaleConvertUtils.convert(new Integer(123))); assertEquals("Long->String", "123", LocaleConvertUtils.convert(new Long(123))); assertEquals("Short->String", "123", LocaleConvertUtils.convert(new Short((short) 123))); assertEquals("String->String", "abc", LocaleConvertUtils.convert("abc")); assertEquals("String->String null", null, LocaleConvertUtils.convert(null)); } /** * Positive array conversion tests. */ public void fixmetestPositiveArray() { fail("Array conversions not implemented yet."); String values1[] = {"10", "20", "30"}; Object value = LocaleConvertUtils.convert(values1, Integer.TYPE); int shape[] = new int[0]; assertEquals(shape.getClass(), value.getClass()); int results1[] = (int[]) value; assertEquals(results1[0], 10); assertEquals(results1[1], 20); assertEquals(results1[2], 30); String values2[] = {"100", "200", "300"}; value = LocaleConvertUtils.convert(values2, shape.getClass()); assertEquals(shape.getClass(), value.getClass()); int results2[] = (int[]) value; assertEquals(results2[0], 100); assertEquals(results2[1], 200); assertEquals(results2[2], 300); } /** * Positive String to primitive integer array tests. */ public void fixmetestPositiveIntegerArray() { fail("Array conversions not implemented yet."); Object value = null; int intArray[] = new int[0]; int intArray1[] = new int[]{0}; int intArray2[] = new int[]{0, 10}; value = LocaleConvertUtils.convert("{ }", intArray.getClass()); checkIntegerArray(value, intArray); value = LocaleConvertUtils.convert("0", intArray.getClass()); checkIntegerArray(value, intArray1); value = LocaleConvertUtils.convert(" 0 ", intArray.getClass()); checkIntegerArray(value, intArray1); value = LocaleConvertUtils.convert("{ 0 }", intArray.getClass()); checkIntegerArray(value, intArray1); value = LocaleConvertUtils.convert("0,10", intArray.getClass()); checkIntegerArray(value, intArray2); value = LocaleConvertUtils.convert("0 10", intArray.getClass()); checkIntegerArray(value, intArray2); value = LocaleConvertUtils.convert("{0,10}", intArray.getClass()); checkIntegerArray(value, intArray2); value = LocaleConvertUtils.convert("{0 10}", intArray.getClass()); checkIntegerArray(value, intArray2); value = LocaleConvertUtils.convert("{ 0, 10 }", intArray.getClass()); checkIntegerArray(value, intArray2); value = LocaleConvertUtils.convert("{ 0 10 }", intArray.getClass()); checkIntegerArray(value, intArray2); } /** * Positive scalar conversion tests. */ public void testPositiveScalar() { Object value = null; /* fixme Boolean converters not implemented value = LocaleConvertUtils.convert("true", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = LocaleConvertUtils.convert("true", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = LocaleConvertUtils.convert("yes", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = LocaleConvertUtils.convert("yes", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = LocaleConvertUtils.convert("y", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = LocaleConvertUtils.convert("y", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = LocaleConvertUtils.convert("on", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = LocaleConvertUtils.convert("on", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), true); value = LocaleConvertUtils.convert("false", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = LocaleConvertUtils.convert("false", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = LocaleConvertUtils.convert("no", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = LocaleConvertUtils.convert("no", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = LocaleConvertUtils.convert("n", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = LocaleConvertUtils.convert("n", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = LocaleConvertUtils.convert("off", Boolean.TYPE); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); value = LocaleConvertUtils.convert("off", Boolean.class); assertTrue(value instanceof Boolean); assertEquals(((Boolean) value).booleanValue(), false); */ value = LocaleConvertUtils.convert("123", Byte.TYPE); assertTrue(value instanceof Byte); assertEquals(((Byte) value).byteValue(), (byte) 123); value = LocaleConvertUtils.convert("123", Byte.class); assertTrue(value instanceof Byte); assertEquals(((Byte) value).byteValue(), (byte) 123); /*fixme Character conversion not implemented yet value = LocaleConvertUtils.convert("a", Character.TYPE); assertTrue(value instanceof Character); assertEquals(((Character) value).charValue(), 'a'); value = LocaleConvertUtils.convert("a", Character.class); assertTrue(value instanceof Character); assertEquals(((Character) value).charValue(), 'a'); */ /* fixme - this is a discrepancy with standard converters ( probably not major issue ) value = LocaleConvertUtils.convert("java.lang.String", Class.class); assertTrue(value instanceof Class); assertEquals(String.class, (Class) value); */ value = LocaleConvertUtils.convert("123" + m_decimalSeparator + "456", Double.TYPE); assertTrue(value instanceof Double); assertEquals(((Double) value).doubleValue(), 123.456, 0.005); value = LocaleConvertUtils.convert("123" + m_decimalSeparator + "456", Double.class); assertTrue(value instanceof Double); assertEquals(((Double) value).doubleValue(), 123.456, 0.005); value = LocaleConvertUtils.convert("123" + m_decimalSeparator + "456", Float.TYPE); assertTrue(value instanceof Float); assertEquals(((Float) value).floatValue(), (float) 123.456, (float) 0.005); value = LocaleConvertUtils.convert("123" + m_decimalSeparator + "456", Float.class); assertTrue(value instanceof Float); assertEquals(((Float) value).floatValue(), (float) 123.456, (float) 0.005); value = LocaleConvertUtils.convert("123", Integer.TYPE); assertTrue(value instanceof Integer); assertEquals(((Integer) value).intValue(), 123); value = LocaleConvertUtils.convert("123", Integer.class); assertTrue(value instanceof Integer); assertEquals(((Integer) value).intValue(), 123); value = LocaleConvertUtils.convert("123", Long.TYPE); assertTrue(value instanceof Long); assertEquals(((Long) value).longValue(), 123); value = LocaleConvertUtils.convert("123456", Long.class); assertTrue(value instanceof Long); assertEquals(((Long) value).longValue(), 123456); /* fixme - Short conversion not implemented at this point value = LocaleConvertUtils.convert("123", Short.TYPE); assertTrue(value instanceof Short); assertEquals(((Short) value).shortValue(), (short) 123); value = LocaleConvertUtils.convert("123", Short.class); assertTrue(value instanceof Short); assertEquals(((Short) value).shortValue(), (short) 123); */ String input = null; input = "2002-03-17"; value = LocaleConvertUtils.convert(input, Date.class); assertTrue(value instanceof Date); assertEquals(input, value.toString()); input = "20:30:40"; value = LocaleConvertUtils.convert(input, Time.class); assertTrue(value instanceof Time); assertEquals(input, value.toString()); input = "2002-03-17 20:30:40.0"; value = LocaleConvertUtils.convert(input, Timestamp.class); assertTrue(value instanceof Timestamp); assertEquals(input, value.toString()); } /** * Positive String to String array tests. */ public void fixmetestPositiveStringArray() { fail("Array conversions not implemented yet."); Object value = null; String stringArray[] = new String[0]; String stringArray1[] = new String[] {"abc"}; String stringArray2[] = new String[] {"abc", "de,f"}; value = LocaleConvertUtils.convert("", stringArray.getClass()); checkStringArray(value, stringArray); value = LocaleConvertUtils.convert(" ", stringArray.getClass()); checkStringArray(value, stringArray); value = LocaleConvertUtils.convert("{}", stringArray.getClass()); checkStringArray(value, stringArray); value = LocaleConvertUtils.convert("{ }", stringArray.getClass()); checkStringArray(value, stringArray); value = LocaleConvertUtils.convert("abc", stringArray.getClass()); checkStringArray(value, stringArray1); value = LocaleConvertUtils.convert("{abc}", stringArray.getClass()); checkStringArray(value, stringArray1); value = LocaleConvertUtils.convert("\"abc\"", stringArray.getClass()); checkStringArray(value, stringArray1); value = LocaleConvertUtils.convert("{\"abc\"}", stringArray.getClass()); checkStringArray(value, stringArray1); value = LocaleConvertUtils.convert("'abc'", stringArray.getClass()); checkStringArray(value, stringArray1); value = LocaleConvertUtils.convert("{'abc'}", stringArray.getClass()); checkStringArray(value, stringArray1); value = LocaleConvertUtils.convert("abc 'de,f'", stringArray.getClass()); checkStringArray(value, stringArray2); value = LocaleConvertUtils.convert("{abc, 'de,f'}", stringArray.getClass()); checkStringArray(value, stringArray2); value = LocaleConvertUtils.convert("\"abc\",\"de,f\"", stringArray.getClass()); checkStringArray(value, stringArray2); value = LocaleConvertUtils.convert("{\"abc\" 'de,f'}", stringArray.getClass()); checkStringArray(value, stringArray2); value = LocaleConvertUtils.convert("'abc' 'de,f'", stringArray.getClass()); checkStringArray(value, stringArray2); value = LocaleConvertUtils.convert("{'abc', \"de,f\"}", stringArray.getClass()); checkStringArray(value, stringArray2); } /** * Test conversion of a String using a Locale and pattern. */ public void testConvertStringLocaleNull() { Object result = null; try { result = LocaleConvertUtils.convert("123", Integer.class, (Locale)null, "#,###"); } catch (Exception e) { e.printStackTrace(); fail("Threw: " + e); } assertNotNull("Null Result", result); assertEquals("Integer Type", Integer.class, result.getClass()); assertEquals("Integer Value", new Integer(123), result); } /** * Test conversion of a String array using a Locale and pattern. */ public void testConvertStringArrayLocaleNull() { Object result = null; try { result = LocaleConvertUtils.convert(new String[] {"123"}, Integer[].class, (Locale)null, "#,###"); } catch (Exception e) { e.printStackTrace(); fail("Threw: " + e); } assertNotNull("Null Result", result); assertEquals("Integer Array Type", Integer[].class, result.getClass()); assertEquals("Integer Array Length", 1, ((Integer[])result).length); assertEquals("Integer Array Value", new Integer(123), ((Integer[])result)[0]); } /** * Tests a conversion if there is no suitable converter registered. In this * case, the string converter is used, and the passed in target type is * ignored. (This test is added to prevent a regression after the locale * converters have been generified.) */ public void testDefaultToStringConversionUnsupportedType() { Integer value = 20131101; assertEquals("Wrong result", value.toString(), LocaleConvertUtils.convert(value.toString(), getClass())); } // -------------------------------------------------------- Private Methods private void checkIntegerArray(Object value, int intArray[]) { assertNotNull("Returned value is not null", value); assertEquals("Returned value is int[]", intArray.getClass(), value.getClass()); int results[] = (int[]) value; assertEquals("Returned array length", intArray.length, results.length); for (int i = 0; i < intArray.length; i++) { assertEquals("Returned array value " + i, intArray[i], results[i]); } } private void checkStringArray(Object value, String stringArray[]) { assertNotNull("Returned value is not null", value); assertEquals("Returned value is String[]", stringArray.getClass(), value.getClass()); String results[] = (String[]) value; assertEquals("Returned array length", stringArray.length, results.length); for (int i = 0; i < stringArray.length; i++) { assertEquals("Returned array value " + i, stringArray[i], results[i]); } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/MappedPropertyChildBean.java100644 0 0 2074 12262570607 30617 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * Inherited Mapped property test bean. * * @version $Id: MappedPropertyChildBean.java 1454597 2013-03-08 21:58:12Z britter $ */ public class MappedPropertyChildBean extends MappedPropertyTestBean{ } ././@LongLink100644 0 0 151 12262571655 10263 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/MappedPropertyChildInterface.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/MappedPropertyChildInterface.100644 0 0 2105 12262570610 30775 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * Test Child Interface * * @version $Id: MappedPropertyChildInterface.java 1454597 2013-03-08 21:58:12Z britter $ */ public interface MappedPropertyChildInterface extends MappedPropertyTestInterface { } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/MappedPropertyTestBean.java100644 0 0 6134 12262570610 30506 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.HashMap; import java.util.Map; /** * Just a java bean (JAJB) to try to replicate a reported bug * * @version $Id: MappedPropertyTestBean.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class MappedPropertyTestBean { private final Map map = new HashMap(); private final Map myMap = new HashMap(); // -------------------------------------------------------------- Properties public String getMapproperty(String key) { return (String) map.get(key); } public void setMapproperty(String key, String value) { map.put(key, value); } public boolean isMappedBoolean(String key) { return ((Boolean)map.get(key)).booleanValue(); } public void setMappedBoolean(String key, boolean value) { map.put(key, (value ? Boolean.TRUE : Boolean.FALSE)); } protected String getProtectedMapped(String key) { return (String) map.get(key); } protected void setProtectedMapped(String key, String value) { map.put(key, value); } public void setMappedPrimitive(int key, int value) { map.put(new Integer(key), new Integer(value)); } public void setAnyMapped(MappedPropertyTestBean key, MappedPropertyTestBean value) { map.put(key, value); } public void setMappedSetterOnly(String key, String value) { map.put(key, value); } public String getMappedGetterOnly(String key) { return (String) map.get(key); } public String getInvalidGetter(String key, String other) { return (String) map.get(key); } public Map getMyMap() { return myMap; } public void setInvalidGetter(String key, String value) { map.put(key, value); } public String getInvalidSetter(String key) { return (String) map.get(key); } public void setInvalidSetter(String key, String value, String other) { } public Long getDifferentTypes(String key) { return new Long(((Number)map.get(key)).longValue()); } public void setDifferentTypes(String key, Integer value) { map.put(key, value); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/MappedPropertyTestCase.java100644 0 0 27614 12262570610 30542 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** *

          Test Case for the MappedPropertyDescriptor.

          * * @version $Id: MappedPropertyTestCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class MappedPropertyTestCase extends TestCase { // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public MappedPropertyTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Run this Test */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(MappedPropertyTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { } // ------------------------------------------------ Individual Test Methods /** * Test valid method name */ public void testFound() { String property = "mapproperty"; Class clazz = MappedPropertyTestBean.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNotNull("Getter is missing", desc.getMappedReadMethod()); assertNotNull("Setter is missing", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test boolean "is" method name */ public void testBooleanMapped() { String property = "mappedBoolean"; Class clazz = MappedPropertyTestBean.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNotNull("Getter is missing", desc.getMappedReadMethod()); assertNotNull("Setter is missing", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test invalid method name */ public void testNotFound() { String property = "xxxxxxx"; Class clazz = MappedPropertyTestBean.class; try { new MappedPropertyDescriptor(property, clazz); fail("Property '" + property + "' found in " + clazz.getName()); } catch (Exception ex) { // expected result } } /** * Test Mapped Property - Getter only */ public void testMappedGetterOnly() { String property = "mappedGetterOnly"; Class clazz = MappedPropertyTestBean.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNotNull("Getter is missing", desc.getMappedReadMethod()); assertNull("Setter is found", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test Mapped Property - Setter Only */ public void testMappedSetterOnly() { String property = "mappedSetterOnly"; Class clazz = MappedPropertyTestBean.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNull("Getter is found", desc.getMappedReadMethod()); assertNotNull("Setter is missing", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test Mapped Property - Invalid Setter */ public void testInvalidSetter() { String property = "invalidSetter"; Class clazz = MappedPropertyTestBean.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNotNull("Getter is missing", desc.getMappedReadMethod()); assertNull("Setter is found", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test Mapped Property - Invalid Getter */ public void testInvalidGetter() { String property = "invalidGetter"; Class clazz = MappedPropertyTestBean.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNull("Getter is found", desc.getMappedReadMethod()); assertNotNull("Setter is missing", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test Mapped Property - Different Types * * Expect to find the getDifferentTypes() method, but not * the setDifferentTypes() method because setDifferentTypes() * sets and Integer, while getDifferentTypes() returns a Long. */ public void testDifferentTypes() { String property = "differentTypes"; Class clazz = MappedPropertyTestBean.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNotNull("Getter is missing", desc.getMappedReadMethod()); assertNull("Setter is found", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test Map getter */ public void testMapGetter() { MappedPropertyTestBean bean = new MappedPropertyTestBean(); try { String testValue = "test value"; String testKey = "testKey"; BeanUtils.setProperty(bean, "myMap("+testKey+")", "test value"); assertEquals("Map getter", testValue, bean.getMyMap().get(testKey)); } catch (Exception ex) { fail("Test set mapped property failed: " + ex); } } /** * Test property with any two args */ public void testAnyArgsProperty() { String property = "anyMapped"; Class clazz = MappedPropertyTestBean.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNull("Getter is found", desc.getMappedReadMethod()); assertNotNull("Setter is missing", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test property with two primitive args */ public void testPrimitiveArgsProperty() { String property = "mappedPrimitive"; Class clazz = MappedPropertyTestBean.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNull("Getter is found", desc.getMappedReadMethod()); assertNotNull("Setter is missing", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test 'protected' mapped property */ public void testProtected() { String property = "protectedProperty"; Class clazz = MappedPropertyTestBean.class; try { new MappedPropertyDescriptor(property, clazz); fail("Property '" + property + "' found in " + clazz.getName()); } catch (Exception ex) { // expected result } } /** * Test 'public' method in parent */ public void testPublicParentMethod() { String property = "mapproperty"; Class clazz = MappedPropertyChildBean.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNotNull("Getter is missing", desc.getMappedReadMethod()); assertNotNull("Setter is missing", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test 'protected' method in parent */ public void testProtectedParentMethod() { String property = "protectedMapped"; Class clazz = MappedPropertyChildBean.class; try { new MappedPropertyDescriptor(property, clazz); fail("Property '" + property + "' found in " + clazz.getName()); } catch (Exception ex) { } } /** * Test Interface with mapped property */ public void testInterfaceMapped() { String property = "mapproperty"; Class clazz = MappedPropertyTestInterface.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNotNull("Getter is missing", desc.getMappedReadMethod()); assertNotNull("Setter is missing", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } /** * Test property not found in interface */ public void testInterfaceNotFound() { String property = "XXXXXX"; Class clazz = MappedPropertyTestInterface.class; try { new MappedPropertyDescriptor(property, clazz); fail("Property '" + property + "' found in " + clazz.getName()); } catch (Exception ex) { } } /** * Test Interface Inherited mapped property */ public void testChildInterfaceMapped() { String property = "mapproperty"; Class clazz = MappedPropertyChildInterface.class; try { MappedPropertyDescriptor desc = new MappedPropertyDescriptor(property, clazz); assertNotNull("Getter is missing", desc.getMappedReadMethod()); assertNotNull("Setter is missing", desc.getMappedWriteMethod()); } catch (Exception ex) { fail("Property '" + property + "' Not Found in " + clazz.getName() + ": " + ex); } } }././@LongLink100644 0 0 150 12262571655 10262 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/MappedPropertyTestInterface.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/MappedPropertyTestInterface.j100644 0 0 2202 12262570610 31041 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * Test Interface * * @version $Id: MappedPropertyTestInterface.java 1454597 2013-03-08 21:58:12Z britter $ */ public interface MappedPropertyTestInterface { public String getMapproperty(String key); public void setMapproperty(String key, String value); } ././@LongLink100644 0 0 157 12262571655 10271 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/memoryleaktests/MemoryLeakTestCase.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/memoryleaktests/MemoryLeakTes100644 0 0 64154 12262570607 31172 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.memoryleaktests; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Locale; import java.util.StringTokenizer; import junit.framework.TestCase; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.MappedPropertyDescriptor; import org.apache.commons.beanutils.MethodUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.WrapDynaBean; import org.apache.commons.beanutils.WrapDynaClass; import org.apache.commons.beanutils.converters.IntegerConverter; import org.apache.commons.beanutils.locale.LocaleBeanUtilsBean; import org.apache.commons.beanutils.locale.LocaleConvertUtils; import org.apache.commons.beanutils.locale.converters.IntegerLocaleConverter; /** * Test BeanUtils memory leaks. * * See https://issues.apache.org/jira/browse/BEANUTILS-291 * * @version $Id: MemoryLeakTestCase.java 1546738 2013-11-30 16:24:19Z oheger $ */ public class MemoryLeakTestCase extends TestCase { /** * Tests that PropertyUtilsBean's descriptorsCache doesn't cause a memory leak. */ public void testPropertyUtilsBean_descriptorsCache_memoryLeak() throws Exception { if (isPre15JVM()) { return; } // Clear All BeanUtils caches before the test clearAllBeanUtilsCaches(); String className = "org.apache.commons.beanutils.memoryleaktests.pojotests.SomePojo"; // The classLoader will go away only when these following variables are released ClassLoader loader = newClassLoader(); Class beanClass = loader.loadClass(className); Object bean = beanClass.newInstance(); // ----------------------------------------------------------------------------- WeakReference someRef = new WeakReference(loader); // Sanity checks only assertNotNull("ClassLoader is null", loader); assertNotNull("BeanClass is null", beanClass); assertNotSame("ClassLoaders should be different..", getClass().getClassLoader(), beanClass.getClassLoader()); assertSame("BeanClass ClassLoader incorrect", beanClass.getClassLoader(), loader); // if you comment the following line, the testcase will work, and the ClassLoader will be released. // That proves that nothing is wrong with the test, and PropertyUtils is holding a reference assertEquals("initialValue", PropertyUtils.getProperty(bean, "name")); // this should make the reference go away. loader = null; beanClass = null; bean = null; forceGarbageCollection(); /* Try to force the garbage collector to run by filling up memory */ if (someRef.get() != null) { profilerLeakReport("PropertyUtilsBean descriptorsCache", className); } // if everything is fine, this will be null assertNull("PropertyUtilsBean is holding a reference to the classLoader", someRef.get()); // Clear All BeanUtils caches after the test clearAllBeanUtilsCaches(); } /** * Tests that PropertyUtilsBean's mappedDescriptorsCache doesn't cause a memory leak. */ public void testPropertyUtilsBean_mappedDescriptorsCache_memoryLeak() throws Exception { if (isPre15JVM()) { return; } // Clear All BeanUtils caches before the test clearAllBeanUtilsCaches(); String className = "org.apache.commons.beanutils.memoryleaktests.pojotests.SomeMappedPojo"; // The classLoader will go away only when these following variables are released ClassLoader loader = newClassLoader(); Class beanClass = loader.loadClass(className); Object bean = beanClass.newInstance(); // ----------------------------------------------------------------------------- WeakReference someRef = new WeakReference(loader); // Sanity checks only assertNotNull("ClassLoader is null", loader); assertNotNull("BeanClass is null", beanClass); assertNotSame("ClassLoaders should be different..", getClass().getClassLoader(), beanClass.getClassLoader()); assertSame("BeanClass ClassLoader incorrect", beanClass.getClassLoader(), loader); // if you comment the following three lines, the testcase will work, and the ClassLoader will be released. // That proves that nothing is wrong with the test, and PropertyUtils is holding a reference assertEquals("Second Value", PropertyUtils.getProperty(bean, "mappedProperty(Second Key)")); PropertyUtils.setProperty(bean, "mappedProperty(Second Key)", "New Second Value"); assertEquals("New Second Value", PropertyUtils.getProperty(bean, "mappedProperty(Second Key)")); // this should make the reference go away. loader = null; beanClass = null; bean = null; // PropertyUtilsBean uses the MethodUtils's method cache for mapped properties. // Uncomment the following line to check this is not just a repeat of that memory leak. // MethodUtils.clearCache(); forceGarbageCollection(); /* Try to force the garbage collector to run by filling up memory */ if (someRef.get() != null) { profilerLeakReport("PropertyUtilsBean mappedDescriptorsCache", className); } // if everything is fine, this will be null assertNull("PropertyUtilsBean is holding a reference to the classLoader", someRef.get()); // Clear All BeanUtils caches after the test clearAllBeanUtilsCaches(); } /** * Tests that MappedPropertyDescriptor can re-create the Method reference after it * has been garbage collected. */ public void testMappedPropertyDescriptor_MappedMethodReference1() throws Exception { // Clear All BeanUtils caches before the test clearAllBeanUtilsCaches(); String className = "org.apache.commons.beanutils.memoryleaktests.pojotests.SomeMappedPojo"; ClassLoader loader = newClassLoader(); Class beanClass = loader.loadClass(className); Object bean = beanClass.newInstance(); // ----------------------------------------------------------------------------- // Sanity checks only assertNotNull("ClassLoader is null", loader); assertNotNull("BeanClass is null", beanClass); assertNotNull("Bean is null", bean); assertNotSame("ClassLoaders should be different..", getClass().getClassLoader(), beanClass.getClassLoader()); assertSame("BeanClass ClassLoader incorrect", beanClass.getClassLoader(), loader); MappedPropertyDescriptor descriptor = new MappedPropertyDescriptor("mappedProperty", beanClass); assertNotNull("1-Read Method null", descriptor.getMappedReadMethod()); assertNotNull("1-Write Method null", descriptor.getMappedWriteMethod()); assertEquals("1-Read Method name", "getMappedProperty", descriptor.getMappedReadMethod().getName()); assertEquals("1-Read Write name", "setMappedProperty", descriptor.getMappedWriteMethod().getName()); forceGarbageCollection(); /* Try to force the garbage collector to run by filling up memory */ // The aim of this test is to check the functinality in MappedPropertyDescriptor which // re-creates the Method references after they have been garbage collected. However theres no // way of knowing the method references were garbage collected and that code was run, except by // un-commeting the System.out statement in MappedPropertyDescriptor's MappedMethodReference's // get() method. assertNotNull("1-Read Method null", descriptor.getMappedReadMethod()); assertNotNull("1-Write Method null", descriptor.getMappedWriteMethod()); assertEquals("1-Read Method name", "getMappedProperty", descriptor.getMappedReadMethod().getName()); assertEquals("1-Read Write name", "setMappedProperty", descriptor.getMappedWriteMethod().getName()); // Clear All BeanUtils caches after the test clearAllBeanUtilsCaches(); } /** * Tests that MappedPropertyDescriptor can re-create the Method reference after it * has been garbage collected. */ public void testMappedPropertyDescriptor_MappedMethodReference2() throws Exception { // Clear All BeanUtils caches before the test clearAllBeanUtilsCaches(); String className = "org.apache.commons.beanutils.memoryleaktests.pojotests.SomeMappedPojo"; ClassLoader loader = newClassLoader(); Class beanClass = loader.loadClass(className); Object bean = beanClass.newInstance(); // ----------------------------------------------------------------------------- // Sanity checks only assertNotNull("ClassLoader is null", loader); assertNotNull("BeanClass is null", beanClass); assertNotNull("Bean is null", bean); assertNotSame("ClassLoaders should be different..", getClass().getClassLoader(), beanClass.getClassLoader()); assertSame("BeanClass ClassLoader incorrect", beanClass.getClassLoader(), loader); MappedPropertyDescriptor descriptor = new MappedPropertyDescriptor("mappedProperty", beanClass); assertNotNull("1-Read Method null", descriptor.getMappedReadMethod()); assertNotNull("1-Write Method null", descriptor.getMappedWriteMethod()); assertEquals("1-Read Method name", "getMappedProperty", descriptor.getMappedReadMethod().getName()); assertEquals("1-Read Write name", "setMappedProperty", descriptor.getMappedWriteMethod().getName()); // this should make the reference go away. loader = null; beanClass = null; bean = null; forceGarbageCollection(); /* Try to force the garbage collector to run by filling up memory */ // The aim of this test is to check the functinality in MappedPropertyDescriptor which // re-creates the Method references after they have been garbage collected. However theres no // way of knowing the method references were garbage collected and that code was run, except by // un-commeting the System.out statement in MappedPropertyDescriptor's MappedMethodReference's // get() method. assertNotNull("1-Read Method null", descriptor.getMappedReadMethod()); assertNotNull("1-Write Method null", descriptor.getMappedWriteMethod()); assertEquals("1-Read Method name", "getMappedProperty", descriptor.getMappedReadMethod().getName()); assertEquals("1-Read Write name", "setMappedProperty", descriptor.getMappedWriteMethod().getName()); // Clear All BeanUtils caches after the test clearAllBeanUtilsCaches(); } /** * Tests that MethodUtils's cache doesn't cause a memory leak. */ public void testMethodUtils_cache_memoryLeak() throws Exception { // Clear All BeanUtils caches before the test clearAllBeanUtilsCaches(); String className = "org.apache.commons.beanutils.memoryleaktests.pojotests.SomePojo"; // The classLoader will go away only when these following variables are released ClassLoader loader = newClassLoader(); Class beanClass = loader.loadClass(className); Object bean = beanClass.newInstance(); // ----------------------------------------------------------------------------- WeakReference someRef = new WeakReference(loader); // Sanity checks only assertNotNull("ClassLoader is null", loader); assertNotNull("BeanClass is null", beanClass); assertNotSame("ClassLoaders should be different..", getClass().getClassLoader(), beanClass.getClassLoader()); assertSame("BeanClass ClassLoader incorrect", beanClass.getClassLoader(), loader); // if you comment the following line, the testcase will work, and the ClassLoader will be released. // That proves that nothing is wrong with the test, and MethodUtils is holding a reference assertEquals("initialValue", MethodUtils.invokeExactMethod(bean, "getName", new Object[0])); // this should make the reference go away. loader = null; beanClass = null; bean = null; forceGarbageCollection(); /* Try to force the garbage collector to run by filling up memory */ if (someRef.get() != null) { profilerLeakReport("MethodUtils cache", className); } // if everything is fine, this will be null assertNull("MethodUtils is holding a reference to the classLoader", someRef.get()); // Clear All BeanUtils caches after the test clearAllBeanUtilsCaches(); } /** * Tests that WrapDynaClass's dynaClasses doesn't cause a memory leak. */ public void testWrapDynaClass_dynaClasses_memoryLeak() throws Exception { if (isPre15JVM()) { return; } // Clear All BeanUtils caches before the test clearAllBeanUtilsCaches(); String className = "org.apache.commons.beanutils.memoryleaktests.pojotests.SomePojo"; // The classLoader will go away only when these following variables are released ClassLoader loader = newClassLoader(); Class beanClass = loader.loadClass(className); Object bean = beanClass.newInstance(); WrapDynaBean wrapDynaBean = new WrapDynaBean(bean); // ----------------------------------------------------------------------------- WeakReference someRef = new WeakReference(loader); // Sanity checks only assertNotNull("ClassLoader is null", loader); assertNotNull("BeanClass is null", beanClass); assertNotSame("ClassLoaders should be different..", getClass().getClassLoader(), beanClass.getClassLoader()); assertSame("BeanClass ClassLoader incorrect", beanClass.getClassLoader(), loader); // if you comment the following line, the testcase will work, and the ClassLoader will be released. // That proves that nothing is wrong with the test, and WrapDynaClass is holding a reference assertEquals("initialValue", wrapDynaBean.get("name")); // this should make the reference go away. loader = null; beanClass = null; bean = null; wrapDynaBean = null; // Wrap Dyna Class uses the PropertyUtilsBean's decriptor caches. // Uncomment the following line to check this is not just a repeat of that memory leak. // BeanUtilsBean.getInstance().getPropertyUtils().clearDescriptors(); forceGarbageCollection(); /* Try to force the garbage collector to run by filling up memory */ if (someRef.get() != null) { profilerLeakReport("WrapDynaClass dynaClasses", className); } // if everything is fine, this will be null assertNull("WrapDynaClass is holding a reference to the classLoader", someRef.get()); // Clear All BeanUtils caches after the test clearAllBeanUtilsCaches(); } /** * Tests that ConvertUtilsBean's converters doesn't cause a memory leak. */ public void testConvertUtilsBean_converters_memoryLeak() throws Exception { // Clear All BeanUtils caches before the test clearAllBeanUtilsCaches(); String className = "org.apache.commons.beanutils.memoryleaktests.pojotests.CustomInteger"; // The classLoader will go away only when these following variables are released ClassLoader loader = newClassLoader(); Class beanClass = loader.loadClass(className); Object bean = beanClass.newInstance(); // ----------------------------------------------------------------------------- WeakReference someRef = new WeakReference(loader); // Sanity checks only assertNotNull("ClassLoader is null", loader); assertNotNull("BeanClass is null", beanClass); assertNotSame("ClassLoaders should be different..", getClass().getClassLoader(), beanClass.getClassLoader()); assertSame("BeanClass ClassLoader incorrect", beanClass.getClassLoader(), loader); // if you comment the following two lines, the testcase will work, and the ClassLoader will be released. // That proves that nothing is wrong with the test, and ConvertUtilsBean is holding a reference ConvertUtils.register(new IntegerConverter(), beanClass); assertEquals("12345", ConvertUtils.convert(bean, String.class)); // this should make the reference go away. loader = null; beanClass = null; bean = null; forceGarbageCollection(); /* Try to force the garbage collector to run by filling up memory */ if (someRef.get() != null) { profilerLeakReport("ConvertUtilsBean converters", className); } // if everything is fine, this will be null assertNull("ConvertUtilsBean is holding a reference to the classLoader", someRef.get()); // Clear All BeanUtils caches after the test clearAllBeanUtilsCaches(); } /** * Tests that LocaleConvertUtilsBean's converters doesn't cause a memory leak. */ public void testLocaleConvertUtilsBean_converters_memoryLeak() throws Exception { // Clear All BeanUtils caches before the test clearAllBeanUtilsCaches(); String className = "org.apache.commons.beanutils.memoryleaktests.pojotests.CustomInteger"; // The classLoader will go away only when these following variables are released ClassLoader loader = newClassLoader(); Class beanClass = loader.loadClass(className); Object bean = beanClass.newInstance(); // ----------------------------------------------------------------------------- WeakReference someRef = new WeakReference(loader); // Sanity checks only assertNotNull("ClassLoader is null", loader); assertNotNull("BeanClass is null", beanClass); assertNotSame("ClassLoaders should be different..", getClass().getClassLoader(), beanClass.getClassLoader()); assertSame("BeanClass ClassLoader incorrect", beanClass.getClassLoader(), loader); // if you comment the following two lines, the testcase will work, and the ClassLoader will be released. // That proves that nothing is wrong with the test, and LocaleConvertUtilsBean is holding a reference LocaleConvertUtils.register(new IntegerLocaleConverter(Locale.US, false), beanClass, Locale.US); assertEquals(new Integer(12345), LocaleConvertUtils.convert(bean.toString(), Integer.class, Locale.US, "#,###")); // this should make the reference go away. loader = null; beanClass = null; bean = null; forceGarbageCollection(); /* Try to force the garbage collector to run by filling up memory */ if (someRef.get() != null) { profilerLeakReport("LocaleConvertUtilsBean converters", className); } // if everything is fine, this will be null assertNull("LocaleConvertUtilsBean is holding a reference to the classLoader", someRef.get()); // Clear All BeanUtils caches after the test clearAllBeanUtilsCaches(); } /** * Clear all the BeanUtils Caches manually. * * This is probably overkill, but since we're dealing with static caches * it seems sensible to ensure that all test cases start with a clean sheet. */ private void clearAllBeanUtilsCaches() { // Clear BeanUtilsBean's PropertyUtilsBean descriptor caches BeanUtilsBean.getInstance().getPropertyUtils().clearDescriptors(); // Clear LocaleBeanUtilsBean's PropertyUtilsBean descriptor caches LocaleBeanUtilsBean.getInstance().getPropertyUtils().clearDescriptors(); // Clear MethodUtils's method cache MethodUtils.clearCache(); // Clear WrapDynaClass cache WrapDynaClass.clear(); // replace the existing BeanUtilsBean instance for the current class loader with a new, clean instance BeanUtilsBean.setInstance(new BeanUtilsBean()); // replace the existing LocaleBeanUtilsBean instance for the current class loader with a new, clean instance LocaleBeanUtilsBean.setInstance(new LocaleBeanUtilsBean()); } /** * Try to force the garbage collector to run by filling up memory and calling System.gc(). */ private void forceGarbageCollection() throws Exception { // Fill up memory SoftReference ref = new SoftReference(new Object()); int count = 0; while(ref.get() != null && count++ < 5) { java.util.ArrayList list = new java.util.ArrayList(); try { long i = 0; while (true && ref.get() != null) { list.add("A Big String A Big String A Big String A Big String A Big String A Big String A Big String A Big String A Big String A Big String " + (i++)); } } catch (Throwable ignored) { } list.clear(); list = null; // System.out.println("Count " + count + " : " + getMemoryStats()); System.gc(); Thread.sleep(1000); } // System.out.println("After GC: " + getMemoryStats()); if (ref.get() != null) { throw new IllegalStateException("Your JVM is not releasing SoftReference, try running the testcase with less memory (-Xmx)"); } } /** * Create a new class loader instance. */ private static URLClassLoader newClassLoader() throws MalformedURLException { String dataFilePath = MemoryLeakTestCase.class.getResource("pojotests").getFile(); //System.out.println("dataFilePath: " + dataFilePath); String location = "file://" + dataFilePath.substring(0,dataFilePath.length()-"org.apache.commons.beanutils.memoryleaktests.pojotests".length()); //System.out.println("location: " + location); StringBuilder newString = new StringBuilder(); for (int i=0;i mappedProperty = null; public String getMappedProperty(String key) { // Create the map the very first time if (mappedProperty == null) { mappedProperty = new HashMap(); mappedProperty.put("First Key", "First Value"); mappedProperty.put("Second Key", "Second Value"); } return mappedProperty.get(key); } public void setMappedProperty(String key, String value) { // Create the map the very first time if (mappedProperty == null) { mappedProperty = new HashMap(); mappedProperty.put("First Key", "First Value"); mappedProperty.put("Second Key", "Second Value"); } mappedProperty.put(key, value); } } ././@LongLink100644 0 0 157 12262571655 10271 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/memoryleaktests/pojotests/SomePojo.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/memoryleaktests/pojotests/Som100644 0 0 2246 12262570607 31213 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.memoryleaktests.pojotests; /** * Test POJO * * @version $Id: SomePojo.java 1454597 2013-03-08 21:58:12Z britter $ */ public class SomePojo { String name = "initialValue"; public void setName(String name) { this.name = name; } public String getName() { return name; } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/MethodUtilsTestCase.java100644 0 0 57732 12262570610 30034 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.priv.PrivateBeanFactory; import org.apache.commons.beanutils.priv.PublicSubBean; /** *

          Test case for MethodUtils

          * * @version $Id: MethodUtilsTestCase.java 1454884 2013-03-10 17:44:51Z britter $ */ public class MethodUtilsTestCase extends TestCase { // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public MethodUtilsTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(MethodUtilsTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { } // ------------------------------------------------ Individual Test Methods /** *

          Test getAccessibleMethod. */ public void testGetAccessibleMethod() { // easy bit first - find a public method Method method = MethodUtils.getAccessibleMethod (TestBean.class, "setStringProperty", String.class); assertMethod(method, "setStringProperty"); } public void testGetAccessibleMethodFromInterface() { Method method; // trickier this one - find a method in a direct interface method = MethodUtils.getAccessibleMethod (PrivateBeanFactory.create().getClass(), "methodBar", String.class); assertMethod(method, "methodBar"); } public void testGetAccessibleMethodIndirectInterface() { Method method; // trickier this one - find a method in a indirect interface method = MethodUtils.getAccessibleMethod (PrivateBeanFactory.createSubclass().getClass(), "methodBaz", String.class); assertMethod(method, "methodBaz"); } private static void assertMethod(Method method, String methodName) { assertNotNull(method); assertEquals("Method is not named correctly", methodName, method.getName()); assertTrue("Method is not public", Modifier.isPublic(method.getModifiers())); } /** *

          Test invokeExactMethod. */ public void testInvokeExactMethod() throws Exception { TestBean bean = new TestBean(); Object ret = MethodUtils.invokeExactMethod(bean, "setStringProperty", "TEST"); assertNull(ret); assertEquals("Method ONE was invoked", "TEST", bean.getStringProperty()); } public void testInvokeExactMethodFromInterface() throws Exception { Object ret = MethodUtils.invokeExactMethod( PrivateBeanFactory.create(), "methodBar", "ANOTHER TEST"); assertEquals("Method TWO wasn't invoked correctly", "ANOTHER TEST", ret); } public void testInvokeExactMethodIndirectInterface() throws Exception { Object ret = MethodUtils.invokeExactMethod( PrivateBeanFactory.createSubclass(), "methodBaz", "YET ANOTHER TEST"); assertEquals("Method TWO was invoked correctly", "YET ANOTHER TEST", ret); } public void testInvokeExactMethodNullArray() throws Exception { Object result = MethodUtils.invokeExactMethod( new AlphaBean("parent"), "getName", null); assertEquals("parent", result); } public void testInvokeExactMethodNullArrayNullArray() throws Exception { Object result = MethodUtils.invokeExactMethod( new AlphaBean("parent"), "getName", null, null); assertEquals("parent", result); } public void testInvokeExactMethodNull() throws Exception { Object object = new Object(); Object result = MethodUtils.invokeExactMethod(object, "toString", (Object) null); assertEquals(object.toString(), result); } /** *

          Test invokeMethod. */ public void testInvokeMethod() throws Exception { AbstractParent parent = new AlphaBean("parent"); BetaBean childOne = new BetaBean("ChildOne"); assertEquals( "Cannot invoke through abstract class (1)", "ChildOne", MethodUtils.invokeMethod(parent, "testAddChild", childOne)); } public void testInvokeMethodObject() throws Exception { AbstractParent parent = new AlphaBean("parent"); Child childTwo = new AlphaBean("ChildTwo"); assertEquals("Cannot invoke through interface (1)", "ChildTwo", MethodUtils.invokeMethod(parent, "testAddChild", childTwo)); } public void testInvokeMethodArray() throws Exception { AbstractParent parent = new AlphaBean("parent"); AlphaBean childTwo = new AlphaBean("ChildTwo"); Object[] params = new Object[2]; params[0] = "parameter"; params[1] = childTwo; assertEquals("Cannot invoke through abstract class", "ChildTwo", MethodUtils.invokeMethod(parent, "testAddChild2", params)); } public void testInvokeMethodUnknown() throws Exception { // test that exception is correctly thrown when a method cannot be found with matching params try { AbstractParent parent = new AlphaBean("parent"); BetaBean childOne = new BetaBean("ChildOne"); MethodUtils.invokeMethod(parent, "bogus", childOne); fail("No exception thrown when no appropriate method exists"); } catch (NoSuchMethodException expected) { // this is what we're expecting! } } public void testInvokeMethodNullArray() throws Exception { Object result = MethodUtils.invokeMethod( new AlphaBean("parent"), "getName", null); assertEquals("parent", result); } public void testInvokeMethodNullArrayNullArray() throws Exception { Object result = MethodUtils.invokeMethod( new AlphaBean("parent"), "getName", null, null); assertEquals("parent", result); } public void testInvokeMethodNull() throws Exception { Object object = new Object(); Object result = MethodUtils.invokeMethod(object, "toString", (Object) null); assertEquals(object.toString(), result); } public void testInvokeMethodPrimitiveBoolean() throws Exception { PrimitiveBean bean = new PrimitiveBean(); MethodUtils.invokeMethod(bean, "setBoolean", Boolean.FALSE); assertEquals("Call boolean property using invokeMethod", false, bean.getBoolean()); } public void testInvokeMethodPrimitiveFloat() throws Exception { PrimitiveBean bean = new PrimitiveBean(); MethodUtils.invokeMethod(bean, "setFloat", Float.valueOf(20.0f)); assertEquals("Call float property using invokeMethod", 20.0f, bean.getFloat(), 0.01f); } public void testInvokeMethodPrimitiveLong() throws Exception { PrimitiveBean bean = new PrimitiveBean(); MethodUtils.invokeMethod(bean, "setLong", Long.valueOf(10)); assertEquals("Call long property using invokeMethod", 10, bean.getLong()); } public void testInvokeMethodPrimitiveInt() throws Exception { PrimitiveBean bean = new PrimitiveBean(); MethodUtils.invokeMethod(bean, "setInt", Integer.valueOf(12)); assertEquals("Set int property using invokeMethod", 12, bean.getInt()); } public void testInvokeMethodPrimitiveDouble() throws Exception { PrimitiveBean bean = new PrimitiveBean(); MethodUtils.invokeMethod(bean, "setDouble", Double.valueOf(25.5d)); assertEquals("Set double property using invokeMethod", 25.5d, bean.getDouble(), 0.01d); } public void testStaticInvokeMethod() throws Exception { Object value = null; int current = TestBean.currentCounter(); value = MethodUtils.invokeStaticMethod(TestBean.class, "currentCounter", new Object[0]); assertEquals("currentCounter value", current, ((Integer) value).intValue()); MethodUtils.invokeStaticMethod(TestBean.class, "incrementCounter", new Object[0]); current++; value = MethodUtils.invokeStaticMethod(TestBean.class, "currentCounter", new Object[0]); assertEquals("currentCounter value", current, ((Integer) value).intValue()); MethodUtils.invokeStaticMethod(TestBean.class, "incrementCounter", new Object[] { new Integer(8) } ); current += 8; value = MethodUtils.invokeStaticMethod(TestBean.class, "currentCounter", new Object[0]); assertEquals("currentCounter value", current, ((Integer) value).intValue()); MethodUtils.invokeExactStaticMethod(TestBean.class, "incrementCounter", new Object[] { new Integer(8) }, new Class[] { Number.class } ); current += 16; value = MethodUtils.invokeStaticMethod(TestBean.class, "currentCounter", new Object[0]); assertEquals("currentCounter value", current, ((Integer) value).intValue()); } public void testInvokeStaticMethodNull() throws Exception { int current = TestBean.currentCounter(); Object value = MethodUtils.invokeStaticMethod(TestBean.class, "currentCounter", (Object) null); assertEquals("currentCounter value", current, ((Integer) value).intValue()); } public void testInvokeExactStaticMethodNull() throws Exception { int current = TestBean.currentCounter(); Object value = MethodUtils.invokeExactStaticMethod(TestBean.class, "currentCounter", (Object) null); assertEquals("currentCounter value", current, ((Integer) value).intValue()); } /** * Simple tests for accessing static methods via invokeMethod(). */ public void testSimpleStatic1() { TestBean bean = new TestBean(); Object value = null; int current = TestBean.currentCounter(); try { // Return initial value of the counter value = MethodUtils.invokeMethod (bean, "currentCounter", new Object[0], new Class[0]); assertNotNull("currentCounter exists", value); assertTrue("currentCounter type", value instanceof Integer); assertEquals("currentCounter value", current, ((Integer) value).intValue()); // Increment via no-arguments version MethodUtils.invokeMethod (bean, "incrementCounter", new Object[0], new Class[0]); // Validate updated value current++; value = MethodUtils.invokeMethod (bean, "currentCounter", new Object[0], new Class[0]); assertNotNull("currentCounter exists", value); assertTrue("currentCounter type", value instanceof Integer); assertEquals("currentCounter value", current, ((Integer) value).intValue()); // Increment via specified-argument version MethodUtils.invokeMethod (bean, "incrementCounter", new Object[] { new Integer(5) }, new Class[] { Integer.TYPE }); // Validate updated value current += 5; value = MethodUtils.invokeMethod (bean, "currentCounter", new Object[0], new Class[0]); assertNotNull("currentCounter exists", value); assertTrue("currentCounter type", value instanceof Integer); assertEquals("currentCounter value", current, ((Integer) value).intValue()); } catch (Exception e) { fail("Threw exception" + e); } } /** * Simple tests for accessing static methods via invokeExactMethod(). */ public void testSimpleStatic2() { TestBean bean = new TestBean(); Object value = null; int current = TestBean.currentCounter(); try { // Return initial value of the counter value = MethodUtils.invokeExactMethod (bean, "currentCounter", new Object[0], new Class[0]); assertNotNull("currentCounter exists", value); assertTrue("currentCounter type", value instanceof Integer); assertEquals("currentCounter value", current, ((Integer) value).intValue()); // Increment via no-arguments version MethodUtils.invokeExactMethod (bean, "incrementCounter", new Object[0], new Class[0]); // Validate updated value current++; value = MethodUtils.invokeExactMethod (bean, "currentCounter", new Object[0], new Class[0]); assertNotNull("currentCounter exists", value); assertTrue("currentCounter type", value instanceof Integer); assertEquals("currentCounter value", current, ((Integer) value).intValue()); // Increment via specified-argument version MethodUtils.invokeExactMethod (bean, "incrementCounter", new Object[] { new Integer(5) }, new Class[] { Integer.TYPE }); // Validate updated value current += 5; value = MethodUtils.invokeExactMethod (bean, "currentCounter", new Object[0], new Class[0]); assertNotNull("currentCounter exists", value); assertTrue("currentCounter type", value instanceof Integer); assertEquals("currentCounter value", current, ((Integer) value).intValue()); } catch (Exception e) { fail("Threw exception" + e); } } /** * Simple tests for accessing static methods via getAccessibleMethod() */ public void testSimpleStatic3() { Object value = null; int current = TestBean.currentCounter(); try { // Acquire the methods we need Method currentCounterMethod = MethodUtils.getAccessibleMethod (TestBean.class, "currentCounter", new Class[0]); assertNotNull("currentCounterMethod exists", currentCounterMethod); assertEquals("currentCounterMethod name", "currentCounter", currentCounterMethod.getName()); assertEquals("currentCounterMethod args", 0, currentCounterMethod.getParameterTypes().length); assertTrue("currentCounterMethod public", Modifier.isPublic(currentCounterMethod.getModifiers())); assertTrue("currentCounterMethod static", Modifier.isStatic(currentCounterMethod.getModifiers())); Method incrementCounterMethod1 = MethodUtils.getAccessibleMethod (TestBean.class, "incrementCounter", new Class[0]); assertNotNull("incrementCounterMethod1 exists", incrementCounterMethod1); assertEquals("incrementCounterMethod1 name", "incrementCounter", incrementCounterMethod1.getName()); assertEquals("incrementCounterMethod1 args", 0, incrementCounterMethod1.getParameterTypes().length); assertTrue("incrementCounterMethod1 public", Modifier.isPublic(incrementCounterMethod1.getModifiers())); assertTrue("incrementCounterMethod1 static", Modifier.isStatic(incrementCounterMethod1.getModifiers())); Method incrementCounterMethod2 = MethodUtils.getAccessibleMethod (TestBean.class, "incrementCounter", new Class[] { Integer.TYPE }); assertNotNull("incrementCounterMethod2 exists", incrementCounterMethod2); assertEquals("incrementCounterMethod2 name", "incrementCounter", incrementCounterMethod2.getName()); assertEquals("incrementCounterMethod2 args", 1, incrementCounterMethod2.getParameterTypes().length); assertTrue("incrementCounterMethod2 public", Modifier.isPublic(incrementCounterMethod2.getModifiers())); assertTrue("incrementCounterMethod2 static", Modifier.isStatic(incrementCounterMethod2.getModifiers())); // Return initial value of the counter value = currentCounterMethod.invoke(null, new Object[0]); assertNotNull("currentCounter exists", value); assertTrue("currentCounter type", value instanceof Integer); assertEquals("currentCounter value", current, ((Integer) value).intValue()); // Increment via no-arguments version incrementCounterMethod1.invoke(null, new Object[0]); // Validate updated value current++; value = currentCounterMethod.invoke(null, new Object[0]); assertNotNull("currentCounter exists", value); assertTrue("currentCounter type", value instanceof Integer); assertEquals("currentCounter value", current, ((Integer) value).intValue()); // Increment via specified-argument version incrementCounterMethod2.invoke(null, new Object[] { new Integer(5) }); // Validate updated value current += 5; value = currentCounterMethod.invoke(null, new Object[0]); assertNotNull("currentCounter exists", value); assertTrue("currentCounter type", value instanceof Integer); assertEquals("currentCounter value", current, ((Integer) value).intValue()); } catch (Exception e) { fail("Threw exception" + e); } } public void testPublicSub() throws Exception { // make sure that bean does what it should PublicSubBean bean = new PublicSubBean(); assertEquals("Start value (foo)", bean.getFoo(), "This is foo"); assertEquals("Start value (bar)", bean.getBar(), "This is bar"); bean.setFoo("new foo"); bean.setBar("new bar"); assertEquals("Set value (foo)", bean.getFoo(), "new foo"); assertEquals("Set value (bar)", bean.getBar(), "new bar"); // see if we can access public methods in a default access superclass // from a public access subclass instance MethodUtils.invokeMethod(bean, "setFoo", "alpha"); assertEquals("Set value (foo:2)", bean.getFoo(), "alpha"); MethodUtils.invokeMethod(bean, "setBar", "beta"); assertEquals("Set value (bar:2)", bean.getBar(), "beta"); Method method = null; try { method = MethodUtils.getAccessibleMethod(PublicSubBean.class, "setFoo", String.class); } catch (Throwable t) { fail("getAccessibleMethod() setFoo threw " + t); } assertNotNull("getAccessibleMethod() setFoo is Null", method); try { method.invoke(bean, new Object[] {"1111"}); } catch (Throwable t) { fail("Invoking setFoo threw " + t); } assertEquals("Set value (foo:3)", "1111", bean.getFoo()); try { method = MethodUtils.getAccessibleMethod(PublicSubBean.class, "setBar", String.class); } catch (Throwable t) { fail("getAccessibleMethod() setBar threw " + t); } assertNotNull("getAccessibleMethod() setBar is Null", method); try { method.invoke(bean, new Object[] {"2222"}); } catch (Throwable t) { fail("Invoking setBar threw " + t); } assertEquals("Set value (bar:3)", "2222", bean.getBar()); } public void testParentMethod() throws Exception { OutputStream os = new PrintStream(System.out); PrintStream ps = new PrintStream(System.out); A a = new A(); MethodUtils.invokeMethod(a, "foo", os); assertTrue("Method Invoked(1)", a.called); a = new A(); MethodUtils.invokeMethod(a, "foo", ps); assertTrue("Method Invoked(2)", a.called); } /** * Test {@link MethodUtils#clearCache()}. */ public void testClearCache() throws Exception { MethodUtils.clearCache(); // make sure it starts empty PublicSubBean bean = new PublicSubBean(); MethodUtils.invokeMethod(bean, "setFoo", "alpha"); assertEquals(1, MethodUtils.clearCache()); assertEquals(0, MethodUtils.clearCache()); } /** * Test {@link MethodUtils#setCacheMethods(boolean)}. */ public void testSetCacheMethods() throws Exception { MethodUtils.setCacheMethods(true); MethodUtils.clearCache(); // make sure it starts empty PublicSubBean bean = new PublicSubBean(); MethodUtils.invokeMethod(bean, "setFoo", "alpha"); assertEquals(1, MethodUtils.clearCache()); assertEquals(0, MethodUtils.clearCache()); } public void testNoCaching() throws Exception { // no caching MethodUtils.setCacheMethods(false); PublicSubBean bean = new PublicSubBean(); MethodUtils.invokeMethod(bean, "setFoo", "alpha"); assertEquals(0, MethodUtils.clearCache()); // reset default MethodUtils.setCacheMethods(true); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/NestedTestBean.java100644 0 0 5437 12262570610 26762 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * Specialist test bean for complex nested properties. * * @version $Id: NestedTestBean.java 1454597 2013-03-08 21:58:12Z britter $ */ public class NestedTestBean { // ------------------------------------------------------------- Constructors public NestedTestBean(String name) { setName(name); } // ------------------------------------------------------------- Properties private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private String testString = "NOT SET"; public String getTestString() { return testString; } public void setTestString(String testString) { this.testString = testString; } private boolean testBoolean = false; public boolean getTestBoolean() { return testBoolean; } public void setTestBoolean(boolean testBoolean) { this.testBoolean = testBoolean; } private NestedTestBean indexedBeans[]; public void init() { indexedBeans = new NestedTestBean[5]; indexedBeans[0] = new NestedTestBean("Bean@0"); indexedBeans[1] = new NestedTestBean("Bean@1"); indexedBeans[2] = new NestedTestBean("Bean@2"); indexedBeans[3] = new NestedTestBean("Bean@3"); indexedBeans[4] = new NestedTestBean("Bean@4"); simpleBean = new NestedTestBean("Simple Property Bean"); } public NestedTestBean getIndexedProperty(int index) { return (this.indexedBeans[index]); } public void setIndexedProperty(int index, NestedTestBean value) { this.indexedBeans[index] = value; } private NestedTestBean simpleBean; public NestedTestBean getSimpleBeanProperty() { return simpleBean; } // ------------------------------------------------------- Static Variables } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/PassTestException.java100644 0 0 2104 12262570607 27531 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * Just a runtime exception. Useful for check that a method is called. * * @version $Id: PassTestException.java 1454597 2013-03-08 21:58:12Z britter $ */ public class PassTestException extends RuntimeException { }commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/PrimitiveBean.java100644 0 0 3543 12262570607 26652 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * Bean that has primitive properties * * @version $Id: PrimitiveBean.java 1454597 2013-03-08 21:58:12Z britter $ */ public class PrimitiveBean { private float _float; private double _double; private boolean _boolean; private long _long; private int _int; public float getFloat() { return _float; } public void setFloat(float _float) { this._float = _float; } public double getDouble() { return _double; } public void setDouble(double _double) { this._double = _double; } public boolean getBoolean() { return _boolean; } public void setBoolean(boolean _boolean) { this._boolean = _boolean; } public long getLong() { return _long; } public void setLong(long _long) { this._long = _long; } public int getInt() { return _int; } public void setInt(int _int) { this._int = _int; } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/priv/PackageBean.java100644 0 0 3511 12262570607 27210 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.priv; /** *

          This class is designed to test the default access jvm problem workaround. * The issue is that public methods of a public subclass contained in a default access * superclass are returned by reflection but an IllegalAccessException is thrown * when they are invoked.

          * *

          This is the default access superclass

          * * @version $Id: PackageBean.java 1454597 2013-03-08 21:58:12Z britter $ */ class PackageBean { // ----------------------------------------------------------- Constructors /** * Package private constructor - can only use factory method to create * beans. */ PackageBean() { super(); } // ------------------------------------------------------------- Properties /** */ private String bar = "This is bar"; public String getBar() { return (this.bar); } public void setBar(String bar) { this.bar = bar; } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/priv/PrivateBean.java100644 0 0 5052 12262570607 27271 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.priv; /** * Bean that has a private constructor that exposes properties via * various mechanisms (based on property name): *
            *
          • foo - Via direct public method *
          • bar - Via directly implemented interface *
          • baz - Via indirectly implemented interface *
          * * @version $Id: PrivateBean.java 1454597 2013-03-08 21:58:12Z britter $ */ class PrivateBean implements PrivateDirect { // ----------------------------------------------------------- Constructors /** * Package private constructor - can only use factory method to create * beans. */ PrivateBean() { super(); } // ------------------------------------------------------------- Properties /** * A directly implemented property. */ private final String foo = "This is foo"; public String getFoo() { return (this.foo); } /** * A property accessible via a directly implemented interface. */ private final String bar = "This is bar"; public String getBar() { return (this.bar); } /** * A method accessible via a directly implemented interface. */ public String methodBar(String in) { return (in); } /** * A property accessible via an indirectly implemented interface. */ private final String baz = "This is baz"; public String getBaz() { return (this.baz); } /** * A method accessible via an indirectly implemented interface. */ public String methodBaz(String in) { return (in); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/priv/PrivateBeanFactory.java100644 0 0 2553 12262570607 30624 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.priv; /** * Factory class for PrivateBean instances. * * @version $Id: PrivateBeanFactory.java 1454597 2013-03-08 21:58:12Z britter $ */ public class PrivateBeanFactory { /** * Factory method to create new beans. */ public static PrivateDirect create() { return (new PrivateBean()); } /** * Factory method to create new beans. */ public static PrivateDirect createSubclass() { return (new PrivateBeanSubclass()); } } ././@LongLink100644 0 0 145 12262571655 10266 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/priv/PrivateBeanSubclass.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/priv/PrivateBeanSubclass.java100644 0 0 3061 12262570607 30767 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.priv; /** * Bean that exposes methods defined by an interface that is implemented * in the superclass. * * @version $Id: PrivateBeanSubclass.java 1454606 2013-03-08 22:30:51Z britter $ */ class PrivateBeanSubclass extends PrivateBean { // ----------------------------------------------------------- Constructors /** * Create a new PrivateBeanSubclass instance. */ PrivateBeanSubclass() { super(); } // ------------------------------------------------------------- Properties /** * A property accessible via the superclass. */ @Override public String getBar() { return (super.getBar()); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/priv/PrivateDirect.java100644 0 0 2574 12262570607 27644 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.priv; /** * Interface that is directly implemented by PrivateBean. * * @version $Id: PrivateDirect.java 1454597 2013-03-08 21:58:12Z britter $ */ public interface PrivateDirect extends PrivateIndirect { // ------------------------------------------------------------- Properties /** * A property accessible via a directly implemented interface. */ String getBar(); /** * A method accessible via a directly implemented interface. */ String methodBar(String in); } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/priv/PrivateIndirect.java100644 0 0 2600 12262570607 30161 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.priv; /** * Interface that is indirectly implemented by PrivateBean. * * @version $Id: PrivateIndirect.java 1454597 2013-03-08 21:58:12Z britter $ */ public interface PrivateIndirect { // ------------------------------------------------------------- Properties /** * A property accessible via an indirectly implemented interface. */ public String getBaz(); /** * A method accessible via an indirectly implemented interface. */ public String methodBaz(String in); } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/priv/PublicSubBean.java100644 0 0 3630 12262570607 27547 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils.priv; /** *

          This class is designed to test the default access jvm problem workaround. * The issue is that public methods of a public subclass contained in a default access * superclass are returned by reflection but an IllegalAccessException is thrown * when they are invoked.

          * *

          This is the default access superclass

          * * @version $Id: PublicSubBean.java 1454597 2013-03-08 21:58:12Z britter $ */ public class PublicSubBean extends PackageBean { // ----------------------------------------------------------- Constructors /** * Package private constructor - can only use factory method to create * beans. */ public PublicSubBean() { super(); } // ------------------------------------------------------------- Properties /** * A directly implemented property. */ private String foo = "This is foo"; public String getFoo() { return (this.foo); } public void setFoo(String foo) { this.foo = foo; } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/PropertyUtilsBenchCase.java100644 0 0 20545 12262570607 30536 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * JUnit Test Case containing microbenchmarks for PropertyUtils. * * @version $Id: PropertyUtilsBenchCase.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class PropertyUtilsBenchCase extends TestCase { // ------------------------------------------------------------ Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public PropertyUtilsBenchCase(String name) { super(name); } // ------------------------------------------------------ Instance Variables // Basic loop counter private long counter = 100000; // DynaClass for inDyna and outDyna private DynaClass dynaClass = null; // Input objects that have identical sets of properties and values. private BenchBean inBean = null; private DynaBean inDyna = null; private Map inMap = null; // Output objects that have identical sets of properties. private BenchBean outBean = null; private DynaBean outDyna = null; // PropertyUtilsBean instance to be used private PropertyUtilsBean pu = null; // ---------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { // Set up loop counter (if property specified) String prop = System.getProperty("counter"); if (prop != null) { counter = Long.parseLong(prop); } // Set up DynaClass for our DynaBean instances dynaClass = new BasicDynaClass ("BenchDynaClass", null, new DynaProperty[]{ new DynaProperty("booleanProperty", Boolean.TYPE), new DynaProperty("byteProperty", Byte.TYPE), new DynaProperty("doubleProperty", Double.TYPE), new DynaProperty("floatProperty", Float.TYPE), new DynaProperty("intProperty", Integer.TYPE), new DynaProperty("longProperty", Long.TYPE), new DynaProperty("shortProperty", Short.TYPE), new DynaProperty("stringProperty", String.class), }); // Create input instances inBean = new BenchBean(); inMap = new HashMap(); inMap.put("booleanProperty", new Boolean(inBean.getBooleanProperty())); inMap.put("byteProperty", new Byte(inBean.getByteProperty())); inMap.put("doubleProperty", new Double(inBean.getDoubleProperty())); inMap.put("floatProperty", new Float(inBean.getFloatProperty())); inMap.put("intProperty", new Integer(inBean.getIntProperty())); inMap.put("longProperty", new Long(inBean.getLongProperty())); inMap.put("shortProperty", new Short(inBean.getShortProperty())); inMap.put("stringProperty", inBean.getStringProperty()); inDyna = dynaClass.newInstance(); for (Map.Entry e : inMap.entrySet()) { inDyna.set(e.getKey(), e.getValue()); } // Create output instances outBean = new BenchBean(); outDyna = dynaClass.newInstance(); inDyna = dynaClass.newInstance(); for (Map.Entry e : inMap.entrySet()) { outDyna.set(e.getKey(), e.getValue()); } // Set up PropertyUtilsBean instance we will use pu = PropertyUtilsBean.getInstance(); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(PropertyUtilsBenchCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { dynaClass = null; inBean = null; inDyna = null; inMap = null; outBean = null; outDyna = null; pu = null; } // ------------------------------------------------- Individual Test Methods // Time copyProperties() from a bean public void testCopyPropertiesBean() throws Exception { long start; long stop; // Bean->Bean for (long i = 0; i < counter; i++) { pu.copyProperties(outBean, inBean); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { pu.copyProperties(outBean, inBean); } stop = System.currentTimeMillis(); System.err.println("PU.copyProperties(bean,bean), count=" + counter + ", time=" + (stop - start)); // Bean->Dyna for (long i = 0; i < counter; i++) { pu.copyProperties(outDyna, inBean); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { pu.copyProperties(outDyna, inBean); } stop = System.currentTimeMillis(); System.err.println("PU.copyProperties(dyna,bean), count=" + counter + ", time=" + (stop - start)); } // Time copyProperties() from a DynaBean public void testCopyPropertiesDyna() throws Exception { long start; long stop; // Dyna->Bean for (long i = 0; i < counter; i++) { pu.copyProperties(outBean, inDyna); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { pu.copyProperties(outBean, inDyna); } stop = System.currentTimeMillis(); System.err.println("PU.copyProperties(bean,dyna), count=" + counter + ", time=" + (stop - start)); // Dyna->Dyna for (long i = 0; i < counter; i++) { pu.copyProperties(outDyna, inDyna); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { pu.copyProperties(outDyna, inDyna); } stop = System.currentTimeMillis(); System.err.println("PU.copyProperties(dyna,dyna), count=" + counter + ", time=" + (stop - start)); } // Time copyProperties() from a Map public void testCopyPropertiesMap() throws Exception { long start; long stop; // Dyna->Bean for (long i = 0; i < counter; i++) { pu.copyProperties(outBean, inMap); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { pu.copyProperties(outBean, inMap); } stop = System.currentTimeMillis(); System.err.println("PU.copyProperties(bean, map), count=" + counter + ", time=" + (stop - start)); // Dyna->Dyna for (long i = 0; i < counter; i++) { pu.copyProperties(outDyna, inMap); } start = System.currentTimeMillis(); for (long i = 0; i < counter; i++) { pu.copyProperties(outDyna, inMap); } stop = System.currentTimeMillis(); System.err.println("PU.copyProperties(dyna, map), count=" + counter + ", time=" + (stop - start)); } // --------------------------------------------------------- Support Methods } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/PropertyUtilsTestCase.java100644 0 0 517025 12262570607 30462 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.beanutils.priv.PrivateBeanFactory; import org.apache.commons.beanutils.priv.PrivateDirect; import org.apache.commons.beanutils.priv.PublicSubBean; /** *

          Test Case for the PropertyUtils class. The majority of these tests use * instances of the TestBean class, so be sure to update the tests if you * change the characteristics of that class.

          * *

          So far, this test case has tests for the following methods of the * PropertyUtils class:

          *
            *
          • getIndexedProperty(Object,String)
          • *
          • getIndexedProperty(Object,String,int)
          • *
          • getMappedProperty(Object,String)
          • *
          • getMappedProperty(Object,String,String
          • *
          • getNestedProperty(Object,String)
          • *
          • getPropertyDescriptor(Object,String)
          • *
          • getPropertyDescriptors(Object)
          • *
          • getPropertyType(Object,String)
          • *
          • getSimpleProperty(Object,String)
          • *
          • setIndexedProperty(Object,String,Object)
          • *
          • setIndexedProperty(Object,String,String,Object)
          • *
          • setMappedProperty(Object,String,Object)
          • *
          • setMappedProperty(Object,String,String,Object)
          • *
          • setNestedProperty(Object,String,Object)
          • *
          • setSimpleProperty(Object,String,Object)
          • *
          * * @version $Id: PropertyUtilsTestCase.java 1547898 2013-12-04 20:33:06Z oheger $ */ public class PropertyUtilsTestCase extends TestCase { // ---------------------------------------------------- Instance Variables /** * The fully qualified class name of our private directly * implemented interface. */ private static final String PRIVATE_DIRECT_CLASS = "org.apache.commons.beanutils.priv.PrivateDirect"; /** * The fully qualified class name of our private indirectly * implemented interface. */ private static final String PRIVATE_INDIRECT_CLASS = "org.apache.commons.beanutils.priv.PrivateIndirect"; /** * The fully qualified class name of our test bean class. */ private static final String TEST_BEAN_CLASS = "org.apache.commons.beanutils.TestBean"; /** * The basic test bean for each test. */ protected TestBean bean = null; /** * The "package private subclass" test bean for each test. */ protected TestBeanPackageSubclass beanPackageSubclass = null; /** * The test bean for private access tests. */ protected PrivateDirect beanPrivate = null; /** * The test bean for private access tests of subclasses. */ protected PrivateDirect beanPrivateSubclass = null; /** * The "public subclass" test bean for each test. */ protected TestBeanPublicSubclass beanPublicSubclass = null; /** * The set of properties that should be described. */ protected String describes[] = { "booleanProperty", "booleanSecond", "doubleProperty", "floatProperty", "intArray", // "intIndexed", "intProperty", "listIndexed", "longProperty", // "mappedObjects", // "mappedProperty", // "mappedIntProperty", "nested", "nullProperty", // "readOnlyProperty", "shortProperty", "stringArray", // "stringIndexed", "stringProperty" }; /** * The set of property names we expect to have returned when calling * getPropertyDescriptors(). You should update this list * when new properties are added to TestBean. */ protected final static String[] properties = { "booleanProperty", "booleanSecond", "doubleProperty", "dupProperty", "floatProperty", "intArray", "intIndexed", "intProperty", "listIndexed", "longProperty", "nested", "nullProperty", "readOnlyProperty", "shortProperty", "stringArray", "stringIndexed", "stringProperty", "writeOnlyProperty", }; // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public PropertyUtilsTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() { bean = new TestBean(); beanPackageSubclass = new TestBeanPackageSubclass(); beanPrivate = PrivateBeanFactory.create(); beanPrivateSubclass = PrivateBeanFactory.createSubclass(); beanPublicSubclass = new TestBeanPublicSubclass(); DynaProperty[] properties = new DynaProperty[] { new DynaProperty("stringProperty", String.class), new DynaProperty("nestedBean", TestBean.class), new DynaProperty("nullDynaBean", DynaBean.class) }; BasicDynaClass dynaClass = new BasicDynaClass("nestedDynaBean", BasicDynaBean.class, properties); BasicDynaBean nestedDynaBean = new BasicDynaBean(dynaClass); nestedDynaBean.set("nestedBean", bean); bean.setNestedDynaBean(nestedDynaBean); PropertyUtils.clearDescriptors(); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(PropertyUtilsTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { bean = null; beanPackageSubclass = null; beanPrivate = null; beanPrivateSubclass = null; beanPublicSubclass = null; PropertyUtils.resetBeanIntrospectors(); } // ------------------------------------------------ Individual Test Methods /** * Test copyProperties() when the origin is a a Map. */ public void testCopyPropertiesMap() { Map map = new HashMap(); map.put("booleanProperty", Boolean.FALSE); map.put("doubleProperty", new Double(333.0)); map.put("dupProperty", new String[] { "New 0", "New 1", "New 2" }); map.put("floatProperty", new Float((float) 222.0)); map.put("intArray", new int[] { 0, 100, 200 }); map.put("intProperty", new Integer(111)); map.put("longProperty", new Long(444)); map.put("shortProperty", new Short((short) 555)); map.put("stringProperty", "New String Property"); try { PropertyUtils.copyProperties(bean, map); } catch (Throwable t) { fail("Threw " + t.toString()); } // Scalar properties assertEquals("booleanProperty", false, bean.getBooleanProperty()); assertEquals("doubleProperty", 333.0, bean.getDoubleProperty(), 0.005); assertEquals("floatProperty", (float) 222.0, bean.getFloatProperty(), (float) 0.005); assertEquals("intProperty", 111, bean.getIntProperty()); assertEquals("longProperty", 444, bean.getLongProperty()); assertEquals("shortProperty", (short) 555, bean.getShortProperty()); assertEquals("stringProperty", "New String Property", bean.getStringProperty()); // Indexed Properties String dupProperty[] = bean.getDupProperty(); assertNotNull("dupProperty present", dupProperty); assertEquals("dupProperty length", 3, dupProperty.length); assertEquals("dupProperty[0]", "New 0", dupProperty[0]); assertEquals("dupProperty[1]", "New 1", dupProperty[1]); assertEquals("dupProperty[2]", "New 2", dupProperty[2]); int intArray[] = bean.getIntArray(); assertNotNull("intArray present", intArray); assertEquals("intArray length", 3, intArray.length); assertEquals("intArray[0]", 0, intArray[0]); assertEquals("intArray[1]", 100, intArray[1]); assertEquals("intArray[2]", 200, intArray[2]); } /** * Test the describe() method. */ public void testDescribe() { Map map = null; try { map = PropertyUtils.describe(bean); } catch (Exception e) { fail("Threw exception " + e); } // Verify existence of all the properties that should be present for (int i = 0; i < describes.length; i++) { assertTrue("Property '" + describes[i] + "' is present", map.containsKey(describes[i])); } assertTrue("Property 'writeOnlyProperty' is not present", !map.containsKey("writeOnlyProperty")); // Verify the values of scalar properties assertEquals("Value of 'booleanProperty'", Boolean.TRUE, map.get("booleanProperty")); assertEquals("Value of 'doubleProperty'", new Double(321.0), map.get("doubleProperty")); assertEquals("Value of 'floatProperty'", new Float((float) 123.0), map.get("floatProperty")); assertEquals("Value of 'intProperty'", new Integer(123), map.get("intProperty")); assertEquals("Value of 'longProperty'", new Long(321), map.get("longProperty")); assertEquals("Value of 'shortProperty'", new Short((short) 987), map.get("shortProperty")); assertEquals("Value of 'stringProperty'", "This is a string", (String) map.get("stringProperty")); } /** * Corner cases on getPropertyDescriptor invalid arguments. */ public void testGetDescriptorArguments() { try { PropertyUtils.getPropertyDescriptor(null, "stringProperty"); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getPropertyDescriptor(bean, null); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } } /** * Positive getPropertyDescriptor on property booleanProperty. */ public void testGetDescriptorBoolean() { testGetDescriptorBase("booleanProperty", "getBooleanProperty", "setBooleanProperty"); } /** * Positive getPropertyDescriptor on property doubleProperty. */ public void testGetDescriptorDouble() { testGetDescriptorBase("doubleProperty", "getDoubleProperty", "setDoubleProperty"); } /** * Positive getPropertyDescriptor on property floatProperty. */ public void testGetDescriptorFloat() { testGetDescriptorBase("floatProperty", "getFloatProperty", "setFloatProperty"); } /** * Positive getPropertyDescriptor on property intProperty. */ public void testGetDescriptorInt() { testGetDescriptorBase("intProperty", "getIntProperty", "setIntProperty"); } /** *

          Negative tests on an invalid property with two different boolean * getters (which is fine, according to the JavaBeans spec) but a * String setter instead of a boolean setter.

          * *

          Although one could logically argue that this combination of method * signatures should not identify a property at all, there is a sentence * in Section 8.3.1 making it clear that the behavior tested for here * is correct: "If we find only one of these methods, then we regard * it as defining either a read-only or write-only property called * <property-name>.

          */ public void testGetDescriptorInvalidBoolean() throws Exception { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, "invalidBoolean"); assertNotNull("invalidBoolean is a property", pd); assertNotNull("invalidBoolean has a getter method", pd.getReadMethod()); assertNull("invalidBoolean has no write method", pd.getWriteMethod()); assertTrue("invalidBoolean getter method is isInvalidBoolean", "isInvalidBoolean".equals(pd.getReadMethod().getName())); } /** * Positive getPropertyDescriptor on property longProperty. */ public void testGetDescriptorLong() { testGetDescriptorBase("longProperty", "getLongProperty", "setLongProperty"); } /** * Test getting mapped descriptor with periods in the key. */ public void testGetDescriptorMappedPeriods() { bean.getMappedIntProperty("xyz"); // initializes mappedIntProperty PropertyDescriptor desc; Integer testIntegerValue = new Integer(1234); bean.setMappedIntProperty("key.with.a.dot", testIntegerValue.intValue()); assertEquals("Can retrieve directly", testIntegerValue, new Integer(bean.getMappedIntProperty("key.with.a.dot"))); try { desc = PropertyUtils.getPropertyDescriptor (bean, "mappedIntProperty(key.with.a.dot)"); assertEquals("Check descriptor type (A)", Integer.TYPE, ((MappedPropertyDescriptor)desc).getMappedPropertyType()); } catch (Exception e) { fail("Threw exception (A): " + e); } bean.setMappedObjects("nested.property", new TestBean(testIntegerValue.intValue())); assertEquals("Can retrieve directly", testIntegerValue, new Integer(((TestBean)bean.getMappedObjects("nested.property")).getIntProperty())); try { desc = PropertyUtils.getPropertyDescriptor (bean, "mappedObjects(nested.property).intProperty"); assertEquals("Check descriptor type (B)", Integer.TYPE, desc.getPropertyType()); } catch (Exception e) { fail("Threw exception (B): " + e); } } /** * Positive getPropertyDescriptor on property * readOnlyProperty. */ public void testGetDescriptorReadOnly() { testGetDescriptorBase("readOnlyProperty", "getReadOnlyProperty", null); } /** * Positive getPropertyDescriptor on property booleanSecond * that uses an "is" method as the getter. */ public void testGetDescriptorSecond() { testGetDescriptorBase("booleanSecond", "isBooleanSecond", "setBooleanSecond"); } /** * Positive getPropertyDescriptor on property shortProperty. */ public void testGetDescriptorShort() { testGetDescriptorBase("shortProperty", "getShortProperty", "setShortProperty"); } /** * Positive getPropertyDescriptor on property stringProperty. */ public void testGetDescriptorString() { testGetDescriptorBase("stringProperty", "getStringProperty", "setStringProperty"); } /** * Negative getPropertyDescriptor on property unknown. */ public void testGetDescriptorUnknown() { testGetDescriptorBase("unknown", null, null); } /** * Positive getPropertyDescriptor on property * writeOnlyProperty. */ public void testGetDescriptorWriteOnly() { testGetDescriptorBase("writeOnlyProperty", null, "setWriteOnlyProperty"); } /** * Positive test for getPropertyDescriptors(). Each property name * listed in properties should be returned exactly once. */ public void testGetDescriptors() { PropertyDescriptor pd[] = PropertyUtils.getPropertyDescriptors(bean); assertNotNull("Got descriptors", pd); int count[] = new int[properties.length]; for (int i = 0; i < pd.length; i++) { String name = pd[i].getName(); for (int j = 0; j < properties.length; j++) { if (name.equals(properties[j])) count[j]++; } } for (int j = 0; j < properties.length; j++) { if (count[j] < 0) fail("Missing property " + properties[j]); else if (count[j] > 1) fail("Duplicate property " + properties[j]); } } /** * Corner cases on getPropertyDescriptors invalid arguments. */ public void testGetDescriptorsArguments() { try { PropertyUtils.getPropertyDescriptors(null); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException"); } } /** * Corner cases on getIndexedProperty invalid arguments. */ public void testGetIndexedArguments() { // Use explicit index argument try { PropertyUtils.getIndexedProperty(null, "intArray", 0); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getIndexedProperty(bean, null, 0); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } // Use index expression try { PropertyUtils.getIndexedProperty(null, "intArray[0]"); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } try { PropertyUtils.getIndexedProperty(bean, "[0]"); fail("Should throw NoSuchMethodException 4"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 4"); } try { PropertyUtils.getIndexedProperty(bean, "intArray"); fail("Should throw IllegalArgumentException 5"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 5"); } // Use explicit index argument try { PropertyUtils.getIndexedProperty(null, "intIndexed", 0); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getIndexedProperty(bean, null, 0); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } // Use index expression try { PropertyUtils.getIndexedProperty(null, "intIndexed[0]"); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } try { PropertyUtils.getIndexedProperty(bean, "[0]"); fail("Should throw NoSuchMethodException 4"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 4"); } try { PropertyUtils.getIndexedProperty(bean, "intIndexed"); fail("Should throw IllegalArgumentException 5"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 5"); } } /** * Positive and negative tests on getIndexedProperty valid arguments. */ public void testGetIndexedValues() { Object value = null; // Use explicit key argument for (int i = 0; i < 5; i++) { try { value = PropertyUtils.getIndexedProperty (bean, "dupProperty", i); assertNotNull("dupProperty returned value " + i, value); assertTrue("dupProperty returned String " + i, value instanceof String); assertEquals("dupProperty returned correct " + i, "Dup " + i, (String) value); } catch (Throwable t) { fail("dupProperty " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "intArray", i); assertNotNull("intArray returned value " + i, value); assertTrue("intArray returned Integer " + i, value instanceof Integer); assertEquals("intArray returned correct " + i, i * 10, ((Integer) value).intValue()); } catch (Throwable t) { fail("intArray " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "intIndexed", i); assertNotNull("intIndexed returned value " + i, value); assertTrue("intIndexed returned Integer " + i, value instanceof Integer); assertEquals("intIndexed returned correct " + i, i * 10, ((Integer) value).intValue()); } catch (Throwable t) { fail("intIndexed " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "listIndexed", i); assertNotNull("listIndexed returned value " + i, value); assertTrue("list returned String " + i, value instanceof String); assertEquals("listIndexed returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("listIndexed " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "stringArray", i); assertNotNull("stringArray returned value " + i, value); assertTrue("stringArray returned String " + i, value instanceof String); assertEquals("stringArray returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("stringArray " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "stringIndexed", i); assertNotNull("stringIndexed returned value " + i, value); assertTrue("stringIndexed returned String " + i, value instanceof String); assertEquals("stringIndexed returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("stringIndexed " + i + " threw " + t); } } // Use key expression for (int i = 0; i < 5; i++) { try { value = PropertyUtils.getIndexedProperty (bean, "dupProperty[" + i + "]"); assertNotNull("dupProperty returned value " + i, value); assertTrue("dupProperty returned String " + i, value instanceof String); assertEquals("dupProperty returned correct " + i, "Dup " + i, (String) value); } catch (Throwable t) { fail("dupProperty " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "intArray[" + i + "]"); assertNotNull("intArray returned value " + i, value); assertTrue("intArray returned Integer " + i, value instanceof Integer); assertEquals("intArray returned correct " + i, i * 10, ((Integer) value).intValue()); } catch (Throwable t) { fail("intArray " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "intIndexed[" + i + "]"); assertNotNull("intIndexed returned value " + i, value); assertTrue("intIndexed returned Integer " + i, value instanceof Integer); assertEquals("intIndexed returned correct " + i, i * 10, ((Integer) value).intValue()); } catch (Throwable t) { fail("intIndexed " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "listIndexed[" + i + "]"); assertNotNull("listIndexed returned value " + i, value); assertTrue("listIndexed returned String " + i, value instanceof String); assertEquals("listIndexed returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("listIndexed " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "stringArray[" + i + "]"); assertNotNull("stringArray returned value " + i, value); assertTrue("stringArray returned String " + i, value instanceof String); assertEquals("stringArray returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("stringArray " + i + " threw " + t); } try { value = PropertyUtils.getIndexedProperty(bean, "stringIndexed[" + i + "]"); assertNotNull("stringIndexed returned value " + i, value); assertTrue("stringIndexed returned String " + i, value instanceof String); assertEquals("stringIndexed returned correct " + i, "String " + i, (String) value); } catch (Throwable t) { fail("stringIndexed " + i + " threw " + t); } } // Index out of bounds tests try { value = PropertyUtils.getIndexedProperty(bean, "dupProperty", -1); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "dupProperty", 5); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "intArray", -1); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "intArray", 5); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "intIndexed", -1); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "intIndexed", 5); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "listIndexed", -1); fail("Should have thrown IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of IndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "listIndexed", 5); fail("Should have thrown IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of IndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "stringArray", -1); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "stringArray", 5); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "stringIndexed", -1); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { value = PropertyUtils.getIndexedProperty(bean, "stringIndexed", 5); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } } /** * Test getting an indexed value out of a multi-dimensional array */ public void testGetIndexedArray() { String[] firstArray = new String[] {"FIRST-1", "FIRST-2", "FIRST-3"}; String[] secondArray = new String[] {"SECOND-1", "SECOND-2", "SECOND-3", "SECOND-4"}; String[][] mainArray = {firstArray, secondArray}; TestBean bean = new TestBean(mainArray); try { assertEquals("firstArray[0]", firstArray[0], PropertyUtils.getProperty(bean, "string2dArray[0][0]")); assertEquals("firstArray[1]", firstArray[1], PropertyUtils.getProperty(bean, "string2dArray[0][1]")); assertEquals("firstArray[2]", firstArray[2], PropertyUtils.getProperty(bean, "string2dArray[0][2]")); assertEquals("secondArray[0]", secondArray[0], PropertyUtils.getProperty(bean, "string2dArray[1][0]")); assertEquals("secondArray[1]", secondArray[1], PropertyUtils.getProperty(bean, "string2dArray[1][1]")); assertEquals("secondArray[2]", secondArray[2], PropertyUtils.getProperty(bean, "string2dArray[1][2]")); assertEquals("secondArray[3]", secondArray[3], PropertyUtils.getProperty(bean, "string2dArray[1][3]")); } catch (Throwable t) { fail("Threw " + t + ""); } } /** * Test getting an indexed value out of List of Lists */ public void testGetIndexedList() { String[] firstArray = new String[] {"FIRST-1", "FIRST-2", "FIRST-3"}; String[] secondArray = new String[] {"SECOND-1", "SECOND-2", "SECOND-3", "SECOND-4"}; List mainList = new ArrayList(); mainList.add(Arrays.asList(firstArray)); mainList.add(Arrays.asList(secondArray)); TestBean bean = new TestBean(mainList); try { assertEquals("firstArray[0]", firstArray[0], PropertyUtils.getProperty(bean, "listIndexed[0][0]")); assertEquals("firstArray[1]", firstArray[1], PropertyUtils.getProperty(bean, "listIndexed[0][1]")); assertEquals("firstArray[2]", firstArray[2], PropertyUtils.getProperty(bean, "listIndexed[0][2]")); assertEquals("secondArray[0]", secondArray[0], PropertyUtils.getProperty(bean, "listIndexed[1][0]")); assertEquals("secondArray[1]", secondArray[1], PropertyUtils.getProperty(bean, "listIndexed[1][1]")); assertEquals("secondArray[2]", secondArray[2], PropertyUtils.getProperty(bean, "listIndexed[1][2]")); assertEquals("secondArray[3]", secondArray[3], PropertyUtils.getProperty(bean, "listIndexed[1][3]")); } catch (Throwable t) { fail("Threw " + t + ""); } } /** * Test getting a value out of a mapped Map */ public void testGetIndexedMap() { Map firstMap = new HashMap(); firstMap.put("FIRST-KEY-1", "FIRST-VALUE-1"); firstMap.put("FIRST-KEY-2", "FIRST-VALUE-2"); Map secondMap = new HashMap(); secondMap.put("SECOND-KEY-1", "SECOND-VALUE-1"); secondMap.put("SECOND-KEY-2", "SECOND-VALUE-2"); List mainList = new ArrayList(); mainList.add(firstMap); mainList.add(secondMap); TestBean bean = new TestBean(mainList); try { assertEquals("listIndexed[0](FIRST-KEY-1)", "FIRST-VALUE-1", PropertyUtils.getProperty(bean, "listIndexed[0](FIRST-KEY-1)")); assertEquals("listIndexed[0](FIRST-KEY-2)", "FIRST-VALUE-2", PropertyUtils.getProperty(bean, "listIndexed[0](FIRST-KEY-2)")); assertEquals("listIndexed[1](SECOND-KEY-1)", "SECOND-VALUE-1", PropertyUtils.getProperty(bean, "listIndexed[1](SECOND-KEY-1)")); assertEquals("listIndexed[1](SECOND-KEY-2)", "SECOND-VALUE-2", PropertyUtils.getProperty(bean, "listIndexed[1](SECOND-KEY-2)")); } catch (Throwable t) { fail("Threw " + t + ""); } } /** * Corner cases on getMappedProperty invalid arguments. */ public void testGetMappedArguments() { // Use explicit key argument try { PropertyUtils.getMappedProperty(null, "mappedProperty", "First Key"); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getMappedProperty(bean, null, "First Key"); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } try { PropertyUtils.getMappedProperty(bean, "mappedProperty", null); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } // Use key expression try { PropertyUtils.getMappedProperty(null, "mappedProperty(First Key)"); fail("Should throw IllegalArgumentException 4"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 4"); } try { PropertyUtils.getMappedProperty(bean, "(Second Key)"); fail("Should throw IllegalArgumentException 5"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 5"); } try { PropertyUtils.getMappedProperty(bean, "mappedProperty"); fail("Should throw IllegalArgumentException 6"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 6"); } } /** * Test getting an indexed value out of a mapped array */ public void testGetMappedArray() { TestBean bean = new TestBean(); String[] array = new String[] {"abc", "def", "ghi"}; bean.getMapProperty().put("mappedArray", array); try { assertEquals("abc", PropertyUtils.getProperty(bean, "mapProperty(mappedArray)[0]")); assertEquals("def", PropertyUtils.getProperty(bean, "mapProperty(mappedArray)[1]")); assertEquals("ghi", PropertyUtils.getProperty(bean, "mapProperty(mappedArray)[2]")); } catch (Throwable t) { fail("Threw " + t + ""); } } /** * Test getting an indexed value out of a mapped List */ public void testGetMappedList() { TestBean bean = new TestBean(); List list = new ArrayList(); list.add("klm"); list.add("nop"); list.add("qrs"); bean.getMapProperty().put("mappedList", list); try { assertEquals("klm", PropertyUtils.getProperty(bean, "mapProperty(mappedList)[0]")); assertEquals("nop", PropertyUtils.getProperty(bean, "mapProperty(mappedList)[1]")); assertEquals("qrs", PropertyUtils.getProperty(bean, "mapProperty(mappedList)[2]")); } catch (Throwable t) { fail("Threw " + t + ""); } } /** * Test getting a value out of a mapped Map */ public void testGetMappedMap() { TestBean bean = new TestBean(); Map map = new HashMap(); map.put("sub-key-1", "sub-value-1"); map.put("sub-key-2", "sub-value-2"); map.put("sub-key-3", "sub-value-3"); bean.getMapProperty().put("mappedMap", map); try { assertEquals("sub-value-1", PropertyUtils.getProperty(bean, "mapProperty(mappedMap)(sub-key-1)")); assertEquals("sub-value-2", PropertyUtils.getProperty(bean, "mapProperty(mappedMap)(sub-key-2)")); assertEquals("sub-value-3", PropertyUtils.getProperty(bean, "mapProperty(mappedMap)(sub-key-3)")); } catch (Throwable t) { fail("Threw " + t + ""); } } /** * Test getting mapped values with periods in the key. */ public void testGetMappedPeriods() { bean.setMappedProperty("key.with.a.dot", "Special Value"); assertEquals("Can retrieve directly", "Special Value", bean.getMappedProperty("key.with.a.dot")); try { assertEquals("Can retrieve via getMappedProperty", "Special Value", PropertyUtils.getMappedProperty (bean, "mappedProperty", "key.with.a.dot")); } catch (Exception e) { fail("Thew exception: " + e); } try { assertEquals("Can retrieve via getNestedProperty", "Special Value", PropertyUtils.getNestedProperty (bean, "mappedProperty(key.with.a.dot)")); } catch (Exception e) { fail("Thew exception: " + e); } bean.setMappedObjects("nested.property", new TestBean()); assertNotNull("Can retrieve directly", bean.getMappedObjects("nested.property")); try { assertEquals("Can retrieve nested", "This is a string", PropertyUtils.getNestedProperty (bean, "mappedObjects(nested.property).stringProperty")); } catch (Exception e) { fail("Thew exception: " + e); } try { assertEquals("Can't retrieved nested with mapped property", "Mapped Value", PropertyUtils.getNestedProperty( bean,"mappedNested.value(Mapped Key)")); } catch (Exception e) { fail("Thew exception: " + e); } } /** * Test getting mapped values with slashes in the key. This is different * from periods because slashes are not syntactically significant. */ public void testGetMappedSlashes() { bean.setMappedProperty("key/with/a/slash", "Special Value"); assertEquals("Can retrieve directly", "Special Value", bean.getMappedProperty("key/with/a/slash")); try { assertEquals("Can retrieve via getMappedProperty", "Special Value", PropertyUtils.getMappedProperty (bean, "mappedProperty", "key/with/a/slash")); } catch (Exception e) { fail("Thew exception: " + e); } try { assertEquals("Can retrieve via getNestedProperty", "Special Value", PropertyUtils.getNestedProperty (bean, "mappedProperty(key/with/a/slash)")); } catch (Exception e) { fail("Thew exception: " + e); } bean.setMappedObjects("nested/property", new TestBean()); assertNotNull("Can retrieve directly", bean.getMappedObjects("nested/property")); try { assertEquals("Can retrieve nested", "This is a string", PropertyUtils.getNestedProperty (bean, "mappedObjects(nested/property).stringProperty")); } catch (Exception e) { fail("Thew exception: " + e); } } /** * Positive and negative tests on getMappedProperty valid arguments. */ public void testGetMappedValues() { Object value = null; // Use explicit key argument try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty", "First Key"); assertEquals("Can find first value", "First Value", value); } catch (Throwable t) { fail("Finding first value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty", "Second Key"); assertEquals("Can find second value", "Second Value", value); } catch (Throwable t) { fail("Finding second value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty", "Third Key"); assertNull("Can not find third value", value); } catch (Throwable t) { fail("Finding third value threw " + t); } // Use key expression with parentheses try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty(First Key)"); assertEquals("Can find first value", "First Value", value); } catch (Throwable t) { fail("Finding first value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty(Second Key)"); assertEquals("Can find second value", "Second Value", value); } catch (Throwable t) { fail("Finding second value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty(Third Key)"); assertNull("Can not find third value", value); } catch (Throwable t) { fail("Finding third value threw " + t); } // Use key expression with dotted syntax try { value = PropertyUtils.getNestedProperty(bean, "mapProperty.First Key"); assertEquals("Can find first value", "First Value", value); } catch (Throwable t) { fail("Finding first value threw " + t); } try { value = PropertyUtils.getNestedProperty(bean, "mapProperty.Second Key"); assertEquals("Can find second value", "Second Value", value); } catch (Throwable t) { fail("Finding second value threw " + t); } try { value = PropertyUtils.getNestedProperty(bean, "mapProperty.Third Key"); assertNull("Can not find third value", value); } catch (Throwable t) { fail("Finding third value threw " + t); } } /** * Corner cases on getNestedProperty invalid arguments. */ public void testGetNestedArguments() { try { PropertyUtils.getNestedProperty(null, "stringProperty"); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getNestedProperty(bean, null); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } } /** * Test getNestedProperty on a boolean property. */ public void testGetNestedBoolean() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.booleanProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Boolean)); assertTrue("Got correct value", ((Boolean) value).booleanValue() == bean.getNested().getBooleanProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a double property. */ public void testGetNestedDouble() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.doubleProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Double)); assertEquals("Got correct value", ((Double) value).doubleValue(), bean.getNested().getDoubleProperty(), 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a float property. */ public void testGetNestedFloat() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.floatProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Float)); assertEquals("Got correct value", ((Float) value).floatValue(), bean.getNested().getFloatProperty(), (float) 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on an int property. */ public void testGetNestedInt() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.intProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Integer)); assertEquals("Got correct value", ((Integer) value).intValue(), bean.getNested().getIntProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a long property. */ public void testGetNestedLong() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.longProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Long)); assertEquals("Got correct value", ((Long) value).longValue(), bean.getNested().getLongProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a read-only String property. */ public void testGetNestedReadOnly() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.readOnlyProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof String)); assertEquals("Got correct value", (String) value, bean.getReadOnlyProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a short property. */ public void testGetNestedShort() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.shortProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Short)); assertEquals("Got correct value", ((Short) value).shortValue(), bean.getNested().getShortProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getNestedProperty on a String property. */ public void testGetNestedString() { try { Object value = PropertyUtils.getNestedProperty (bean, "nested.stringProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof String)); assertEquals("Got correct value", ((String) value), bean.getNested().getStringProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test getNestedProperty on an unknown property. */ public void testGetNestedUnknown() { try { PropertyUtils.getNestedProperty(bean, "nested.unknown"); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test } } /** * When a bean has a null property which is reference by the standard access language, * this should throw a NestedNullException. */ public void testThrowNestedNull() throws Exception { NestedTestBean nestedBean = new NestedTestBean("base"); // don't init! try { PropertyUtils.getProperty( nestedBean, "simpleBeanProperty.indexedProperty[0]"); fail("NestedNullException not thrown"); } catch (NestedNullException e) { // that's what we wanted! } } /** * Test getNestedProperty on a write-only String property. */ public void testGetNestedWriteOnly() { try { PropertyUtils.getNestedProperty(bean, "writeOnlyProperty"); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test } } /** * Test getPropertyType() on all kinds of properties. */ public void testGetPropertyType() { Class clazz = null; int intArray[] = new int[0]; String stringArray[] = new String[0]; try { // Scalar and Indexed Properties clazz = PropertyUtils.getPropertyType(bean, "booleanProperty"); assertEquals("booleanProperty type", Boolean.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "booleanSecond"); assertEquals("booleanSecond type", Boolean.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "doubleProperty"); assertEquals("doubleProperty type", Double.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "dupProperty"); assertEquals("dupProperty type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "floatProperty"); assertEquals("floatProperty type", Float.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "intArray"); assertEquals("intArray type", intArray.getClass(), clazz); clazz = PropertyUtils.getPropertyType(bean, "intIndexed"); assertEquals("intIndexed type", Integer.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "intProperty"); assertEquals("intProperty type", Integer.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "listIndexed"); assertEquals("listIndexed type", List.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "longProperty"); assertEquals("longProperty type", Long.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "mappedProperty"); assertEquals("mappedProperty type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "mappedIntProperty"); assertEquals("mappedIntProperty type", Integer.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "readOnlyProperty"); assertEquals("readOnlyProperty type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "shortProperty"); assertEquals("shortProperty type", Short.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "stringArray"); assertEquals("stringArray type", stringArray.getClass(), clazz); clazz = PropertyUtils.getPropertyType(bean, "stringIndexed"); assertEquals("stringIndexed type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "stringProperty"); assertEquals("stringProperty type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "writeOnlyProperty"); assertEquals("writeOnlyProperty type", String.class, clazz); // Nested Properties clazz = PropertyUtils.getPropertyType(bean, "nested.booleanProperty"); assertEquals("booleanProperty type", Boolean.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.booleanSecond"); assertEquals("booleanSecond type", Boolean.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.doubleProperty"); assertEquals("doubleProperty type", Double.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.dupProperty"); assertEquals("dupProperty type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.floatProperty"); assertEquals("floatProperty type", Float.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.intArray"); assertEquals("intArray type", intArray.getClass(), clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.intIndexed"); assertEquals("intIndexed type", Integer.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.intProperty"); assertEquals("intProperty type", Integer.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.listIndexed"); assertEquals("listIndexed type", List.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.longProperty"); assertEquals("longProperty type", Long.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.mappedProperty"); assertEquals("mappedProperty type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.mappedIntProperty"); assertEquals("mappedIntProperty type", Integer.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.readOnlyProperty"); assertEquals("readOnlyProperty type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.shortProperty"); assertEquals("shortProperty type", Short.TYPE, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.stringArray"); assertEquals("stringArray type", stringArray.getClass(), clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.stringIndexed"); assertEquals("stringIndexed type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.stringProperty"); assertEquals("stringProperty type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "nested.writeOnlyProperty"); assertEquals("writeOnlyProperty type", String.class, clazz); // Nested DynaBean clazz = PropertyUtils.getPropertyType(bean, "nestedDynaBean"); assertEquals("nestedDynaBean type", DynaBean.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "nestedDynaBean.stringProperty"); assertEquals("nestedDynaBean.stringProperty type", String.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "nestedDynaBean.nestedBean"); assertEquals("nestedDynaBean.nestedBean type", TestBean.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "nestedDynaBean.nestedBean.nestedDynaBean"); assertEquals("nestedDynaBean.nestedBean.nestedDynaBean type", DynaBean.class, clazz); clazz = PropertyUtils.getPropertyType(bean, "nestedDynaBean.nestedBean.nestedDynaBean.stringProperty"); assertEquals("nestedDynaBean.nestedBean.nestedDynaBean.stringPropert type", String.class, clazz); // test Null clazz = PropertyUtils.getPropertyType(bean, "nestedDynaBean.nullDynaBean"); assertEquals("nestedDynaBean.nullDynaBean type", DynaBean.class, clazz); try { clazz = PropertyUtils.getPropertyType(bean, "nestedDynaBean.nullDynaBean.foo"); fail("Expected NestedNullException for nestedDynaBean.nullDynaBean.foo"); } catch (NestedNullException e) { // expected } } catch (Exception e) { fail("Exception: " + e.getMessage()); } } /** * Test accessing a public sub-bean of a package scope bean */ public void testGetPublicSubBean_of_PackageBean() { PublicSubBean bean = new PublicSubBean(); bean.setFoo("foo-start"); bean.setBar("bar-start"); Object result = null; // Get Foo try { result = PropertyUtils.getProperty(bean, "foo"); } catch (Throwable t) { fail("getProperty(foo) threw " + t); } assertEquals("foo property", "foo-start", result); // Get Bar try { result = PropertyUtils.getProperty(bean, "bar"); } catch (Throwable t) { fail("getProperty(bar) threw " + t); } assertEquals("bar property", "bar-start", result); } /** * Test getting accessible property reader methods for a specified * list of properties of our standard test bean. */ public void testGetReadMethodBasic() { testGetReadMethod(bean, properties, TEST_BEAN_CLASS); } /** * Test getting accessible property reader methods for a specified * list of properties of a package private subclass of our standard * test bean. */ public void testGetReadMethodPackageSubclass() { testGetReadMethod(beanPackageSubclass, properties, TEST_BEAN_CLASS); } /** * Test getting accessible property reader methods for a specified * list of properties that are declared either directly or via * implemented interfaces. */ public void testGetReadMethodPublicInterface() { // Properties "bar" and "baz" are visible via implemented interfaces // (one direct and one indirect) testGetReadMethod(beanPrivate, new String[]{ "bar" }, PRIVATE_DIRECT_CLASS); testGetReadMethod(beanPrivate, new String[]{ "baz" }, PRIVATE_INDIRECT_CLASS); // Properties "bar" and "baz" are visible via implemented interfaces // (one direct and one indirect). The interface is implemented in // a superclass testGetReadMethod(beanPrivateSubclass, new String[]{ "bar" }, PRIVATE_DIRECT_CLASS); testGetReadMethod(beanPrivateSubclass, new String[]{ "baz" }, PRIVATE_INDIRECT_CLASS); // Property "foo" is not accessible because the underlying // class has package scope PropertyDescriptor pd[] = PropertyUtils.getPropertyDescriptors(beanPrivate); int n = -1; for (int i = 0; i < pd.length; i++) { if ("foo".equals(pd[i].getName())) { n = i; break; } } assertTrue("Found foo descriptor", n >= 0); Method reader = pd[n].getReadMethod(); assertNotNull("Found foo read method", reader); try { reader.invoke(beanPrivate, (Object[]) new Class[0]); fail("Foo reader did throw IllegalAccessException"); } catch (IllegalAccessException e) { // Expected result for this test } catch (Throwable t) { fail("Invoke foo reader: " + t); } } /** * Test getting accessible property reader methods for a specified * list of properties of a public subclass of our standard test bean. */ public void testGetReadMethodPublicSubclass() { testGetReadMethod(beanPublicSubclass, properties, TEST_BEAN_CLASS); } /** * Corner cases on getSimpleProperty invalid arguments. */ public void testGetSimpleArguments() { try { PropertyUtils.getSimpleProperty(null, "stringProperty"); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.getSimpleProperty(bean, null); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } } /** * Test getSimpleProperty on a boolean property. */ public void testGetSimpleBoolean() { try { Object value = PropertyUtils.getSimpleProperty(bean, "booleanProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Boolean)); assertTrue("Got correct value", ((Boolean) value).booleanValue() == bean.getBooleanProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a double property. */ public void testGetSimpleDouble() { try { Object value = PropertyUtils.getSimpleProperty(bean, "doubleProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Double)); assertEquals("Got correct value", ((Double) value).doubleValue(), bean.getDoubleProperty(), 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a float property. */ public void testGetSimpleFloat() { try { Object value = PropertyUtils.getSimpleProperty(bean, "floatProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Float)); assertEquals("Got correct value", ((Float) value).floatValue(), bean.getFloatProperty(), (float) 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test getSimpleProperty on an indexed property. */ public void testGetSimpleIndexed() { try { PropertyUtils.getSimpleProperty(bean, "intIndexed[0]"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { // Correct result for this test } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on an int property. */ public void testGetSimpleInt() { try { Object value = PropertyUtils.getSimpleProperty(bean, "intProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Integer)); assertEquals("Got correct value", ((Integer) value).intValue(), bean.getIntProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a long property. */ public void testGetSimpleLong() { try { Object value = PropertyUtils.getSimpleProperty(bean, "longProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Long)); assertEquals("Got correct value", ((Long) value).longValue(), bean.getLongProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test getSimpleProperty on a nested property. */ public void testGetSimpleNested() { try { PropertyUtils.getSimpleProperty(bean, "nested.stringProperty"); fail("Should have thrown IllegaArgumentException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { // Correct result for this test } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a read-only String property. */ public void testGetSimpleReadOnly() { try { Object value = PropertyUtils.getSimpleProperty(bean, "readOnlyProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof String)); assertEquals("Got correct value", (String) value, bean.getReadOnlyProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a short property. */ public void testGetSimpleShort() { try { Object value = PropertyUtils.getSimpleProperty(bean, "shortProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof Short)); assertEquals("Got correct value", ((Short) value).shortValue(), bean.getShortProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test getSimpleProperty on a String property. */ public void testGetSimpleString() { try { Object value = PropertyUtils.getSimpleProperty(bean, "stringProperty"); assertNotNull("Got a value", value); assertTrue("Got correct type", (value instanceof String)); assertEquals("Got correct value", (String) value, bean.getStringProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test getSimpleProperty on an unknown property. */ public void testGetSimpleUnknown() { try { PropertyUtils.getSimpleProperty(bean, "unknown"); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test assertEquals("Unknown property 'unknown' on class '" + bean.getClass() + "'", e.getMessage() ); } } /** * Test getSimpleProperty on a write-only String property. */ public void testGetSimpleWriteOnly() { try { PropertyUtils.getSimpleProperty(bean, "writeOnlyProperty"); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test assertEquals("Property 'writeOnlyProperty' has no getter method in class '" + bean.getClass() + "'", e.getMessage() ); } } /** * Test getting accessible property writer methods for a specified * list of properties of our standard test bean. */ public void testGetWriteMethodBasic() { testGetWriteMethod(bean, properties, TEST_BEAN_CLASS); } /** * Test getting accessible property writer methods for a specified * list of properties of a package private subclass of our standard * test bean. */ public void testGetWriteMethodPackageSubclass() { testGetWriteMethod(beanPackageSubclass, properties, TEST_BEAN_CLASS); } /** * Test getting accessible property writer methods for a specified * list of properties of a public subclass of our standard test bean. */ public void testGetWriteMethodPublicSubclass() { testGetWriteMethod(beanPublicSubclass, properties, TEST_BEAN_CLASS); } /** * Test isReadable() method. */ public void testIsReadable() { String property = null; try { property = "stringProperty"; assertTrue("Property " + property +" isReadable expeced TRUE", PropertyUtils.isReadable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isReadable Threw exception: " + t); } try { property = "stringIndexed"; assertTrue("Property " + property +" isReadable expeced TRUE", PropertyUtils.isReadable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isReadable Threw exception: " + t); } try { property = "mappedProperty"; assertTrue("Property " + property +" isReadable expeced TRUE", PropertyUtils.isReadable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isReadable Threw exception: " + t); } try { property = "nestedDynaBean"; assertTrue("Property " + property +" isReadable expeced TRUE", PropertyUtils.isReadable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isReadable Threw exception: " + t); } try { property = "nestedDynaBean.stringProperty"; assertTrue("Property " + property +" isReadable expeced TRUE", PropertyUtils.isReadable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isReadable Threw exception: " + t); } try { property = "nestedDynaBean.nestedBean"; assertTrue("Property " + property +" isReadable expeced TRUE", PropertyUtils.isReadable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isReadable Threw exception: " + t); } try { property = "nestedDynaBean.nestedBean.nestedDynaBean"; assertTrue("Property " + property +" isReadable expeced TRUE", PropertyUtils.isReadable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isReadable Threw exception: " + t); } try { property = "nestedDynaBean.nestedBean.nestedDynaBean.stringProperty"; assertTrue("Property " + property +" isReadable expeced TRUE", PropertyUtils.isReadable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isReadable Threw exception: " + t); } try { property = "nestedDynaBean.nullDynaBean"; assertTrue("Property " + property +" isReadable expeced TRUE", PropertyUtils.isReadable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isReadable Threw exception: " + t); } try { property = "nestedDynaBean.nullDynaBean.foo"; assertTrue("Property " + property +" isReadable expeced TRUE", PropertyUtils.isReadable(bean, property)); fail("Property " + property +" isReadable expected NestedNullException"); } catch (NestedNullException e) { // expected result } catch (Throwable t) { fail("Property " + property +" isReadable Threw exception: " + t); } } /** * Test isWriteable() method. */ public void testIsWriteable() { String property = null; try { property = "stringProperty"; assertTrue("Property " + property +" isWriteable expeced TRUE", PropertyUtils.isWriteable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isWriteable Threw exception: " + t); } try { property = "stringIndexed"; assertTrue("Property " + property +" isWriteable expeced TRUE", PropertyUtils.isWriteable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isWriteable Threw exception: " + t); } try { property = "mappedProperty"; assertTrue("Property " + property +" isWriteable expeced TRUE", PropertyUtils.isWriteable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isWriteable Threw exception: " + t); } try { property = "nestedDynaBean"; assertTrue("Property " + property +" isWriteable expeced TRUE", PropertyUtils.isWriteable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isWriteable Threw exception: " + t); } try { property = "nestedDynaBean.stringProperty"; assertTrue("Property " + property +" isWriteable expeced TRUE", PropertyUtils.isWriteable(bean, property)); } catch (Throwable t) { t.printStackTrace(); fail("Property " + property +" isWriteable Threw exception: " + t); } try { property = "nestedDynaBean.nestedBean"; assertTrue("Property " + property +" isWriteable expeced TRUE", PropertyUtils.isWriteable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isWriteable Threw exception: " + t); } try { property = "nestedDynaBean.nestedBean.nestedDynaBean"; assertTrue("Property " + property +" isWriteable expeced TRUE", PropertyUtils.isWriteable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isWriteable Threw exception: " + t); } try { property = "nestedDynaBean.nestedBean.nestedDynaBean.stringProperty"; assertTrue("Property " + property +" isWriteable expeced TRUE", PropertyUtils.isWriteable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isWriteable Threw exception: " + t); } try { property = "nestedDynaBean.nullDynaBean"; assertTrue("Property " + property +" isWriteable expeced TRUE", PropertyUtils.isWriteable(bean, property)); } catch (Throwable t) { fail("Property " + property +" isWriteable Threw exception: " + t); } try { property = "nestedDynaBean.nullDynaBean.foo"; assertTrue("Property " + property +" isWriteable expeced TRUE", PropertyUtils.isWriteable(bean, property)); fail("Property " + property +" isWriteable expected NestedNullException"); } catch (NestedNullException e) { // expected result } catch (Throwable t) { fail("Property " + property +" isWriteable Threw exception: " + t); } } /** * Test the mappedPropertyType of MappedPropertyDescriptor. */ public void testMappedPropertyType() throws Exception { MappedPropertyDescriptor desc; // Check a String property desc = (MappedPropertyDescriptor) PropertyUtils.getPropertyDescriptor(bean, "mappedProperty"); assertEquals(String.class, desc.getMappedPropertyType()); // Check an int property desc = (MappedPropertyDescriptor) PropertyUtils.getPropertyDescriptor(bean, "mappedIntProperty"); assertEquals(Integer.TYPE, desc.getMappedPropertyType()); } /** * Corner cases on setIndexedProperty invalid arguments. */ public void testSetIndexedArguments() { // Use explicit index argument try { PropertyUtils.setIndexedProperty(null, "intArray", 0, new Integer(1)); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.setIndexedProperty(bean, null, 0, new Integer(1)); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } // Use index expression try { PropertyUtils.setIndexedProperty(null, "intArray[0]", new Integer(1)); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } try { PropertyUtils.setIndexedProperty(bean, "[0]", new Integer(1)); fail("Should throw NoSuchMethodException 4"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 4"); } try { PropertyUtils.setIndexedProperty(bean, "intArray", new Integer(1)); fail("Should throw IllegalArgumentException 5"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 5"); } // Use explicit index argument try { PropertyUtils.setIndexedProperty(null, "intIndexed", 0, new Integer(1)); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.setIndexedProperty(bean, null, 0, new Integer(1)); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } // Use index expression try { PropertyUtils.setIndexedProperty(null, "intIndexed[0]", new Integer(1)); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } try { PropertyUtils.setIndexedProperty(bean, "[0]", new Integer(1)); fail("Should throw NoSuchMethodException 4"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 4"); } try { PropertyUtils.setIndexedProperty(bean, "intIndexed", new Integer(1)); fail("Should throw IllegalArgumentException 5"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 5"); } } /** * Test setting an indexed value out of a multi-dimensional array */ public void testSetIndexedArray() { String[] firstArray = new String[] {"FIRST-1", "FIRST-2", "FIRST-3"}; String[] secondArray = new String[] {"SECOND-1", "SECOND-2", "SECOND-3", "SECOND-4"}; String[][] mainArray = {firstArray, secondArray}; TestBean bean = new TestBean(mainArray); assertEquals("BEFORE", "SECOND-3", bean.getString2dArray(1)[2]); try { PropertyUtils.setProperty(bean, "string2dArray[1][2]", "SECOND-3-UPDATED"); } catch (Throwable t) { fail("Threw " + t + ""); } assertEquals("AFTER", "SECOND-3-UPDATED", bean.getString2dArray(1)[2]); } /** * Test setting an indexed value out of List of Lists */ public void testSetIndexedList() { String[] firstArray = new String[] {"FIRST-1", "FIRST-2", "FIRST-3"}; String[] secondArray = new String[] {"SECOND-1", "SECOND-2", "SECOND-3", "SECOND-4"}; List mainList = new ArrayList(); mainList.add(Arrays.asList(firstArray)); mainList.add(Arrays.asList(secondArray)); TestBean bean = new TestBean(mainList); assertEquals("BEFORE", "SECOND-4", ((List)bean.getListIndexed().get(1)).get(3)); try { PropertyUtils.setProperty(bean, "listIndexed[1][3]", "SECOND-4-UPDATED"); } catch (Throwable t) { fail("Threw " + t + ""); } assertEquals("AFTER", "SECOND-4-UPDATED", ((List)bean.getListIndexed().get(1)).get(3)); } /** * Test setting a value out of a mapped Map */ public void testSetIndexedMap() { Map firstMap = new HashMap(); firstMap.put("FIRST-KEY-1", "FIRST-VALUE-1"); firstMap.put("FIRST-KEY-2", "FIRST-VALUE-2"); Map secondMap = new HashMap(); secondMap.put("SECOND-KEY-1", "SECOND-VALUE-1"); secondMap.put("SECOND-KEY-2", "SECOND-VALUE-2"); List mainList = new ArrayList(); mainList.add(firstMap); mainList.add(secondMap); TestBean bean = new TestBean(mainList); assertEquals("BEFORE", null, ((Map)bean.getListIndexed().get(0)).get("FIRST-NEW-KEY")); assertEquals("BEFORE", "SECOND-VALUE-1", ((Map)bean.getListIndexed().get(1)).get("SECOND-KEY-1")); try { PropertyUtils.setProperty(bean, "listIndexed[0](FIRST-NEW-KEY)", "FIRST-NEW-VALUE"); PropertyUtils.setProperty(bean, "listIndexed[1](SECOND-KEY-1)", "SECOND-VALUE-1-UPDATED"); } catch (Throwable t) { fail("Threw " + t + ""); } assertEquals("BEFORE", "FIRST-NEW-VALUE", ((Map)bean.getListIndexed().get(0)).get("FIRST-NEW-KEY")); assertEquals("AFTER", "SECOND-VALUE-1-UPDATED", ((Map)bean.getListIndexed().get(1)).get("SECOND-KEY-1")); } /** * Positive and negative tests on setIndexedProperty valid arguments. */ public void testSetIndexedValues() { Object value = null; // Use explicit index argument try { PropertyUtils.setIndexedProperty(bean, "dupProperty", 0, "New 0"); value = PropertyUtils.getIndexedProperty(bean, "dupProperty", 0); assertNotNull("Returned new value 0", value); assertTrue("Returned String new value 0", value instanceof String); assertEquals("Returned correct new value 0", "New 0", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "intArray", 0, new Integer(1)); value = PropertyUtils.getIndexedProperty(bean, "intArray", 0); assertNotNull("Returned new value 0", value); assertTrue("Returned Integer new value 0", value instanceof Integer); assertEquals("Returned correct new value 0", 1, ((Integer) value).intValue()); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "intIndexed", 1, new Integer(11)); value = PropertyUtils.getIndexedProperty(bean, "intIndexed", 1); assertNotNull("Returned new value 1", value); assertTrue("Returned Integer new value 1", value instanceof Integer); assertEquals("Returned correct new value 1", 11, ((Integer) value).intValue()); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "listIndexed", 2, "New Value 2"); value = PropertyUtils.getIndexedProperty(bean, "listIndexed", 2); assertNotNull("Returned new value 2", value); assertTrue("Returned String new value 2", value instanceof String); assertEquals("Returned correct new value 2", "New Value 2", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "stringArray", 2, "New Value 2"); value = PropertyUtils.getIndexedProperty(bean, "stringArray", 2); assertNotNull("Returned new value 2", value); assertTrue("Returned String new value 2", value instanceof String); assertEquals("Returned correct new value 2", "New Value 2", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "stringArray", 3, "New Value 3"); value = PropertyUtils.getIndexedProperty(bean, "stringArray", 3); assertNotNull("Returned new value 3", value); assertTrue("Returned String new value 3", value instanceof String); assertEquals("Returned correct new value 3", "New Value 3", (String) value); } catch (Throwable t) { fail("Threw " + t); } // Use index expression try { PropertyUtils.setIndexedProperty(bean, "dupProperty[4]", "New 4"); value = PropertyUtils.getIndexedProperty(bean, "dupProperty[4]"); assertNotNull("Returned new value 4", value); assertTrue("Returned String new value 4", value instanceof String); assertEquals("Returned correct new value 4", "New 4", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "intArray[4]", new Integer(1)); value = PropertyUtils.getIndexedProperty(bean, "intArray[4]"); assertNotNull("Returned new value 4", value); assertTrue("Returned Integer new value 4", value instanceof Integer); assertEquals("Returned correct new value 4", 1, ((Integer) value).intValue()); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "intIndexed[3]", new Integer(11)); value = PropertyUtils.getIndexedProperty(bean, "intIndexed[3]"); assertNotNull("Returned new value 5", value); assertTrue("Returned Integer new value 5", value instanceof Integer); assertEquals("Returned correct new value 5", 11, ((Integer) value).intValue()); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "listIndexed[1]", "New Value 2"); value = PropertyUtils.getIndexedProperty(bean, "listIndexed[1]"); assertNotNull("Returned new value 6", value); assertTrue("Returned String new value 6", value instanceof String); assertEquals("Returned correct new value 6", "New Value 2", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "stringArray[1]", "New Value 2"); value = PropertyUtils.getIndexedProperty(bean, "stringArray[2]"); assertNotNull("Returned new value 6", value); assertTrue("Returned String new value 6", value instanceof String); assertEquals("Returned correct new value 6", "New Value 2", (String) value); } catch (Throwable t) { fail("Threw " + t); } try { PropertyUtils.setIndexedProperty(bean, "stringArray[0]", "New Value 3"); value = PropertyUtils.getIndexedProperty(bean, "stringArray[0]"); assertNotNull("Returned new value 7", value); assertTrue("Returned String new value 7", value instanceof String); assertEquals("Returned correct new value 7", "New Value 3", (String) value); } catch (Throwable t) { fail("Threw " + t); } // Index out of bounds tests try { PropertyUtils.setIndexedProperty(bean, "dupProperty", -1, "New -1"); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "dupProperty", 5, "New 5"); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "intArray", -1, new Integer(0)); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "intArray", 5, new Integer(0)); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "intIndexed", -1, new Integer(0)); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "intIndexed", 5, new Integer(0)); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "listIndexed", 5, "New String"); fail("Should have thrown IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of IndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "listIndexed", -1, "New String"); fail("Should have thrown IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of IndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "stringArray", -1, "New String"); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "stringArray", 5, "New String"); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "stringIndexed", -1, "New String"); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } try { PropertyUtils.setIndexedProperty(bean, "stringIndexed", 5, "New String"); fail("Should have thrown ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException t) { // Expected results } catch (Throwable t) { fail("Threw " + t + " instead of ArrayIndexOutOfBoundsException"); } } /** * Corner cases on getMappedProperty invalid arguments. */ public void testSetMappedArguments() { // Use explicit key argument try { PropertyUtils.setMappedProperty(null, "mappedProperty", "First Key", "First Value"); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.setMappedProperty(bean, null, "First Key", "First Value"); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } try { PropertyUtils.setMappedProperty(bean, "mappedProperty", null, "First Value"); fail("Should throw IllegalArgumentException 3"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 3"); } // Use key expression try { PropertyUtils.setMappedProperty(null, "mappedProperty(First Key)", "First Value"); fail("Should throw IllegalArgumentException 4"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 4"); } try { PropertyUtils.setMappedProperty(bean, "(Second Key)", "Second Value"); fail("Should throw IllegalArgumentException 5"); } catch (NoSuchMethodException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of NoSuchMethodException 5"); } try { PropertyUtils.setMappedProperty(bean, "mappedProperty", "Third Value"); fail("Should throw IllegalArgumentException 6"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 6"); } } /** * Test setting an indexed value out of a mapped array */ public void testSetMappedArray() { TestBean bean = new TestBean(); String[] array = new String[] {"abc", "def", "ghi"}; bean.getMapProperty().put("mappedArray", array); assertEquals("BEFORE", "def", ((String[])bean.getMapProperty().get("mappedArray"))[1]); try { PropertyUtils.setProperty(bean, "mapProperty(mappedArray)[1]", "DEF-UPDATED"); } catch (Throwable t) { fail("Threw " + t + ""); } assertEquals("AFTER", "DEF-UPDATED", ((String[])bean.getMapProperty().get("mappedArray"))[1]); } /** * Test setting an indexed value out of a mapped List */ public void testSetMappedList() { TestBean bean = new TestBean(); List list = new ArrayList(); list.add("klm"); list.add("nop"); list.add("qrs"); bean.getMapProperty().put("mappedList", list); assertEquals("BEFORE", "klm", ((List)bean.getMapProperty().get("mappedList")).get(0)); try { PropertyUtils.setProperty(bean, "mapProperty(mappedList)[0]", "KLM-UPDATED"); } catch (Throwable t) { fail("Threw " + t + ""); } assertEquals("AFTER", "KLM-UPDATED", ((List)bean.getMapProperty().get("mappedList")).get(0)); } /** * Test setting a value out of a mapped Map */ public void testSetMappedMap() { TestBean bean = new TestBean(); Map map = new HashMap(); map.put("sub-key-1", "sub-value-1"); map.put("sub-key-2", "sub-value-2"); map.put("sub-key-3", "sub-value-3"); bean.getMapProperty().put("mappedMap", map); assertEquals("BEFORE", "sub-value-3", ((Map)bean.getMapProperty().get("mappedMap")).get("sub-key-3")); try { PropertyUtils.setProperty(bean, "mapProperty(mappedMap)(sub-key-3)", "SUB-KEY-3-UPDATED"); } catch (Throwable t) { fail("Threw " + t + ""); } assertEquals("AFTER", "SUB-KEY-3-UPDATED", ((Map)bean.getMapProperty().get("mappedMap")).get("sub-key-3")); } /** * Positive and negative tests on setMappedProperty valid arguments. */ public void testSetMappedValues() { Object value = null; // Use explicit key argument try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty", "Fourth Key"); assertNull("Can not find fourth value", value); } catch (Throwable t) { fail("Finding fourth value threw " + t); } try { PropertyUtils.setMappedProperty(bean, "mappedProperty", "Fourth Key", "Fourth Value"); } catch (Throwable t) { fail("Setting fourth value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty", "Fourth Key"); assertEquals("Can find fourth value", "Fourth Value", value); } catch (Throwable t) { fail("Finding fourth value threw " + t); } // Use key expression with parentheses try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty(Fifth Key)"); assertNull("Can not find fifth value", value); } catch (Throwable t) { fail("Finding fifth value threw " + t); } try { PropertyUtils.setMappedProperty(bean, "mappedProperty(Fifth Key)", "Fifth Value"); } catch (Throwable t) { fail("Setting fifth value threw " + t); } try { value = PropertyUtils.getMappedProperty(bean, "mappedProperty(Fifth Key)"); assertEquals("Can find fifth value", "Fifth Value", value); } catch (Throwable t) { fail("Finding fifth value threw " + t); } // Use key expression with dotted expression try { value = PropertyUtils.getNestedProperty(bean, "mapProperty.Sixth Key"); assertNull("Can not find sixth value", value); } catch (Throwable t) { fail("Finding fifth value threw " + t); } try { PropertyUtils.setNestedProperty(bean, "mapProperty.Sixth Key", "Sixth Value"); } catch (Throwable t) { fail("Setting sixth value threw " + t); } try { value = PropertyUtils.getNestedProperty(bean, "mapProperty.Sixth Key"); assertEquals("Can find sixth value", "Sixth Value", value); } catch (Throwable t) { fail("Finding sixth value threw " + t); } } /** * Test setting mapped values with periods in the key. */ public void testSetMappedPeriods() { // -------- PropertyUtils.setMappedProperty()-------- bean.setMappedProperty("key.with.a.dot", "Special Value"); assertEquals("Can retrieve directly (A)", "Special Value", bean.getMappedProperty("key.with.a.dot")); try { PropertyUtils.setMappedProperty(bean, "mappedProperty", "key.with.a.dot", "Updated Special Value"); assertEquals("Check set via setMappedProperty", "Updated Special Value", bean.getMappedProperty("key.with.a.dot")); } catch (Exception e) { fail("Thew exception: " + e); } // -------- PropertyUtils.setNestedProperty() -------- bean.setMappedProperty("key.with.a.dot", "Special Value"); assertEquals("Can retrieve directly (B)", "Special Value", bean.getMappedProperty("key.with.a.dot")); try { PropertyUtils.setNestedProperty(bean, "mappedProperty(key.with.a.dot)", "Updated Special Value"); assertEquals("Check set via setNestedProperty (B)", "Updated Special Value", bean.getMappedProperty("key.with.a.dot")); } catch (Exception e) { fail("Thew exception: " + e); } // -------- PropertyUtils.setNestedProperty() -------- TestBean testBean = new TestBean(); bean.setMappedObjects("nested.property", testBean); assertEquals("Can retrieve directly (C)", "This is a string", testBean.getStringProperty()); try { PropertyUtils.setNestedProperty(bean, "mappedObjects(nested.property).stringProperty", "Updated String Value"); assertEquals("Check set via setNestedProperty (C)", "Updated String Value", testBean.getStringProperty()); } catch (Exception e) { fail("Thew exception: " + e); } // -------- PropertyUtils.setNestedProperty() -------- bean.getNested().setMappedProperty("Mapped Key", "Nested Mapped Value"); try { assertEquals("Can retrieve via getNestedProperty (D)", "Nested Mapped Value", PropertyUtils.getNestedProperty( bean,"nested.mappedProperty(Mapped Key)")); PropertyUtils.setNestedProperty(bean, "nested.mappedProperty(Mapped Key)", "Updated Nested Mapped Value"); assertEquals("Check set via setNestedProperty (D)", "Updated Nested Mapped Value", PropertyUtils.getNestedProperty( bean,"nested.mappedProperty(Mapped Key)")); } catch (Exception e) { fail("Thew exception: " + e); } } /** * Corner cases on setNestedProperty invalid arguments. */ public void testSetNestedArguments() { try { PropertyUtils.setNestedProperty(null, "stringProperty", ""); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.setNestedProperty(bean, null, ""); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } } /** * Test setNextedProperty on a boolean property. */ public void testSetNestedBoolean() { try { boolean oldValue = bean.getNested().getBooleanProperty(); boolean newValue = !oldValue; PropertyUtils.setNestedProperty(bean, "nested.booleanProperty", new Boolean(newValue)); assertTrue("Matched new value", newValue == bean.getNested().getBooleanProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a double property. */ public void testSetNestedDouble() { try { double oldValue = bean.getNested().getDoubleProperty(); double newValue = oldValue + 1.0; PropertyUtils.setNestedProperty(bean, "nested.doubleProperty", new Double(newValue)); assertEquals("Matched new value", newValue, bean.getNested().getDoubleProperty(), 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a float property. */ public void testSetNestedFloat() { try { float oldValue = bean.getNested().getFloatProperty(); float newValue = oldValue + (float) 1.0; PropertyUtils.setNestedProperty(bean, "nested.floatProperty", new Float(newValue)); assertEquals("Matched new value", newValue, bean.getNested().getFloatProperty(), (float) 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a int property. */ public void testSetNestedInt() { try { int oldValue = bean.getNested().getIntProperty(); int newValue = oldValue + 1; PropertyUtils.setNestedProperty(bean, "nested.intProperty", new Integer(newValue)); assertEquals("Matched new value", newValue, bean.getNested().getIntProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a long property. */ public void testSetNestedLong() { try { long oldValue = bean.getNested().getLongProperty(); long newValue = oldValue + 1; PropertyUtils.setNestedProperty(bean, "nested.longProperty", new Long(newValue)); assertEquals("Matched new value", newValue, bean.getNested().getLongProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a read-only String property. */ public void testSetNestedReadOnly() { try { String oldValue = bean.getNested().getWriteOnlyPropertyValue(); String newValue = oldValue + " Extra Value"; PropertyUtils.setNestedProperty(bean, "nested.readOnlyProperty", newValue); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test } } /** * Test setNestedProperty on a short property. */ public void testSetNestedShort() { try { short oldValue = bean.getNested().getShortProperty(); short newValue = oldValue; newValue++; PropertyUtils.setNestedProperty(bean, "nested.shortProperty", new Short(newValue)); assertEquals("Matched new value", newValue, bean.getNested().getShortProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on a String property. */ public void testSetNestedString() { try { String oldValue = bean.getNested().getStringProperty(); String newValue = oldValue + " Extra Value"; PropertyUtils.setNestedProperty(bean, "nested.stringProperty", newValue); assertEquals("Matched new value", newValue, bean.getNested().getStringProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setNestedProperty on an unknown property name. */ public void testSetNestedUnknown() { try { String newValue = "New String Value"; PropertyUtils.setNestedProperty(bean, "nested.unknown", newValue); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test } } /** * Test setNestedProperty on a write-only String property. */ public void testSetNestedWriteOnly() { try { String oldValue = bean.getNested().getWriteOnlyPropertyValue(); String newValue = oldValue + " Extra Value"; PropertyUtils.setNestedProperty(bean, "nested.writeOnlyProperty", newValue); assertEquals("Matched new value", newValue, bean.getNested().getWriteOnlyPropertyValue()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Corner cases on setSimpleProperty invalid arguments. */ public void testSetSimpleArguments() { try { PropertyUtils.setSimpleProperty(null, "stringProperty", ""); fail("Should throw IllegalArgumentException 1"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 1"); } try { PropertyUtils.setSimpleProperty(bean, null, ""); fail("Should throw IllegalArgumentException 2"); } catch (IllegalArgumentException e) { // Expected response } catch (Throwable t) { fail("Threw " + t + " instead of IllegalArgumentException 2"); } } /** * Test setSimpleProperty on a boolean property. */ public void testSetSimpleBoolean() { try { boolean oldValue = bean.getBooleanProperty(); boolean newValue = !oldValue; PropertyUtils.setSimpleProperty(bean, "booleanProperty", new Boolean(newValue)); assertTrue("Matched new value", newValue == bean.getBooleanProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a double property. */ public void testSetSimpleDouble() { try { double oldValue = bean.getDoubleProperty(); double newValue = oldValue + 1.0; PropertyUtils.setSimpleProperty(bean, "doubleProperty", new Double(newValue)); assertEquals("Matched new value", newValue, bean.getDoubleProperty(), 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a float property. */ public void testSetSimpleFloat() { try { float oldValue = bean.getFloatProperty(); float newValue = oldValue + (float) 1.0; PropertyUtils.setSimpleProperty(bean, "floatProperty", new Float(newValue)); assertEquals("Matched new value", newValue, bean.getFloatProperty(), (float) 0.005); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test setSimpleProperty on an indexed property. */ public void testSetSimpleIndexed() { try { PropertyUtils.setSimpleProperty(bean, "stringIndexed[0]", "New String Value"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { // Correct result for this test } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a int property. */ public void testSetSimpleInt() { try { int oldValue = bean.getIntProperty(); int newValue = oldValue + 1; PropertyUtils.setSimpleProperty(bean, "intProperty", new Integer(newValue)); assertEquals("Matched new value", newValue, bean.getIntProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a long property. */ public void testSetSimpleLong() { try { long oldValue = bean.getLongProperty(); long newValue = oldValue + 1; PropertyUtils.setSimpleProperty(bean, "longProperty", new Long(newValue)); assertEquals("Matched new value", newValue, bean.getLongProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Negative test setSimpleProperty on a nested property. */ public void testSetSimpleNested() { try { PropertyUtils.setSimpleProperty(bean, "nested.stringProperty", "New String Value"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { // Correct result for this test } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a read-only String property. */ public void testSetSimpleReadOnly() { try { String oldValue = bean.getWriteOnlyPropertyValue(); String newValue = oldValue + " Extra Value"; PropertyUtils.setSimpleProperty(bean, "readOnlyProperty", newValue); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test assertEquals("Property 'readOnlyProperty' has no setter method in class '" + bean.getClass() + "'", e.getMessage() ); } } /** * Test setSimpleProperty on a short property. */ public void testSetSimpleShort() { try { short oldValue = bean.getShortProperty(); short newValue = oldValue; newValue++; PropertyUtils.setSimpleProperty(bean, "shortProperty", new Short(newValue)); assertEquals("Matched new value", newValue, bean.getShortProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on a String property. */ public void testSetSimpleString() { try { String oldValue = bean.getStringProperty(); String newValue = oldValue + " Extra Value"; PropertyUtils.setSimpleProperty(bean, "stringProperty", newValue); assertEquals("Matched new value", newValue, bean.getStringProperty()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Test setSimpleProperty on an unknown property name. */ public void testSetSimpleUnknown() { try { String newValue = "New String Value"; PropertyUtils.setSimpleProperty(bean, "unknown", newValue); fail("Should have thrown NoSuchMethodException"); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { // Correct result for this test assertEquals("Unknown property 'unknown' on class '" + bean.getClass() + "'", e.getMessage() ); } } /** * Test setSimpleProperty on a write-only String property. */ public void testSetSimpleWriteOnly() { try { String oldValue = bean.getWriteOnlyPropertyValue(); String newValue = oldValue + " Extra Value"; PropertyUtils.setSimpleProperty(bean, "writeOnlyProperty", newValue); assertEquals("Matched new value", newValue, bean.getWriteOnlyPropertyValue()); } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } // ------------------------------------------------------ Protected Methods /** * Base for testGetDescriptorXxxxx() series of tests. * * @param name Name of the property to be retrieved * @param read Expected name of the read method (or null) * @param write Expected name of the write method (or null) */ protected void testGetDescriptorBase(String name, String read, String write) { try { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, name); if ((read != null) || (write != null)) { assertNotNull("Got descriptor", pd); } else { assertNull("Got descriptor", pd); return; } Method rm = pd.getReadMethod(); if (read != null) { assertNotNull("Got read method", rm); assertEquals("Got correct read method", rm.getName(), read); } else { assertNull("Got read method", rm); } Method wm = pd.getWriteMethod(); if (write != null) { assertNotNull("Got write method", wm); assertEquals("Got correct write method", wm.getName(), write); } else { assertNull("Got write method", wm); } } catch (IllegalAccessException e) { fail("IllegalAccessException"); } catch (InvocationTargetException e) { fail("InvocationTargetException"); } catch (NoSuchMethodException e) { fail("NoSuchMethodException"); } } /** * Base for testGetReadMethod() series of tests. * * @param bean Bean for which to retrieve read methods. * @param properties Property names to search for * @param className Class name where this method should be defined */ protected void testGetReadMethod(Object bean, String properties[], String className) { PropertyDescriptor pd[] = PropertyUtils.getPropertyDescriptors(bean); for (int i = 0; i < properties.length; i++) { // Identify the property descriptor for this property if (properties[i].equals("intIndexed")) continue; if (properties[i].equals("stringIndexed")) continue; if (properties[i].equals("writeOnlyProperty")) continue; int n = -1; for (int j = 0; j < pd.length; j++) { if (properties[i].equals(pd[j].getName())) { n = j; break; } } assertTrue("PropertyDescriptor for " + properties[i], n >= 0); // Locate an accessible property reader method for it Method reader = PropertyUtils.getReadMethod(pd[n]); assertNotNull("Reader for " + properties[i], reader); Class clazz = reader.getDeclaringClass(); assertNotNull("Declaring class for " + properties[i], clazz); assertEquals("Correct declaring class for " + properties[i], clazz.getName(), className); // Actually call the reader method we received try { reader.invoke(bean, (Object[]) new Class[0]); } catch (Throwable t) { fail("Call for " + properties[i] + ": " + t); } } } /** * Base for testGetWriteMethod() series of tests. * * @param bean Bean for which to retrieve write methods. * @param properties Property names to search for * @param className Class name where this method should be defined */ protected void testGetWriteMethod(Object bean, String properties[], String className) { PropertyDescriptor pd[] = PropertyUtils.getPropertyDescriptors(bean); for (int i = 0; i < properties.length; i++) { // Identify the property descriptor for this property if (properties[i].equals("intIndexed")) continue; if (properties[i].equals("listIndexed")) continue; if (properties[i].equals("nested")) continue; // This property is read only if (properties[i].equals("readOnlyProperty")) continue; if (properties[i].equals("stringIndexed")) continue; int n = -1; for (int j = 0; j < pd.length; j++) { if (properties[i].equals(pd[j].getName())) { n = j; break; } } assertTrue("PropertyDescriptor for " + properties[i], n >= 0); // Locate an accessible property reader method for it Method writer = PropertyUtils.getWriteMethod(pd[n]); assertNotNull("Writer for " + properties[i], writer); Class clazz = writer.getDeclaringClass(); assertNotNull("Declaring class for " + properties[i], clazz); assertEquals("Correct declaring class for " + properties[i], clazz.getName(), className); } } public void testNestedWithIndex() throws Exception { NestedTestBean nestedBean = new NestedTestBean("base"); nestedBean.init(); nestedBean.getSimpleBeanProperty().init(); NestedTestBean // test first calling properties on indexed beans value = (NestedTestBean) PropertyUtils.getProperty( nestedBean, "indexedProperty[0]"); assertEquals("Cannot get simple index(1)", "Bean@0", value.getName()); assertEquals("Bug in NestedTestBean", "NOT SET", value.getTestString()); value = (NestedTestBean) PropertyUtils.getProperty( nestedBean, "indexedProperty[1]"); assertEquals("Cannot get simple index(1)", "Bean@1", value.getName()); assertEquals("Bug in NestedTestBean", "NOT SET", value.getTestString()); String prop = (String) PropertyUtils.getProperty( nestedBean, "indexedProperty[0].testString"); assertEquals("Get property on indexes failed (1)", "NOT SET", prop); prop = (String) PropertyUtils.getProperty( nestedBean, "indexedProperty[1].testString"); assertEquals("Get property on indexes failed (2)", "NOT SET", prop); PropertyUtils.setProperty( nestedBean, "indexedProperty[0].testString", "Test#1"); assertEquals( "Cannot set property on indexed bean (1)", "Test#1", nestedBean.getIndexedProperty(0).getTestString()); PropertyUtils.setProperty( nestedBean, "indexedProperty[1].testString", "Test#2"); assertEquals( "Cannot set property on indexed bean (2)", "Test#2", nestedBean.getIndexedProperty(1).getTestString()); // test first calling indexed properties on a simple property value = (NestedTestBean) PropertyUtils.getProperty( nestedBean, "simpleBeanProperty"); assertEquals("Cannot get simple bean", "Simple Property Bean", value.getName()); assertEquals("Bug in NestedTestBean", "NOT SET", value.getTestString()); value = (NestedTestBean) PropertyUtils.getProperty( nestedBean, "simpleBeanProperty.indexedProperty[3]"); assertEquals("Cannot get index property on property", "Bean@3", value.getName()); assertEquals("Bug in NestedTestBean", "NOT SET", value.getTestString()); PropertyUtils.setProperty( nestedBean, "simpleBeanProperty.indexedProperty[3].testString", "Test#3"); assertEquals( "Cannot set property on indexed property on property", "Test#3", nestedBean.getSimpleBeanProperty().getIndexedProperty(3).getTestString()); } /** Text case for setting properties on inner classes */ public void testGetSetInnerBean() throws Exception { BeanWithInnerBean bean = new BeanWithInnerBean(); PropertyUtils.setProperty(bean, "innerBean.fish(loiterTimer)", "5"); String out = (String) PropertyUtils.getProperty(bean.getInnerBean(), "fish(loiterTimer)"); assertEquals( "(1) Inner class property set/get property failed.", "5", out); out = (String) PropertyUtils.getProperty(bean, "innerBean.fish(loiterTimer)"); assertEquals( "(2) Inner class property set/get property failed.", "5", out); } /** Text case for setting properties on parent */ public void testGetSetParentBean() throws Exception { SonOfAlphaBean bean = new SonOfAlphaBean("Roger"); String out = (String) PropertyUtils.getProperty(bean, "name"); assertEquals( "(1) Get/Set On Parent.", "Roger", out); PropertyUtils.setProperty(bean, "name", "abcd"); assertEquals( "(2) Get/Set On Parent.", "abcd", bean.getName()); } public void testSetNoGetter() throws Exception { BetaBean bean = new BetaBean("Cedric"); // test standard no getter bean.setNoGetterProperty("Sigma"); assertEquals("BetaBean test failed", "Sigma", bean.getSecret()); assertNotNull("Descriptor is null", PropertyUtils.getPropertyDescriptor(bean, "noGetterProperty")); BeanUtils.setProperty(bean, "noGetterProperty", "Omega"); assertEquals("Cannot set no-getter property", "Omega", bean.getSecret()); // test mapped no getter descriptor assertNotNull("Map Descriptor is null", PropertyUtils.getPropertyDescriptor(bean, "noGetterMappedProperty")); PropertyUtils.setMappedProperty(bean, "noGetterMappedProperty", "Epsilon", "Epsilon"); assertEquals("Cannot set mapped no-getter property", "MAP:Epsilon", bean.getSecret()); } /** * Test accessing a public sub-bean of a package scope bean */ public void testSetPublicSubBean_of_PackageBean() { PublicSubBean bean = new PublicSubBean(); bean.setFoo("foo-start"); bean.setBar("bar-start"); // Set Foo try { PropertyUtils.setProperty(bean, "foo", "foo-updated"); } catch (Throwable t) { fail("setProperty(foo) threw " + t); } assertEquals("foo property", "foo-updated", bean.getFoo()); // Set Bar try { PropertyUtils.setProperty(bean, "bar", "bar-updated"); } catch (Throwable t) { fail("setProperty(bar) threw " + t); } assertEquals("bar property", "bar-updated", bean.getBar()); } /** * There is an issue in setNestedProperty/getNestedProperty when the * target bean is a map and the name string requests mapped or indexed * operations on a field. These are not supported for fields of a Map, * but it's an easy mistake to make and this test case ensures that an * appropriate exception is thrown when a user does this. *

          * The problem is with passing strings of form "a(b)" or "a[3]" to * setNestedProperty or getNestedProperty when the target bean they * are applied to implements Map. These strings are actually requesting * "the result of calling mapped method a on the target object with * a parameter of b" or "the result of calling indexed method a on the * target object with a parameter of 3". And these requests are not valid * when the target is a Map as a Map only supports calling get(fieldName) * or put(fieldName), neither of which can be further indexed with a * string or an integer. *

          * However it is likely that some users will assume that "a[3]" when applied * to a map will be equivalent to (map.get("a"))[3] with the appropriate * typecasting, or for "a(b)" to be equivalent to map.get("a").get("b"). *

          * Here we verify that an exception is thrown if the user makes this * mistake. */ public void testNestedPropertyKeyOrIndexOnBeanImplementingMap() throws Exception { HashMap map = new HashMap(); HashMap submap = new HashMap(); BetaBean betaBean1 = new BetaBean("test1"); BetaBean betaBean2 = new BetaBean("test2"); // map.put("submap", submap) PropertyUtils.setNestedProperty(map, "submap", submap); // map.get("submap").put("beta1", betaBean1) PropertyUtils.setNestedProperty(map, "submap.beta1", betaBean1); assertEquals("Unexpected keys in map", "submap", keysToString(map)); assertEquals("Unexpected keys in submap", "beta1", keysToString(submap)); try { // One would expect that the command below would be equivalent to // Map m = (Map) map.get("submap"); // m.put("beta2", betaBean2) // However this isn't how javabeans property methods work. A map // only effectively has "simple" properties, even when the // returned object is a Map or Array. PropertyUtils.setNestedProperty(map, "submap(beta2)", betaBean2); // What, no exception? In that case, setNestedProperties has // probably just tried to do // map.set("submap(beta2)", betaBean2) // which is almost certainly not what the used expected. This is // what beanutils 1.5.0 to 1.7.1 did.... fail("Exception not thrown for invalid setNestedProperty syntax"); } catch(IllegalArgumentException ex) { // ok, getting an exception was expected. As it is of a generic // type, let's check the message string to make sure it really // was caused by the issue we expected. int index = ex.getMessage().indexOf( "Indexed or mapped properties are not supported"); assertTrue("Unexpected exception message", index>=0); } try { // One would expect that "submap[3]" would be equivalent to // Object[] objects = (Object[]) map.get("submap"); // return objects[3]; // However this isn't how javabeans property methods work. A map // only effectively has "simple" properties, even when the // returned object is a Map or Array. PropertyUtils.getNestedProperty(map, "submap[3]"); // What, no exception? In that case, getNestedProperties has // probably just tried to do // map.get("submap[3]") // which is almost certainly not what the used expected. This is // what beanutils 1.5.0 to 1.7.1 did.... fail("Exception not thrown for invalid setNestedProperty syntax"); } catch(IllegalArgumentException ex) { // ok, getting an exception was expected. As it is of a generic // type, let's check the message string to make sure it really // was caused by the issue we expected. int index = ex.getMessage().indexOf( "Indexed or mapped properties are not supported"); assertTrue("Unexpected exception message", index>=0); } } /** * Returns a single string containing all the keys in the map, * sorted in alphabetical order and separated by ", ". *

          * If there are no keys, an empty string is returned. */ private String keysToString(Map map) { Object[] mapKeys = map.keySet().toArray(); java.util.Arrays.sort(mapKeys); StringBuilder buf = new StringBuilder(); for(int i=0; i * Note that this behaviour has changed several times over past releases * of beanutils, breaking backwards compatibility each time. Here's hoping * that the current 1.7.1 release is the last time this behaviour changes! */ public void testMapExtensionDefault() throws Exception { ExtendMapBean bean = new ExtendMapBean(); // setting property direct should work, and not affect map bean.setUnusuallyNamedProperty("bean value"); assertEquals("Set property direct failed", "bean value", bean.getUnusuallyNamedProperty()); assertNull("Get on unset map property failed", PropertyUtils.getNestedProperty(bean, "unusuallyNamedProperty")); // setting simple property should call the setter method only, and not // affect the map. PropertyUtils.setSimpleProperty(bean, "unusuallyNamedProperty", "new value"); assertEquals("Set property on map failed (1)", "new value", bean.getUnusuallyNamedProperty()); assertNull("Get on unset map property failed", PropertyUtils.getNestedProperty(bean, "unusuallyNamedProperty")); // setting via setNestedProperty should affect the map only, and not // call the setter method. PropertyUtils.setProperty(bean, "unusuallyNamedProperty", "next value"); assertEquals( "setNestedProperty on map not visible to getNestedProperty", "next value", PropertyUtils.getNestedProperty(bean, "unusuallyNamedProperty")); assertEquals( "Set nested property on map unexpected affected simple property", "new value", bean.getUnusuallyNamedProperty()); } /** * This tests to see that it is possible to subclass PropertyUtilsBean * and change the behaviour of setNestedProperty/getNestedProperty when * dealing with objects that implement Map. */ public void testMapExtensionCustom() throws Exception { PropsFirstPropertyUtilsBean utilsBean = new PropsFirstPropertyUtilsBean(); ExtendMapBean bean = new ExtendMapBean(); // hardly worth testing this, really :-) bean.setUnusuallyNamedProperty("bean value"); assertEquals("Set property direct failed", "bean value", bean.getUnusuallyNamedProperty()); // setSimpleProperty should affect the simple property utilsBean.setSimpleProperty(bean, "unusuallyNamedProperty", "new value"); assertEquals("Set property on map failed (1)", "new value", bean.getUnusuallyNamedProperty()); // setNestedProperty with setter should affect the simple property // getNestedProperty with getter should obtain the simple property utilsBean.setProperty(bean, "unusuallyNamedProperty", "next value"); assertEquals("Set property on map failed (2)", "next value", bean.getUnusuallyNamedProperty()); assertEquals("setNestedProperty on non-simple property failed", "next value", utilsBean.getNestedProperty(bean, "unusuallyNamedProperty")); // setting property without setter should update the map // getting property without setter should fetch from the map utilsBean.setProperty(bean, "mapProperty", "value1"); assertEquals("setNestedProperty on non-simple property failed", "value1", utilsBean.getNestedProperty(bean, "mapProperty")); HashMap myMap = new HashMap(); myMap.put("thebean", bean); utilsBean.getNestedProperty(myMap, "thebean.mapitem"); utilsBean.getNestedProperty(myMap, "thebean(mapitem)"); } /** * Test {@link PropertyUtilsBean}'s invoke method throwing an IllegalArgumentException * and check that the "cause" has been properly initialized for JDK 1.4+ * See BEANUTILS-266 for changes and reason for test */ public void testExceptionFromInvoke() throws Exception { if (BeanUtilsTestCase.isPre14JVM()) { return; } try { PropertyUtils.setSimpleProperty(bean, "intProperty","XXX"); } catch(IllegalArgumentException t) { Throwable cause = (Throwable)PropertyUtils.getProperty(t, "cause"); assertNotNull("Cause not found", cause); assertTrue("Expected cause to be IllegalArgumentException, but was: " + cause.getClass(), cause instanceof IllegalArgumentException); // JDK 1.6 doesn't have "argument type mismatch" message // assertEquals("Check error message", "argument type mismatch", cause.getMessage()); } catch(Throwable t) { fail("Expected IllegalArgumentException, but threw " + t); } } /** * Tests whether the default introspection mechanism can be replaced by a * custom BeanIntrospector. */ public void testCustomIntrospection() { PropertyDescriptor[] desc1 = PropertyUtils .getPropertyDescriptors(AlphaBean.class); PropertyDescriptor nameDescriptor = findNameDescriptor(desc1); assertNotNull("No write method", nameDescriptor.getWriteMethod()); BeanIntrospector bi = new BeanIntrospector() { // Only produce read-only property descriptors public void introspect(IntrospectionContext icontext) throws IntrospectionException { Set names = icontext.propertyNames(); PropertyDescriptor[] newDescs = new PropertyDescriptor[names .size()]; int idx = 0; for (Iterator it = names.iterator(); it.hasNext(); idx++) { String propName = it.next(); PropertyDescriptor pd = icontext .getPropertyDescriptor(propName); newDescs[idx] = new PropertyDescriptor(pd.getName(), pd.getReadMethod(), null); } icontext.addPropertyDescriptors(newDescs); } }; PropertyUtils.clearDescriptors(); PropertyUtils.addBeanIntrospector(bi); PropertyDescriptor[] desc2 = PropertyUtils .getPropertyDescriptors(AlphaBean.class); assertEquals("Different number of properties", desc1.length, desc2.length); nameDescriptor = findNameDescriptor(desc2); assertNull("Got a write method", nameDescriptor.getWriteMethod()); PropertyUtils.removeBeanIntrospector(bi); } /** * Finds the descriptor of the name property. * * @param desc the array with descriptors * @return the found descriptor or null */ private static PropertyDescriptor findNameDescriptor( PropertyDescriptor[] desc) { for (int i = 0; i < desc.length; i++) { if (desc[i].getName().equals("name")) { return desc[i]; } } return null; } /** * Tests whether exceptions during custom introspection are handled. */ public void testCustomIntrospectionEx() { BeanIntrospector bi = new BeanIntrospector() { public void introspect(IntrospectionContext icontext) throws IntrospectionException { throw new IntrospectionException("TestException"); } }; PropertyUtils.clearDescriptors(); PropertyUtils.addBeanIntrospector(bi); PropertyDescriptor[] desc = PropertyUtils .getPropertyDescriptors(AlphaBean.class); assertNotNull("Introspection did not work", findNameDescriptor(desc)); PropertyUtils.removeBeanIntrospector(bi); } /** * Tests whether a BeanIntrospector can be removed. */ public void testRemoveBeanIntrospector() { assertTrue( "Wrong result", PropertyUtils .removeBeanIntrospector(DefaultBeanIntrospector.INSTANCE)); PropertyDescriptor[] desc = PropertyUtils .getPropertyDescriptors(AlphaBean.class); assertEquals("Got descriptors", 0, desc.length); PropertyUtils.addBeanIntrospector(DefaultBeanIntrospector.INSTANCE); } /** * Tries to add a null BeanIntrospector. */ public void testAddBeanIntrospectorNull() { try { PropertyUtils.addBeanIntrospector(null); fail("Could add null BeanIntrospector!"); } catch (IllegalArgumentException iex) { // ok } } /** * Tests whether a reset of the registered BeanIntrospectors can be performed. */ public void testResetBeanIntrospectors() { assertTrue("Wrong result", PropertyUtils.removeBeanIntrospector(DefaultBeanIntrospector.INSTANCE)); PropertyUtils.resetBeanIntrospectors(); PropertyDescriptor[] desc = PropertyUtils.getPropertyDescriptors(AlphaBean.class); assertTrue("Got no descriptors", desc.length > 0); } } ././@LongLink100644 0 0 150 12262571655 10262 Lustar 0 0 commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/PropsFirstPropertyUtilsBean.javacommons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/PropsFirstPropertyUtilsBean.j100644 0 0 6065 12262570610 31107 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.util.Map; /** * A PropertyUtilsBean which customises the behaviour of the * setNestedProperty and getNestedProperty methods to look for * simple properties in preference to map entries. * * @version $Id: PropsFirstPropertyUtilsBean.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class PropsFirstPropertyUtilsBean extends PropertyUtilsBean { public PropsFirstPropertyUtilsBean() { super(); } /** * Note: this is a *very rough* override of this method. In particular, * it does not handle MAPPED_DELIM and INDEXED_DELIM chars in the * propertyName, so propertyNames like "a(b)" or "a[3]" will not * be correctly handled. */ @Override protected Object getPropertyOfMapBean(Map bean, String propertyName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyDescriptor descriptor = getPropertyDescriptor(bean, propertyName); if (descriptor == null) { // no simple property exists so return the value from the map return bean.get(propertyName); } else { // a simple property exists so return its value instead. return getSimpleProperty(bean, propertyName); } } /** * Note: this is a *very rough* override of this method. In particular, * it does not handle MAPPED_DELIM and INDEXED_DELIM chars in the * propertyName, so propertyNames like "a(b)" or "a[3]" will not * be correctly handled. */ @Override protected void setPropertyOfMapBean(Map bean, String propertyName, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyDescriptor descriptor = getPropertyDescriptor(bean, propertyName); if (descriptor == null) { // no simple property exists so put the value into the map bean.put(propertyName, value); } else { // a simple property exists so set that instead. setSimpleProperty(bean, propertyName, value); } } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/SonOfAlphaBean.java100644 0 0 2062 12262570610 26661 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * @version $Id: SonOfAlphaBean.java 1454597 2013-03-08 21:58:12Z britter $ */ public class SonOfAlphaBean extends AlphaBean { public SonOfAlphaBean(String name) { super(name); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/TestBean.java100644 0 0 40737 12262570607 25647 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * General purpose test bean for JUnit tests for the "beanutils" component. * * @version $Id: TestBean.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class TestBean implements Serializable { // ----------------------------------------------------------- Constructors public TestBean() { listIndexed.add("String 0"); listIndexed.add("String 1"); listIndexed.add("String 2"); listIndexed.add("String 3"); listIndexed.add("String 4"); } public TestBean(String stringProperty) { setStringProperty(stringProperty); } public TestBean(float floatProperty) { setFloatProperty(floatProperty); } public TestBean(boolean booleanProperty) { setBooleanProperty(booleanProperty); } public TestBean(Boolean booleanSecond) { setBooleanSecond(booleanSecond.booleanValue()); } public TestBean(float floatProperty, String stringProperty) { setFloatProperty(floatProperty); setStringProperty(stringProperty); } public TestBean(boolean booleanProperty, String stringProperty) { setBooleanProperty(booleanProperty); setStringProperty(stringProperty); } public TestBean(Boolean booleanSecond, String stringProperty) { setBooleanSecond(booleanSecond.booleanValue()); setStringProperty(stringProperty); } public TestBean(Integer intProperty) { setIntProperty(intProperty.intValue()); } public TestBean(double doubleProperty) { setDoubleProperty(doubleProperty); } TestBean(int intProperty) { setIntProperty(intProperty); } protected TestBean(boolean booleanProperty, boolean booleanSecond, String stringProperty) { setBooleanProperty(booleanProperty); setBooleanSecond(booleanSecond); setStringProperty(stringProperty); } public TestBean(List listIndexed) { this.listIndexed = listIndexed; } public TestBean(String[][] string2dArray) { this.string2dArray = string2dArray; } // ------------------------------------------------------------- Properties /** * A boolean property. */ private boolean booleanProperty = true; public boolean getBooleanProperty() { return (booleanProperty); } public void setBooleanProperty(boolean booleanProperty) { this.booleanProperty = booleanProperty; } /** * A boolean property that uses an "is" method for the getter. */ private boolean booleanSecond = true; public boolean isBooleanSecond() { return (booleanSecond); } public void setBooleanSecond(boolean booleanSecond) { this.booleanSecond = booleanSecond; } /** * A byte property. */ private byte byteProperty = (byte) 121; public byte getByteProperty() { return (this.byteProperty); } public void setByteProperty(byte byteProperty) { this.byteProperty = byteProperty; } /** * A java.util.Date property. */ private java.util.Date dateProperty; public java.util.Date getDateProperty() { return dateProperty; } public void setDateProperty(java.util.Date dateProperty) { this.dateProperty = dateProperty; } /** * A java.util.Date property. */ private java.util.Date[] dateArrayProperty; public java.util.Date[] getDateArrayProperty() { return dateArrayProperty; } public void setDateArrayProperty(java.util.Date[] dateArrayProperty) { this.dateArrayProperty = dateArrayProperty; } /** * A double property. */ private double doubleProperty = 321.0; public double getDoubleProperty() { return (this.doubleProperty); } public void setDoubleProperty(double doubleProperty) { this.doubleProperty = doubleProperty; } /** * An "indexed property" accessible via both array and subscript * based getters and setters. */ private String[] dupProperty = { "Dup 0", "Dup 1", "Dup 2", "Dup 3", "Dup 4" }; public String[] getDupProperty() { return (this.dupProperty); } public String getDupProperty(int index) { return (this.dupProperty[index]); } public void setDupProperty(int index, String value) { this.dupProperty[index] = value; } public void setDupProperty(String[] dupProperty) { this.dupProperty = dupProperty; } /** * A float property. */ private float floatProperty = (float) 123.0; public float getFloatProperty() { return (this.floatProperty); } public void setFloatProperty(float floatProperty) { this.floatProperty = floatProperty; } /** * An integer array property accessed as an array. */ private int intArray[] = { 0, 10, 20, 30, 40 }; public int[] getIntArray() { return (this.intArray); } public void setIntArray(int[] intArray) { this.intArray = intArray; } /** * An integer array property accessed as an indexed property. */ private final int intIndexed[] = { 0, 10, 20, 30, 40 }; public int getIntIndexed(int index) { return (intIndexed[index]); } public void setIntIndexed(int index, int value) { intIndexed[index] = value; } /** * An integer property. */ private int intProperty = 123; public int getIntProperty() { return (this.intProperty); } public void setIntProperty(int intProperty) { this.intProperty = intProperty; } /** * A List property accessed as an indexed property. */ private List listIndexed = new ArrayList(); public List getListIndexed() { return (listIndexed); } /** * A long property. */ private long longProperty = 321; public long getLongProperty() { return (this.longProperty); } public void setLongProperty(long longProperty) { this.longProperty = longProperty; } /** * A mapped property with only a getter and setter for a Map. */ private Map mapProperty = null; public Map getMapProperty() { // Create the map the very first time if (mapProperty == null) { mapProperty = new HashMap(); mapProperty.put("First Key", "First Value"); mapProperty.put("Second Key", "Second Value"); } return (mapProperty); } public void setMapProperty(Map mapProperty) { // Create the map the very first time if (mapProperty == null) { mapProperty = new HashMap(); mapProperty.put("First Key", "First Value"); mapProperty.put("Second Key", "Second Value"); } this.mapProperty = mapProperty; } /** * A mapped property that has String keys and Object values. */ private HashMap mappedObjects = null; public Object getMappedObjects(String key) { // Create the map the very first time if (mappedObjects == null) { mappedObjects = new HashMap(); mappedObjects.put("First Key", "First Value"); mappedObjects.put("Second Key", "Second Value"); } return (mappedObjects.get(key)); } public void setMappedObjects(String key, Object value) { // Create the map the very first time if (mappedObjects == null) { mappedObjects = new HashMap(); mappedObjects.put("First Key", "First Value"); mappedObjects.put("Second Key", "Second Value"); } mappedObjects.put(key, value); } /** * A mapped property that has String keys and String values. */ private HashMap mappedProperty = null; public String getMappedProperty(String key) { // Create the map the very first time if (mappedProperty == null) { mappedProperty = new HashMap(); mappedProperty.put("First Key", "First Value"); mappedProperty.put("Second Key", "Second Value"); } return (mappedProperty.get(key)); } public void setMappedProperty(String key, String value) { // Create the map the very first time if (mappedProperty == null) { mappedProperty = new HashMap(); mappedProperty.put("First Key", "First Value"); mappedProperty.put("Second Key", "Second Value"); } mappedProperty.put(key, value); } /** * A mapped property that has String keys and int values. */ private HashMap mappedIntProperty = null; public int getMappedIntProperty(String key) { // Create the map the very first time if (mappedIntProperty == null) { mappedIntProperty = new HashMap(); mappedIntProperty.put("One", 1); mappedIntProperty.put("Two", 2); } Integer x = mappedIntProperty.get(key); return ((x == null) ? 0 : x.intValue()); } public void setMappedIntProperty(String key, int value) { mappedIntProperty.put(key, value); } /** * A nested reference to another test bean (populated as needed). */ private TestBean nested = null; public TestBean getNested() { if (nested == null) nested = new TestBean(); return (nested); } /** * Another nested reference to another test bean, */ private TestBean anotherNested = null; public TestBean getAnotherNested() { return anotherNested; } public void setAnotherNested( TestBean anotherNested ) { this.anotherNested = anotherNested; } /** * Another nested reference to another test bean, */ private DynaBean nestedDynaBean = null; public DynaBean getNestedDynaBean() { return nestedDynaBean; } public void setNestedDynaBean(DynaBean nestedDynaBean) { this.nestedDynaBean = nestedDynaBean; } /* * Another nested reference to a bean containing mapp properties */ public class MappedTestBean { public void setValue(String key,String val) { } public String getValue(String key) { return "Mapped Value"; } } private MappedTestBean mappedNested = null; public MappedTestBean getMappedNested() { if (mappedNested == null) { mappedNested = new MappedTestBean(); } return mappedNested; } /** * A String property with an initial value of null. */ private String nullProperty = null; public String getNullProperty() { return (this.nullProperty); } public void setNullProperty(String nullProperty) { this.nullProperty = nullProperty; } /** * A read-only String property. */ private final String readOnlyProperty = "Read Only String Property"; public String getReadOnlyProperty() { return (this.readOnlyProperty); } /** * A short property. */ private short shortProperty = (short) 987; public short getShortProperty() { return (this.shortProperty); } public void setShortProperty(short shortProperty) { this.shortProperty = shortProperty; } /** * A String array property accessed as a String. */ private String[] stringArray = { "String 0", "String 1", "String 2", "String 3", "String 4" }; public String[] getStringArray() { return (this.stringArray); } public void setStringArray(String[] stringArray) { this.stringArray = stringArray; } /** * A String array property accessed as an indexed property. */ private final String[] stringIndexed = { "String 0", "String 1", "String 2", "String 3", "String 4" }; public String getStringIndexed(int index) { return (stringIndexed[index]); } public void setStringIndexed(int index, String value) { stringIndexed[index] = value; } private String[][] string2dArray = new String[][] {new String[] {"1", "2", "3"}, new String[] {"4","5","6"}}; public String[] getString2dArray(int index) { return string2dArray[index]; } /** * A String property. */ private String stringProperty = "This is a string"; public String getStringProperty() { return (this.stringProperty); } public void setStringProperty(String stringProperty) { this.stringProperty = stringProperty; } /** * A write-only String property. */ private String writeOnlyProperty = "Write Only String Property"; public String getWriteOnlyPropertyValue() { return (this.writeOnlyProperty); } public void setWriteOnlyProperty(String writeOnlyProperty) { this.writeOnlyProperty = writeOnlyProperty; } // ------------------------------------------------------ Invalid Properties /** *

          An invalid property that has two boolean getters (getInvalidBoolean * and isInvalidBoolean) plus a String setter (setInvalidBoolean). By the * rules described in the JavaBeans Specification, this will be considered * a read-only boolean property, using isInvalidBoolean() as the getter.

          */ private boolean invalidBoolean = false; public boolean getInvalidBoolean() { return (this.invalidBoolean); } public boolean isInvalidBoolean() { return (this.invalidBoolean); } public void setInvalidBoolean(String invalidBoolean) { if ("true".equalsIgnoreCase(invalidBoolean) || "yes".equalsIgnoreCase(invalidBoolean) || "1".equalsIgnoreCase(invalidBoolean)) { this.invalidBoolean = true; } else { this.invalidBoolean = false; } } // ------------------------------------------------------- Static Variables /** * A static variable that is accessed and updated via static methods * for MethodUtils testing. */ private static int counter = 0; /** * Return the current value of the counter. */ public static int currentCounter() { return (counter); } /** * Increment the current value of the counter by 1. */ public static void incrementCounter() { incrementCounter(1); } /** * Increment the current value of the counter by the specified amount. * * @param amount Amount to be added to the current counter */ public static void incrementCounter(int amount) { counter += amount; } /** * Increments the current value of the count by the * specified amount * 2. It has the same name * as the method above so as to test the looseness * of getMethod. */ public static void incrementCounter(Number amount) { counter += 2 * amount.intValue(); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/TestBeanPackageSubclass.java100644 0 0 2173 12262570610 30565 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * This is a package private subclass of TestBean. All of our properties * should still be accessible via reflection. * * @version $Id: TestBeanPackageSubclass.java 1454597 2013-03-08 21:58:12Z britter $ */ class TestBeanPackageSubclass extends TestBean { } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/TestBeanPublicSubclass.java100644 0 0 2167 12262570610 30453 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * This is a public subclass of TestBean. All of our properties should still * be accessible via reflection. * * @version $Id: TestBeanPublicSubclass.java 1454597 2013-03-08 21:58:12Z britter $ */ public class TestBeanPublicSubclass extends TestBean { } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/TestResultSet.java100644 0 0 62673 12262570610 26731 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import java.util.Map; /** *

          Mock object that implements enough of java.sql.ResultSet * to exercise the {@link ResultSetDynaClass} functionality.

          * * @version $Id: TestResultSet.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class TestResultSet implements InvocationHandler { // ----------------------------------------------------- Instance Variables /** * Current row number (0 means "before the first one"). */ protected int row = 0; /** * The constant (per run) value used to initialize date/time/timestamp. */ protected long timestamp = System.currentTimeMillis(); /** * Meta data for the result set. */ protected ResultSetMetaData resultSetMetaData; /** * Factory method for creating {@link ResultSet} proxies. * * @return A result set proxy */ public static ResultSet createProxy() { return TestResultSet.createProxy(new TestResultSet()); } /** * Factory method for creating {@link ResultSet} proxies. * * @param invocationHandler Invocation Handler * @return A result set proxy */ public static ResultSet createProxy(InvocationHandler invocationHandler) { ClassLoader classLoader = ResultSet.class.getClassLoader(); Class[] interfaces = new Class[] { ResultSet.class }; return (ResultSet)Proxy.newProxyInstance(classLoader, interfaces, invocationHandler); } /** * Create a proxy ResultSet. */ public TestResultSet() { this(TestResultSetMetaData.createProxy()); } /** * Create a proxy ResultSet with the specified meta data. * * @param resultSetMetaData The result set meta data */ public TestResultSet(ResultSetMetaData resultSetMetaData) { this.resultSetMetaData = resultSetMetaData; } /** * Handles method invocation on the ResultSet proxy. * * @param proxy The proxy ResultSet object * @param method the method being invoked * @param args The method arguments * @return The result of invoking the method. * @throws Throwable if an error occurs. */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); if ("close".equals(methodName)) { return null; } if ("getMetaData".equals(methodName)) { return getMetaData(); } if ("getObject".equals(methodName)) { return getObject(columnName(args[0])); } if ("getDate".equals(methodName)) { return getDate(columnName(args[0])); } if ("getTime".equals(methodName)) { return getTime(columnName(args[0])); } if ("getTimestamp".equals(methodName)) { return getTimestamp(columnName(args[0])); } if ("next".equals(methodName)) { return (next() ? Boolean.TRUE : Boolean.FALSE); } if ("updateObject".equals(methodName)) { updateObject((String)args[0], args[1]); return null; } throw new UnsupportedOperationException(methodName + " not implemented"); } private String columnName(Object arg) throws SQLException { if (arg instanceof Integer) { return resultSetMetaData.getColumnName(((Integer)arg).intValue()); } else { return (String)arg; } } // ---------------------------------------------------- Implemented Methods public void close() throws SQLException { // No action required } public ResultSetMetaData getMetaData() throws SQLException { return resultSetMetaData; } public Object getObject(String columnName) throws SQLException { if (row > 5) { throw new SQLException("No current row"); } if ("bigDecimalProperty".equals(columnName)) { return (new BigDecimal(123.45)); } else if ("booleanProperty".equals(columnName)) { if ((row % 2) == 0) { return (Boolean.TRUE); } else { return (Boolean.FALSE); } } else if ("byteProperty".equals(columnName)) { return (new Byte((byte) row)); } else if ("dateProperty".equals(columnName)) { return (new Date(timestamp)); } else if ("doubleProperty".equals(columnName)) { return (new Double(321.0)); } else if ("floatProperty".equals(columnName)) { return (new Float((float) 123.0)); } else if ("intProperty".equals(columnName)) { return (new Integer(100 + row)); } else if ("longProperty".equals(columnName)) { return (new Long(200 + row)); } else if ("nullProperty".equals(columnName)) { return (null); } else if ("shortProperty".equals(columnName)) { return (new Short((short) (300 + row))); } else if ("stringProperty".equals(columnName)) { return ("This is a string"); } else if ("timeProperty".equals(columnName)) { return (new Time(timestamp)); } else if ("timestampProperty".equals(columnName)) { return (new Timestamp(timestamp)); } else { throw new SQLException("Unknown column name " + columnName); } } public Date getDate(String columnName) throws SQLException { return (new Date(timestamp)); } public Time getTime(String columnName) throws SQLException { return (new Time(timestamp)); } public Timestamp getTimestamp(String columnName) throws SQLException { return (new Timestamp(timestamp)); } public boolean next() throws SQLException { if (row++ < 5) { return (true); } else { return (false); } } public void updateObject(String columnName, Object x) throws SQLException { if (row > 5) { throw new SQLException("No current row"); } // FIXME - updateObject() } // -------------------------------------------------- Unimplemented Methods public boolean absolute(int row) throws SQLException { throw new UnsupportedOperationException(); } public void afterLast() throws SQLException { throw new UnsupportedOperationException(); } public void beforeFirst() throws SQLException { throw new UnsupportedOperationException(); } public void cancelRowUpdates() throws SQLException { throw new UnsupportedOperationException(); } public void clearWarnings() throws SQLException { throw new UnsupportedOperationException(); } public void deleteRow() throws SQLException { throw new UnsupportedOperationException(); } public int findColumn(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public boolean first() throws SQLException { throw new UnsupportedOperationException(); } public Array getArray(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public Array getArray(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public InputStream getAsciiStream(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public InputStream getAsciiStream(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public BigDecimal getBigDecimal(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } /** @deprecated */ @Deprecated public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { throw new UnsupportedOperationException(); } public BigDecimal getBigDecimal(String columnName) throws SQLException { throw new UnsupportedOperationException(); } /** @deprecated */ @Deprecated public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { throw new UnsupportedOperationException(); } public InputStream getBinaryStream(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public InputStream getBinaryStream(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public Blob getBlob(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public Blob getBlob(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public boolean getBoolean(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public boolean getBoolean(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public byte getByte(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public byte getByte(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public byte[] getBytes(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public byte[] getBytes(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public Reader getCharacterStream(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public Reader getCharacterStream(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public Clob getClob(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public Clob getClob(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public int getConcurrency() throws SQLException { throw new UnsupportedOperationException(); } public String getCursorName() throws SQLException { throw new UnsupportedOperationException(); } public Date getDate(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public Date getDate(int columnIndex, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public Date getDate(String columnName, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public double getDouble(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public double getDouble(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public int getFetchDirection() throws SQLException { throw new UnsupportedOperationException(); } public int getFetchSize() throws SQLException { throw new UnsupportedOperationException(); } public float getFloat(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public float getFloat(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public int getInt(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public int getInt(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public long getLong(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public long getLong(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public Object getObject(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public Object getObject(int columnIndex, Map map) throws SQLException { throw new UnsupportedOperationException(); } public Object getObject(String columnName, Map map) throws SQLException { throw new UnsupportedOperationException(); } public Ref getRef(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public Ref getRef(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public int getRow() throws SQLException { throw new UnsupportedOperationException(); } public short getShort(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public short getShort(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public Statement getStatement() throws SQLException { throw new UnsupportedOperationException(); } public String getString(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public String getString(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public Time getTime(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public Time getTime(int columnIndex, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public Time getTime(String columnName, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public Timestamp getTimestamp(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public int getType() throws SQLException { throw new UnsupportedOperationException(); } /** @deprecated */ @Deprecated public InputStream getUnicodeStream(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } /** @deprecated */ @Deprecated public InputStream getUnicodeStream(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public URL getURL(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public URL getURL(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public SQLWarning getWarnings() throws SQLException { throw new UnsupportedOperationException(); } public void insertRow() throws SQLException { throw new UnsupportedOperationException(); } public boolean isAfterLast() throws SQLException { throw new UnsupportedOperationException(); } public boolean isBeforeFirst() throws SQLException { throw new UnsupportedOperationException(); } public boolean isFirst() throws SQLException { throw new UnsupportedOperationException(); } public boolean isLast() throws SQLException { throw new UnsupportedOperationException(); } public boolean last() throws SQLException { throw new UnsupportedOperationException(); } public void moveToCurrentRow() throws SQLException { throw new UnsupportedOperationException(); } public void moveToInsertRow() throws SQLException { throw new UnsupportedOperationException(); } public boolean previous() throws SQLException { throw new UnsupportedOperationException(); } public void refreshRow() throws SQLException { throw new UnsupportedOperationException(); } public boolean relative(int rows) throws SQLException { throw new UnsupportedOperationException(); } public boolean rowDeleted() throws SQLException { throw new UnsupportedOperationException(); } public boolean rowInserted() throws SQLException { throw new UnsupportedOperationException(); } public boolean rowUpdated() throws SQLException { throw new UnsupportedOperationException(); } public void setFetchDirection(int direction) throws SQLException { throw new UnsupportedOperationException(); } public void setFetchSize(int size) throws SQLException { throw new UnsupportedOperationException(); } public void updateArray(int columnPosition, Array x) throws SQLException { throw new UnsupportedOperationException(); } public void updateArray(String columnName, Array x) throws SQLException { throw new UnsupportedOperationException(); } public void updateAsciiStream(int columnPosition, InputStream x, int len) throws SQLException { throw new UnsupportedOperationException(); } public void updateAsciiStream(String columnName, InputStream x, int len) throws SQLException { throw new UnsupportedOperationException(); } public void updateBigDecimal(int columnPosition, BigDecimal x) throws SQLException { throw new UnsupportedOperationException(); } public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { throw new UnsupportedOperationException(); } public void updateBinaryStream(int columnPosition, InputStream x, int len) throws SQLException { throw new UnsupportedOperationException(); } public void updateBinaryStream(String columnName, InputStream x, int len) throws SQLException { throw new UnsupportedOperationException(); } public void updateBlob(int columnPosition, Blob x) throws SQLException { throw new UnsupportedOperationException(); } public void updateBlob(String columnName, Blob x) throws SQLException { throw new UnsupportedOperationException(); } public void updateBoolean(int columnPosition, boolean x) throws SQLException { throw new UnsupportedOperationException(); } public void updateBoolean(String columnName, boolean x) throws SQLException { throw new UnsupportedOperationException(); } public void updateByte(int columnPosition, byte x) throws SQLException { throw new UnsupportedOperationException(); } public void updateByte(String columnName, byte x) throws SQLException { throw new UnsupportedOperationException(); } public void updateBytes(int columnPosition, byte x[]) throws SQLException { throw new UnsupportedOperationException(); } public void updateBytes(String columnName, byte x[]) throws SQLException { throw new UnsupportedOperationException(); } public void updateCharacterStream(int columnPosition, Reader x, int len) throws SQLException { throw new UnsupportedOperationException(); } public void updateCharacterStream(String columnName, Reader x, int len) throws SQLException { throw new UnsupportedOperationException(); } public void updateClob(int columnPosition, Clob x) throws SQLException { throw new UnsupportedOperationException(); } public void updateClob(String columnName, Clob x) throws SQLException { throw new UnsupportedOperationException(); } public void updateDate(int columnPosition, Date x) throws SQLException { throw new UnsupportedOperationException(); } public void updateDate(String columnName, Date x) throws SQLException { throw new UnsupportedOperationException(); } public void updateDouble(int columnPosition, double x) throws SQLException { throw new UnsupportedOperationException(); } public void updateDouble(String columnName, double x) throws SQLException { throw new UnsupportedOperationException(); } public void updateFloat(int columnPosition, float x) throws SQLException { throw new UnsupportedOperationException(); } public void updateFloat(String columnName, float x) throws SQLException { throw new UnsupportedOperationException(); } public void updateInt(int columnPosition, int x) throws SQLException { throw new UnsupportedOperationException(); } public void updateInt(String columnName, int x) throws SQLException { throw new UnsupportedOperationException(); } public void updateLong(int columnPosition, long x) throws SQLException { throw new UnsupportedOperationException(); } public void updateLong(String columnName, long x) throws SQLException { throw new UnsupportedOperationException(); } public void updateNull(int columnPosition) throws SQLException { throw new UnsupportedOperationException(); } public void updateNull(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public void updateObject(int columnPosition, Object x) throws SQLException { throw new UnsupportedOperationException(); } public void updateObject(int columnPosition, Object x, int scale) throws SQLException { throw new UnsupportedOperationException(); } public void updateObject(String columnName, Object x, int scale) throws SQLException { throw new UnsupportedOperationException(); } public void updateRef(int columnPosition, Ref x) throws SQLException { throw new UnsupportedOperationException(); } public void updateRef(String columnName, Ref x) throws SQLException { throw new UnsupportedOperationException(); } public void updateRow() throws SQLException { throw new UnsupportedOperationException(); } public void updateShort(int columnPosition, short x) throws SQLException { throw new UnsupportedOperationException(); } public void updateShort(String columnName, short x) throws SQLException { throw new UnsupportedOperationException(); } public void updateString(int columnPosition, String x) throws SQLException { throw new UnsupportedOperationException(); } public void updateString(String columnName, String x) throws SQLException { throw new UnsupportedOperationException(); } public void updateTime(int columnPosition, Time x) throws SQLException { throw new UnsupportedOperationException(); } public void updateTime(String columnName, Time x) throws SQLException { throw new UnsupportedOperationException(); } public void updateTimestamp(int columnPosition, Timestamp x) throws SQLException { throw new UnsupportedOperationException(); } public void updateTimestamp(String columnName, Timestamp x) throws SQLException { throw new UnsupportedOperationException(); } public boolean wasNull() throws SQLException { throw new UnsupportedOperationException(); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/TestResultSetMetaData.java100644 0 0 20662 12262570610 30322 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; /** *

          Mock object that implements enough of * java.sql.ResultSetMetaData * to exercise the {@link ResultSetDynaClass} functionality.

          * * @version $Id: TestResultSetMetaData.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class TestResultSetMetaData implements InvocationHandler { // ----------------------------------------------------- Instance Variables /** *

          Array of column names and class names for metadata.

          */ protected String metadata[][] = { { "bigDecimalProperty", java.math.BigDecimal.class.getName() }, { "booleanProperty", Boolean.class.getName() }, { "byteProperty", Byte.class.getName() }, { "dateProperty", java.sql.Date.class.getName() }, { "doubleProperty", Double.class.getName() }, { "floatProperty", Float.class.getName() }, { "intProperty", Integer.class.getName() }, { "longProperty", Long.class.getName() }, { "nullProperty", String.class.getName() }, { "shortProperty", Short.class.getName() }, { "stringProperty", String.class.getName() }, { "timeProperty", java.sql.Time.class.getName() }, { "timestampProperty", java.sql.Timestamp.class.getName() }, }; /** * Factory method for creating {@link ResultSetMetaData} proxies. * * @return A result set meta data proxy */ public static ResultSetMetaData createProxy() { return TestResultSetMetaData.createProxy(new TestResultSetMetaData()); } /** * Factory method for creating {@link ResultSetMetaData} proxies. * @param invocationHandler Invocation Handler * @return A result set meta data proxy */ public static ResultSetMetaData createProxy(InvocationHandler invocationHandler) { ClassLoader classLoader = ResultSetMetaData.class.getClassLoader(); Class[] interfaces = new Class[] { ResultSetMetaData.class }; return (ResultSetMetaData)Proxy.newProxyInstance(classLoader, interfaces, invocationHandler); } /** * Handles method invocation on the {@link ResultSetMetaData} proxy. * * @param proxy The proxy ResultSet object * @param method the method being invoked * @param args The method arguments * @return The result of invoking the method. * @throws Throwable if an error occurs. */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); if ("getColumnClassName".equals(methodName)) { return getColumnClassName(((Integer)args[0]).intValue()); } if ("getColumnCount".equals(methodName)) { return new Integer(getColumnCount()); } if ("getColumnName".equals(methodName)) { return getColumnName(((Integer)args[0]).intValue()); } if ("getColumnType".equals(methodName)) { return getColumnType(((Integer)args[0]).intValue()); } throw new UnsupportedOperationException(methodName + " not implemented"); } // ---------------------------------------------------- Implemented Methods public String getColumnClassName(int columnIndex) throws SQLException { return (metadata[columnIndex - 1][1]); } public int getColumnCount() throws SQLException { return (metadata.length); } public String getColumnName(int columnIndex) throws SQLException { return (metadata[columnIndex - 1][0]); } public Integer getColumnType(int columnIndex) throws SQLException { String columnName = getColumnName(columnIndex); int sqlType = Types.OTHER; if (columnName.equals("bigDecimalProperty")) { sqlType = Types.DECIMAL; // Types.BOOLEAN only introduced in JDK 1.4 // } else if (columnName.equals("booleanProperty")) { // sqlType = Types.BOOLEAN; } else if (columnName.equals("byteProperty")) { sqlType = Types.TINYINT; } else if (columnName.equals("dateProperty")) { sqlType = Types.DATE; } else if (columnName.equals("doubleProperty")) { sqlType = Types.DOUBLE; } else if (columnName.equals("floatProperty")) { sqlType = Types.FLOAT; } else if (columnName.equals("intProperty")) { sqlType = Types.INTEGER; } else if (columnName.equals("longProperty")) { sqlType = Types.BIGINT; } else if (columnName.equals("nullProperty")) { sqlType = Types.VARCHAR; } else if (columnName.equals("shortProperty")) { sqlType = Types.SMALLINT; } else if (columnName.equals("stringProperty")) { sqlType = Types.VARCHAR; } else if (columnName.equals("timeProperty")) { sqlType = Types.TIME; } else if (columnName.equals("timestampProperty")) { sqlType = Types.TIMESTAMP; } else { sqlType = Types.OTHER; } return new Integer(sqlType); } // -------------------------------------------------- Unimplemented Methods public String getCatalogName(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public int getColumnDisplaySize(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public String getColumnLabel(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public String getColumnTypeName(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public int getPrecision(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public int getScale(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public String getSchemaName(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public String getTableName(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public boolean isAutoIncrement(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public boolean isCaseSensitive(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public boolean isCurrency(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public boolean isDefinitelyWritable(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public int isNullable(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public boolean isReadOnly(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public boolean isSearchable(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public boolean isSigned(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public boolean isWritable(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/ThrowExceptionConverter.java100644 0 0 2474 12262570607 30770 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * Converter implementation that throws a PassTestException * when convert is called. * The idea is that catching this exception is a clear signal that this method * has been called. * * @version $Id: ThrowExceptionConverter.java 1540186 2013-11-08 21:08:30Z oheger $ */ public class ThrowExceptionConverter implements Converter { public T convert(Class type, Object value) { throw new PassTestException(); } } commons-beanutils-1.9.1-src/src/test/java/org/apache/commons/beanutils/WrapDynaBeanTestCase.java100644 0 0 30527 12262570607 30105 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestSuite; /** *

          Test Case for the WrapDynaBean implementation class. * These tests were based on the ones in PropertyUtilsTestCase * because the two classes provide similar levels of functionality.

          * * @version $Id: WrapDynaBeanTestCase.java 1547902 2013-12-04 20:35:01Z oheger $ */ public class WrapDynaBeanTestCase extends BasicDynaBeanTestCase { // ---------------------------------------------------- Instance Variables // ---------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public WrapDynaBeanTestCase(String name) { super(name); } // -------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ @Override public void setUp() throws Exception { bean = new WrapDynaBean(new TestBean()); } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(WrapDynaBeanTestCase.class)); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { bean = null; } // ------------------------------------------------ Individual Test Methods /** * The set() method. */ public void testSimpleProperties() { checkSimplePropertyAccess(); } /** * Helper method for testing whether basic access to properties works as * expected. */ private void checkSimplePropertyAccess() { // Invalid getter try { bean.get("invalidProperty"); fail("Invalid get should have thrown IllegalArgumentException"); } catch (IllegalArgumentException t) { // Expected result } // Invalid setter try { bean.set("invalidProperty", "XYZ"); fail("Invalid set should have thrown IllegalArgumentException"); } catch (IllegalArgumentException t) { // Expected result } // Set up initial Value String testValue = "Original Value"; String testProperty = "stringProperty"; TestBean instance = (TestBean)((WrapDynaBean)bean).getInstance(); instance.setStringProperty(testValue); assertEquals("Check String property", testValue, instance.getStringProperty()); // Test Valid Get & Set try { testValue = "Some new value"; bean.set(testProperty, testValue); assertEquals("Test Set", testValue, instance.getStringProperty()); assertEquals("Test Get", testValue, bean.get(testProperty)); } catch (IllegalArgumentException t) { fail("Get threw exception: " + t); } } /** * The set() method. */ public void testIndexedProperties() { // Invalid getter try { bean.get("invalidProperty", 0); fail("Invalid get should have thrown IllegalArgumentException"); } catch (IllegalArgumentException t) { // Expected result } // Invalid setter try { bean.set("invalidProperty", 0, "XYZ"); fail("Invalid set should have thrown IllegalArgumentException"); } catch (IllegalArgumentException t) { // Expected result } // Set up initial Value String testValue = "Original Value"; String testProperty = "stringIndexed"; TestBean instance = (TestBean)((WrapDynaBean)bean).getInstance(); instance.setStringIndexed(0, testValue); assertEquals("Check String property", testValue, instance.getStringIndexed(0)); // Test Valid Get & Set try { testValue = "Some new value"; bean.set(testProperty, 0, testValue); assertEquals("Test Set", testValue, instance.getStringIndexed(0)); assertEquals("Test Get", testValue, bean.get(testProperty, 0)); } catch (IllegalArgumentException t) { fail("Get threw exception: " + t); } } /** * The contains() method is not supported by the * WrapDynaBean implementation class. */ @Override public void testMappedContains() { try { assertTrue("Can see first key", bean.contains("mappedProperty", "First Key")); fail("Should have thrown UnsupportedOperationException"); } catch (UnsupportedOperationException t) { // Expected result } catch (Throwable t) { fail("Exception: " + t); } try { assertTrue("Can not see unknown key", !bean.contains("mappedProperty", "Unknown Key")); fail("Should have thrown UnsupportedOperationException"); } catch (UnsupportedOperationException t) { // Expected result } catch (Throwable t) { fail("Exception: " + t); } } /** * The remove() method is not supported by the * WrapDynaBean implementation class. */ @Override public void testMappedRemove() { try { assertTrue("Can see first key", bean.contains("mappedProperty", "First Key")); bean.remove("mappedProperty", "First Key"); fail("Should have thrown UnsupportedOperationException"); // assertTrue("Can not see first key", // !bean.contains("mappedProperty", "First Key")); } catch (UnsupportedOperationException t) { // Expected result } catch (Throwable t) { fail("Exception: " + t); } try { assertTrue("Can not see unknown key", !bean.contains("mappedProperty", "Unknown Key")); bean.remove("mappedProperty", "Unknown Key"); fail("Should have thrown UnsupportedOperationException"); // assertTrue("Can not see unknown key", // !bean.contains("mappedProperty", "Unknown Key")); } catch (UnsupportedOperationException t) { // Expected result } catch (Throwable t) { fail("Exception: " + t); } } /** Tests getInstance method */ public void testGetInstance() { AlphaBean alphaBean = new AlphaBean("Now On Air... John Peel"); WrapDynaBean dynaBean = new WrapDynaBean(alphaBean); Object wrappedInstance = dynaBean.getInstance(); assertTrue("Object type is AlphaBean", wrappedInstance instanceof AlphaBean); AlphaBean wrappedAlphaBean = (AlphaBean) wrappedInstance; assertTrue("Same Object", wrappedAlphaBean == alphaBean); } /** Tests the newInstance implementation for WrapDynaClass */ public void testNewInstance() throws Exception { WrapDynaClass dynaClass = WrapDynaClass.createDynaClass(AlphaBean.class); Object createdInstance = dynaClass.newInstance(); assertTrue("Object type is WrapDynaBean", createdInstance instanceof WrapDynaBean); WrapDynaBean dynaBean = (WrapDynaBean) createdInstance; assertTrue("Object type is AlphaBean", dynaBean.getInstance() instanceof AlphaBean); } /** * Serialization and deserialization tests. * (WrapDynaBean is now serializable, although WrapDynaClass still is not) */ @Override public void testSerialization() { // Create a bean and set a value WrapDynaBean origBean = new WrapDynaBean(new TestBean()); Integer newValue = new Integer(789); assertEquals("origBean default", new Integer(123), origBean.get("intProperty")); origBean.set("intProperty", newValue); assertEquals("origBean new value", newValue, origBean.get("intProperty")); // Serialize/Deserialize & test value WrapDynaBean bean = (WrapDynaBean)serializeDeserialize(origBean, "First Test"); assertEquals("bean value", newValue, bean.get("intProperty")); } /** * Do serialization and deserialization. */ private Object serializeDeserialize(Object target, String text) { // Serialize the test object ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(target); oos.flush(); oos.close(); } catch (Exception e) { fail(text + ": Exception during serialization: " + e); } // Deserialize the test object Object result = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = ois.readObject(); bais.close(); } catch (Exception e) { fail(text + ": Exception during deserialization: " + e); } return result; } /** * Tests whether a WrapDynaClass can be provided when constructing a bean. */ public void testInitWithDynaClass() { WrapDynaClass clazz = WrapDynaClass.createDynaClass(TestBean.class); bean = new WrapDynaBean(new TestBean(), clazz); assertSame("Wrong DynaClass", clazz, bean.getDynaClass()); checkSimplePropertyAccess(); } /** * Tests whether caching works for WrapDynaClass objects. */ public void testGetWrapDynaClassFromCache() { WrapDynaClass clazz = WrapDynaClass.createDynaClass(TestBean.class); assertSame("Instance not cached", clazz, WrapDynaClass.createDynaClass(TestBean.class)); } /** * Tests whether the PropertyUtilsBean instance associated with a WrapDynaClass is * taken into account when accessing an instance from the cache. */ public void testGetWrapDynaClassFromCacheWithPropUtils() { WrapDynaClass clazz = WrapDynaClass.createDynaClass(TestBean.class); PropertyUtilsBean pu = new PropertyUtilsBean(); WrapDynaClass clazz2 = WrapDynaClass.createDynaClass(TestBean.class, pu); assertNotSame("Got same instance from cache", clazz, clazz2); } /** * Tests whether a custom PropertyUtilsBean instance can be used for introspection of * bean properties. */ public void testIntrospectionWithCustomPropUtils() { PropertyUtilsBean pu = new PropertyUtilsBean(); pu.addBeanIntrospector(new FluentPropertyBeanIntrospector()); WrapDynaClass dynaClass = WrapDynaClass.createDynaClass( FluentIntrospectionTestBean.class, pu); FluentIntrospectionTestBean obj = new FluentIntrospectionTestBean(); bean = new WrapDynaBean(obj, dynaClass); bean.set("fluentProperty", "testvalue"); assertEquals("Property not set", "testvalue", obj.getStringProperty()); } }