first commit
This commit is contained in:
commit
4d332ef662
27586 changed files with 3281783 additions and 0 deletions
202
rus/WEB-INF/lib/commons-lang-2.4_src/META-INF/LICENSE.txt
Normal file
202
rus/WEB-INF/lib/commons-lang-2.4_src/META-INF/LICENSE.txt
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
39
rus/WEB-INF/lib/commons-lang-2.4_src/META-INF/MANIFEST.MF
Normal file
39
rus/WEB-INF/lib/commons-lang-2.4_src/META-INF/MANIFEST.MF
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
Manifest-Version: 1.0
|
||||
Archiver-Version: Plexus Archiver
|
||||
Created-By: 1.4.2_16 (Apple Computer, Inc.)
|
||||
Built-By: hen
|
||||
Build-Jdk: 1.4.2_16
|
||||
Implementation-Title: Commons Lang
|
||||
Implementation-Vendor: The Apache Software Foundation
|
||||
Implementation-Vendor-Id: org.apache
|
||||
Implementation-Version: 2.4
|
||||
Specification-Title: Commons Lang
|
||||
Specification-Vendor: The Apache Software Foundation
|
||||
Specification-Version: 2.4
|
||||
X-Compile-Source-JDK: 1.3
|
||||
X-Compile-Target-JDK: 1.2
|
||||
Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
|
||||
Import-Package: org.apache.commons.lang;version="2.4",org.apache.commo
|
||||
ns.lang.builder;version="2.4",org.apache.commons.lang.enum;version="2
|
||||
.4",org.apache.commons.lang.enums;version="2.4",org.apache.commons.la
|
||||
ng.exception;version="2.4",org.apache.commons.lang.math;version="2.4"
|
||||
,org.apache.commons.lang.mutable;version="2.4",org.apache.commons.lan
|
||||
g.text;version="2.4",org.apache.commons.lang.time;version="2.4"
|
||||
Bnd-LastModified: 1205638979942
|
||||
Export-Package: org.apache.commons.lang.math;version="2.4",org.apache.
|
||||
commons.lang.enums;version="2.4",org.apache.commons.lang.builder;vers
|
||||
ion="2.4",org.apache.commons.lang.exception;version="2.4",org.apache.
|
||||
commons.lang.enum;version="2.4",org.apache.commons.lang.mutable;versi
|
||||
on="2.4",org.apache.commons.lang.text;version="2.4",org.apache.common
|
||||
s.lang.time;version="2.4",org.apache.commons.lang;version="2.4"
|
||||
Bundle-Version: 2.4
|
||||
Bundle-Description: Commons Lang, a package of Java utility classes fo
|
||||
r the classes that are in java.lang's hierarchy, or are consid
|
||||
ered to be so standard as to justify existence in java.lang.
|
||||
Bundle-Name: Commons Lang
|
||||
Bundle-DocURL: http://commons.apache.org/lang/
|
||||
Bundle-ManifestVersion: 2
|
||||
Bundle-Vendor: The Apache Software Foundation
|
||||
Bundle-SymbolicName: org.apache.commons.lang
|
||||
Tool: Bnd-0.0.238
|
||||
|
||||
5
rus/WEB-INF/lib/commons-lang-2.4_src/META-INF/NOTICE.txt
Normal file
5
rus/WEB-INF/lib/commons-lang-2.4_src/META-INF/NOTICE.txt
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
Apache Commons Lang
|
||||
Copyright 2001-2008 The Apache Software Foundation
|
||||
|
||||
This product includes software developed by
|
||||
The Apache Software Foundation (http://www.apache.org/).
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
#Generated by Maven
|
||||
#Sat Mar 15 20:43:16 PDT 2008
|
||||
version=2.4
|
||||
groupId=commons-lang
|
||||
artifactId=commons-lang
|
||||
|
|
@ -0,0 +1,462 @@
|
|||
<?xml version="1.0"?>
|
||||
<!--
|
||||
Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
contributor license agreements. See the NOTICE file distributed with
|
||||
this work for additional information regarding copyright ownership.
|
||||
The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
(the "License"); you may not use this file except in compliance with
|
||||
the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-->
|
||||
<project
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<parent>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-parent</artifactId>
|
||||
<version>9</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>commons-lang</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
<version>2.4</version>
|
||||
<name>Commons Lang</name>
|
||||
|
||||
<inceptionYear>2001</inceptionYear>
|
||||
<description>
|
||||
Commons Lang, a package of Java utility classes for the
|
||||
classes that are in java.lang's hierarchy, or are considered to be so
|
||||
standard as to justify existence in java.lang.
|
||||
</description>
|
||||
|
||||
<url>http://commons.apache.org/lang/</url>
|
||||
|
||||
<issueManagement>
|
||||
<system>jira</system>
|
||||
<url>http://issues.apache.org/jira/browse/LANG</url>
|
||||
</issueManagement>
|
||||
|
||||
<scm>
|
||||
<connection>scm:svn:http://svn.apache.org/repos/asf/commons/proper/lang/trunk</connection>
|
||||
<developerConnection>scm:svn:https://svn.apache.org/repos/asf/commons/proper/lang/trunk</developerConnection>
|
||||
<url>http://svn.apache.org/viewvc/commons/proper/lang/trunk</url>
|
||||
</scm>
|
||||
|
||||
<developers>
|
||||
<developer>
|
||||
<name>Daniel Rall</name>
|
||||
<id>dlr</id>
|
||||
<email>dlr@finemaltcoding.com</email>
|
||||
<organization>CollabNet, Inc.</organization>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
</developer>
|
||||
<developer>
|
||||
<name>Stephen Colebourne</name>
|
||||
<id>scolebourne</id>
|
||||
<email>scolebourne@joda.org</email>
|
||||
<organization>SITA ATS Ltd</organization>
|
||||
<timezone>0</timezone>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
</developer>
|
||||
<developer>
|
||||
<name>Henri Yandell</name>
|
||||
<id>bayard</id>
|
||||
<email>bayard@apache.org</email>
|
||||
<organization/>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
</developer>
|
||||
<developer>
|
||||
<name>Steven Caswell</name>
|
||||
<id>scaswell</id>
|
||||
<email>stevencaswell@apache.org</email>
|
||||
<organization/>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
<timezone>-5</timezone>
|
||||
</developer>
|
||||
<developer>
|
||||
<name>Robert Burrell Donkin</name>
|
||||
<id>rdonkin</id>
|
||||
<email>rdonkin@apache.org</email>
|
||||
<organization/>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
</developer>
|
||||
<developer>
|
||||
<name>Gary D. Gregory</name>
|
||||
<id>ggregory</id>
|
||||
<email>ggregory@seagullsw.com</email>
|
||||
<organization>Seagull Software</organization>
|
||||
<timezone>-8</timezone>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
</developer>
|
||||
<developer>
|
||||
<name>Phil Steitz</name>
|
||||
<id>psteitz</id>
|
||||
<email>phil@steitz.com</email>
|
||||
<organization/>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
</developer>
|
||||
<developer>
|
||||
<name>Fredrik Westermarck</name>
|
||||
<id>fredrik</id>
|
||||
<email/>
|
||||
<organization/>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
</developer>
|
||||
<developer>
|
||||
<name>James Carman</name>
|
||||
<id>jcarman</id>
|
||||
<email>jcarman@apache.org</email>
|
||||
<organization>Carman Consulting, Inc.</organization>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
</developer>
|
||||
<developer>
|
||||
<name>Niall Pemberton</name>
|
||||
<id>niallp</id>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
</developer>
|
||||
<developer>
|
||||
<name>Matt Benson</name>
|
||||
<id>mbenson</id>
|
||||
<roles>
|
||||
<role>Java Developer</role>
|
||||
</roles>
|
||||
</developer>
|
||||
</developers>
|
||||
<contributors>
|
||||
<contributor>
|
||||
<name>C. Scott Ananian</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Chris Audley</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Stephane Bailliez</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Michael Becke</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Ola Berg</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Nathan Beyer</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Stefan Bodewig</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Janek Bogucki</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Mike Bowler</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Sean Brown</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Alexander Day Chaffee</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Al Chou</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Greg Coladonato</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Maarten Coene</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Justin Couch</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Michael Davey</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Norm Deane</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Ringo De Smet</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Russel Dittmar</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Steve Downey</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Matthias Eichel</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Christopher Elkins</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Chris Feldhacker</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Pete Gieser</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Jason Gritman</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Matthew Hawthorne</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Michael Heuer</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Oliver Heger</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Chris Hyzer</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Marc Johnson</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Shaun Kalley</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Tetsuya Kaneuchi</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Nissim Karpenstein</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Ed Korthof</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Holger Krauth</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Rafal Krupinski</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Rafal Krzewski</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Craig R. McClanahan</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Rand McNeely</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Dave Meikle</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Nikolay Metchev</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Kasper Nielsen</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Tim O'Brien</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Brian S O'Neill</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Andrew C. Oliver</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Alban Peignier</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Moritz Petersen</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Dmitri Plotnikov</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Neeme Praks</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Eric Pugh</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Stephen Putman</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Travis Reeder</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Antony Riley</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Scott Sanders</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Ralph Schaer</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Henning P. Schmiedehausen</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Sean Schofield</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Reuben Sivan</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Ville Skytta</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Jan Sorensen</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Glen Stampoultzis</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Scott Stanchfield</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Jon S. Stevens</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Sean C. Sullivan</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Ashwin Suresh</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Helge Tesgaard</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Arun Mammen Thomas</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Masato Tezuka</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Jeff Varszegi</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Chris Webb</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Mario Winterer</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Stepan Koltsov</name>
|
||||
</contributor>
|
||||
<contributor>
|
||||
<name>Holger Hoffstatte</name>
|
||||
</contributor>
|
||||
</contributors>
|
||||
|
||||
<!-- Lang should depend on very little -->
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<maven.compile.source>1.3</maven.compile.source>
|
||||
<maven.compile.target>1.2</maven.compile.target>
|
||||
<commons.componentid>lang</commons.componentid>
|
||||
<commons.release.version>2.4</commons.release.version>
|
||||
<commons.jira.id>LANG</commons.jira.id>
|
||||
<commons.jira.pid>12310481</commons.jira.pid>
|
||||
</properties>
|
||||
|
||||
|
||||
<build>
|
||||
<sourceDirectory>src/java</sourceDirectory>
|
||||
<testSourceDirectory>src/test</testSourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*TestSuite.java</include>
|
||||
</includes>
|
||||
<excludes>
|
||||
<exclude>**/AllLangTestSuite.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<configuration>
|
||||
<descriptors>
|
||||
<descriptor>src/assembly/bin.xml</descriptor>
|
||||
<descriptor>src/assembly/src.xml</descriptor>
|
||||
</descriptors>
|
||||
<tarLongFileMode>gnu</tarLongFileMode>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<reporting>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||
<version>2.1</version>
|
||||
<configuration>
|
||||
<configLocation>${basedir}/checkstyle.xml</configLocation>
|
||||
<enableRulesSummary>false</enableRulesSummary>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!--
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>findbugs-maven-plugin</artifactId>
|
||||
<version>1.1.1</version>
|
||||
<configuration>
|
||||
<threshold>Normal</threshold>
|
||||
<effort>Default</effort>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>cobertura-maven-plugin</artifactId>
|
||||
<version>2.2</version>
|
||||
</plugin>
|
||||
-->
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>clirr-maven-plugin</artifactId>
|
||||
<version>2.1.1</version>
|
||||
<configuration>
|
||||
<comparisonVersion>2.3</comparisonVersion>
|
||||
<minSeverity>info</minSeverity>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</reporting>
|
||||
|
||||
</project>
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,87 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
public class BitField {
|
||||
private final int _mask;
|
||||
|
||||
private final int _shift_count;
|
||||
|
||||
public BitField(int mask) {
|
||||
this._mask = mask;
|
||||
int count = 0;
|
||||
int bit_pattern = mask;
|
||||
if (bit_pattern != 0)
|
||||
while ((bit_pattern & 0x1) == 0) {
|
||||
count++;
|
||||
bit_pattern >>= 1;
|
||||
}
|
||||
this._shift_count = count;
|
||||
}
|
||||
|
||||
public int getValue(int holder) {
|
||||
return getRawValue(holder) >> this._shift_count;
|
||||
}
|
||||
|
||||
public short getShortValue(short holder) {
|
||||
return (short)getValue(holder);
|
||||
}
|
||||
|
||||
public int getRawValue(int holder) {
|
||||
return holder & this._mask;
|
||||
}
|
||||
|
||||
public short getShortRawValue(short holder) {
|
||||
return (short)getRawValue(holder);
|
||||
}
|
||||
|
||||
public boolean isSet(int holder) {
|
||||
return ((holder & this._mask) != 0);
|
||||
}
|
||||
|
||||
public boolean isAllSet(int holder) {
|
||||
return ((holder & this._mask) == this._mask);
|
||||
}
|
||||
|
||||
public int setValue(int holder, int value) {
|
||||
return holder & (this._mask ^ 0xFFFFFFFF) | value << this._shift_count & this._mask;
|
||||
}
|
||||
|
||||
public short setShortValue(short holder, short value) {
|
||||
return (short)setValue(holder, value);
|
||||
}
|
||||
|
||||
public int clear(int holder) {
|
||||
return holder & (this._mask ^ 0xFFFFFFFF);
|
||||
}
|
||||
|
||||
public short clearShort(short holder) {
|
||||
return (short)clear(holder);
|
||||
}
|
||||
|
||||
public byte clearByte(byte holder) {
|
||||
return (byte)clear(holder);
|
||||
}
|
||||
|
||||
public int set(int holder) {
|
||||
return holder | this._mask;
|
||||
}
|
||||
|
||||
public short setShort(short holder) {
|
||||
return (short)set(holder);
|
||||
}
|
||||
|
||||
public byte setByte(byte holder) {
|
||||
return (byte)set(holder);
|
||||
}
|
||||
|
||||
public int setBoolean(int holder, boolean flag) {
|
||||
return flag ? set(holder) : clear(holder);
|
||||
}
|
||||
|
||||
public short setShortBoolean(short holder, boolean flag) {
|
||||
return flag ? setShort(holder) : clearShort(holder);
|
||||
}
|
||||
|
||||
public byte setByteBoolean(byte holder, boolean flag) {
|
||||
return flag ? setByte(holder) : clearByte(holder);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,291 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import org.apache.commons.lang.math.NumberUtils;
|
||||
|
||||
public class BooleanUtils {
|
||||
public static Boolean negate(Boolean bool) {
|
||||
if (bool == null)
|
||||
return null;
|
||||
return bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE;
|
||||
}
|
||||
|
||||
public static boolean isTrue(Boolean bool) {
|
||||
if (bool == null)
|
||||
return false;
|
||||
return bool.booleanValue();
|
||||
}
|
||||
|
||||
public static boolean isNotTrue(Boolean bool) {
|
||||
return !isTrue(bool);
|
||||
}
|
||||
|
||||
public static boolean isFalse(Boolean bool) {
|
||||
if (bool == null)
|
||||
return false;
|
||||
return !bool.booleanValue();
|
||||
}
|
||||
|
||||
public static boolean isNotFalse(Boolean bool) {
|
||||
return !isFalse(bool);
|
||||
}
|
||||
|
||||
public static Boolean toBooleanObject(boolean bool) {
|
||||
return bool ? Boolean.TRUE : Boolean.FALSE;
|
||||
}
|
||||
|
||||
public static boolean toBoolean(Boolean bool) {
|
||||
if (bool == null)
|
||||
return false;
|
||||
return bool.booleanValue();
|
||||
}
|
||||
|
||||
public static boolean toBooleanDefaultIfNull(Boolean bool, boolean valueIfNull) {
|
||||
if (bool == null)
|
||||
return valueIfNull;
|
||||
return bool.booleanValue();
|
||||
}
|
||||
|
||||
public static boolean toBoolean(int value) {
|
||||
return !(value == 0);
|
||||
}
|
||||
|
||||
public static Boolean toBooleanObject(int value) {
|
||||
return (value == 0) ? Boolean.FALSE : Boolean.TRUE;
|
||||
}
|
||||
|
||||
public static Boolean toBooleanObject(Integer value) {
|
||||
if (value == null)
|
||||
return null;
|
||||
return (value.intValue() == 0) ? Boolean.FALSE : Boolean.TRUE;
|
||||
}
|
||||
|
||||
public static boolean toBoolean(int value, int trueValue, int falseValue) {
|
||||
if (value == trueValue)
|
||||
return true;
|
||||
if (value == falseValue)
|
||||
return false;
|
||||
throw new IllegalArgumentException("The Integer did not match either specified value");
|
||||
}
|
||||
|
||||
public static boolean toBoolean(Integer value, Integer trueValue, Integer falseValue) {
|
||||
if (value == null) {
|
||||
if (trueValue == null)
|
||||
return true;
|
||||
if (falseValue == null)
|
||||
return false;
|
||||
} else {
|
||||
if (value.equals(trueValue))
|
||||
return true;
|
||||
if (value.equals(falseValue))
|
||||
return false;
|
||||
}
|
||||
throw new IllegalArgumentException("The Integer did not match either specified value");
|
||||
}
|
||||
|
||||
public static Boolean toBooleanObject(int value, int trueValue, int falseValue, int nullValue) {
|
||||
if (value == trueValue)
|
||||
return Boolean.TRUE;
|
||||
if (value == falseValue)
|
||||
return Boolean.FALSE;
|
||||
if (value == nullValue)
|
||||
return null;
|
||||
throw new IllegalArgumentException("The Integer did not match any specified value");
|
||||
}
|
||||
|
||||
public static Boolean toBooleanObject(Integer value, Integer trueValue, Integer falseValue, Integer nullValue) {
|
||||
if (value == null) {
|
||||
if (trueValue == null)
|
||||
return Boolean.TRUE;
|
||||
if (falseValue == null)
|
||||
return Boolean.FALSE;
|
||||
if (nullValue == null)
|
||||
return null;
|
||||
} else {
|
||||
if (value.equals(trueValue))
|
||||
return Boolean.TRUE;
|
||||
if (value.equals(falseValue))
|
||||
return Boolean.FALSE;
|
||||
if (value.equals(nullValue))
|
||||
return null;
|
||||
}
|
||||
throw new IllegalArgumentException("The Integer did not match any specified value");
|
||||
}
|
||||
|
||||
public static int toInteger(boolean bool) {
|
||||
return bool ? 1 : 0;
|
||||
}
|
||||
|
||||
public static Integer toIntegerObject(boolean bool) {
|
||||
return bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
|
||||
}
|
||||
|
||||
public static Integer toIntegerObject(Boolean bool) {
|
||||
if (bool == null)
|
||||
return null;
|
||||
return bool.booleanValue() ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
|
||||
}
|
||||
|
||||
public static int toInteger(boolean bool, int trueValue, int falseValue) {
|
||||
return bool ? trueValue : falseValue;
|
||||
}
|
||||
|
||||
public static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue) {
|
||||
if (bool == null)
|
||||
return nullValue;
|
||||
return bool.booleanValue() ? trueValue : falseValue;
|
||||
}
|
||||
|
||||
public static Integer toIntegerObject(boolean bool, Integer trueValue, Integer falseValue) {
|
||||
return bool ? trueValue : falseValue;
|
||||
}
|
||||
|
||||
public static Integer toIntegerObject(Boolean bool, Integer trueValue, Integer falseValue, Integer nullValue) {
|
||||
if (bool == null)
|
||||
return nullValue;
|
||||
return bool.booleanValue() ? trueValue : falseValue;
|
||||
}
|
||||
|
||||
public static Boolean toBooleanObject(String str) {
|
||||
if ("true".equalsIgnoreCase(str))
|
||||
return Boolean.TRUE;
|
||||
if ("false".equalsIgnoreCase(str))
|
||||
return Boolean.FALSE;
|
||||
if ("on".equalsIgnoreCase(str))
|
||||
return Boolean.TRUE;
|
||||
if ("off".equalsIgnoreCase(str))
|
||||
return Boolean.FALSE;
|
||||
if ("yes".equalsIgnoreCase(str))
|
||||
return Boolean.TRUE;
|
||||
if ("no".equalsIgnoreCase(str))
|
||||
return Boolean.FALSE;
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString) {
|
||||
if (str == null) {
|
||||
if (trueString == null)
|
||||
return Boolean.TRUE;
|
||||
if (falseString == null)
|
||||
return Boolean.FALSE;
|
||||
if (nullString == null)
|
||||
return null;
|
||||
} else {
|
||||
if (str.equals(trueString))
|
||||
return Boolean.TRUE;
|
||||
if (str.equals(falseString))
|
||||
return Boolean.FALSE;
|
||||
if (str.equals(nullString))
|
||||
return null;
|
||||
}
|
||||
throw new IllegalArgumentException("The String did not match any specified value");
|
||||
}
|
||||
|
||||
public static boolean toBoolean(String str) {
|
||||
char ch0, ch, ch1;
|
||||
if (str == "true")
|
||||
return true;
|
||||
if (str == null)
|
||||
return false;
|
||||
switch (str.length()) {
|
||||
case 2:
|
||||
ch0 = str.charAt(0);
|
||||
ch1 = str.charAt(1);
|
||||
return ((ch0 == 'o' || ch0 == 'O') && (ch1 == 'n' || ch1 == 'N'));
|
||||
case 3:
|
||||
ch = str.charAt(0);
|
||||
if (ch == 'y')
|
||||
return ((str.charAt(1) == 'e' || str.charAt(1) == 'E') && (str.charAt(2) == 's' || str.charAt(2) == 'S'));
|
||||
if (ch == 'Y')
|
||||
return ((str.charAt(1) == 'E' || str.charAt(1) == 'e') && (str.charAt(2) == 'S' || str.charAt(2) == 's'));
|
||||
return false;
|
||||
case 4:
|
||||
ch = str.charAt(0);
|
||||
if (ch == 't')
|
||||
return ((str.charAt(1) == 'r' || str.charAt(1) == 'R') && (str.charAt(2) == 'u' || str.charAt(2) == 'U') && (str.charAt(3) == 'e' || str.charAt(3) == 'E'));
|
||||
if (ch == 'T')
|
||||
return ((str.charAt(1) == 'R' || str.charAt(1) == 'r') && (str.charAt(2) == 'U' || str.charAt(2) == 'u') && (str.charAt(3) == 'E' || str.charAt(3) == 'e'));
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean toBoolean(String str, String trueString, String falseString) {
|
||||
if (str == null) {
|
||||
if (trueString == null)
|
||||
return true;
|
||||
if (falseString == null)
|
||||
return false;
|
||||
} else {
|
||||
if (str.equals(trueString))
|
||||
return true;
|
||||
if (str.equals(falseString))
|
||||
return false;
|
||||
}
|
||||
throw new IllegalArgumentException("The String did not match either specified value");
|
||||
}
|
||||
|
||||
public static String toStringTrueFalse(Boolean bool) {
|
||||
return toString(bool, "true", "false", null);
|
||||
}
|
||||
|
||||
public static String toStringOnOff(Boolean bool) {
|
||||
return toString(bool, "on", "off", null);
|
||||
}
|
||||
|
||||
public static String toStringYesNo(Boolean bool) {
|
||||
return toString(bool, "yes", "no", null);
|
||||
}
|
||||
|
||||
public static String toString(Boolean bool, String trueString, String falseString, String nullString) {
|
||||
if (bool == null)
|
||||
return nullString;
|
||||
return bool.booleanValue() ? trueString : falseString;
|
||||
}
|
||||
|
||||
public static String toStringTrueFalse(boolean bool) {
|
||||
return toString(bool, "true", "false");
|
||||
}
|
||||
|
||||
public static String toStringOnOff(boolean bool) {
|
||||
return toString(bool, "on", "off");
|
||||
}
|
||||
|
||||
public static String toStringYesNo(boolean bool) {
|
||||
return toString(bool, "yes", "no");
|
||||
}
|
||||
|
||||
public static String toString(boolean bool, String trueString, String falseString) {
|
||||
return bool ? trueString : falseString;
|
||||
}
|
||||
|
||||
public static boolean xor(boolean[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array is empty");
|
||||
int trueCount = 0;
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (array[i])
|
||||
if (trueCount < 1) {
|
||||
trueCount++;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return (trueCount == 1);
|
||||
}
|
||||
|
||||
public static Boolean xor(Boolean[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array is empty");
|
||||
boolean[] primitive = null;
|
||||
try {
|
||||
primitive = ArrayUtils.toPrimitive(array);
|
||||
} catch (NullPointerException ex) {
|
||||
throw new IllegalArgumentException("The array must not contain any null elements");
|
||||
}
|
||||
return xor(primitive) ? Boolean.TRUE : Boolean.FALSE;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
public class CharEncoding {
|
||||
public static final String ISO_8859_1 = "ISO-8859-1";
|
||||
|
||||
public static final String US_ASCII = "US-ASCII";
|
||||
|
||||
public static final String UTF_16 = "UTF-16";
|
||||
|
||||
public static final String UTF_16BE = "UTF-16BE";
|
||||
|
||||
public static final String UTF_16LE = "UTF-16LE";
|
||||
|
||||
public static final String UTF_8 = "UTF-8";
|
||||
|
||||
public static boolean isSupported(String name) {
|
||||
if (name == null)
|
||||
return false;
|
||||
try {
|
||||
new String(ArrayUtils.EMPTY_BYTE_ARRAY, name);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public final class CharRange implements Serializable {
|
||||
private static final long serialVersionUID = 8270183163158333422L;
|
||||
|
||||
private final char start;
|
||||
|
||||
private final char end;
|
||||
|
||||
private final boolean negated;
|
||||
|
||||
private transient String iToString;
|
||||
|
||||
public CharRange(char ch) {
|
||||
this(ch, ch, false);
|
||||
}
|
||||
|
||||
public CharRange(char ch, boolean negated) {
|
||||
this(ch, ch, negated);
|
||||
}
|
||||
|
||||
public CharRange(char start, char end) {
|
||||
this(start, end, false);
|
||||
}
|
||||
|
||||
public CharRange(char start, char end, boolean negated) {
|
||||
if (start > end) {
|
||||
char temp = start;
|
||||
start = end;
|
||||
end = temp;
|
||||
}
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
this.negated = negated;
|
||||
}
|
||||
|
||||
public char getStart() {
|
||||
return this.start;
|
||||
}
|
||||
|
||||
public char getEnd() {
|
||||
return this.end;
|
||||
}
|
||||
|
||||
public boolean isNegated() {
|
||||
return this.negated;
|
||||
}
|
||||
|
||||
public boolean contains(char ch) {
|
||||
return (((ch >= this.start && ch <= this.end)) != this.negated);
|
||||
}
|
||||
|
||||
public boolean contains(CharRange range) {
|
||||
if (range == null)
|
||||
throw new IllegalArgumentException("The Range must not be null");
|
||||
if (this.negated) {
|
||||
if (range.negated)
|
||||
return (this.start >= range.start && this.end <= range.end);
|
||||
return (range.end < this.start || range.start > this.end);
|
||||
}
|
||||
if (range.negated)
|
||||
return (this.start == '\000' && this.end == Character.MAX_VALUE);
|
||||
return (this.start <= range.start && this.end >= range.end);
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (!(obj instanceof CharRange))
|
||||
return false;
|
||||
CharRange other = (CharRange)obj;
|
||||
return (this.start == other.start && this.end == other.end && this.negated == other.negated);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return 83 + this.start + 7 * this.end + (this.negated ? 1 : 0);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.iToString == null) {
|
||||
StringBuffer buf = new StringBuffer(4);
|
||||
if (isNegated())
|
||||
buf.append('^');
|
||||
buf.append(this.start);
|
||||
if (this.start != this.end) {
|
||||
buf.append('-');
|
||||
buf.append(this.end);
|
||||
}
|
||||
this.iToString = buf.toString();
|
||||
}
|
||||
return this.iToString;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class CharSet implements Serializable {
|
||||
private static final long serialVersionUID = 5947847346149275958L;
|
||||
|
||||
public static final CharSet EMPTY = new CharSet((String)null);
|
||||
|
||||
public static final CharSet ASCII_ALPHA = new CharSet("a-zA-Z");
|
||||
|
||||
public static final CharSet ASCII_ALPHA_LOWER = new CharSet("a-z");
|
||||
|
||||
public static final CharSet ASCII_ALPHA_UPPER = new CharSet("A-Z");
|
||||
|
||||
public static final CharSet ASCII_NUMERIC = new CharSet("0-9");
|
||||
|
||||
protected static final Map COMMON = new HashMap();
|
||||
|
||||
static {
|
||||
COMMON.put(null, EMPTY);
|
||||
COMMON.put("", EMPTY);
|
||||
COMMON.put("a-zA-Z", ASCII_ALPHA);
|
||||
COMMON.put("A-Za-z", ASCII_ALPHA);
|
||||
COMMON.put("a-z", ASCII_ALPHA_LOWER);
|
||||
COMMON.put("A-Z", ASCII_ALPHA_UPPER);
|
||||
COMMON.put("0-9", ASCII_NUMERIC);
|
||||
}
|
||||
|
||||
private Set set = new HashSet();
|
||||
|
||||
public static CharSet getInstance(String setStr) {
|
||||
Object set = COMMON.get(setStr);
|
||||
if (set != null)
|
||||
return (CharSet)set;
|
||||
return new CharSet(setStr);
|
||||
}
|
||||
|
||||
public static CharSet getInstance(String[] setStrs) {
|
||||
if (setStrs == null)
|
||||
return null;
|
||||
return new CharSet(setStrs);
|
||||
}
|
||||
|
||||
protected CharSet(String setStr) {
|
||||
add(setStr);
|
||||
}
|
||||
|
||||
protected CharSet(String[] set) {
|
||||
int sz = set.length;
|
||||
for (int i = 0; i < sz; i++)
|
||||
add(set[i]);
|
||||
}
|
||||
|
||||
protected void add(String str) {
|
||||
if (str == null)
|
||||
return;
|
||||
int len = str.length();
|
||||
int pos = 0;
|
||||
while (pos < len) {
|
||||
int remainder = len - pos;
|
||||
if (remainder >= 4 && str.charAt(pos) == '^' && str.charAt(pos + 2) == '-') {
|
||||
this.set.add(new CharRange(str.charAt(pos + 1), str.charAt(pos + 3), true));
|
||||
pos += 4;
|
||||
continue;
|
||||
}
|
||||
if (remainder >= 3 && str.charAt(pos + 1) == '-') {
|
||||
this.set.add(new CharRange(str.charAt(pos), str.charAt(pos + 2)));
|
||||
pos += 3;
|
||||
continue;
|
||||
}
|
||||
if (remainder >= 2 && str.charAt(pos) == '^') {
|
||||
this.set.add(new CharRange(str.charAt(pos + 1), true));
|
||||
pos += 2;
|
||||
continue;
|
||||
}
|
||||
this.set.add(new CharRange(str.charAt(pos)));
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
|
||||
public CharRange[] getCharRanges() {
|
||||
return (CharRange[])this.set.toArray(new CharRange[this.set.size()]);
|
||||
}
|
||||
|
||||
public boolean contains(char ch) {
|
||||
for (Iterator it = this.set.iterator(); it.hasNext(); ) {
|
||||
CharRange range = (CharRange)it.next();
|
||||
if (range.contains(ch))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (!(obj instanceof CharSet))
|
||||
return false;
|
||||
CharSet other = (CharSet)obj;
|
||||
return this.set.equals(other.set);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return 89 + this.set.hashCode();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.set.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
public class CharSetUtils {
|
||||
public static CharSet evaluateSet(String[] set) {
|
||||
if (set == null)
|
||||
return null;
|
||||
return new CharSet(set);
|
||||
}
|
||||
|
||||
public static String squeeze(String str, String set) {
|
||||
if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set))
|
||||
return str;
|
||||
String[] strs = new String[1];
|
||||
strs[0] = set;
|
||||
return squeeze(str, strs);
|
||||
}
|
||||
|
||||
public static String squeeze(String str, String[] set) {
|
||||
if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set))
|
||||
return str;
|
||||
CharSet chars = CharSet.getInstance(set);
|
||||
StringBuffer buffer = new StringBuffer(str.length());
|
||||
char[] chrs = str.toCharArray();
|
||||
int sz = chrs.length;
|
||||
char lastChar = ' ';
|
||||
char ch = ' ';
|
||||
for (int i = 0; i < sz; i++) {
|
||||
ch = chrs[i];
|
||||
if (!chars.contains(ch) ||
|
||||
ch != lastChar || i == 0) {
|
||||
buffer.append(ch);
|
||||
lastChar = ch;
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
public static int count(String str, String set) {
|
||||
if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set))
|
||||
return 0;
|
||||
String[] strs = new String[1];
|
||||
strs[0] = set;
|
||||
return count(str, strs);
|
||||
}
|
||||
|
||||
public static int count(String str, String[] set) {
|
||||
if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set))
|
||||
return 0;
|
||||
CharSet chars = CharSet.getInstance(set);
|
||||
int count = 0;
|
||||
char[] chrs = str.toCharArray();
|
||||
int sz = chrs.length;
|
||||
for (int i = 0; i < sz; i++) {
|
||||
if (chars.contains(chrs[i]))
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
public static String keep(String str, String set) {
|
||||
if (str == null)
|
||||
return null;
|
||||
if (str.length() == 0 || StringUtils.isEmpty(set))
|
||||
return "";
|
||||
String[] strs = new String[1];
|
||||
strs[0] = set;
|
||||
return keep(str, strs);
|
||||
}
|
||||
|
||||
public static String keep(String str, String[] set) {
|
||||
if (str == null)
|
||||
return null;
|
||||
if (str.length() == 0 || ArrayUtils.isEmpty(set))
|
||||
return "";
|
||||
return modify(str, set, true);
|
||||
}
|
||||
|
||||
public static String delete(String str, String set) {
|
||||
if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set))
|
||||
return str;
|
||||
String[] strs = new String[1];
|
||||
strs[0] = set;
|
||||
return delete(str, strs);
|
||||
}
|
||||
|
||||
public static String delete(String str, String[] set) {
|
||||
if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set))
|
||||
return str;
|
||||
return modify(str, set, false);
|
||||
}
|
||||
|
||||
private static String modify(String str, String[] set, boolean expect) {
|
||||
CharSet chars = CharSet.getInstance(set);
|
||||
StringBuffer buffer = new StringBuffer(str.length());
|
||||
char[] chrs = str.toCharArray();
|
||||
int sz = chrs.length;
|
||||
for (int i = 0; i < sz; i++) {
|
||||
if (chars.contains(chrs[i]) == expect)
|
||||
buffer.append(chrs[i]);
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
public static String translate(String str, String searchChars, String replaceChars) {
|
||||
if (StringUtils.isEmpty(str))
|
||||
return str;
|
||||
StringBuffer buffer = new StringBuffer(str.length());
|
||||
char[] chrs = str.toCharArray();
|
||||
char[] withChrs = replaceChars.toCharArray();
|
||||
int sz = chrs.length;
|
||||
int withMax = replaceChars.length() - 1;
|
||||
for (int i = 0; i < sz; i++) {
|
||||
int idx = searchChars.indexOf(chrs[i]);
|
||||
if (idx != -1) {
|
||||
if (idx > withMax)
|
||||
idx = withMax;
|
||||
buffer.append(withChrs[idx]);
|
||||
} else {
|
||||
buffer.append(chrs[i]);
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
public class CharUtils {
|
||||
private static final String CHAR_STRING = "\000\001\002\003\004\005\006\007\b\t\n\013\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
|
||||
|
||||
private static final String[] CHAR_STRING_ARRAY = new String[128];
|
||||
|
||||
private static final Character[] CHAR_ARRAY = new Character[128];
|
||||
|
||||
public static final char LF = '\n';
|
||||
|
||||
public static final char CR = '\r';
|
||||
|
||||
static {
|
||||
for (int i = 127; i >= 0; i--) {
|
||||
CHAR_STRING_ARRAY[i] = "\000\001\002\003\004\005\006\007\b\t\n\013\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".substring(i, i + 1);
|
||||
CHAR_ARRAY[i] = new Character((char)i);
|
||||
}
|
||||
}
|
||||
|
||||
public static Character toCharacterObject(char ch) {
|
||||
if (ch < CHAR_ARRAY.length)
|
||||
return CHAR_ARRAY[ch];
|
||||
return new Character(ch);
|
||||
}
|
||||
|
||||
public static Character toCharacterObject(String str) {
|
||||
if (StringUtils.isEmpty(str))
|
||||
return null;
|
||||
return toCharacterObject(str.charAt(0));
|
||||
}
|
||||
|
||||
public static char toChar(Character ch) {
|
||||
if (ch == null)
|
||||
throw new IllegalArgumentException("The Character must not be null");
|
||||
return ch.charValue();
|
||||
}
|
||||
|
||||
public static char toChar(Character ch, char defaultValue) {
|
||||
if (ch == null)
|
||||
return defaultValue;
|
||||
return ch.charValue();
|
||||
}
|
||||
|
||||
public static char toChar(String str) {
|
||||
if (StringUtils.isEmpty(str))
|
||||
throw new IllegalArgumentException("The String must not be empty");
|
||||
return str.charAt(0);
|
||||
}
|
||||
|
||||
public static char toChar(String str, char defaultValue) {
|
||||
if (StringUtils.isEmpty(str))
|
||||
return defaultValue;
|
||||
return str.charAt(0);
|
||||
}
|
||||
|
||||
public static int toIntValue(char ch) {
|
||||
if (!isAsciiNumeric(ch))
|
||||
throw new IllegalArgumentException("The character " + ch + " is not in the range '0' - '9'");
|
||||
return ch - 48;
|
||||
}
|
||||
|
||||
public static int toIntValue(char ch, int defaultValue) {
|
||||
if (!isAsciiNumeric(ch))
|
||||
return defaultValue;
|
||||
return ch - 48;
|
||||
}
|
||||
|
||||
public static int toIntValue(Character ch) {
|
||||
if (ch == null)
|
||||
throw new IllegalArgumentException("The character must not be null");
|
||||
return toIntValue(ch.charValue());
|
||||
}
|
||||
|
||||
public static int toIntValue(Character ch, int defaultValue) {
|
||||
if (ch == null)
|
||||
return defaultValue;
|
||||
return toIntValue(ch.charValue(), defaultValue);
|
||||
}
|
||||
|
||||
public static String toString(char ch) {
|
||||
if (ch < '\u0080')
|
||||
return CHAR_STRING_ARRAY[ch];
|
||||
return new String(new char[] { ch });
|
||||
}
|
||||
|
||||
public static String toString(Character ch) {
|
||||
if (ch == null)
|
||||
return null;
|
||||
return toString(ch.charValue());
|
||||
}
|
||||
|
||||
public static String unicodeEscaped(char ch) {
|
||||
if (ch < '\020')
|
||||
return "\\u000" + Integer.toHexString(ch);
|
||||
if (ch < 'Ā')
|
||||
return "\\u00" + Integer.toHexString(ch);
|
||||
if (ch < 'က')
|
||||
return "\\u0" + Integer.toHexString(ch);
|
||||
return "\\u" + Integer.toHexString(ch);
|
||||
}
|
||||
|
||||
public static String unicodeEscaped(Character ch) {
|
||||
if (ch == null)
|
||||
return null;
|
||||
return unicodeEscaped(ch.charValue());
|
||||
}
|
||||
|
||||
public static boolean isAscii(char ch) {
|
||||
return (ch < '\u0080');
|
||||
}
|
||||
|
||||
public static boolean isAsciiPrintable(char ch) {
|
||||
return (ch >= ' ' && ch < '\u007F');
|
||||
}
|
||||
|
||||
public static boolean isAsciiControl(char ch) {
|
||||
return (ch < ' ' || ch == '\u007F');
|
||||
}
|
||||
|
||||
public static boolean isAsciiAlpha(char ch) {
|
||||
return ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'));
|
||||
}
|
||||
|
||||
public static boolean isAsciiAlphaUpper(char ch) {
|
||||
return (ch >= 'A' && ch <= 'Z');
|
||||
}
|
||||
|
||||
public static boolean isAsciiAlphaLower(char ch) {
|
||||
return (ch >= 'a' && ch <= 'z');
|
||||
}
|
||||
|
||||
public static boolean isAsciiNumeric(char ch) {
|
||||
return (ch >= '0' && ch <= '9');
|
||||
}
|
||||
|
||||
public static boolean isAsciiAlphanumeric(char ch) {
|
||||
return ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,391 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class ClassUtils {
|
||||
public static final char PACKAGE_SEPARATOR_CHAR = '.';
|
||||
|
||||
public static final String PACKAGE_SEPARATOR = String.valueOf('.');
|
||||
|
||||
public static final char INNER_CLASS_SEPARATOR_CHAR = '$';
|
||||
|
||||
public static final String INNER_CLASS_SEPARATOR = String.valueOf('$');
|
||||
|
||||
private static Map primitiveWrapperMap = new HashMap();
|
||||
|
||||
static {
|
||||
primitiveWrapperMap.put(boolean.class, Boolean.class);
|
||||
primitiveWrapperMap.put(byte.class, Byte.class);
|
||||
primitiveWrapperMap.put(char.class, Character.class);
|
||||
primitiveWrapperMap.put(short.class, Short.class);
|
||||
primitiveWrapperMap.put(int.class, Integer.class);
|
||||
primitiveWrapperMap.put(long.class, Long.class);
|
||||
primitiveWrapperMap.put(double.class, Double.class);
|
||||
primitiveWrapperMap.put(float.class, Float.class);
|
||||
primitiveWrapperMap.put(void.class, void.class);
|
||||
}
|
||||
|
||||
private static Map wrapperPrimitiveMap = new HashMap();
|
||||
|
||||
static {
|
||||
for (Iterator it = primitiveWrapperMap.keySet().iterator(); it.hasNext(); ) {
|
||||
Class primitiveClass = (Class)it.next();
|
||||
Class wrapperClass = (Class)primitiveWrapperMap.get(primitiveClass);
|
||||
if (!primitiveClass.equals(wrapperClass))
|
||||
wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map abbreviationMap = new HashMap();
|
||||
|
||||
private static Map reverseAbbreviationMap = new HashMap();
|
||||
|
||||
private static void addAbbreviation(String primitive, String abbreviation) {
|
||||
abbreviationMap.put(primitive, abbreviation);
|
||||
reverseAbbreviationMap.put(abbreviation, primitive);
|
||||
}
|
||||
|
||||
static {
|
||||
addAbbreviation("int", "I");
|
||||
addAbbreviation("boolean", "Z");
|
||||
addAbbreviation("float", "F");
|
||||
addAbbreviation("long", "J");
|
||||
addAbbreviation("short", "S");
|
||||
addAbbreviation("byte", "B");
|
||||
addAbbreviation("double", "D");
|
||||
addAbbreviation("char", "C");
|
||||
}
|
||||
|
||||
public static String getShortClassName(Object object, String valueIfNull) {
|
||||
if (object == null)
|
||||
return valueIfNull;
|
||||
return getShortClassName(object.getClass().getName());
|
||||
}
|
||||
|
||||
public static String getShortClassName(Class cls) {
|
||||
if (cls == null)
|
||||
return "";
|
||||
return getShortClassName(cls.getName());
|
||||
}
|
||||
|
||||
public static String getShortClassName(String className) {
|
||||
if (className == null)
|
||||
return "";
|
||||
if (className.length() == 0)
|
||||
return "";
|
||||
int lastDotIdx = className.lastIndexOf('.');
|
||||
int innerIdx = className.indexOf('$', (lastDotIdx == -1) ? 0 : (lastDotIdx + 1));
|
||||
String out = className.substring(lastDotIdx + 1);
|
||||
if (innerIdx != -1)
|
||||
out = out.replace('$', '.');
|
||||
return out;
|
||||
}
|
||||
|
||||
public static String getPackageName(Object object, String valueIfNull) {
|
||||
if (object == null)
|
||||
return valueIfNull;
|
||||
return getPackageName(object.getClass().getName());
|
||||
}
|
||||
|
||||
public static String getPackageName(Class cls) {
|
||||
if (cls == null)
|
||||
return "";
|
||||
return getPackageName(cls.getName());
|
||||
}
|
||||
|
||||
public static String getPackageName(String className) {
|
||||
if (className == null)
|
||||
return "";
|
||||
int i = className.lastIndexOf('.');
|
||||
if (i == -1)
|
||||
return "";
|
||||
return className.substring(0, i);
|
||||
}
|
||||
|
||||
public static List getAllSuperclasses(Class cls) {
|
||||
if (cls == null)
|
||||
return null;
|
||||
List classes = new ArrayList();
|
||||
Class superclass = cls.getSuperclass();
|
||||
while (superclass != null) {
|
||||
classes.add(superclass);
|
||||
superclass = superclass.getSuperclass();
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
|
||||
public static List getAllInterfaces(Class cls) {
|
||||
if (cls == null)
|
||||
return null;
|
||||
List list = new ArrayList();
|
||||
while (cls != null) {
|
||||
Class[] interfaces = cls.getInterfaces();
|
||||
for (int i = 0; i < interfaces.length; i++) {
|
||||
if (!list.contains(interfaces[i]))
|
||||
list.add(interfaces[i]);
|
||||
List superInterfaces = getAllInterfaces(interfaces[i]);
|
||||
for (Iterator it = superInterfaces.iterator(); it.hasNext(); ) {
|
||||
Class intface = (Class)it.next();
|
||||
if (!list.contains(intface))
|
||||
list.add(intface);
|
||||
}
|
||||
}
|
||||
cls = cls.getSuperclass();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List convertClassNamesToClasses(List classNames) {
|
||||
if (classNames == null)
|
||||
return null;
|
||||
List classes = new ArrayList(classNames.size());
|
||||
for (Iterator it = classNames.iterator(); it.hasNext(); ) {
|
||||
String className = (String)it.next();
|
||||
try {
|
||||
classes.add(Class.forName(className));
|
||||
} catch (Exception ex) {
|
||||
classes.add(null);
|
||||
}
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
|
||||
public static List convertClassesToClassNames(List classes) {
|
||||
if (classes == null)
|
||||
return null;
|
||||
List classNames = new ArrayList(classes.size());
|
||||
for (Iterator it = classes.iterator(); it.hasNext(); ) {
|
||||
Class cls = (Class)it.next();
|
||||
if (cls == null) {
|
||||
classNames.add(null);
|
||||
continue;
|
||||
}
|
||||
classNames.add(cls.getName());
|
||||
}
|
||||
return classNames;
|
||||
}
|
||||
|
||||
public static boolean isAssignable(Class[] classArray, Class[] toClassArray) {
|
||||
if (!ArrayUtils.isSameLength(classArray, toClassArray))
|
||||
return false;
|
||||
if (classArray == null)
|
||||
classArray = ArrayUtils.EMPTY_CLASS_ARRAY;
|
||||
if (toClassArray == null)
|
||||
toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY;
|
||||
for (int i = 0; i < classArray.length; i++) {
|
||||
if (!isAssignable(classArray[i], toClassArray[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isAssignable(Class cls, Class toClass) {
|
||||
if (toClass == null)
|
||||
return false;
|
||||
if (cls == null)
|
||||
return !toClass.isPrimitive();
|
||||
if (cls.equals(toClass))
|
||||
return true;
|
||||
if (cls.isPrimitive()) {
|
||||
if (!toClass.isPrimitive())
|
||||
return false;
|
||||
if (int.class.equals(cls))
|
||||
return (long.class.equals(toClass) || float.class.equals(toClass) || double.class.equals(toClass));
|
||||
if (long.class.equals(cls))
|
||||
return (float.class.equals(toClass) || double.class.equals(toClass));
|
||||
if (boolean.class.equals(cls))
|
||||
return false;
|
||||
if (double.class.equals(cls))
|
||||
return false;
|
||||
if (float.class.equals(cls))
|
||||
return double.class.equals(toClass);
|
||||
if (char.class.equals(cls))
|
||||
return (int.class.equals(toClass) || long.class.equals(toClass) || float.class.equals(toClass) || double.class.equals(toClass));
|
||||
if (short.class.equals(cls))
|
||||
return (int.class.equals(toClass) || long.class.equals(toClass) || float.class.equals(toClass) || double.class.equals(toClass));
|
||||
if (byte.class.equals(cls))
|
||||
return (short.class.equals(toClass) || int.class.equals(toClass) || long.class.equals(toClass) || float.class.equals(toClass) || double.class.equals(toClass));
|
||||
return false;
|
||||
}
|
||||
return toClass.isAssignableFrom(cls);
|
||||
}
|
||||
|
||||
public static Class primitiveToWrapper(Class cls) {
|
||||
Class convertedClass = cls;
|
||||
if (cls != null && cls.isPrimitive())
|
||||
convertedClass = (Class)primitiveWrapperMap.get(cls);
|
||||
return convertedClass;
|
||||
}
|
||||
|
||||
public static Class[] primitivesToWrappers(Class[] classes) {
|
||||
if (classes == null)
|
||||
return null;
|
||||
if (classes.length == 0)
|
||||
return classes;
|
||||
Class[] convertedClasses = new Class[classes.length];
|
||||
for (int i = 0; i < classes.length; i++)
|
||||
convertedClasses[i] = primitiveToWrapper(classes[i]);
|
||||
return convertedClasses;
|
||||
}
|
||||
|
||||
public static Class wrapperToPrimitive(Class cls) {
|
||||
return (Class)wrapperPrimitiveMap.get(cls);
|
||||
}
|
||||
|
||||
public static Class[] wrappersToPrimitives(Class[] classes) {
|
||||
if (classes == null)
|
||||
return null;
|
||||
if (classes.length == 0)
|
||||
return classes;
|
||||
Class[] convertedClasses = new Class[classes.length];
|
||||
for (int i = 0; i < classes.length; i++)
|
||||
convertedClasses[i] = wrapperToPrimitive(classes[i]);
|
||||
return convertedClasses;
|
||||
}
|
||||
|
||||
public static boolean isInnerClass(Class cls) {
|
||||
if (cls == null)
|
||||
return false;
|
||||
return (cls.getName().indexOf('$') >= 0);
|
||||
}
|
||||
|
||||
public static Class getClass(ClassLoader classLoader, String className, boolean initialize) throws ClassNotFoundException {
|
||||
Class clazz;
|
||||
if (abbreviationMap.containsKey(className)) {
|
||||
String clsName = "[" + abbreviationMap.get(className);
|
||||
clazz = Class.forName(clsName, initialize, classLoader).getComponentType();
|
||||
} else {
|
||||
clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
|
||||
}
|
||||
return clazz;
|
||||
}
|
||||
|
||||
public static Class getClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
|
||||
return getClass(classLoader, className, true);
|
||||
}
|
||||
|
||||
public static Class getClass(String className) throws ClassNotFoundException {
|
||||
return getClass(className, true);
|
||||
}
|
||||
|
||||
public static Class getClass(String className, boolean initialize) throws ClassNotFoundException {
|
||||
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
|
||||
ClassLoader loader = (contextCL == null) ? ClassUtils.class.getClassLoader() : contextCL;
|
||||
return getClass(loader, className, initialize);
|
||||
}
|
||||
|
||||
public static Method getPublicMethod(Class cls, String methodName, Class[] parameterTypes) throws SecurityException, NoSuchMethodException {
|
||||
Method declaredMethod = cls.getMethod(methodName, parameterTypes);
|
||||
if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers()))
|
||||
return declaredMethod;
|
||||
List candidateClasses = new ArrayList();
|
||||
candidateClasses.addAll(getAllInterfaces(cls));
|
||||
candidateClasses.addAll(getAllSuperclasses(cls));
|
||||
for (Iterator it = candidateClasses.iterator(); it.hasNext(); ) {
|
||||
Method candidateMethod;
|
||||
Class candidateClass = (Class)it.next();
|
||||
if (!Modifier.isPublic(candidateClass.getModifiers()))
|
||||
continue;
|
||||
try {
|
||||
candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
|
||||
} catch (NoSuchMethodException ex) {
|
||||
continue;
|
||||
}
|
||||
if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers()))
|
||||
return candidateMethod;
|
||||
}
|
||||
throw new NoSuchMethodException("Can't find a public method for " + methodName + " " + ArrayUtils.toString(parameterTypes));
|
||||
}
|
||||
|
||||
private static String toCanonicalName(String className) {
|
||||
className = StringUtils.deleteWhitespace(className);
|
||||
if (className == null)
|
||||
throw new NullArgumentException("className");
|
||||
if (className.endsWith("[]")) {
|
||||
StringBuffer classNameBuffer = new StringBuffer();
|
||||
while (className.endsWith("[]")) {
|
||||
className = className.substring(0, className.length() - 2);
|
||||
classNameBuffer.append("[");
|
||||
}
|
||||
String abbreviation = (String)abbreviationMap.get(className);
|
||||
if (abbreviation != null) {
|
||||
classNameBuffer.append(abbreviation);
|
||||
} else {
|
||||
classNameBuffer.append("L").append(className).append(";");
|
||||
}
|
||||
className = classNameBuffer.toString();
|
||||
}
|
||||
return className;
|
||||
}
|
||||
|
||||
public static Class[] toClass(Object[] array) {
|
||||
if (array == null)
|
||||
return null;
|
||||
if (array.length == 0)
|
||||
return ArrayUtils.EMPTY_CLASS_ARRAY;
|
||||
Class[] classes = new Class[array.length];
|
||||
for (int i = 0; i < array.length; i++)
|
||||
classes[i] = array[i].getClass();
|
||||
return classes;
|
||||
}
|
||||
|
||||
public static String getShortCanonicalName(Object object, String valueIfNull) {
|
||||
if (object == null)
|
||||
return valueIfNull;
|
||||
return getShortCanonicalName(object.getClass().getName());
|
||||
}
|
||||
|
||||
public static String getShortCanonicalName(Class cls) {
|
||||
if (cls == null)
|
||||
return "";
|
||||
return getShortCanonicalName(cls.getName());
|
||||
}
|
||||
|
||||
public static String getShortCanonicalName(String canonicalName) {
|
||||
return getShortClassName(getCanonicalName(canonicalName));
|
||||
}
|
||||
|
||||
public static String getPackageCanonicalName(Object object, String valueIfNull) {
|
||||
if (object == null)
|
||||
return valueIfNull;
|
||||
return getPackageCanonicalName(object.getClass().getName());
|
||||
}
|
||||
|
||||
public static String getPackageCanonicalName(Class cls) {
|
||||
if (cls == null)
|
||||
return "";
|
||||
return getPackageCanonicalName(cls.getName());
|
||||
}
|
||||
|
||||
public static String getPackageCanonicalName(String canonicalName) {
|
||||
return getPackageName(getCanonicalName(canonicalName));
|
||||
}
|
||||
|
||||
private static String getCanonicalName(String className) {
|
||||
className = StringUtils.deleteWhitespace(className);
|
||||
if (className == null)
|
||||
return null;
|
||||
int dim = 0;
|
||||
while (className.startsWith("[")) {
|
||||
dim++;
|
||||
className = className.substring(1);
|
||||
}
|
||||
if (dim < 1)
|
||||
return className;
|
||||
if (className.startsWith("L")) {
|
||||
className = className.substring(1, className.endsWith(";") ? (className.length() - 1) : className.length());
|
||||
} else if (className.length() > 0) {
|
||||
className = (String)reverseAbbreviationMap.get(className.substring(0, 1));
|
||||
}
|
||||
StringBuffer canonicalClassNameBuffer = new StringBuffer(className);
|
||||
for (int i = 0; i < dim; i++)
|
||||
canonicalClassNameBuffer.append("[]");
|
||||
return canonicalClassNameBuffer.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,385 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
class Entities {
|
||||
private static final String[][] BASIC_ARRAY = new String[][] { new String[] { "quot", "34" }, new String[] { "amp", "38" }, new String[] { "lt", "60" }, new String[] { "gt", "62" } };
|
||||
|
||||
private static final String[][] APOS_ARRAY = new String[][] { new String[] { "apos", "39" } };
|
||||
|
||||
static final String[][] ISO8859_1_ARRAY = new String[][] {
|
||||
new String[] { "nbsp", "160" }, new String[] { "iexcl", "161" }, new String[] { "cent", "162" }, new String[] { "pound", "163" }, new String[] { "curren", "164" }, new String[] { "yen", "165" }, new String[] { "brvbar", "166" }, new String[] { "sect", "167" }, new String[] { "uml", "168" }, new String[] { "copy", "169" },
|
||||
new String[] { "ordf", "170" }, new String[] { "laquo", "171" }, new String[] { "not", "172" }, new String[] { "shy", "173" }, new String[] { "reg", "174" }, new String[] { "macr", "175" }, new String[] { "deg", "176" }, new String[] { "plusmn", "177" }, new String[] { "sup2", "178" }, new String[] { "sup3", "179" },
|
||||
new String[] { "acute", "180" }, new String[] { "micro", "181" }, new String[] { "para", "182" }, new String[] { "middot", "183" }, new String[] { "cedil", "184" }, new String[] { "sup1", "185" }, new String[] { "ordm", "186" }, new String[] { "raquo", "187" }, new String[] { "frac14", "188" }, new String[] { "frac12", "189" },
|
||||
new String[] { "frac34", "190" }, new String[] { "iquest", "191" }, new String[] { "Agrave", "192" }, new String[] { "Aacute", "193" }, new String[] { "Acirc", "194" }, new String[] { "Atilde", "195" }, new String[] { "Auml", "196" }, new String[] { "Aring", "197" }, new String[] { "AElig", "198" }, new String[] { "Ccedil", "199" },
|
||||
new String[] { "Egrave", "200" }, new String[] { "Eacute", "201" }, new String[] { "Ecirc", "202" }, new String[] { "Euml", "203" }, new String[] { "Igrave", "204" }, new String[] { "Iacute", "205" }, new String[] { "Icirc", "206" }, new String[] { "Iuml", "207" }, new String[] { "ETH", "208" }, new String[] { "Ntilde", "209" },
|
||||
new String[] { "Ograve", "210" }, new String[] { "Oacute", "211" }, new String[] { "Ocirc", "212" }, new String[] { "Otilde", "213" }, new String[] { "Ouml", "214" }, new String[] { "times", "215" }, new String[] { "Oslash", "216" }, new String[] { "Ugrave", "217" }, new String[] { "Uacute", "218" }, new String[] { "Ucirc", "219" },
|
||||
new String[] { "Uuml", "220" }, new String[] { "Yacute", "221" }, new String[] { "THORN", "222" }, new String[] { "szlig", "223" }, new String[] { "agrave", "224" }, new String[] { "aacute", "225" }, new String[] { "acirc", "226" }, new String[] { "atilde", "227" }, new String[] { "auml", "228" }, new String[] { "aring", "229" },
|
||||
new String[] { "aelig", "230" }, new String[] { "ccedil", "231" }, new String[] { "egrave", "232" }, new String[] { "eacute", "233" }, new String[] { "ecirc", "234" }, new String[] { "euml", "235" }, new String[] { "igrave", "236" }, new String[] { "iacute", "237" }, new String[] { "icirc", "238" }, new String[] { "iuml", "239" },
|
||||
new String[] { "eth", "240" }, new String[] { "ntilde", "241" }, new String[] { "ograve", "242" }, new String[] { "oacute", "243" }, new String[] { "ocirc", "244" }, new String[] { "otilde", "245" }, new String[] { "ouml", "246" }, new String[] { "divide", "247" }, new String[] { "oslash", "248" }, new String[] { "ugrave", "249" },
|
||||
new String[] { "uacute", "250" }, new String[] { "ucirc", "251" }, new String[] { "uuml", "252" }, new String[] { "yacute", "253" }, new String[] { "thorn", "254" }, new String[] { "yuml", "255" } };
|
||||
|
||||
static final String[][] HTML40_ARRAY = new String[][] {
|
||||
new String[] { "fnof", "402" }, new String[] { "Alpha", "913" }, new String[] { "Beta", "914" }, new String[] { "Gamma", "915" }, new String[] { "Delta", "916" }, new String[] { "Epsilon", "917" }, new String[] { "Zeta", "918" }, new String[] { "Eta", "919" }, new String[] { "Theta", "920" }, new String[] { "Iota", "921" },
|
||||
new String[] { "Kappa", "922" }, new String[] { "Lambda", "923" }, new String[] { "Mu", "924" }, new String[] { "Nu", "925" }, new String[] { "Xi", "926" }, new String[] { "Omicron", "927" }, new String[] { "Pi", "928" }, new String[] { "Rho", "929" }, new String[] { "Sigma", "931" }, new String[] { "Tau", "932" },
|
||||
new String[] { "Upsilon", "933" }, new String[] { "Phi", "934" }, new String[] { "Chi", "935" }, new String[] { "Psi", "936" }, new String[] { "Omega", "937" }, new String[] { "alpha", "945" }, new String[] { "beta", "946" }, new String[] { "gamma", "947" }, new String[] { "delta", "948" }, new String[] { "epsilon", "949" },
|
||||
new String[] { "zeta", "950" }, new String[] { "eta", "951" }, new String[] { "theta", "952" }, new String[] { "iota", "953" }, new String[] { "kappa", "954" }, new String[] { "lambda", "955" }, new String[] { "mu", "956" }, new String[] { "nu", "957" }, new String[] { "xi", "958" }, new String[] { "omicron", "959" },
|
||||
new String[] { "pi", "960" }, new String[] { "rho", "961" }, new String[] { "sigmaf", "962" }, new String[] { "sigma", "963" }, new String[] { "tau", "964" }, new String[] { "upsilon", "965" }, new String[] { "phi", "966" }, new String[] { "chi", "967" }, new String[] { "psi", "968" }, new String[] { "omega", "969" },
|
||||
new String[] { "thetasym", "977" }, new String[] { "upsih", "978" }, new String[] { "piv", "982" }, new String[] { "bull", "8226" }, new String[] { "hellip", "8230" }, new String[] { "prime", "8242" }, new String[] { "Prime", "8243" }, new String[] { "oline", "8254" }, new String[] { "frasl", "8260" }, new String[] { "weierp", "8472" },
|
||||
new String[] { "image", "8465" }, new String[] { "real", "8476" }, new String[] { "trade", "8482" }, new String[] { "alefsym", "8501" }, new String[] { "larr", "8592" }, new String[] { "uarr", "8593" }, new String[] { "rarr", "8594" }, new String[] { "darr", "8595" }, new String[] { "harr", "8596" }, new String[] { "crarr", "8629" },
|
||||
new String[] { "lArr", "8656" }, new String[] { "uArr", "8657" }, new String[] { "rArr", "8658" }, new String[] { "dArr", "8659" }, new String[] { "hArr", "8660" }, new String[] { "forall", "8704" }, new String[] { "part", "8706" }, new String[] { "exist", "8707" }, new String[] { "empty", "8709" }, new String[] { "nabla", "8711" },
|
||||
new String[] { "isin", "8712" }, new String[] { "notin", "8713" }, new String[] { "ni", "8715" }, new String[] { "prod", "8719" }, new String[] { "sum", "8721" }, new String[] { "minus", "8722" }, new String[] { "lowast", "8727" }, new String[] { "radic", "8730" }, new String[] { "prop", "8733" }, new String[] { "infin", "8734" },
|
||||
new String[] { "ang", "8736" }, new String[] { "and", "8743" }, new String[] { "or", "8744" }, new String[] { "cap", "8745" }, new String[] { "cup", "8746" }, new String[] { "int", "8747" }, new String[] { "there4", "8756" }, new String[] { "sim", "8764" }, new String[] { "cong", "8773" }, new String[] { "asymp", "8776" },
|
||||
new String[] { "ne", "8800" }, new String[] { "equiv", "8801" }, new String[] { "le", "8804" }, new String[] { "ge", "8805" }, new String[] { "sub", "8834" }, new String[] { "sup", "8835" }, new String[] { "sube", "8838" }, new String[] { "supe", "8839" }, new String[] { "oplus", "8853" }, new String[] { "otimes", "8855" },
|
||||
new String[] { "perp", "8869" }, new String[] { "sdot", "8901" }, new String[] { "lceil", "8968" }, new String[] { "rceil", "8969" }, new String[] { "lfloor", "8970" }, new String[] { "rfloor", "8971" }, new String[] { "lang", "9001" }, new String[] { "rang", "9002" }, new String[] { "loz", "9674" }, new String[] { "spades", "9824" },
|
||||
new String[] { "clubs", "9827" }, new String[] { "hearts", "9829" }, new String[] { "diams", "9830" }, new String[] { "OElig", "338" }, new String[] { "oelig", "339" }, new String[] { "Scaron", "352" }, new String[] { "scaron", "353" }, new String[] { "Yuml", "376" }, new String[] { "circ", "710" }, new String[] { "tilde", "732" },
|
||||
new String[] { "ensp", "8194" }, new String[] { "emsp", "8195" }, new String[] { "thinsp", "8201" }, new String[] { "zwnj", "8204" }, new String[] { "zwj", "8205" }, new String[] { "lrm", "8206" }, new String[] { "rlm", "8207" }, new String[] { "ndash", "8211" }, new String[] { "mdash", "8212" }, new String[] { "lsquo", "8216" },
|
||||
new String[] { "rsquo", "8217" }, new String[] { "sbquo", "8218" }, new String[] { "ldquo", "8220" }, new String[] { "rdquo", "8221" }, new String[] { "bdquo", "8222" }, new String[] { "dagger", "8224" }, new String[] { "Dagger", "8225" }, new String[] { "permil", "8240" }, new String[] { "lsaquo", "8249" }, new String[] { "rsaquo", "8250" },
|
||||
new String[] { "euro", "8364" } };
|
||||
|
||||
public static final Entities XML = new Entities();
|
||||
|
||||
static {
|
||||
XML.addEntities(BASIC_ARRAY);
|
||||
XML.addEntities(APOS_ARRAY);
|
||||
}
|
||||
|
||||
public static final Entities HTML32 = new Entities();
|
||||
|
||||
static {
|
||||
HTML32.addEntities(BASIC_ARRAY);
|
||||
HTML32.addEntities(ISO8859_1_ARRAY);
|
||||
}
|
||||
|
||||
public static final Entities HTML40 = new Entities();
|
||||
|
||||
static {
|
||||
fillWithHtml40Entities(HTML40);
|
||||
}
|
||||
|
||||
static void fillWithHtml40Entities(Entities entities) {
|
||||
entities.addEntities(BASIC_ARRAY);
|
||||
entities.addEntities(ISO8859_1_ARRAY);
|
||||
entities.addEntities(HTML40_ARRAY);
|
||||
}
|
||||
|
||||
static interface EntityMap {
|
||||
void add(String param1String, int param1Int);
|
||||
|
||||
String name(int param1Int);
|
||||
|
||||
int value(String param1String);
|
||||
}
|
||||
|
||||
static class PrimitiveEntityMap implements EntityMap {
|
||||
private Map mapNameToValue = new HashMap();
|
||||
|
||||
private IntHashMap mapValueToName = new IntHashMap();
|
||||
|
||||
public void add(String name, int value) {
|
||||
this.mapNameToValue.put(name, new Integer(value));
|
||||
this.mapValueToName.put(value, name);
|
||||
}
|
||||
|
||||
public String name(int value) {
|
||||
return (String)this.mapValueToName.get(value);
|
||||
}
|
||||
|
||||
public int value(String name) {
|
||||
Object value = this.mapNameToValue.get(name);
|
||||
if (value == null)
|
||||
return -1;
|
||||
return ((Integer)value).intValue();
|
||||
}
|
||||
}
|
||||
|
||||
static abstract class MapIntMap implements EntityMap {
|
||||
protected Map mapNameToValue;
|
||||
|
||||
protected Map mapValueToName;
|
||||
|
||||
public void add(String name, int value) {
|
||||
this.mapNameToValue.put(name, new Integer(value));
|
||||
this.mapValueToName.put(new Integer(value), name);
|
||||
}
|
||||
|
||||
public String name(int value) {
|
||||
return (String)this.mapValueToName.get(new Integer(value));
|
||||
}
|
||||
|
||||
public int value(String name) {
|
||||
Object value = this.mapNameToValue.get(name);
|
||||
if (value == null)
|
||||
return -1;
|
||||
return ((Integer)value).intValue();
|
||||
}
|
||||
}
|
||||
|
||||
static class HashEntityMap extends MapIntMap {}
|
||||
|
||||
static class TreeEntityMap extends MapIntMap {}
|
||||
|
||||
static class LookupEntityMap extends PrimitiveEntityMap {
|
||||
private String[] lookupTable;
|
||||
|
||||
private int LOOKUP_TABLE_SIZE = 256;
|
||||
|
||||
public String name(int value) {
|
||||
if (value < this.LOOKUP_TABLE_SIZE)
|
||||
return lookupTable()[value];
|
||||
return super.name(value);
|
||||
}
|
||||
|
||||
private String[] lookupTable() {
|
||||
if (this.lookupTable == null)
|
||||
createLookupTable();
|
||||
return this.lookupTable;
|
||||
}
|
||||
|
||||
private void createLookupTable() {
|
||||
this.lookupTable = new String[this.LOOKUP_TABLE_SIZE];
|
||||
for (int i = 0; i < this.LOOKUP_TABLE_SIZE; i++)
|
||||
this.lookupTable[i] = super.name(i);
|
||||
}
|
||||
}
|
||||
|
||||
static class ArrayEntityMap implements EntityMap {
|
||||
protected int growBy = 100;
|
||||
|
||||
protected int size = 0;
|
||||
|
||||
protected String[] names;
|
||||
|
||||
protected int[] values;
|
||||
|
||||
public ArrayEntityMap() {
|
||||
this.names = new String[this.growBy];
|
||||
this.values = new int[this.growBy];
|
||||
}
|
||||
|
||||
public ArrayEntityMap(int growBy) {
|
||||
this.growBy = growBy;
|
||||
this.names = new String[growBy];
|
||||
this.values = new int[growBy];
|
||||
}
|
||||
|
||||
public void add(String name, int value) {
|
||||
ensureCapacity(this.size + 1);
|
||||
this.names[this.size] = name;
|
||||
this.values[this.size] = value;
|
||||
this.size++;
|
||||
}
|
||||
|
||||
protected void ensureCapacity(int capacity) {
|
||||
if (capacity > this.names.length) {
|
||||
int newSize = Math.max(capacity, this.size + this.growBy);
|
||||
String[] newNames = new String[newSize];
|
||||
System.arraycopy(this.names, 0, newNames, 0, this.size);
|
||||
this.names = newNames;
|
||||
int[] newValues = new int[newSize];
|
||||
System.arraycopy(this.values, 0, newValues, 0, this.size);
|
||||
this.values = newValues;
|
||||
}
|
||||
}
|
||||
|
||||
public String name(int value) {
|
||||
for (int i = 0; i < this.size; i++) {
|
||||
if (this.values[i] == value)
|
||||
return this.names[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public int value(String name) {
|
||||
for (int i = 0; i < this.size; i++) {
|
||||
if (this.names[i].equals(name))
|
||||
return this.values[i];
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
static class BinaryEntityMap extends ArrayEntityMap {
|
||||
public BinaryEntityMap() {}
|
||||
|
||||
public BinaryEntityMap(int growBy) {
|
||||
super(growBy);
|
||||
}
|
||||
|
||||
private int binarySearch(int key) {
|
||||
int low = 0;
|
||||
int high = this.size - 1;
|
||||
while (low <= high) {
|
||||
int mid = low + high >>> 1;
|
||||
int midVal = this.values[mid];
|
||||
if (midVal < key) {
|
||||
low = mid + 1;
|
||||
continue;
|
||||
}
|
||||
if (midVal > key) {
|
||||
high = mid - 1;
|
||||
continue;
|
||||
}
|
||||
return mid;
|
||||
}
|
||||
return -(low + 1);
|
||||
}
|
||||
|
||||
public void add(String name, int value) {
|
||||
ensureCapacity(this.size + 1);
|
||||
int insertAt = binarySearch(value);
|
||||
if (insertAt > 0)
|
||||
return;
|
||||
insertAt = -(insertAt + 1);
|
||||
System.arraycopy(this.values, insertAt, this.values, insertAt + 1, this.size - insertAt);
|
||||
this.values[insertAt] = value;
|
||||
System.arraycopy(this.names, insertAt, this.names, insertAt + 1, this.size - insertAt);
|
||||
this.names[insertAt] = name;
|
||||
this.size++;
|
||||
}
|
||||
|
||||
public String name(int value) {
|
||||
int index = binarySearch(value);
|
||||
if (index < 0)
|
||||
return null;
|
||||
return this.names[index];
|
||||
}
|
||||
}
|
||||
|
||||
EntityMap map = new LookupEntityMap();
|
||||
|
||||
public void addEntities(String[][] entityArray) {
|
||||
for (int i = 0; i < entityArray.length; i++)
|
||||
addEntity(entityArray[i][0], Integer.parseInt(entityArray[i][1]));
|
||||
}
|
||||
|
||||
public void addEntity(String name, int value) {
|
||||
this.map.add(name, value);
|
||||
}
|
||||
|
||||
public String entityName(int value) {
|
||||
return this.map.name(value);
|
||||
}
|
||||
|
||||
public int entityValue(String name) {
|
||||
return this.map.value(name);
|
||||
}
|
||||
|
||||
public String escape(String str) {
|
||||
StringWriter stringWriter = createStringWriter(str);
|
||||
try {
|
||||
escape(stringWriter, str);
|
||||
} catch (IOException e) {
|
||||
throw new UnhandledException(e);
|
||||
}
|
||||
return stringWriter.toString();
|
||||
}
|
||||
|
||||
public void escape(Writer writer, String str) throws IOException {
|
||||
int len = str.length();
|
||||
for (int i = 0; i < len; i++) {
|
||||
char c = str.charAt(i);
|
||||
String entityName = entityName(c);
|
||||
if (entityName == null) {
|
||||
if (c > '\u007F') {
|
||||
writer.write("&#");
|
||||
writer.write(Integer.toString(c, 10));
|
||||
writer.write(59);
|
||||
} else {
|
||||
writer.write(c);
|
||||
}
|
||||
} else {
|
||||
writer.write(38);
|
||||
writer.write(entityName);
|
||||
writer.write(59);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String unescape(String str) {
|
||||
int firstAmp = str.indexOf('&');
|
||||
if (firstAmp < 0)
|
||||
return str;
|
||||
StringWriter stringWriter = createStringWriter(str);
|
||||
try {
|
||||
doUnescape(stringWriter, str, firstAmp);
|
||||
} catch (IOException e) {
|
||||
throw new UnhandledException(e);
|
||||
}
|
||||
return stringWriter.toString();
|
||||
}
|
||||
|
||||
private StringWriter createStringWriter(String str) {
|
||||
return new StringWriter((int)((double)str.length() + (double)str.length() * 0.1D));
|
||||
}
|
||||
|
||||
public void unescape(Writer writer, String str) throws IOException {
|
||||
int firstAmp = str.indexOf('&');
|
||||
if (firstAmp < 0) {
|
||||
writer.write(str);
|
||||
return;
|
||||
}
|
||||
doUnescape(writer, str, firstAmp);
|
||||
}
|
||||
|
||||
private void doUnescape(Writer writer, String str, int firstAmp) throws IOException {
|
||||
writer.write(str, 0, firstAmp);
|
||||
int len = str.length();
|
||||
for (int i = firstAmp; i < len; i++) {
|
||||
char c = str.charAt(i);
|
||||
if (c == '&') {
|
||||
int nextIdx = i + 1;
|
||||
int semiColonIdx = str.indexOf(';', nextIdx);
|
||||
if (semiColonIdx == -1) {
|
||||
writer.write(c);
|
||||
} else {
|
||||
int amphersandIdx = str.indexOf('&', i + 1);
|
||||
if (amphersandIdx != -1 && amphersandIdx < semiColonIdx) {
|
||||
writer.write(c);
|
||||
} else {
|
||||
String entityContent = str.substring(nextIdx, semiColonIdx);
|
||||
int entityValue = -1;
|
||||
int entityContentLen = entityContent.length();
|
||||
if (entityContentLen > 0)
|
||||
if (entityContent.charAt(0) == '#') {
|
||||
if (entityContentLen > 1) {
|
||||
char isHexChar = entityContent.charAt(1);
|
||||
try {
|
||||
switch (isHexChar) {
|
||||
case 'X':
|
||||
case 'x':
|
||||
entityValue = Integer.parseInt(entityContent.substring(2), 16);
|
||||
break;
|
||||
default:
|
||||
entityValue = Integer.parseInt(entityContent.substring(1), 10);
|
||||
break;
|
||||
}
|
||||
if (entityValue > 65535)
|
||||
entityValue = -1;
|
||||
} catch (NumberFormatException e) {
|
||||
entityValue = -1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
entityValue = entityValue(entityContent);
|
||||
}
|
||||
if (entityValue == -1) {
|
||||
writer.write(38);
|
||||
writer.write(entityContent);
|
||||
writer.write(59);
|
||||
} else {
|
||||
writer.write(entityValue);
|
||||
}
|
||||
i = semiColonIdx;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
writer.write(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
public class IllegalClassException extends IllegalArgumentException {
|
||||
private static final long serialVersionUID = 8063272569377254819L;
|
||||
|
||||
public IllegalClassException(Class expected, Object actual) {
|
||||
super("Expected: " + safeGetClassName(expected) + ", actual: " + ((actual == null) ? "null" : actual.getClass().getName()));
|
||||
}
|
||||
|
||||
public IllegalClassException(Class expected, Class actual) {
|
||||
super("Expected: " + safeGetClassName(expected) + ", actual: " + safeGetClassName(actual));
|
||||
}
|
||||
|
||||
public IllegalClassException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
private static final String safeGetClassName(Class cls) {
|
||||
return (cls == null) ? null : cls.getName();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class IncompleteArgumentException extends IllegalArgumentException {
|
||||
private static final long serialVersionUID = 4954193403612068178L;
|
||||
|
||||
public IncompleteArgumentException(String argName) {
|
||||
super(argName + " is incomplete.");
|
||||
}
|
||||
|
||||
public IncompleteArgumentException(String argName, String[] items) {
|
||||
super(argName + " is missing the following items: " + safeArrayToString(items));
|
||||
}
|
||||
|
||||
private static final String safeArrayToString(Object[] array) {
|
||||
return (array == null) ? null : Arrays.asList(array).toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,163 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
class IntHashMap {
|
||||
private transient Entry[] table;
|
||||
|
||||
private transient int count;
|
||||
|
||||
private int threshold;
|
||||
|
||||
private float loadFactor;
|
||||
|
||||
private static class Entry {
|
||||
int hash;
|
||||
|
||||
int key;
|
||||
|
||||
Object value;
|
||||
|
||||
Entry next;
|
||||
|
||||
protected Entry(int hash, int key, Object value, Entry next) {
|
||||
this.hash = hash;
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
this.next = next;
|
||||
}
|
||||
}
|
||||
|
||||
public IntHashMap() {
|
||||
this(20, 0.75F);
|
||||
}
|
||||
|
||||
public IntHashMap(int initialCapacity) {
|
||||
this(initialCapacity, 0.75F);
|
||||
}
|
||||
|
||||
public IntHashMap(int initialCapacity, float loadFactor) {
|
||||
if (initialCapacity < 0)
|
||||
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
|
||||
if (loadFactor <= 0.0F)
|
||||
throw new IllegalArgumentException("Illegal Load: " + loadFactor);
|
||||
if (initialCapacity == 0)
|
||||
initialCapacity = 1;
|
||||
this.loadFactor = loadFactor;
|
||||
this.table = new Entry[initialCapacity];
|
||||
this.threshold = (int)((float)initialCapacity * loadFactor);
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return this.count;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return (this.count == 0);
|
||||
}
|
||||
|
||||
public boolean contains(Object value) {
|
||||
if (value == null)
|
||||
throw new NullPointerException();
|
||||
Entry[] tab = this.table;
|
||||
for (int i = tab.length; i-- > 0;) {
|
||||
for (Entry e = tab[i]; e != null; e = e.next) {
|
||||
if (e.value.equals(value))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean containsValue(Object value) {
|
||||
return contains(value);
|
||||
}
|
||||
|
||||
public boolean containsKey(int key) {
|
||||
Entry[] tab = this.table;
|
||||
int hash = key;
|
||||
int index = (hash & Integer.MAX_VALUE) % tab.length;
|
||||
for (Entry e = tab[index]; e != null; e = e.next) {
|
||||
if (e.hash == hash)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Object get(int key) {
|
||||
Entry[] tab = this.table;
|
||||
int hash = key;
|
||||
int index = (hash & Integer.MAX_VALUE) % tab.length;
|
||||
for (Entry e = tab[index]; e != null; e = e.next) {
|
||||
if (e.hash == hash)
|
||||
return e.value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected void rehash() {
|
||||
int oldCapacity = this.table.length;
|
||||
Entry[] oldMap = this.table;
|
||||
int newCapacity = oldCapacity * 2 + 1;
|
||||
Entry[] newMap = new Entry[newCapacity];
|
||||
this.threshold = (int)((float)newCapacity * this.loadFactor);
|
||||
this.table = newMap;
|
||||
for (int i = oldCapacity; i-- > 0;) {
|
||||
for (Entry old = oldMap[i]; old != null; ) {
|
||||
Entry e = old;
|
||||
old = old.next;
|
||||
int index = (e.hash & Integer.MAX_VALUE) % newCapacity;
|
||||
e.next = newMap[index];
|
||||
newMap[index] = e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Object put(int key, Object value) {
|
||||
Entry[] tab = this.table;
|
||||
int hash = key;
|
||||
int index = (hash & Integer.MAX_VALUE) % tab.length;
|
||||
Entry e;
|
||||
for (e = tab[index]; e != null; e = e.next) {
|
||||
if (e.hash == hash) {
|
||||
Object old = e.value;
|
||||
e.value = value;
|
||||
return old;
|
||||
}
|
||||
}
|
||||
if (this.count >= this.threshold) {
|
||||
rehash();
|
||||
tab = this.table;
|
||||
index = (hash & Integer.MAX_VALUE) % tab.length;
|
||||
}
|
||||
e = new Entry(hash, key, value, tab[index]);
|
||||
tab[index] = e;
|
||||
this.count++;
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object remove(int key) {
|
||||
Entry[] tab = this.table;
|
||||
int hash = key;
|
||||
int index = (hash & Integer.MAX_VALUE) % tab.length;
|
||||
for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.next) {
|
||||
if (e.hash == hash) {
|
||||
if (prev != null) {
|
||||
prev.next = e.next;
|
||||
} else {
|
||||
tab[index] = e.next;
|
||||
}
|
||||
this.count--;
|
||||
Object oldValue = e.value;
|
||||
e.value = null;
|
||||
return oldValue;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public synchronized void clear() {
|
||||
Entry[] tab = this.table;
|
||||
for (int index = tab.length; --index >= 0;)
|
||||
tab[index] = null;
|
||||
this.count = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class LocaleUtils {
|
||||
private static final List cAvailableLocaleList;
|
||||
|
||||
private static Set cAvailableLocaleSet;
|
||||
|
||||
private static final Map cLanguagesByCountry = Collections.synchronizedMap(new HashMap());
|
||||
|
||||
private static final Map cCountriesByLanguage = Collections.synchronizedMap(new HashMap());
|
||||
|
||||
static {
|
||||
List list = Arrays.asList(Locale.getAvailableLocales());
|
||||
cAvailableLocaleList = Collections.unmodifiableList(list);
|
||||
}
|
||||
|
||||
public static Locale toLocale(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
int len = str.length();
|
||||
if (len != 2 && len != 5 && len < 7)
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
char ch0 = str.charAt(0);
|
||||
char ch1 = str.charAt(1);
|
||||
if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z')
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
if (len == 2)
|
||||
return new Locale(str, "");
|
||||
if (str.charAt(2) != '_')
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
char ch3 = str.charAt(3);
|
||||
if (ch3 == '_')
|
||||
return new Locale(str.substring(0, 2), "", str.substring(4));
|
||||
char ch4 = str.charAt(4);
|
||||
if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z')
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
if (len == 5)
|
||||
return new Locale(str.substring(0, 2), str.substring(3, 5));
|
||||
if (str.charAt(5) != '_')
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
|
||||
}
|
||||
|
||||
public static List localeLookupList(Locale locale) {
|
||||
return localeLookupList(locale, locale);
|
||||
}
|
||||
|
||||
public static List localeLookupList(Locale locale, Locale defaultLocale) {
|
||||
List list = new ArrayList(4);
|
||||
if (locale != null) {
|
||||
list.add(locale);
|
||||
if (locale.getVariant().length() > 0)
|
||||
list.add(new Locale(locale.getLanguage(), locale.getCountry()));
|
||||
if (locale.getCountry().length() > 0)
|
||||
list.add(new Locale(locale.getLanguage(), ""));
|
||||
if (!list.contains(defaultLocale))
|
||||
list.add(defaultLocale);
|
||||
}
|
||||
return Collections.unmodifiableList(list);
|
||||
}
|
||||
|
||||
public static List availableLocaleList() {
|
||||
return cAvailableLocaleList;
|
||||
}
|
||||
|
||||
public static Set availableLocaleSet() {
|
||||
Set set = cAvailableLocaleSet;
|
||||
if (set == null) {
|
||||
set = new HashSet(availableLocaleList());
|
||||
set = Collections.unmodifiableSet(set);
|
||||
cAvailableLocaleSet = set;
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
public static boolean isAvailableLocale(Locale locale) {
|
||||
return availableLocaleList().contains(locale);
|
||||
}
|
||||
|
||||
public static List languagesByCountry(String countryCode) {
|
||||
List langs = (List)cLanguagesByCountry.get(countryCode);
|
||||
if (langs == null) {
|
||||
if (countryCode != null) {
|
||||
langs = new ArrayList();
|
||||
List locales = availableLocaleList();
|
||||
for (int i = 0; i < locales.size(); i++) {
|
||||
Locale locale = (Locale)locales.get(i);
|
||||
if (countryCode.equals(locale.getCountry()) && locale.getVariant().length() == 0)
|
||||
langs.add(locale);
|
||||
}
|
||||
langs = Collections.unmodifiableList(langs);
|
||||
} else {
|
||||
langs = Collections.EMPTY_LIST;
|
||||
}
|
||||
cLanguagesByCountry.put(countryCode, langs);
|
||||
}
|
||||
return langs;
|
||||
}
|
||||
|
||||
public static List countriesByLanguage(String languageCode) {
|
||||
List countries = (List)cCountriesByLanguage.get(languageCode);
|
||||
if (countries == null) {
|
||||
if (languageCode != null) {
|
||||
countries = new ArrayList();
|
||||
List locales = availableLocaleList();
|
||||
for (int i = 0; i < locales.size(); i++) {
|
||||
Locale locale = (Locale)locales.get(i);
|
||||
if (languageCode.equals(locale.getLanguage()) && locale.getCountry().length() != 0 && locale.getVariant().length() == 0)
|
||||
countries.add(locale);
|
||||
}
|
||||
countries = Collections.unmodifiableList(countries);
|
||||
} else {
|
||||
countries = Collections.EMPTY_LIST;
|
||||
}
|
||||
cCountriesByLanguage.put(languageCode, countries);
|
||||
}
|
||||
return countries;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
import org.apache.commons.lang.exception.Nestable;
|
||||
import org.apache.commons.lang.exception.NestableDelegate;
|
||||
|
||||
public class NotImplementedException extends UnsupportedOperationException implements Nestable {
|
||||
private static final String DEFAULT_MESSAGE = "Code is not implemented";
|
||||
|
||||
private static final long serialVersionUID = -6894122266938754088L;
|
||||
|
||||
private NestableDelegate delegate = new NestableDelegate(this);
|
||||
|
||||
private Throwable cause;
|
||||
|
||||
public NotImplementedException() {
|
||||
super("Code is not implemented");
|
||||
}
|
||||
|
||||
public NotImplementedException(String msg) {
|
||||
super((msg == null) ? "Code is not implemented" : msg);
|
||||
}
|
||||
|
||||
public NotImplementedException(Throwable cause) {
|
||||
super("Code is not implemented");
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
public NotImplementedException(String msg, Throwable cause) {
|
||||
super((msg == null) ? "Code is not implemented" : msg);
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
public NotImplementedException(Class clazz) {
|
||||
super((clazz == null) ? "Code is not implemented" : ("Code is not implemented in " + clazz));
|
||||
}
|
||||
|
||||
public Throwable getCause() {
|
||||
return this.cause;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
if (super.getMessage() != null)
|
||||
return super.getMessage();
|
||||
if (this.cause != null)
|
||||
return this.cause.toString();
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getMessage(int index) {
|
||||
if (index == 0)
|
||||
return super.getMessage();
|
||||
return this.delegate.getMessage(index);
|
||||
}
|
||||
|
||||
public String[] getMessages() {
|
||||
return this.delegate.getMessages();
|
||||
}
|
||||
|
||||
public Throwable getThrowable(int index) {
|
||||
return this.delegate.getThrowable(index);
|
||||
}
|
||||
|
||||
public int getThrowableCount() {
|
||||
return this.delegate.getThrowableCount();
|
||||
}
|
||||
|
||||
public Throwable[] getThrowables() {
|
||||
return this.delegate.getThrowables();
|
||||
}
|
||||
|
||||
public int indexOfThrowable(Class type) {
|
||||
return this.delegate.indexOfThrowable(type, 0);
|
||||
}
|
||||
|
||||
public int indexOfThrowable(Class type, int fromIndex) {
|
||||
return this.delegate.indexOfThrowable(type, fromIndex);
|
||||
}
|
||||
|
||||
public void printStackTrace() {
|
||||
this.delegate.printStackTrace();
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintStream out) {
|
||||
this.delegate.printStackTrace(out);
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintWriter out) {
|
||||
this.delegate.printStackTrace(out);
|
||||
}
|
||||
|
||||
public final void printPartialStackTrace(PrintWriter out) {
|
||||
super.printStackTrace(out);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
public class NullArgumentException extends IllegalArgumentException {
|
||||
private static final long serialVersionUID = 1174360235354917591L;
|
||||
|
||||
public NullArgumentException(String argName) {
|
||||
super(((argName == null) ? "Argument" : argName) + " must not be null.");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
public final class NumberRange {
|
||||
private final Number min;
|
||||
|
||||
private final Number max;
|
||||
|
||||
public NumberRange(Number num) {
|
||||
if (num == null)
|
||||
throw new NullPointerException("The number must not be null");
|
||||
this.min = num;
|
||||
this.max = num;
|
||||
}
|
||||
|
||||
public NumberRange(Number min, Number max) {
|
||||
if (min == null)
|
||||
throw new NullPointerException("The minimum value must not be null");
|
||||
if (max == null)
|
||||
throw new NullPointerException("The maximum value must not be null");
|
||||
if (max.doubleValue() < min.doubleValue()) {
|
||||
this.min = this.max = min;
|
||||
} else {
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
}
|
||||
|
||||
public Number getMinimum() {
|
||||
return this.min;
|
||||
}
|
||||
|
||||
public Number getMaximum() {
|
||||
return this.max;
|
||||
}
|
||||
|
||||
public boolean includesNumber(Number number) {
|
||||
if (number == null)
|
||||
return false;
|
||||
return (this.min.doubleValue() <= number.doubleValue() && this.max.doubleValue() >= number.doubleValue());
|
||||
}
|
||||
|
||||
public boolean includesRange(NumberRange range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (includesNumber(range.min) && includesNumber(range.max));
|
||||
}
|
||||
|
||||
public boolean overlaps(NumberRange range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (range.includesNumber(this.min) || range.includesNumber(this.max) || includesRange(range));
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (!(obj instanceof NumberRange))
|
||||
return false;
|
||||
NumberRange range = (NumberRange)obj;
|
||||
return (this.min.equals(range.min) && this.max.equals(range.max));
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
int result = 17;
|
||||
result = 37 * result + this.min.hashCode();
|
||||
result = 37 * result + this.max.hashCode();
|
||||
return result;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
if (this.min.doubleValue() < 0.0D) {
|
||||
sb.append('(').append(this.min).append(')');
|
||||
} else {
|
||||
sb.append(this.min);
|
||||
}
|
||||
sb.append('-');
|
||||
if (this.max.doubleValue() < 0.0D) {
|
||||
sb.append('(').append(this.max).append(')');
|
||||
} else {
|
||||
sb.append(this.max);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,285 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
|
||||
public final class NumberUtils {
|
||||
public static int stringToInt(String str) {
|
||||
return stringToInt(str, 0);
|
||||
}
|
||||
|
||||
public static int stringToInt(String str, int defaultValue) {
|
||||
try {
|
||||
return Integer.parseInt(str);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static Number createNumber(String val) throws NumberFormatException {
|
||||
String mant, dec, exp;
|
||||
if (val == null)
|
||||
return null;
|
||||
if (val.length() == 0)
|
||||
throw new NumberFormatException("\"\" is not a valid number.");
|
||||
if (val.startsWith("--"))
|
||||
return null;
|
||||
if (val.startsWith("0x") || val.startsWith("-0x"))
|
||||
return createInteger(val);
|
||||
char lastChar = val.charAt(val.length() - 1);
|
||||
int decPos = val.indexOf('.');
|
||||
int expPos = val.indexOf('e') + val.indexOf('E') + 1;
|
||||
if (decPos > -1) {
|
||||
if (expPos > -1) {
|
||||
if (expPos < decPos)
|
||||
throw new NumberFormatException(val + " is not a valid number.");
|
||||
dec = val.substring(decPos + 1, expPos);
|
||||
} else {
|
||||
dec = val.substring(decPos + 1);
|
||||
}
|
||||
mant = val.substring(0, decPos);
|
||||
} else {
|
||||
if (expPos > -1) {
|
||||
mant = val.substring(0, expPos);
|
||||
} else {
|
||||
mant = val;
|
||||
}
|
||||
dec = null;
|
||||
}
|
||||
if (!Character.isDigit(lastChar)) {
|
||||
if (expPos > -1 && expPos < val.length() - 1) {
|
||||
exp = val.substring(expPos + 1, val.length() - 1);
|
||||
} else {
|
||||
exp = null;
|
||||
}
|
||||
String numeric = val.substring(0, val.length() - 1);
|
||||
boolean bool = (isAllZeros(mant) && isAllZeros(exp));
|
||||
switch (lastChar) {
|
||||
case 'L':
|
||||
case 'l':
|
||||
if (dec == null && exp == null && ((numeric.charAt(0) == '-' && isDigits(numeric.substring(1))) || isDigits(numeric)))
|
||||
try {
|
||||
return createLong(numeric);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return createBigInteger(numeric);
|
||||
}
|
||||
throw new NumberFormatException(val + " is not a valid number.");
|
||||
case 'F':
|
||||
case 'f':
|
||||
try {
|
||||
Float f = createFloat(numeric);
|
||||
if (!f.isInfinite() && (f.floatValue() != 0.0F || bool))
|
||||
return f;
|
||||
} catch (NumberFormatException e) {}
|
||||
case 'D':
|
||||
case 'd':
|
||||
try {
|
||||
Double d = createDouble(numeric);
|
||||
if (!d.isInfinite() && ((double)d.floatValue() != 0.0D || bool))
|
||||
return d;
|
||||
} catch (NumberFormatException nfe) {}
|
||||
try {
|
||||
return createBigDecimal(numeric);
|
||||
} catch (NumberFormatException e) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw new NumberFormatException(val + " is not a valid number.");
|
||||
}
|
||||
if (expPos > -1 && expPos < val.length() - 1) {
|
||||
exp = val.substring(expPos + 1, val.length());
|
||||
} else {
|
||||
exp = null;
|
||||
}
|
||||
if (dec == null && exp == null)
|
||||
try {
|
||||
return createInteger(val);
|
||||
} catch (NumberFormatException nfe) {
|
||||
try {
|
||||
return createLong(val);
|
||||
} catch (NumberFormatException numberFormatException) {
|
||||
return createBigInteger(val);
|
||||
}
|
||||
}
|
||||
boolean allZeros = (isAllZeros(mant) && isAllZeros(exp));
|
||||
try {
|
||||
Float f = createFloat(val);
|
||||
if (!f.isInfinite() && (f.floatValue() != 0.0F || allZeros))
|
||||
return f;
|
||||
} catch (NumberFormatException nfe) {}
|
||||
try {
|
||||
Double d = createDouble(val);
|
||||
if (!d.isInfinite() && (d.doubleValue() != 0.0D || allZeros))
|
||||
return d;
|
||||
} catch (NumberFormatException nfe) {}
|
||||
return createBigDecimal(val);
|
||||
}
|
||||
|
||||
private static boolean isAllZeros(String s) {
|
||||
if (s == null)
|
||||
return true;
|
||||
for (int i = s.length() - 1; i >= 0; i--) {
|
||||
if (s.charAt(i) != '0')
|
||||
return false;
|
||||
}
|
||||
return (s.length() > 0);
|
||||
}
|
||||
|
||||
public static Float createFloat(String val) {
|
||||
return Float.valueOf(val);
|
||||
}
|
||||
|
||||
public static Double createDouble(String val) {
|
||||
return Double.valueOf(val);
|
||||
}
|
||||
|
||||
public static Integer createInteger(String val) {
|
||||
return Integer.decode(val);
|
||||
}
|
||||
|
||||
public static Long createLong(String val) {
|
||||
return Long.valueOf(val);
|
||||
}
|
||||
|
||||
public static BigInteger createBigInteger(String val) {
|
||||
BigInteger bi = new BigInteger(val);
|
||||
return bi;
|
||||
}
|
||||
|
||||
public static BigDecimal createBigDecimal(String val) {
|
||||
BigDecimal bd = new BigDecimal(val);
|
||||
return bd;
|
||||
}
|
||||
|
||||
public static long minimum(long a, long b, long c) {
|
||||
if (b < a)
|
||||
a = b;
|
||||
if (c < a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static int minimum(int a, int b, int c) {
|
||||
if (b < a)
|
||||
a = b;
|
||||
if (c < a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static long maximum(long a, long b, long c) {
|
||||
if (b > a)
|
||||
a = b;
|
||||
if (c > a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static int maximum(int a, int b, int c) {
|
||||
if (b > a)
|
||||
a = b;
|
||||
if (c > a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static int compare(double lhs, double rhs) {
|
||||
if (lhs < rhs)
|
||||
return -1;
|
||||
if (lhs > rhs)
|
||||
return 1;
|
||||
long lhsBits = Double.doubleToLongBits(lhs);
|
||||
long rhsBits = Double.doubleToLongBits(rhs);
|
||||
if (lhsBits == rhsBits)
|
||||
return 0;
|
||||
if (lhsBits < rhsBits)
|
||||
return -1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static int compare(float lhs, float rhs) {
|
||||
if (lhs < rhs)
|
||||
return -1;
|
||||
if (lhs > rhs)
|
||||
return 1;
|
||||
int lhsBits = Float.floatToIntBits(lhs);
|
||||
int rhsBits = Float.floatToIntBits(rhs);
|
||||
if (lhsBits == rhsBits)
|
||||
return 0;
|
||||
if (lhsBits < rhsBits)
|
||||
return -1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static boolean isDigits(String str) {
|
||||
if (str == null || str.length() == 0)
|
||||
return false;
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
if (!Character.isDigit(str.charAt(i)))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isNumber(String str) {
|
||||
if (StringUtils.isEmpty(str))
|
||||
return false;
|
||||
char[] chars = str.toCharArray();
|
||||
int sz = chars.length;
|
||||
boolean hasExp = false;
|
||||
boolean hasDecPoint = false;
|
||||
boolean allowSigns = false;
|
||||
boolean foundDigit = false;
|
||||
int start = (chars[0] == '-') ? 1 : 0;
|
||||
if (sz > start + 1 &&
|
||||
chars[start] == '0' && chars[start + 1] == 'x') {
|
||||
int j = start + 2;
|
||||
if (j == sz)
|
||||
return false;
|
||||
for (; j < chars.length; j++) {
|
||||
if ((chars[j] < '0' || chars[j] > '9') && (chars[j] < 'a' || chars[j] > 'f') && (chars[j] < 'A' || chars[j] > 'F'))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
sz--;
|
||||
int i = start;
|
||||
while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
|
||||
if (chars[i] >= '0' && chars[i] <= '9') {
|
||||
foundDigit = true;
|
||||
allowSigns = false;
|
||||
} else if (chars[i] == '.') {
|
||||
if (hasDecPoint || hasExp)
|
||||
return false;
|
||||
hasDecPoint = true;
|
||||
} else if (chars[i] == 'e' || chars[i] == 'E') {
|
||||
if (hasExp)
|
||||
return false;
|
||||
if (!foundDigit)
|
||||
return false;
|
||||
hasExp = true;
|
||||
allowSigns = true;
|
||||
} else if (chars[i] == '+' || chars[i] == '-') {
|
||||
if (!allowSigns)
|
||||
return false;
|
||||
allowSigns = false;
|
||||
foundDigit = false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if (i < chars.length) {
|
||||
if (chars[i] >= '0' && chars[i] <= '9')
|
||||
return true;
|
||||
if (chars[i] == 'e' || chars[i] == 'E')
|
||||
return false;
|
||||
if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F'))
|
||||
return foundDigit;
|
||||
if (chars[i] == 'l' || chars[i] == 'L')
|
||||
return (foundDigit && !hasExp);
|
||||
return false;
|
||||
}
|
||||
return (!allowSigns && foundDigit);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class ObjectUtils {
|
||||
public static final Null NULL = new Null();
|
||||
|
||||
public static Object defaultIfNull(Object object, Object defaultValue) {
|
||||
return (object != null) ? object : defaultValue;
|
||||
}
|
||||
|
||||
public static boolean equals(Object object1, Object object2) {
|
||||
if (object1 == object2)
|
||||
return true;
|
||||
if (object1 == null || object2 == null)
|
||||
return false;
|
||||
return object1.equals(object2);
|
||||
}
|
||||
|
||||
public static int hashCode(Object obj) {
|
||||
return (obj == null) ? 0 : obj.hashCode();
|
||||
}
|
||||
|
||||
public static String identityToString(Object object) {
|
||||
if (object == null)
|
||||
return null;
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
identityToString(buffer, object);
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
public static void identityToString(StringBuffer buffer, Object object) {
|
||||
if (object == null)
|
||||
throw new NullPointerException("Cannot get the toString of a null identity");
|
||||
buffer.append(object.getClass().getName()).append('@').append(Integer.toHexString(System.identityHashCode(object)));
|
||||
}
|
||||
|
||||
public static StringBuffer appendIdentityToString(StringBuffer buffer, Object object) {
|
||||
if (object == null)
|
||||
return null;
|
||||
if (buffer == null)
|
||||
buffer = new StringBuffer();
|
||||
return buffer.append(object.getClass().getName()).append('@').append(Integer.toHexString(System.identityHashCode(object)));
|
||||
}
|
||||
|
||||
public static String toString(Object obj) {
|
||||
return (obj == null) ? "" : obj.toString();
|
||||
}
|
||||
|
||||
public static String toString(Object obj, String nullStr) {
|
||||
return (obj == null) ? nullStr : obj.toString();
|
||||
}
|
||||
|
||||
public static Object min(Comparable c1, Comparable c2) {
|
||||
if (c1 != null && c2 != null)
|
||||
return (c1.compareTo(c2) < 1) ? c1 : c2;
|
||||
return (c1 != null) ? c1 : c2;
|
||||
}
|
||||
|
||||
public static Object max(Comparable c1, Comparable c2) {
|
||||
if (c1 != null && c2 != null)
|
||||
return (c1.compareTo(c2) >= 0) ? c1 : c2;
|
||||
return (c1 != null) ? c1 : c2;
|
||||
}
|
||||
|
||||
public static class Null implements Serializable {
|
||||
private static final long serialVersionUID = 7092611880189329093L;
|
||||
|
||||
private Object readResolve() {
|
||||
return ObjectUtils.NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class RandomStringUtils {
|
||||
private static final Random RANDOM = new Random();
|
||||
|
||||
public static String random(int count) {
|
||||
return random(count, false, false);
|
||||
}
|
||||
|
||||
public static String randomAscii(int count) {
|
||||
return random(count, 32, 127, false, false);
|
||||
}
|
||||
|
||||
public static String randomAlphabetic(int count) {
|
||||
return random(count, true, false);
|
||||
}
|
||||
|
||||
public static String randomAlphanumeric(int count) {
|
||||
return random(count, true, true);
|
||||
}
|
||||
|
||||
public static String randomNumeric(int count) {
|
||||
return random(count, false, true);
|
||||
}
|
||||
|
||||
public static String random(int count, boolean letters, boolean numbers) {
|
||||
return random(count, 0, 0, letters, numbers);
|
||||
}
|
||||
|
||||
public static String random(int count, int start, int end, boolean letters, boolean numbers) {
|
||||
return random(count, start, end, letters, numbers, null, RANDOM);
|
||||
}
|
||||
|
||||
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars) {
|
||||
return random(count, start, end, letters, numbers, chars, RANDOM);
|
||||
}
|
||||
|
||||
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) {
|
||||
if (count == 0)
|
||||
return "";
|
||||
if (count < 0)
|
||||
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
|
||||
if (start == 0 && end == 0) {
|
||||
end = 123;
|
||||
start = 32;
|
||||
if (!letters && !numbers) {
|
||||
start = 0;
|
||||
end = Integer.MAX_VALUE;
|
||||
}
|
||||
}
|
||||
char[] buffer = new char[count];
|
||||
int gap = end - start;
|
||||
while (count-- != 0) {
|
||||
char ch;
|
||||
if (chars == null) {
|
||||
ch = (char)(random.nextInt(gap) + start);
|
||||
} else {
|
||||
ch = chars[random.nextInt(gap) + start];
|
||||
}
|
||||
if ((letters && Character.isLetter(ch)) || (numbers && Character.isDigit(ch)) || (!letters && !numbers)) {
|
||||
if (ch >= '?' && ch <= '?') {
|
||||
if (count == 0) {
|
||||
count++;
|
||||
continue;
|
||||
}
|
||||
buffer[count] = ch;
|
||||
count--;
|
||||
buffer[count] = (char)(55296 + random.nextInt(128));
|
||||
continue;
|
||||
}
|
||||
if (ch >= '?' && ch <= '?') {
|
||||
if (count == 0) {
|
||||
count++;
|
||||
continue;
|
||||
}
|
||||
buffer[count] = (char)(56320 + random.nextInt(128));
|
||||
count--;
|
||||
buffer[count] = ch;
|
||||
continue;
|
||||
}
|
||||
if (ch >= '?' && ch <= '?') {
|
||||
count++;
|
||||
continue;
|
||||
}
|
||||
buffer[count] = ch;
|
||||
continue;
|
||||
}
|
||||
count++;
|
||||
}
|
||||
return new String(buffer);
|
||||
}
|
||||
|
||||
public static String random(int count, String chars) {
|
||||
if (chars == null)
|
||||
return random(count, 0, 0, false, false, null, RANDOM);
|
||||
return random(count, chars.toCharArray());
|
||||
}
|
||||
|
||||
public static String random(int count, char[] chars) {
|
||||
if (chars == null)
|
||||
return random(count, 0, 0, false, false, null, RANDOM);
|
||||
return random(count, 0, chars.length, false, false, chars, RANDOM);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import org.apache.commons.lang.exception.NestableRuntimeException;
|
||||
|
||||
public class SerializationException extends NestableRuntimeException {
|
||||
private static final long serialVersionUID = 4029025366392702726L;
|
||||
|
||||
public SerializationException() {}
|
||||
|
||||
public SerializationException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public SerializationException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public SerializationException(String msg, Throwable cause) {
|
||||
super(msg, cause);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Serializable;
|
||||
|
||||
public class SerializationUtils {
|
||||
public static Object clone(Serializable object) {
|
||||
return deserialize(serialize(object));
|
||||
}
|
||||
|
||||
public static void serialize(Serializable obj, OutputStream outputStream) {
|
||||
if (outputStream == null)
|
||||
throw new IllegalArgumentException("The OutputStream must not be null");
|
||||
ObjectOutputStream out = null;
|
||||
try {
|
||||
out = new ObjectOutputStream(outputStream);
|
||||
out.writeObject(obj);
|
||||
} catch (IOException ex) {
|
||||
throw new SerializationException(ex);
|
||||
} finally {
|
||||
try {
|
||||
if (out != null)
|
||||
out.close();
|
||||
} catch (IOException ex) {}
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] serialize(Serializable obj) {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
|
||||
serialize(obj, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
public static Object deserialize(InputStream inputStream) {
|
||||
if (inputStream == null)
|
||||
throw new IllegalArgumentException("The InputStream must not be null");
|
||||
ObjectInputStream in = null;
|
||||
try {
|
||||
in = new ObjectInputStream(inputStream);
|
||||
return in.readObject();
|
||||
} catch (ClassNotFoundException ex) {
|
||||
throw new SerializationException(ex);
|
||||
} catch (IOException ex) {
|
||||
throw new SerializationException(ex);
|
||||
} finally {
|
||||
try {
|
||||
if (in != null)
|
||||
in.close();
|
||||
} catch (IOException ex) {}
|
||||
}
|
||||
}
|
||||
|
||||
public static Object deserialize(byte[] objectData) {
|
||||
if (objectData == null)
|
||||
throw new IllegalArgumentException("The byte[] must not be null");
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
|
||||
return deserialize(bais);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,343 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import org.apache.commons.lang.exception.NestableRuntimeException;
|
||||
|
||||
public class StringEscapeUtils {
|
||||
private static final char CSV_DELIMITER = ',';
|
||||
|
||||
private static final char CSV_QUOTE = '"';
|
||||
|
||||
private static final String CSV_QUOTE_STR = String.valueOf('"');
|
||||
|
||||
private static final char[] CSV_SEARCH_CHARS = new char[] { ',', '"', '\r', '\n' };
|
||||
|
||||
public static String escapeJava(String str) {
|
||||
return escapeJavaStyleString(str, false);
|
||||
}
|
||||
|
||||
public static void escapeJava(Writer out, String str) throws IOException {
|
||||
escapeJavaStyleString(out, str, false);
|
||||
}
|
||||
|
||||
public static String escapeJavaScript(String str) {
|
||||
return escapeJavaStyleString(str, true);
|
||||
}
|
||||
|
||||
public static void escapeJavaScript(Writer out, String str) throws IOException {
|
||||
escapeJavaStyleString(out, str, true);
|
||||
}
|
||||
|
||||
private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes) {
|
||||
if (str == null)
|
||||
return null;
|
||||
try {
|
||||
StringWriter writer = new StringWriter(str.length() * 2);
|
||||
escapeJavaStyleString(writer, str, escapeSingleQuotes);
|
||||
return writer.toString();
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException {
|
||||
if (out == null)
|
||||
throw new IllegalArgumentException("The Writer must not be null");
|
||||
if (str == null)
|
||||
return;
|
||||
int sz = str.length();
|
||||
for (int i = 0; i < sz; i++) {
|
||||
char ch = str.charAt(i);
|
||||
if (ch > '') {
|
||||
out.write("\\u" + hex(ch));
|
||||
} else if (ch > 'ÿ') {
|
||||
out.write("\\u0" + hex(ch));
|
||||
} else if (ch > '\u007F') {
|
||||
out.write("\\u00" + hex(ch));
|
||||
} else if (ch < ' ') {
|
||||
switch (ch) {
|
||||
case '\b':
|
||||
out.write(92);
|
||||
out.write(98);
|
||||
break;
|
||||
case '\n':
|
||||
out.write(92);
|
||||
out.write(110);
|
||||
break;
|
||||
case '\t':
|
||||
out.write(92);
|
||||
out.write(116);
|
||||
break;
|
||||
case '\f':
|
||||
out.write(92);
|
||||
out.write(102);
|
||||
break;
|
||||
case '\r':
|
||||
out.write(92);
|
||||
out.write(114);
|
||||
break;
|
||||
default:
|
||||
if (ch > '\017') {
|
||||
out.write("\\u00" + hex(ch));
|
||||
} else {
|
||||
out.write("\\u000" + hex(ch));
|
||||
}
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
switch (ch) {
|
||||
case '\'':
|
||||
if (escapeSingleQuote)
|
||||
out.write(92);
|
||||
out.write(39);
|
||||
break;
|
||||
case '"':
|
||||
out.write(92);
|
||||
out.write(34);
|
||||
break;
|
||||
case '\\':
|
||||
out.write(92);
|
||||
out.write(92);
|
||||
break;
|
||||
case '/':
|
||||
out.write(92);
|
||||
out.write(47);
|
||||
break;
|
||||
default:
|
||||
out.write(ch);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String hex(char ch) {
|
||||
return Integer.toHexString(ch).toUpperCase();
|
||||
}
|
||||
|
||||
public static String unescapeJava(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
try {
|
||||
StringWriter writer = new StringWriter(str.length());
|
||||
unescapeJava(writer, str);
|
||||
return writer.toString();
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void unescapeJava(Writer out, String str) throws IOException {
|
||||
if (out == null)
|
||||
throw new IllegalArgumentException("The Writer must not be null");
|
||||
if (str == null)
|
||||
return;
|
||||
int sz = str.length();
|
||||
StringBuffer unicode = new StringBuffer(4);
|
||||
boolean hadSlash = false;
|
||||
boolean inUnicode = false;
|
||||
for (int i = 0; i < sz; i++) {
|
||||
char ch = str.charAt(i);
|
||||
if (inUnicode) {
|
||||
unicode.append(ch);
|
||||
if (unicode.length() == 4)
|
||||
try {
|
||||
int value = Integer.parseInt(unicode.toString(), 16);
|
||||
out.write((char)value);
|
||||
unicode.setLength(0);
|
||||
inUnicode = false;
|
||||
hadSlash = false;
|
||||
} catch (NumberFormatException nfe) {
|
||||
throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, nfe);
|
||||
}
|
||||
} else if (hadSlash) {
|
||||
hadSlash = false;
|
||||
switch (ch) {
|
||||
case '\\':
|
||||
out.write(92);
|
||||
break;
|
||||
case '\'':
|
||||
out.write(39);
|
||||
break;
|
||||
case '"':
|
||||
out.write(34);
|
||||
break;
|
||||
case 'r':
|
||||
out.write(13);
|
||||
break;
|
||||
case 'f':
|
||||
out.write(12);
|
||||
break;
|
||||
case 't':
|
||||
out.write(9);
|
||||
break;
|
||||
case 'n':
|
||||
out.write(10);
|
||||
break;
|
||||
case 'b':
|
||||
out.write(8);
|
||||
break;
|
||||
case 'u':
|
||||
inUnicode = true;
|
||||
break;
|
||||
default:
|
||||
out.write(ch);
|
||||
break;
|
||||
}
|
||||
} else if (ch == '\\') {
|
||||
hadSlash = true;
|
||||
} else {
|
||||
out.write(ch);
|
||||
}
|
||||
}
|
||||
if (hadSlash)
|
||||
out.write(92);
|
||||
}
|
||||
|
||||
public static String unescapeJavaScript(String str) {
|
||||
return unescapeJava(str);
|
||||
}
|
||||
|
||||
public static void unescapeJavaScript(Writer out, String str) throws IOException {
|
||||
unescapeJava(out, str);
|
||||
}
|
||||
|
||||
public static String escapeHtml(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
try {
|
||||
StringWriter writer = new StringWriter((int)((double)str.length() * 1.5D));
|
||||
escapeHtml(writer, str);
|
||||
return writer.toString();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void escapeHtml(Writer writer, String string) throws IOException {
|
||||
if (writer == null)
|
||||
throw new IllegalArgumentException("The Writer must not be null.");
|
||||
if (string == null)
|
||||
return;
|
||||
Entities.HTML40.escape(writer, string);
|
||||
}
|
||||
|
||||
public static String unescapeHtml(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
try {
|
||||
StringWriter writer = new StringWriter((int)((double)str.length() * 1.5D));
|
||||
unescapeHtml(writer, str);
|
||||
return writer.toString();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void unescapeHtml(Writer writer, String string) throws IOException {
|
||||
if (writer == null)
|
||||
throw new IllegalArgumentException("The Writer must not be null.");
|
||||
if (string == null)
|
||||
return;
|
||||
Entities.HTML40.unescape(writer, string);
|
||||
}
|
||||
|
||||
public static void escapeXml(Writer writer, String str) throws IOException {
|
||||
if (writer == null)
|
||||
throw new IllegalArgumentException("The Writer must not be null.");
|
||||
if (str == null)
|
||||
return;
|
||||
Entities.XML.escape(writer, str);
|
||||
}
|
||||
|
||||
public static String escapeXml(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
return Entities.XML.escape(str);
|
||||
}
|
||||
|
||||
public static void unescapeXml(Writer writer, String str) throws IOException {
|
||||
if (writer == null)
|
||||
throw new IllegalArgumentException("The Writer must not be null.");
|
||||
if (str == null)
|
||||
return;
|
||||
Entities.XML.unescape(writer, str);
|
||||
}
|
||||
|
||||
public static String unescapeXml(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
return Entities.XML.unescape(str);
|
||||
}
|
||||
|
||||
public static String escapeSql(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
return StringUtils.replace(str, "'", "''");
|
||||
}
|
||||
|
||||
public static String escapeCsv(String str) {
|
||||
if (StringUtils.containsNone(str, CSV_SEARCH_CHARS))
|
||||
return str;
|
||||
try {
|
||||
StringWriter writer = new StringWriter();
|
||||
escapeCsv(writer, str);
|
||||
return writer.toString();
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void escapeCsv(Writer out, String str) throws IOException {
|
||||
if (StringUtils.containsNone(str, CSV_SEARCH_CHARS)) {
|
||||
if (str != null)
|
||||
out.write(str);
|
||||
return;
|
||||
}
|
||||
out.write(34);
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char c = str.charAt(i);
|
||||
if (c == '"')
|
||||
out.write(34);
|
||||
out.write(c);
|
||||
}
|
||||
out.write(34);
|
||||
}
|
||||
|
||||
public static String unescapeCsv(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
try {
|
||||
StringWriter writer = new StringWriter();
|
||||
unescapeCsv(writer, str);
|
||||
return writer.toString();
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void unescapeCsv(Writer out, String str) throws IOException {
|
||||
if (str == null)
|
||||
return;
|
||||
if (str.length() < 2) {
|
||||
out.write(str);
|
||||
return;
|
||||
}
|
||||
if (str.charAt(0) != '"' || str.charAt(str.length() - 1) != '"') {
|
||||
out.write(str);
|
||||
return;
|
||||
}
|
||||
String quoteless = str.substring(1, str.length() - 1);
|
||||
if (StringUtils.containsAny(quoteless, CSV_SEARCH_CHARS))
|
||||
str = StringUtils.replace(quoteless, CSV_QUOTE_STR + CSV_QUOTE_STR, CSV_QUOTE_STR);
|
||||
out.write(str);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,252 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class SystemUtils {
|
||||
private static final String OS_NAME_WINDOWS_PREFIX = "Windows";
|
||||
|
||||
private static final String USER_HOME_KEY = "user.home";
|
||||
|
||||
private static final String USER_DIR_KEY = "user.dir";
|
||||
|
||||
private static final String JAVA_IO_TMPDIR_KEY = "java.io.tmpdir";
|
||||
|
||||
private static final String JAVA_HOME_KEY = "java.home";
|
||||
|
||||
public static final String AWT_TOOLKIT = getSystemProperty("awt.toolkit");
|
||||
|
||||
public static final String FILE_ENCODING = getSystemProperty("file.encoding");
|
||||
|
||||
public static final String FILE_SEPARATOR = getSystemProperty("file.separator");
|
||||
|
||||
public static final String JAVA_AWT_FONTS = getSystemProperty("java.awt.fonts");
|
||||
|
||||
public static final String JAVA_AWT_GRAPHICSENV = getSystemProperty("java.awt.graphicsenv");
|
||||
|
||||
public static final String JAVA_AWT_HEADLESS = getSystemProperty("java.awt.headless");
|
||||
|
||||
public static final String JAVA_AWT_PRINTERJOB = getSystemProperty("java.awt.printerjob");
|
||||
|
||||
public static final String JAVA_CLASS_PATH = getSystemProperty("java.class.path");
|
||||
|
||||
public static final String JAVA_CLASS_VERSION = getSystemProperty("java.class.version");
|
||||
|
||||
public static final String JAVA_COMPILER = getSystemProperty("java.compiler");
|
||||
|
||||
public static final String JAVA_ENDORSED_DIRS = getSystemProperty("java.endorsed.dirs");
|
||||
|
||||
public static final String JAVA_EXT_DIRS = getSystemProperty("java.ext.dirs");
|
||||
|
||||
public static final String JAVA_HOME = getSystemProperty("java.home");
|
||||
|
||||
public static final String JAVA_IO_TMPDIR = getSystemProperty("java.io.tmpdir");
|
||||
|
||||
public static final String JAVA_LIBRARY_PATH = getSystemProperty("java.library.path");
|
||||
|
||||
public static final String JAVA_RUNTIME_NAME = getSystemProperty("java.runtime.name");
|
||||
|
||||
public static final String JAVA_RUNTIME_VERSION = getSystemProperty("java.runtime.version");
|
||||
|
||||
public static final String JAVA_SPECIFICATION_NAME = getSystemProperty("java.specification.name");
|
||||
|
||||
public static final String JAVA_SPECIFICATION_VENDOR = getSystemProperty("java.specification.vendor");
|
||||
|
||||
public static final String JAVA_SPECIFICATION_VERSION = getSystemProperty("java.specification.version");
|
||||
|
||||
public static final String JAVA_UTIL_PREFS_PREFERENCES_FACTORY = getSystemProperty("java.util.prefs.PreferencesFactory");
|
||||
|
||||
public static final String JAVA_VENDOR = getSystemProperty("java.vendor");
|
||||
|
||||
public static final String JAVA_VENDOR_URL = getSystemProperty("java.vendor.url");
|
||||
|
||||
public static final String JAVA_VERSION = getSystemProperty("java.version");
|
||||
|
||||
public static final String JAVA_VM_INFO = getSystemProperty("java.vm.info");
|
||||
|
||||
public static final String JAVA_VM_NAME = getSystemProperty("java.vm.name");
|
||||
|
||||
public static final String JAVA_VM_SPECIFICATION_NAME = getSystemProperty("java.vm.specification.name");
|
||||
|
||||
public static final String JAVA_VM_SPECIFICATION_VENDOR = getSystemProperty("java.vm.specification.vendor");
|
||||
|
||||
public static final String JAVA_VM_SPECIFICATION_VERSION = getSystemProperty("java.vm.specification.version");
|
||||
|
||||
public static final String JAVA_VM_VENDOR = getSystemProperty("java.vm.vendor");
|
||||
|
||||
public static final String JAVA_VM_VERSION = getSystemProperty("java.vm.version");
|
||||
|
||||
public static final String LINE_SEPARATOR = getSystemProperty("line.separator");
|
||||
|
||||
public static final String OS_ARCH = getSystemProperty("os.arch");
|
||||
|
||||
public static final String OS_NAME = getSystemProperty("os.name");
|
||||
|
||||
public static final String OS_VERSION = getSystemProperty("os.version");
|
||||
|
||||
public static final String PATH_SEPARATOR = getSystemProperty("path.separator");
|
||||
|
||||
public static final String USER_COUNTRY = (getSystemProperty("user.country") == null) ? getSystemProperty("user.region") : getSystemProperty("user.country");
|
||||
|
||||
public static final String USER_DIR = getSystemProperty("user.dir");
|
||||
|
||||
public static final String USER_HOME = getSystemProperty("user.home");
|
||||
|
||||
public static final String USER_LANGUAGE = getSystemProperty("user.language");
|
||||
|
||||
public static final String USER_NAME = getSystemProperty("user.name");
|
||||
|
||||
public static final String USER_TIMEZONE = getSystemProperty("user.timezone");
|
||||
|
||||
public static final String JAVA_VERSION_TRIMMED = getJavaVersionTrimmed();
|
||||
|
||||
public static final float JAVA_VERSION_FLOAT = getJavaVersionAsFloat();
|
||||
|
||||
public static final int JAVA_VERSION_INT = getJavaVersionAsInt();
|
||||
|
||||
public static final boolean IS_JAVA_1_1 = getJavaVersionMatches("1.1");
|
||||
|
||||
public static final boolean IS_JAVA_1_2 = getJavaVersionMatches("1.2");
|
||||
|
||||
public static final boolean IS_JAVA_1_3 = getJavaVersionMatches("1.3");
|
||||
|
||||
public static final boolean IS_JAVA_1_4 = getJavaVersionMatches("1.4");
|
||||
|
||||
public static final boolean IS_JAVA_1_5 = getJavaVersionMatches("1.5");
|
||||
|
||||
public static final boolean IS_JAVA_1_6 = getJavaVersionMatches("1.6");
|
||||
|
||||
public static final boolean IS_OS_AIX = getOSMatches("AIX");
|
||||
|
||||
public static final boolean IS_OS_HP_UX = getOSMatches("HP-UX");
|
||||
|
||||
public static final boolean IS_OS_IRIX = getOSMatches("Irix");
|
||||
|
||||
public static final boolean IS_OS_LINUX = (getOSMatches("Linux") || getOSMatches("LINUX"));
|
||||
|
||||
public static final boolean IS_OS_MAC = getOSMatches("Mac");
|
||||
|
||||
public static final boolean IS_OS_MAC_OSX = getOSMatches("Mac OS X");
|
||||
|
||||
public static final boolean IS_OS_OS2 = getOSMatches("OS/2");
|
||||
|
||||
public static final boolean IS_OS_SOLARIS = getOSMatches("Solaris");
|
||||
|
||||
public static final boolean IS_OS_SUN_OS = getOSMatches("SunOS");
|
||||
|
||||
public static final boolean IS_OS_UNIX = (IS_OS_AIX || IS_OS_HP_UX || IS_OS_IRIX || IS_OS_LINUX || IS_OS_MAC_OSX || IS_OS_SOLARIS || IS_OS_SUN_OS);
|
||||
|
||||
public static final boolean IS_OS_WINDOWS = getOSMatches("Windows");
|
||||
|
||||
public static final boolean IS_OS_WINDOWS_2000 = getOSMatches("Windows", "5.0");
|
||||
|
||||
public static final boolean IS_OS_WINDOWS_95 = getOSMatches("Windows 9", "4.0");
|
||||
|
||||
public static final boolean IS_OS_WINDOWS_98 = getOSMatches("Windows 9", "4.1");
|
||||
|
||||
public static final boolean IS_OS_WINDOWS_ME = getOSMatches("Windows", "4.9");
|
||||
|
||||
public static final boolean IS_OS_WINDOWS_NT = getOSMatches("Windows NT");
|
||||
|
||||
public static final boolean IS_OS_WINDOWS_XP = getOSMatches("Windows", "5.1");
|
||||
|
||||
public static final boolean IS_OS_WINDOWS_VISTA = getOSMatches("Windows", "6.0");
|
||||
|
||||
public static float getJavaVersion() {
|
||||
return JAVA_VERSION_FLOAT;
|
||||
}
|
||||
|
||||
private static float getJavaVersionAsFloat() {
|
||||
if (JAVA_VERSION_TRIMMED == null)
|
||||
return 0.0F;
|
||||
String str = JAVA_VERSION_TRIMMED.substring(0, 3);
|
||||
if (JAVA_VERSION_TRIMMED.length() >= 5)
|
||||
str = str + JAVA_VERSION_TRIMMED.substring(4, 5);
|
||||
try {
|
||||
return Float.parseFloat(str);
|
||||
} catch (Exception ex) {
|
||||
return 0.0F;
|
||||
}
|
||||
}
|
||||
|
||||
private static int getJavaVersionAsInt() {
|
||||
if (JAVA_VERSION_TRIMMED == null)
|
||||
return 0;
|
||||
String str = JAVA_VERSION_TRIMMED.substring(0, 1);
|
||||
str = str + JAVA_VERSION_TRIMMED.substring(2, 3);
|
||||
if (JAVA_VERSION_TRIMMED.length() >= 5) {
|
||||
str = str + JAVA_VERSION_TRIMMED.substring(4, 5);
|
||||
} else {
|
||||
str = str + "0";
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(str);
|
||||
} catch (Exception ex) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static String getJavaVersionTrimmed() {
|
||||
if (JAVA_VERSION != null)
|
||||
for (int i = 0; i < JAVA_VERSION.length(); i++) {
|
||||
char ch = JAVA_VERSION.charAt(i);
|
||||
if (ch >= '0' && ch <= '9')
|
||||
return JAVA_VERSION.substring(i);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean getJavaVersionMatches(String versionPrefix) {
|
||||
if (JAVA_VERSION_TRIMMED == null)
|
||||
return false;
|
||||
return JAVA_VERSION_TRIMMED.startsWith(versionPrefix);
|
||||
}
|
||||
|
||||
private static boolean getOSMatches(String osNamePrefix) {
|
||||
if (OS_NAME == null)
|
||||
return false;
|
||||
return OS_NAME.startsWith(osNamePrefix);
|
||||
}
|
||||
|
||||
private static boolean getOSMatches(String osNamePrefix, String osVersionPrefix) {
|
||||
if (OS_NAME == null || OS_VERSION == null)
|
||||
return false;
|
||||
return (OS_NAME.startsWith(osNamePrefix) && OS_VERSION.startsWith(osVersionPrefix));
|
||||
}
|
||||
|
||||
private static String getSystemProperty(String property) {
|
||||
try {
|
||||
return System.getProperty(property);
|
||||
} catch (SecurityException ex) {
|
||||
System.err.println("Caught a SecurityException reading the system property '" + property + "'; the SystemUtils property value will default to null.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isJavaVersionAtLeast(float requiredVersion) {
|
||||
return (JAVA_VERSION_FLOAT >= requiredVersion);
|
||||
}
|
||||
|
||||
public static boolean isJavaVersionAtLeast(int requiredVersion) {
|
||||
return (JAVA_VERSION_INT >= requiredVersion);
|
||||
}
|
||||
|
||||
public static boolean isJavaAwtHeadless() {
|
||||
return (JAVA_AWT_HEADLESS != null) ? JAVA_AWT_HEADLESS.equals(Boolean.TRUE.toString()) : false;
|
||||
}
|
||||
|
||||
public static File getJavaHome() {
|
||||
return new File(System.getProperty("java.home"));
|
||||
}
|
||||
|
||||
public static File getJavaIoTmpDir() {
|
||||
return new File(System.getProperty("java.io.tmpdir"));
|
||||
}
|
||||
|
||||
public static File getUserDir() {
|
||||
return new File(System.getProperty("user.dir"));
|
||||
}
|
||||
|
||||
public static File getUserHome() {
|
||||
return new File(System.getProperty("user.home"));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import org.apache.commons.lang.exception.NestableRuntimeException;
|
||||
|
||||
public class UnhandledException extends NestableRuntimeException {
|
||||
private static final long serialVersionUID = 1832101364842773720L;
|
||||
|
||||
public UnhandledException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public UnhandledException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
public class Validate {
|
||||
public static void isTrue(boolean expression, String message, Object value) {
|
||||
if (!expression)
|
||||
throw new IllegalArgumentException(message + value);
|
||||
}
|
||||
|
||||
public static void isTrue(boolean expression, String message, long value) {
|
||||
if (!expression)
|
||||
throw new IllegalArgumentException(message + value);
|
||||
}
|
||||
|
||||
public static void isTrue(boolean expression, String message, double value) {
|
||||
if (!expression)
|
||||
throw new IllegalArgumentException(message + value);
|
||||
}
|
||||
|
||||
public static void isTrue(boolean expression, String message) {
|
||||
if (!expression)
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
|
||||
public static void isTrue(boolean expression) {
|
||||
if (!expression)
|
||||
throw new IllegalArgumentException("The validated expression is false");
|
||||
}
|
||||
|
||||
public static void notNull(Object object, String message) {
|
||||
if (object == null)
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
|
||||
public static void notNull(Object object) {
|
||||
if (object == null)
|
||||
throw new IllegalArgumentException("The validated object is null");
|
||||
}
|
||||
|
||||
public static void notEmpty(Object[] array, String message) {
|
||||
if (array == null || array.length == 0)
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
|
||||
public static void notEmpty(Object[] array) {
|
||||
if (array == null || array.length == 0)
|
||||
throw new IllegalArgumentException("The validated array is empty");
|
||||
}
|
||||
|
||||
public static void notEmpty(Collection collection, String message) {
|
||||
if (collection == null || collection.size() == 0)
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
|
||||
public static void notEmpty(Collection collection) {
|
||||
if (collection == null || collection.size() == 0)
|
||||
throw new IllegalArgumentException("The validated collection is empty");
|
||||
}
|
||||
|
||||
public static void notEmpty(Map map, String message) {
|
||||
if (map == null || map.size() == 0)
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
|
||||
public static void notEmpty(Map map) {
|
||||
if (map == null || map.size() == 0)
|
||||
throw new IllegalArgumentException("The validated map is empty");
|
||||
}
|
||||
|
||||
public static void notEmpty(String string, String message) {
|
||||
if (string == null || string.length() == 0)
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
|
||||
public static void notEmpty(String string) {
|
||||
if (string == null || string.length() == 0)
|
||||
throw new IllegalArgumentException("The validated string is empty");
|
||||
}
|
||||
|
||||
public static void noNullElements(Object[] array, String message) {
|
||||
notNull(array);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (array[i] == null)
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
|
||||
public static void noNullElements(Object[] array) {
|
||||
notNull(array);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (array[i] == null)
|
||||
throw new IllegalArgumentException("The validated array contains null element at index: " + i);
|
||||
}
|
||||
}
|
||||
|
||||
public static void noNullElements(Collection collection, String message) {
|
||||
notNull(collection);
|
||||
for (Iterator it = collection.iterator(); it.hasNext();) {
|
||||
if (it.next() == null)
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
|
||||
public static void noNullElements(Collection collection) {
|
||||
notNull(collection);
|
||||
int i = 0;
|
||||
for (Iterator it = collection.iterator(); it.hasNext(); i++) {
|
||||
if (it.next() == null)
|
||||
throw new IllegalArgumentException("The validated collection contains null element at index: " + i);
|
||||
}
|
||||
}
|
||||
|
||||
public static void allElementsOfType(Collection collection, Class clazz, String message) {
|
||||
notNull(collection);
|
||||
notNull(clazz);
|
||||
for (Iterator it = collection.iterator(); it.hasNext();) {
|
||||
if (!clazz.isInstance(it.next()))
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
|
||||
public static void allElementsOfType(Collection collection, Class clazz) {
|
||||
notNull(collection);
|
||||
notNull(clazz);
|
||||
int i = 0;
|
||||
for (Iterator it = collection.iterator(); it.hasNext(); i++) {
|
||||
if (!clazz.isInstance(it.next()))
|
||||
throw new IllegalArgumentException("The validated collection contains an element not of type " + clazz.getName() + " at index: " + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,202 @@
|
|||
package org.apache.commons.lang;
|
||||
|
||||
public class WordUtils {
|
||||
public static String wrap(String str, int wrapLength) {
|
||||
return wrap(str, wrapLength, null, false);
|
||||
}
|
||||
|
||||
public static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords) {
|
||||
if (str == null)
|
||||
return null;
|
||||
if (newLineStr == null)
|
||||
newLineStr = SystemUtils.LINE_SEPARATOR;
|
||||
if (wrapLength < 1)
|
||||
wrapLength = 1;
|
||||
int inputLineLength = str.length();
|
||||
int offset = 0;
|
||||
StringBuffer wrappedLine = new StringBuffer(inputLineLength + 32);
|
||||
while (inputLineLength - offset > wrapLength) {
|
||||
if (str.charAt(offset) == ' ') {
|
||||
offset++;
|
||||
continue;
|
||||
}
|
||||
int spaceToWrapAt = str.lastIndexOf(' ', wrapLength + offset);
|
||||
if (spaceToWrapAt >= offset) {
|
||||
wrappedLine.append(str.substring(offset, spaceToWrapAt));
|
||||
wrappedLine.append(newLineStr);
|
||||
offset = spaceToWrapAt + 1;
|
||||
continue;
|
||||
}
|
||||
if (wrapLongWords) {
|
||||
wrappedLine.append(str.substring(offset, wrapLength + offset));
|
||||
wrappedLine.append(newLineStr);
|
||||
offset += wrapLength;
|
||||
continue;
|
||||
}
|
||||
spaceToWrapAt = str.indexOf(' ', wrapLength + offset);
|
||||
if (spaceToWrapAt >= 0) {
|
||||
wrappedLine.append(str.substring(offset, spaceToWrapAt));
|
||||
wrappedLine.append(newLineStr);
|
||||
offset = spaceToWrapAt + 1;
|
||||
continue;
|
||||
}
|
||||
wrappedLine.append(str.substring(offset));
|
||||
offset = inputLineLength;
|
||||
}
|
||||
wrappedLine.append(str.substring(offset));
|
||||
return wrappedLine.toString();
|
||||
}
|
||||
|
||||
public static String capitalize(String str) {
|
||||
return capitalize(str, null);
|
||||
}
|
||||
|
||||
public static String capitalize(String str, char[] delimiters) {
|
||||
int delimLen = (delimiters == null) ? -1 : delimiters.length;
|
||||
if (str == null || str.length() == 0 || delimLen == 0)
|
||||
return str;
|
||||
int strLen = str.length();
|
||||
StringBuffer buffer = new StringBuffer(strLen);
|
||||
boolean capitalizeNext = true;
|
||||
for (int i = 0; i < strLen; i++) {
|
||||
char ch = str.charAt(i);
|
||||
if (isDelimiter(ch, delimiters)) {
|
||||
buffer.append(ch);
|
||||
capitalizeNext = true;
|
||||
} else if (capitalizeNext) {
|
||||
buffer.append(Character.toTitleCase(ch));
|
||||
capitalizeNext = false;
|
||||
} else {
|
||||
buffer.append(ch);
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
public static String capitalizeFully(String str) {
|
||||
return capitalizeFully(str, null);
|
||||
}
|
||||
|
||||
public static String capitalizeFully(String str, char[] delimiters) {
|
||||
int delimLen = (delimiters == null) ? -1 : delimiters.length;
|
||||
if (str == null || str.length() == 0 || delimLen == 0)
|
||||
return str;
|
||||
str = str.toLowerCase();
|
||||
return capitalize(str, delimiters);
|
||||
}
|
||||
|
||||
public static String uncapitalize(String str) {
|
||||
return uncapitalize(str, null);
|
||||
}
|
||||
|
||||
public static String uncapitalize(String str, char[] delimiters) {
|
||||
int delimLen = (delimiters == null) ? -1 : delimiters.length;
|
||||
if (str == null || str.length() == 0 || delimLen == 0)
|
||||
return str;
|
||||
int strLen = str.length();
|
||||
StringBuffer buffer = new StringBuffer(strLen);
|
||||
boolean uncapitalizeNext = true;
|
||||
for (int i = 0; i < strLen; i++) {
|
||||
char ch = str.charAt(i);
|
||||
if (isDelimiter(ch, delimiters)) {
|
||||
buffer.append(ch);
|
||||
uncapitalizeNext = true;
|
||||
} else if (uncapitalizeNext) {
|
||||
buffer.append(Character.toLowerCase(ch));
|
||||
uncapitalizeNext = false;
|
||||
} else {
|
||||
buffer.append(ch);
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
public static String swapCase(String str) {
|
||||
int strLen;
|
||||
if (str == null || (strLen = str.length()) == 0)
|
||||
return str;
|
||||
StringBuffer buffer = new StringBuffer(strLen);
|
||||
boolean whitespace = true;
|
||||
char ch = '\000';
|
||||
char tmp = '\000';
|
||||
for (int i = 0; i < strLen; i++) {
|
||||
ch = str.charAt(i);
|
||||
if (Character.isUpperCase(ch)) {
|
||||
tmp = Character.toLowerCase(ch);
|
||||
} else if (Character.isTitleCase(ch)) {
|
||||
tmp = Character.toLowerCase(ch);
|
||||
} else if (Character.isLowerCase(ch)) {
|
||||
if (whitespace) {
|
||||
tmp = Character.toTitleCase(ch);
|
||||
} else {
|
||||
tmp = Character.toUpperCase(ch);
|
||||
}
|
||||
} else {
|
||||
tmp = ch;
|
||||
}
|
||||
buffer.append(tmp);
|
||||
whitespace = Character.isWhitespace(ch);
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
public static String initials(String str) {
|
||||
return initials(str, null);
|
||||
}
|
||||
|
||||
public static String initials(String str, char[] delimiters) {
|
||||
if (str == null || str.length() == 0)
|
||||
return str;
|
||||
if (delimiters != null && delimiters.length == 0)
|
||||
return "";
|
||||
int strLen = str.length();
|
||||
char[] buf = new char[strLen / 2 + 1];
|
||||
int count = 0;
|
||||
boolean lastWasGap = true;
|
||||
for (int i = 0; i < strLen; i++) {
|
||||
char ch = str.charAt(i);
|
||||
if (isDelimiter(ch, delimiters)) {
|
||||
lastWasGap = true;
|
||||
} else if (lastWasGap) {
|
||||
buf[count++] = ch;
|
||||
lastWasGap = false;
|
||||
}
|
||||
}
|
||||
return new String(buf, 0, count);
|
||||
}
|
||||
|
||||
private static boolean isDelimiter(char ch, char[] delimiters) {
|
||||
if (delimiters == null)
|
||||
return Character.isWhitespace(ch);
|
||||
for (int i = 0, isize = delimiters.length; i < isize; i++) {
|
||||
if (ch == delimiters[i])
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static String abbreviate(String str, int lower, int upper, String appendToEnd) {
|
||||
if (str == null)
|
||||
return null;
|
||||
if (str.length() == 0)
|
||||
return "";
|
||||
if (upper == -1 || upper > str.length())
|
||||
upper = str.length();
|
||||
if (upper < lower)
|
||||
upper = lower;
|
||||
StringBuffer result = new StringBuffer();
|
||||
int index = StringUtils.indexOf(str, " ", lower);
|
||||
if (index == -1) {
|
||||
result.append(str.substring(0, upper));
|
||||
if (upper != str.length())
|
||||
result.append(StringUtils.defaultString(appendToEnd));
|
||||
} else if (index > upper) {
|
||||
result.append(str.substring(0, upper));
|
||||
result.append(StringUtils.defaultString(appendToEnd));
|
||||
} else {
|
||||
result.append(str.substring(0, index));
|
||||
result.append(StringUtils.defaultString(appendToEnd));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,387 @@
|
|||
package org.apache.commons.lang.builder;
|
||||
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang.math.NumberUtils;
|
||||
|
||||
public class CompareToBuilder {
|
||||
private int comparison = 0;
|
||||
|
||||
public static int reflectionCompare(Object lhs, Object rhs) {
|
||||
return reflectionCompare(lhs, rhs, false, null, null);
|
||||
}
|
||||
|
||||
public static int reflectionCompare(Object lhs, Object rhs, boolean compareTransients) {
|
||||
return reflectionCompare(lhs, rhs, compareTransients, null, null);
|
||||
}
|
||||
|
||||
public static int reflectionCompare(Object lhs, Object rhs, Collection excludeFields) {
|
||||
return reflectionCompare(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
|
||||
}
|
||||
|
||||
public static int reflectionCompare(Object lhs, Object rhs, String[] excludeFields) {
|
||||
return reflectionCompare(lhs, rhs, false, null, excludeFields);
|
||||
}
|
||||
|
||||
public static int reflectionCompare(Object lhs, Object rhs, boolean compareTransients, Class reflectUpToClass) {
|
||||
return reflectionCompare(lhs, rhs, false, reflectUpToClass, null);
|
||||
}
|
||||
|
||||
public static int reflectionCompare(Object lhs, Object rhs, boolean compareTransients, Class reflectUpToClass, String[] excludeFields) {
|
||||
if (lhs == rhs)
|
||||
return 0;
|
||||
if (lhs == null || rhs == null)
|
||||
throw new NullPointerException();
|
||||
Class lhsClazz = lhs.getClass();
|
||||
if (!lhsClazz.isInstance(rhs))
|
||||
throw new ClassCastException();
|
||||
CompareToBuilder compareToBuilder = new CompareToBuilder();
|
||||
reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields);
|
||||
while (lhsClazz.getSuperclass() != null && lhsClazz != reflectUpToClass) {
|
||||
lhsClazz = lhsClazz.getSuperclass();
|
||||
reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields);
|
||||
}
|
||||
return compareToBuilder.toComparison();
|
||||
}
|
||||
|
||||
private static void reflectionAppend(Object lhs, Object rhs, Class clazz, CompareToBuilder builder, boolean useTransients, String[] excludeFields) {
|
||||
Field[] fields = clazz.getDeclaredFields();
|
||||
List excludedFieldList = (excludeFields != null) ? Arrays.asList(excludeFields) : Collections.EMPTY_LIST;
|
||||
AccessibleObject.setAccessible(fields, true);
|
||||
for (int i = 0; i < fields.length && builder.comparison == 0; i++) {
|
||||
Field f = fields[i];
|
||||
if (!excludedFieldList.contains(f.getName()) && f.getName().indexOf('$') == -1 && (useTransients || !Modifier.isTransient(f.getModifiers())) && !Modifier.isStatic(f.getModifiers()))
|
||||
try {
|
||||
builder.append(f.get(lhs), f.get(rhs));
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new InternalError("Unexpected IllegalAccessException");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CompareToBuilder appendSuper(int superCompareTo) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
this.comparison = superCompareTo;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(Object lhs, Object rhs) {
|
||||
return append(lhs, rhs, null);
|
||||
}
|
||||
|
||||
public CompareToBuilder append(Object lhs, Object rhs, Comparator comparator) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null) {
|
||||
this.comparison = -1;
|
||||
return this;
|
||||
}
|
||||
if (rhs == null) {
|
||||
this.comparison = 1;
|
||||
return this;
|
||||
}
|
||||
if (lhs.getClass().isArray()) {
|
||||
if (lhs instanceof long[]) {
|
||||
append((long[])lhs, (long[])rhs);
|
||||
} else if (lhs instanceof int[]) {
|
||||
append((int[])lhs, (int[])rhs);
|
||||
} else if (lhs instanceof short[]) {
|
||||
append((short[])lhs, (short[])rhs);
|
||||
} else if (lhs instanceof char[]) {
|
||||
append((char[])lhs, (char[])rhs);
|
||||
} else if (lhs instanceof byte[]) {
|
||||
append((byte[])lhs, (byte[])rhs);
|
||||
} else if (lhs instanceof double[]) {
|
||||
append((double[])lhs, (double[])rhs);
|
||||
} else if (lhs instanceof float[]) {
|
||||
append((float[])lhs, (float[])rhs);
|
||||
} else if (lhs instanceof boolean[]) {
|
||||
append((boolean[])lhs, (boolean[])rhs);
|
||||
} else {
|
||||
append((Object[])lhs, (Object[])rhs, comparator);
|
||||
}
|
||||
} else if (comparator == null) {
|
||||
this.comparison = ((Comparable)lhs).compareTo(rhs);
|
||||
} else {
|
||||
this.comparison = comparator.compare(lhs, rhs);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(long lhs, long rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
this.comparison = (lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(int lhs, int rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
this.comparison = (lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(short lhs, short rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
this.comparison = (lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(char lhs, char rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
this.comparison = (lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(byte lhs, byte rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
this.comparison = (lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(double lhs, double rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
this.comparison = NumberUtils.compare(lhs, rhs);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(float lhs, float rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
this.comparison = NumberUtils.compare(lhs, rhs);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(boolean lhs, boolean rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (!lhs) {
|
||||
this.comparison = -1;
|
||||
} else {
|
||||
this.comparison = 1;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(Object[] lhs, Object[] rhs) {
|
||||
return append(lhs, rhs, (Comparator)null);
|
||||
}
|
||||
|
||||
public CompareToBuilder append(Object[] lhs, Object[] rhs, Comparator comparator) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null) {
|
||||
this.comparison = -1;
|
||||
return this;
|
||||
}
|
||||
if (rhs == null) {
|
||||
this.comparison = 1;
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
this.comparison = (lhs.length < rhs.length) ? -1 : 1;
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.comparison == 0; i++)
|
||||
append(lhs[i], rhs[i], comparator);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(long[] lhs, long[] rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null) {
|
||||
this.comparison = -1;
|
||||
return this;
|
||||
}
|
||||
if (rhs == null) {
|
||||
this.comparison = 1;
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
this.comparison = (lhs.length < rhs.length) ? -1 : 1;
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.comparison == 0; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(int[] lhs, int[] rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null) {
|
||||
this.comparison = -1;
|
||||
return this;
|
||||
}
|
||||
if (rhs == null) {
|
||||
this.comparison = 1;
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
this.comparison = (lhs.length < rhs.length) ? -1 : 1;
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.comparison == 0; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(short[] lhs, short[] rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null) {
|
||||
this.comparison = -1;
|
||||
return this;
|
||||
}
|
||||
if (rhs == null) {
|
||||
this.comparison = 1;
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
this.comparison = (lhs.length < rhs.length) ? -1 : 1;
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.comparison == 0; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(char[] lhs, char[] rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null) {
|
||||
this.comparison = -1;
|
||||
return this;
|
||||
}
|
||||
if (rhs == null) {
|
||||
this.comparison = 1;
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
this.comparison = (lhs.length < rhs.length) ? -1 : 1;
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.comparison == 0; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(byte[] lhs, byte[] rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null) {
|
||||
this.comparison = -1;
|
||||
return this;
|
||||
}
|
||||
if (rhs == null) {
|
||||
this.comparison = 1;
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
this.comparison = (lhs.length < rhs.length) ? -1 : 1;
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.comparison == 0; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(double[] lhs, double[] rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null) {
|
||||
this.comparison = -1;
|
||||
return this;
|
||||
}
|
||||
if (rhs == null) {
|
||||
this.comparison = 1;
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
this.comparison = (lhs.length < rhs.length) ? -1 : 1;
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.comparison == 0; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(float[] lhs, float[] rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null) {
|
||||
this.comparison = -1;
|
||||
return this;
|
||||
}
|
||||
if (rhs == null) {
|
||||
this.comparison = 1;
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
this.comparison = (lhs.length < rhs.length) ? -1 : 1;
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.comparison == 0; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public CompareToBuilder append(boolean[] lhs, boolean[] rhs) {
|
||||
if (this.comparison != 0)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null) {
|
||||
this.comparison = -1;
|
||||
return this;
|
||||
}
|
||||
if (rhs == null) {
|
||||
this.comparison = 1;
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
this.comparison = (lhs.length < rhs.length) ? -1 : 1;
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.comparison == 0; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public int toComparison() {
|
||||
return this.comparison;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,352 @@
|
|||
package org.apache.commons.lang.builder;
|
||||
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class EqualsBuilder {
|
||||
private boolean isEquals = true;
|
||||
|
||||
public static boolean reflectionEquals(Object lhs, Object rhs) {
|
||||
return reflectionEquals(lhs, rhs, false, null, null);
|
||||
}
|
||||
|
||||
public static boolean reflectionEquals(Object lhs, Object rhs, Collection excludeFields) {
|
||||
return reflectionEquals(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
|
||||
}
|
||||
|
||||
public static boolean reflectionEquals(Object lhs, Object rhs, String[] excludeFields) {
|
||||
return reflectionEquals(lhs, rhs, false, null, excludeFields);
|
||||
}
|
||||
|
||||
public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients) {
|
||||
return reflectionEquals(lhs, rhs, testTransients, null, null);
|
||||
}
|
||||
|
||||
public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class reflectUpToClass) {
|
||||
return reflectionEquals(lhs, rhs, testTransients, reflectUpToClass, null);
|
||||
}
|
||||
|
||||
public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class reflectUpToClass, String[] excludeFields) {
|
||||
Class testClass;
|
||||
if (lhs == rhs)
|
||||
return true;
|
||||
if (lhs == null || rhs == null)
|
||||
return false;
|
||||
Class lhsClass = lhs.getClass();
|
||||
Class rhsClass = rhs.getClass();
|
||||
if (lhsClass.isInstance(rhs)) {
|
||||
testClass = lhsClass;
|
||||
if (!rhsClass.isInstance(lhs))
|
||||
testClass = rhsClass;
|
||||
} else if (rhsClass.isInstance(lhs)) {
|
||||
testClass = rhsClass;
|
||||
if (!lhsClass.isInstance(rhs))
|
||||
testClass = lhsClass;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
EqualsBuilder equalsBuilder = new EqualsBuilder();
|
||||
try {
|
||||
reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields);
|
||||
while (testClass.getSuperclass() != null && testClass != reflectUpToClass) {
|
||||
testClass = testClass.getSuperclass();
|
||||
reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields);
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
return equalsBuilder.isEquals();
|
||||
}
|
||||
|
||||
private static void reflectionAppend(Object lhs, Object rhs, Class clazz, EqualsBuilder builder, boolean useTransients, String[] excludeFields) {
|
||||
Field[] fields = clazz.getDeclaredFields();
|
||||
List excludedFieldList = (excludeFields != null) ? Arrays.asList(excludeFields) : Collections.EMPTY_LIST;
|
||||
AccessibleObject.setAccessible(fields, true);
|
||||
for (int i = 0; i < fields.length && builder.isEquals; i++) {
|
||||
Field f = fields[i];
|
||||
if (!excludedFieldList.contains(f.getName()) && f.getName().indexOf('$') == -1 && (useTransients || !Modifier.isTransient(f.getModifiers())) && !Modifier.isStatic(f.getModifiers()))
|
||||
try {
|
||||
builder.append(f.get(lhs), f.get(rhs));
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new InternalError("Unexpected IllegalAccessException");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public EqualsBuilder appendSuper(boolean superEquals) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
this.isEquals = superEquals;
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(Object lhs, Object rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null || rhs == null) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
Class lhsClass = lhs.getClass();
|
||||
if (!lhsClass.isArray()) {
|
||||
if (lhs instanceof BigDecimal) {
|
||||
this.isEquals = (((BigDecimal)lhs).compareTo((BigDecimal)rhs) == 0);
|
||||
} else {
|
||||
this.isEquals = lhs.equals(rhs);
|
||||
}
|
||||
} else if (lhs.getClass() != rhs.getClass()) {
|
||||
setEquals(false);
|
||||
} else if (lhs instanceof long[]) {
|
||||
append((long[])lhs, (long[])rhs);
|
||||
} else if (lhs instanceof int[]) {
|
||||
append((int[])lhs, (int[])rhs);
|
||||
} else if (lhs instanceof short[]) {
|
||||
append((short[])lhs, (short[])rhs);
|
||||
} else if (lhs instanceof char[]) {
|
||||
append((char[])lhs, (char[])rhs);
|
||||
} else if (lhs instanceof byte[]) {
|
||||
append((byte[])lhs, (byte[])rhs);
|
||||
} else if (lhs instanceof double[]) {
|
||||
append((double[])lhs, (double[])rhs);
|
||||
} else if (lhs instanceof float[]) {
|
||||
append((float[])lhs, (float[])rhs);
|
||||
} else if (lhs instanceof boolean[]) {
|
||||
append((boolean[])lhs, (boolean[])rhs);
|
||||
} else {
|
||||
append((Object[])lhs, (Object[])rhs);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(long lhs, long rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
this.isEquals = (lhs == rhs);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(int lhs, int rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
this.isEquals = (lhs == rhs);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(short lhs, short rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
this.isEquals = (lhs == rhs);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(char lhs, char rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
this.isEquals = (lhs == rhs);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(byte lhs, byte rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
this.isEquals = (lhs == rhs);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(double lhs, double rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
return append(Double.doubleToLongBits(lhs), Double.doubleToLongBits(rhs));
|
||||
}
|
||||
|
||||
public EqualsBuilder append(float lhs, float rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
return append(Float.floatToIntBits(lhs), Float.floatToIntBits(rhs));
|
||||
}
|
||||
|
||||
public EqualsBuilder append(boolean lhs, boolean rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
this.isEquals = (lhs == rhs);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(Object[] lhs, Object[] rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null || rhs == null) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.isEquals; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(long[] lhs, long[] rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null || rhs == null) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.isEquals; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(int[] lhs, int[] rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null || rhs == null) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.isEquals; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(short[] lhs, short[] rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null || rhs == null) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.isEquals; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(char[] lhs, char[] rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null || rhs == null) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.isEquals; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(byte[] lhs, byte[] rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null || rhs == null) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.isEquals; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(double[] lhs, double[] rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null || rhs == null) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.isEquals; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(float[] lhs, float[] rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null || rhs == null) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.isEquals; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EqualsBuilder append(boolean[] lhs, boolean[] rhs) {
|
||||
if (!this.isEquals)
|
||||
return this;
|
||||
if (lhs == rhs)
|
||||
return this;
|
||||
if (lhs == null || rhs == null) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
if (lhs.length != rhs.length) {
|
||||
setEquals(false);
|
||||
return this;
|
||||
}
|
||||
for (int i = 0; i < lhs.length && this.isEquals; i++)
|
||||
append(lhs[i], rhs[i]);
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isEquals() {
|
||||
return this.isEquals;
|
||||
}
|
||||
|
||||
protected void setEquals(boolean isEquals) {
|
||||
this.isEquals = isEquals;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,290 @@
|
|||
package org.apache.commons.lang.builder;
|
||||
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class HashCodeBuilder {
|
||||
private static ThreadLocal registry = new ThreadLocal() {
|
||||
protected Object initialValue() {
|
||||
return new HashSet();
|
||||
}
|
||||
};
|
||||
|
||||
private final int iConstant;
|
||||
|
||||
static Set getRegistry() {
|
||||
return (Set)registry.get();
|
||||
}
|
||||
|
||||
static boolean isRegistered(Object value) {
|
||||
return getRegistry().contains(toIdentityHashCodeInteger(value));
|
||||
}
|
||||
|
||||
private static void reflectionAppend(Object object, Class clazz, HashCodeBuilder builder, boolean useTransients, String[] excludeFields) {
|
||||
if (isRegistered(object))
|
||||
return;
|
||||
try {
|
||||
register(object);
|
||||
Field[] fields = clazz.getDeclaredFields();
|
||||
List excludedFieldList = (excludeFields != null) ? Arrays.asList(excludeFields) : Collections.EMPTY_LIST;
|
||||
AccessibleObject.setAccessible(fields, true);
|
||||
for (int i = 0; i < fields.length; i++) {
|
||||
Field field = fields[i];
|
||||
if (!excludedFieldList.contains(field.getName()) && field.getName().indexOf('$') == -1 && (useTransients || !Modifier.isTransient(field.getModifiers())) && !Modifier.isStatic(field.getModifiers()))
|
||||
try {
|
||||
Object fieldValue = field.get(object);
|
||||
builder.append(fieldValue);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new InternalError("Unexpected IllegalAccessException");
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
unregister(object);
|
||||
}
|
||||
}
|
||||
|
||||
public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object) {
|
||||
return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, false, null, null);
|
||||
}
|
||||
|
||||
public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object, boolean testTransients) {
|
||||
return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, testTransients, null, null);
|
||||
}
|
||||
|
||||
public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object, boolean testTransients, Class reflectUpToClass) {
|
||||
return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, testTransients, reflectUpToClass, null);
|
||||
}
|
||||
|
||||
public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object, boolean testTransients, Class reflectUpToClass, String[] excludeFields) {
|
||||
if (object == null)
|
||||
throw new IllegalArgumentException("The object to build a hash code for must not be null");
|
||||
HashCodeBuilder builder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
|
||||
Class clazz = object.getClass();
|
||||
reflectionAppend(object, clazz, builder, testTransients, excludeFields);
|
||||
while (clazz.getSuperclass() != null && clazz != reflectUpToClass) {
|
||||
clazz = clazz.getSuperclass();
|
||||
reflectionAppend(object, clazz, builder, testTransients, excludeFields);
|
||||
}
|
||||
return builder.toHashCode();
|
||||
}
|
||||
|
||||
public static int reflectionHashCode(Object object) {
|
||||
return reflectionHashCode(17, 37, object, false, null, null);
|
||||
}
|
||||
|
||||
public static int reflectionHashCode(Object object, boolean testTransients) {
|
||||
return reflectionHashCode(17, 37, object, testTransients, null, null);
|
||||
}
|
||||
|
||||
public static int reflectionHashCode(Object object, Collection excludeFields) {
|
||||
return reflectionHashCode(object, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
|
||||
}
|
||||
|
||||
public static int reflectionHashCode(Object object, String[] excludeFields) {
|
||||
return reflectionHashCode(17, 37, object, false, null, excludeFields);
|
||||
}
|
||||
|
||||
static void register(Object value) {
|
||||
getRegistry().add(toIdentityHashCodeInteger(value));
|
||||
}
|
||||
|
||||
private static Integer toIdentityHashCodeInteger(Object value) {
|
||||
return new Integer(System.identityHashCode(value));
|
||||
}
|
||||
|
||||
static void unregister(Object value) {
|
||||
getRegistry().remove(toIdentityHashCodeInteger(value));
|
||||
}
|
||||
|
||||
private int iTotal = 0;
|
||||
|
||||
public HashCodeBuilder() {
|
||||
this.iConstant = 37;
|
||||
this.iTotal = 17;
|
||||
}
|
||||
|
||||
public HashCodeBuilder(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber) {
|
||||
if (initialNonZeroOddNumber == 0)
|
||||
throw new IllegalArgumentException("HashCodeBuilder requires a non zero initial value");
|
||||
if (initialNonZeroOddNumber % 2 == 0)
|
||||
throw new IllegalArgumentException("HashCodeBuilder requires an odd initial value");
|
||||
if (multiplierNonZeroOddNumber == 0)
|
||||
throw new IllegalArgumentException("HashCodeBuilder requires a non zero multiplier");
|
||||
if (multiplierNonZeroOddNumber % 2 == 0)
|
||||
throw new IllegalArgumentException("HashCodeBuilder requires an odd multiplier");
|
||||
this.iConstant = multiplierNonZeroOddNumber;
|
||||
this.iTotal = initialNonZeroOddNumber;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(boolean value) {
|
||||
this.iTotal = this.iTotal * this.iConstant + (value ? 0 : 1);
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(boolean[] array) {
|
||||
if (array == null) {
|
||||
this.iTotal *= this.iConstant;
|
||||
} else {
|
||||
for (int i = 0; i < array.length; i++)
|
||||
append(array[i]);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(byte value) {
|
||||
this.iTotal = this.iTotal * this.iConstant + value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(byte[] array) {
|
||||
if (array == null) {
|
||||
this.iTotal *= this.iConstant;
|
||||
} else {
|
||||
for (int i = 0; i < array.length; i++)
|
||||
append(array[i]);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(char value) {
|
||||
this.iTotal = this.iTotal * this.iConstant + value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(char[] array) {
|
||||
if (array == null) {
|
||||
this.iTotal *= this.iConstant;
|
||||
} else {
|
||||
for (int i = 0; i < array.length; i++)
|
||||
append(array[i]);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(double value) {
|
||||
return append(Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(double[] array) {
|
||||
if (array == null) {
|
||||
this.iTotal *= this.iConstant;
|
||||
} else {
|
||||
for (int i = 0; i < array.length; i++)
|
||||
append(array[i]);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(float value) {
|
||||
this.iTotal = this.iTotal * this.iConstant + Float.floatToIntBits(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(float[] array) {
|
||||
if (array == null) {
|
||||
this.iTotal *= this.iConstant;
|
||||
} else {
|
||||
for (int i = 0; i < array.length; i++)
|
||||
append(array[i]);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(int value) {
|
||||
this.iTotal = this.iTotal * this.iConstant + value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(int[] array) {
|
||||
if (array == null) {
|
||||
this.iTotal *= this.iConstant;
|
||||
} else {
|
||||
for (int i = 0; i < array.length; i++)
|
||||
append(array[i]);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(long value) {
|
||||
this.iTotal = this.iTotal * this.iConstant + (int)(value ^ value >> 32L);
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(long[] array) {
|
||||
if (array == null) {
|
||||
this.iTotal *= this.iConstant;
|
||||
} else {
|
||||
for (int i = 0; i < array.length; i++)
|
||||
append(array[i]);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(Object object) {
|
||||
if (object == null) {
|
||||
this.iTotal *= this.iConstant;
|
||||
} else if (object instanceof long[]) {
|
||||
append((long[])object);
|
||||
} else if (object instanceof int[]) {
|
||||
append((int[])object);
|
||||
} else if (object instanceof short[]) {
|
||||
append((short[])object);
|
||||
} else if (object instanceof char[]) {
|
||||
append((char[])object);
|
||||
} else if (object instanceof byte[]) {
|
||||
append((byte[])object);
|
||||
} else if (object instanceof double[]) {
|
||||
append((double[])object);
|
||||
} else if (object instanceof float[]) {
|
||||
append((float[])object);
|
||||
} else if (object instanceof boolean[]) {
|
||||
append((boolean[])object);
|
||||
} else if (object instanceof Object[]) {
|
||||
append((Object[])object);
|
||||
} else {
|
||||
this.iTotal = this.iTotal * this.iConstant + object.hashCode();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(Object[] array) {
|
||||
if (array == null) {
|
||||
this.iTotal *= this.iConstant;
|
||||
} else {
|
||||
for (int i = 0; i < array.length; i++)
|
||||
append(array[i]);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(short value) {
|
||||
this.iTotal = this.iTotal * this.iConstant + value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder append(short[] array) {
|
||||
if (array == null) {
|
||||
this.iTotal *= this.iConstant;
|
||||
} else {
|
||||
for (int i = 0; i < array.length; i++)
|
||||
append(array[i]);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public HashCodeBuilder appendSuper(int superHashCode) {
|
||||
this.iTotal = this.iTotal * this.iConstant + superHashCode;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int toHashCode() {
|
||||
return this.iTotal;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,187 @@
|
|||
package org.apache.commons.lang.builder;
|
||||
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import org.apache.commons.lang.ArrayUtils;
|
||||
|
||||
public class ReflectionToStringBuilder extends ToStringBuilder {
|
||||
public static String toString(Object object) {
|
||||
return toString(object, null, false, false, null);
|
||||
}
|
||||
|
||||
public static String toString(Object object, ToStringStyle style) {
|
||||
return toString(object, style, false, false, null);
|
||||
}
|
||||
|
||||
public static String toString(Object object, ToStringStyle style, boolean outputTransients) {
|
||||
return toString(object, style, outputTransients, false, null);
|
||||
}
|
||||
|
||||
public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics) {
|
||||
return toString(object, style, outputTransients, outputStatics, null);
|
||||
}
|
||||
|
||||
public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics, Class reflectUpToClass) {
|
||||
return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics).toString();
|
||||
}
|
||||
|
||||
public static String toString(Object object, ToStringStyle style, boolean outputTransients, Class reflectUpToClass) {
|
||||
return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients).toString();
|
||||
}
|
||||
|
||||
public static String toStringExclude(Object object, String excludeFieldName) {
|
||||
return toStringExclude(object, new String[] { excludeFieldName });
|
||||
}
|
||||
|
||||
public static String toStringExclude(Object object, Collection excludeFieldNames) {
|
||||
return toStringExclude(object, toNoNullStringArray(excludeFieldNames));
|
||||
}
|
||||
|
||||
static String[] toNoNullStringArray(Collection collection) {
|
||||
if (collection == null)
|
||||
return ArrayUtils.EMPTY_STRING_ARRAY;
|
||||
return toNoNullStringArray(collection.toArray());
|
||||
}
|
||||
|
||||
static String[] toNoNullStringArray(Object[] array) {
|
||||
ArrayList list = new ArrayList(array.length);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
Object e = array[i];
|
||||
if (e != null)
|
||||
list.add(e.toString());
|
||||
}
|
||||
return (String[])list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
|
||||
}
|
||||
|
||||
public static String toStringExclude(Object object, String[] excludeFieldNames) {
|
||||
return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString();
|
||||
}
|
||||
|
||||
private boolean appendStatics = false;
|
||||
|
||||
private boolean appendTransients = false;
|
||||
|
||||
private String[] excludeFieldNames;
|
||||
|
||||
private Class upToClass = null;
|
||||
|
||||
public ReflectionToStringBuilder(Object object) {
|
||||
super(object);
|
||||
}
|
||||
|
||||
public ReflectionToStringBuilder(Object object, ToStringStyle style) {
|
||||
super(object, style);
|
||||
}
|
||||
|
||||
public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {
|
||||
super(object, style, buffer);
|
||||
}
|
||||
|
||||
public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer, Class reflectUpToClass, boolean outputTransients) {
|
||||
super(object, style, buffer);
|
||||
setUpToClass(reflectUpToClass);
|
||||
setAppendTransients(outputTransients);
|
||||
}
|
||||
|
||||
public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer, Class reflectUpToClass, boolean outputTransients, boolean outputStatics) {
|
||||
super(object, style, buffer);
|
||||
setUpToClass(reflectUpToClass);
|
||||
setAppendTransients(outputTransients);
|
||||
setAppendStatics(outputStatics);
|
||||
}
|
||||
|
||||
protected boolean accept(Field field) {
|
||||
if (field.getName().indexOf('$') != -1)
|
||||
return false;
|
||||
if (Modifier.isTransient(field.getModifiers()) && !isAppendTransients())
|
||||
return false;
|
||||
if (Modifier.isStatic(field.getModifiers()) && !isAppendStatics())
|
||||
return false;
|
||||
if (getExcludeFieldNames() != null && Arrays.binarySearch(getExcludeFieldNames(), field.getName()) >= 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected void appendFieldsIn(Class clazz) {
|
||||
if (clazz.isArray()) {
|
||||
reflectionAppendArray(getObject());
|
||||
return;
|
||||
}
|
||||
Field[] fields = clazz.getDeclaredFields();
|
||||
AccessibleObject.setAccessible(fields, true);
|
||||
for (int i = 0; i < fields.length; i++) {
|
||||
Field field = fields[i];
|
||||
String fieldName = field.getName();
|
||||
if (accept(field))
|
||||
try {
|
||||
Object fieldValue = getValue(field);
|
||||
append(fieldName, fieldValue);
|
||||
} catch (IllegalAccessException ex) {
|
||||
throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String[] getExcludeFieldNames() {
|
||||
return this.excludeFieldNames;
|
||||
}
|
||||
|
||||
public Class getUpToClass() {
|
||||
return this.upToClass;
|
||||
}
|
||||
|
||||
protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException {
|
||||
return field.get(getObject());
|
||||
}
|
||||
|
||||
public boolean isAppendStatics() {
|
||||
return this.appendStatics;
|
||||
}
|
||||
|
||||
public boolean isAppendTransients() {
|
||||
return this.appendTransients;
|
||||
}
|
||||
|
||||
public ToStringBuilder reflectionAppendArray(Object array) {
|
||||
getStyle().reflectionAppendArrayDetail(getStringBuffer(), null, array);
|
||||
return this;
|
||||
}
|
||||
|
||||
public void setAppendStatics(boolean appendStatics) {
|
||||
this.appendStatics = appendStatics;
|
||||
}
|
||||
|
||||
public void setAppendTransients(boolean appendTransients) {
|
||||
this.appendTransients = appendTransients;
|
||||
}
|
||||
|
||||
public ReflectionToStringBuilder setExcludeFieldNames(String[] excludeFieldNamesParam) {
|
||||
if (excludeFieldNamesParam == null) {
|
||||
this.excludeFieldNames = null;
|
||||
} else {
|
||||
this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam);
|
||||
Arrays.sort(this.excludeFieldNames);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public void setUpToClass(Class clazz) {
|
||||
this.upToClass = clazz;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (getObject() == null)
|
||||
return getStyle().getNullText();
|
||||
Class clazz = getObject().getClass();
|
||||
appendFieldsIn(clazz);
|
||||
while (clazz.getSuperclass() != null && clazz != getUpToClass()) {
|
||||
clazz = clazz.getSuperclass();
|
||||
appendFieldsIn(clazz);
|
||||
}
|
||||
return super.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,173 @@
|
|||
package org.apache.commons.lang.builder;
|
||||
|
||||
public class StandardToStringStyle extends ToStringStyle {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public boolean isUseClassName() {
|
||||
return super.isUseClassName();
|
||||
}
|
||||
|
||||
public void setUseClassName(boolean useClassName) {
|
||||
super.setUseClassName(useClassName);
|
||||
}
|
||||
|
||||
public boolean isUseShortClassName() {
|
||||
return super.isUseShortClassName();
|
||||
}
|
||||
|
||||
public boolean isShortClassName() {
|
||||
return super.isUseShortClassName();
|
||||
}
|
||||
|
||||
public void setUseShortClassName(boolean useShortClassName) {
|
||||
super.setUseShortClassName(useShortClassName);
|
||||
}
|
||||
|
||||
public void setShortClassName(boolean shortClassName) {
|
||||
super.setUseShortClassName(shortClassName);
|
||||
}
|
||||
|
||||
public boolean isUseIdentityHashCode() {
|
||||
return super.isUseIdentityHashCode();
|
||||
}
|
||||
|
||||
public void setUseIdentityHashCode(boolean useIdentityHashCode) {
|
||||
super.setUseIdentityHashCode(useIdentityHashCode);
|
||||
}
|
||||
|
||||
public boolean isUseFieldNames() {
|
||||
return super.isUseFieldNames();
|
||||
}
|
||||
|
||||
public void setUseFieldNames(boolean useFieldNames) {
|
||||
super.setUseFieldNames(useFieldNames);
|
||||
}
|
||||
|
||||
public boolean isDefaultFullDetail() {
|
||||
return super.isDefaultFullDetail();
|
||||
}
|
||||
|
||||
public void setDefaultFullDetail(boolean defaultFullDetail) {
|
||||
super.setDefaultFullDetail(defaultFullDetail);
|
||||
}
|
||||
|
||||
public boolean isArrayContentDetail() {
|
||||
return super.isArrayContentDetail();
|
||||
}
|
||||
|
||||
public void setArrayContentDetail(boolean arrayContentDetail) {
|
||||
super.setArrayContentDetail(arrayContentDetail);
|
||||
}
|
||||
|
||||
public String getArrayStart() {
|
||||
return super.getArrayStart();
|
||||
}
|
||||
|
||||
public void setArrayStart(String arrayStart) {
|
||||
super.setArrayStart(arrayStart);
|
||||
}
|
||||
|
||||
public String getArrayEnd() {
|
||||
return super.getArrayEnd();
|
||||
}
|
||||
|
||||
public void setArrayEnd(String arrayEnd) {
|
||||
super.setArrayEnd(arrayEnd);
|
||||
}
|
||||
|
||||
public String getArraySeparator() {
|
||||
return super.getArraySeparator();
|
||||
}
|
||||
|
||||
public void setArraySeparator(String arraySeparator) {
|
||||
super.setArraySeparator(arraySeparator);
|
||||
}
|
||||
|
||||
public String getContentStart() {
|
||||
return super.getContentStart();
|
||||
}
|
||||
|
||||
public void setContentStart(String contentStart) {
|
||||
super.setContentStart(contentStart);
|
||||
}
|
||||
|
||||
public String getContentEnd() {
|
||||
return super.getContentEnd();
|
||||
}
|
||||
|
||||
public void setContentEnd(String contentEnd) {
|
||||
super.setContentEnd(contentEnd);
|
||||
}
|
||||
|
||||
public String getFieldNameValueSeparator() {
|
||||
return super.getFieldNameValueSeparator();
|
||||
}
|
||||
|
||||
public void setFieldNameValueSeparator(String fieldNameValueSeparator) {
|
||||
super.setFieldNameValueSeparator(fieldNameValueSeparator);
|
||||
}
|
||||
|
||||
public String getFieldSeparator() {
|
||||
return super.getFieldSeparator();
|
||||
}
|
||||
|
||||
public void setFieldSeparator(String fieldSeparator) {
|
||||
super.setFieldSeparator(fieldSeparator);
|
||||
}
|
||||
|
||||
public boolean isFieldSeparatorAtStart() {
|
||||
return super.isFieldSeparatorAtStart();
|
||||
}
|
||||
|
||||
public void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) {
|
||||
super.setFieldSeparatorAtStart(fieldSeparatorAtStart);
|
||||
}
|
||||
|
||||
public boolean isFieldSeparatorAtEnd() {
|
||||
return super.isFieldSeparatorAtEnd();
|
||||
}
|
||||
|
||||
public void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) {
|
||||
super.setFieldSeparatorAtEnd(fieldSeparatorAtEnd);
|
||||
}
|
||||
|
||||
public String getNullText() {
|
||||
return super.getNullText();
|
||||
}
|
||||
|
||||
public void setNullText(String nullText) {
|
||||
super.setNullText(nullText);
|
||||
}
|
||||
|
||||
public String getSizeStartText() {
|
||||
return super.getSizeStartText();
|
||||
}
|
||||
|
||||
public void setSizeStartText(String sizeStartText) {
|
||||
super.setSizeStartText(sizeStartText);
|
||||
}
|
||||
|
||||
public String getSizeEndText() {
|
||||
return super.getSizeEndText();
|
||||
}
|
||||
|
||||
public void setSizeEndText(String sizeEndText) {
|
||||
super.setSizeEndText(sizeEndText);
|
||||
}
|
||||
|
||||
public String getSummaryObjectStartText() {
|
||||
return super.getSummaryObjectStartText();
|
||||
}
|
||||
|
||||
public void setSummaryObjectStartText(String summaryObjectStartText) {
|
||||
super.setSummaryObjectStartText(summaryObjectStartText);
|
||||
}
|
||||
|
||||
public String getSummaryObjectEndText() {
|
||||
return super.getSummaryObjectEndText();
|
||||
}
|
||||
|
||||
public void setSummaryObjectEndText(String summaryObjectEndText) {
|
||||
super.setSummaryObjectEndText(summaryObjectEndText);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,327 @@
|
|||
package org.apache.commons.lang.builder;
|
||||
|
||||
import org.apache.commons.lang.BooleanUtils;
|
||||
import org.apache.commons.lang.ObjectUtils;
|
||||
|
||||
public class ToStringBuilder {
|
||||
private static ToStringStyle defaultStyle = ToStringStyle.DEFAULT_STYLE;
|
||||
|
||||
private final StringBuffer buffer;
|
||||
|
||||
private final Object object;
|
||||
|
||||
private final ToStringStyle style;
|
||||
|
||||
public static ToStringStyle getDefaultStyle() {
|
||||
return defaultStyle;
|
||||
}
|
||||
|
||||
public static String reflectionToString(Object object) {
|
||||
return ReflectionToStringBuilder.toString(object);
|
||||
}
|
||||
|
||||
public static String reflectionToString(Object object, ToStringStyle style) {
|
||||
return ReflectionToStringBuilder.toString(object, style);
|
||||
}
|
||||
|
||||
public static String reflectionToString(Object object, ToStringStyle style, boolean outputTransients) {
|
||||
return ReflectionToStringBuilder.toString(object, style, outputTransients, false, null);
|
||||
}
|
||||
|
||||
public static String reflectionToString(Object object, ToStringStyle style, boolean outputTransients, Class reflectUpToClass) {
|
||||
return ReflectionToStringBuilder.toString(object, style, outputTransients, false, reflectUpToClass);
|
||||
}
|
||||
|
||||
public static void setDefaultStyle(ToStringStyle style) {
|
||||
if (style == null)
|
||||
throw new IllegalArgumentException("The style must not be null");
|
||||
defaultStyle = style;
|
||||
}
|
||||
|
||||
public ToStringBuilder(Object object) {
|
||||
this(object, getDefaultStyle(), null);
|
||||
}
|
||||
|
||||
public ToStringBuilder(Object object, ToStringStyle style) {
|
||||
this(object, style, null);
|
||||
}
|
||||
|
||||
public ToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {
|
||||
if (style == null)
|
||||
style = getDefaultStyle();
|
||||
if (buffer == null)
|
||||
buffer = new StringBuffer(512);
|
||||
this.buffer = buffer;
|
||||
this.style = style;
|
||||
this.object = object;
|
||||
style.appendStart(buffer, object);
|
||||
}
|
||||
|
||||
public ToStringBuilder append(boolean value) {
|
||||
this.style.append(this.buffer, (String)null, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(boolean[] array) {
|
||||
this.style.append(this.buffer, (String)null, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(byte value) {
|
||||
this.style.append(this.buffer, (String)null, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(byte[] array) {
|
||||
this.style.append(this.buffer, (String)null, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(char value) {
|
||||
this.style.append(this.buffer, (String)null, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(char[] array) {
|
||||
this.style.append(this.buffer, (String)null, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(double value) {
|
||||
this.style.append(this.buffer, (String)null, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(double[] array) {
|
||||
this.style.append(this.buffer, (String)null, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(float value) {
|
||||
this.style.append(this.buffer, (String)null, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(float[] array) {
|
||||
this.style.append(this.buffer, (String)null, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(int value) {
|
||||
this.style.append(this.buffer, (String)null, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(int[] array) {
|
||||
this.style.append(this.buffer, (String)null, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(long value) {
|
||||
this.style.append(this.buffer, (String)null, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(long[] array) {
|
||||
this.style.append(this.buffer, (String)null, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(Object obj) {
|
||||
this.style.append(this.buffer, null, obj, null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(Object[] array) {
|
||||
this.style.append(this.buffer, (String)null, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(short value) {
|
||||
this.style.append(this.buffer, (String)null, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(short[] array) {
|
||||
this.style.append(this.buffer, (String)null, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, boolean value) {
|
||||
this.style.append(this.buffer, fieldName, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, boolean[] array) {
|
||||
this.style.append(this.buffer, fieldName, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, boolean[] array, boolean fullDetail) {
|
||||
this.style.append(this.buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, byte value) {
|
||||
this.style.append(this.buffer, fieldName, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, byte[] array) {
|
||||
this.style.append(this.buffer, fieldName, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, byte[] array, boolean fullDetail) {
|
||||
this.style.append(this.buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, char value) {
|
||||
this.style.append(this.buffer, fieldName, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, char[] array) {
|
||||
this.style.append(this.buffer, fieldName, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, char[] array, boolean fullDetail) {
|
||||
this.style.append(this.buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, double value) {
|
||||
this.style.append(this.buffer, fieldName, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, double[] array) {
|
||||
this.style.append(this.buffer, fieldName, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, double[] array, boolean fullDetail) {
|
||||
this.style.append(this.buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, float value) {
|
||||
this.style.append(this.buffer, fieldName, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, float[] array) {
|
||||
this.style.append(this.buffer, fieldName, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, float[] array, boolean fullDetail) {
|
||||
this.style.append(this.buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, int value) {
|
||||
this.style.append(this.buffer, fieldName, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, int[] array) {
|
||||
this.style.append(this.buffer, fieldName, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, int[] array, boolean fullDetail) {
|
||||
this.style.append(this.buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, long value) {
|
||||
this.style.append(this.buffer, fieldName, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, long[] array) {
|
||||
this.style.append(this.buffer, fieldName, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, long[] array, boolean fullDetail) {
|
||||
this.style.append(this.buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, Object obj) {
|
||||
this.style.append(this.buffer, fieldName, obj, null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, Object obj, boolean fullDetail) {
|
||||
this.style.append(this.buffer, fieldName, obj, BooleanUtils.toBooleanObject(fullDetail));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, Object[] array) {
|
||||
this.style.append(this.buffer, fieldName, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, Object[] array, boolean fullDetail) {
|
||||
this.style.append(this.buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, short value) {
|
||||
this.style.append(this.buffer, fieldName, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, short[] array) {
|
||||
this.style.append(this.buffer, fieldName, array, (Boolean)null);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder append(String fieldName, short[] array, boolean fullDetail) {
|
||||
this.style.append(this.buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder appendAsObjectToString(Object object) {
|
||||
ObjectUtils.appendIdentityToString(getStringBuffer(), object);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder appendSuper(String superToString) {
|
||||
if (superToString != null)
|
||||
this.style.appendSuper(this.buffer, superToString);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ToStringBuilder appendToString(String toString) {
|
||||
if (toString != null)
|
||||
this.style.appendToString(this.buffer, toString);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Object getObject() {
|
||||
return this.object;
|
||||
}
|
||||
|
||||
public StringBuffer getStringBuffer() {
|
||||
return this.buffer;
|
||||
}
|
||||
|
||||
public ToStringStyle getStyle() {
|
||||
return this.style;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (getObject() == null) {
|
||||
getStringBuffer().append(getStyle().getNullText());
|
||||
} else {
|
||||
this.style.appendEnd(getStringBuffer(), getObject());
|
||||
}
|
||||
return getStringBuffer().toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,905 @@
|
|||
package org.apache.commons.lang.builder;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.apache.commons.lang.ClassUtils;
|
||||
import org.apache.commons.lang.ObjectUtils;
|
||||
import org.apache.commons.lang.SystemUtils;
|
||||
|
||||
public abstract class ToStringStyle implements Serializable {
|
||||
public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle();
|
||||
|
||||
public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle();
|
||||
|
||||
public static final ToStringStyle NO_FIELD_NAMES_STYLE = new NoFieldNameToStringStyle();
|
||||
|
||||
public static final ToStringStyle SHORT_PREFIX_STYLE = new ShortPrefixToStringStyle();
|
||||
|
||||
public static final ToStringStyle SIMPLE_STYLE = new SimpleToStringStyle();
|
||||
|
||||
private static ThreadLocal registry = new ThreadLocal() {
|
||||
protected Object initialValue() {
|
||||
return new HashSet();
|
||||
}
|
||||
};
|
||||
|
||||
static Set getRegistry() {
|
||||
return (Set)registry.get();
|
||||
}
|
||||
|
||||
static boolean isRegistered(Object value) {
|
||||
return getRegistry().contains(value);
|
||||
}
|
||||
|
||||
static void register(Object value) {
|
||||
if (value != null)
|
||||
getRegistry().add(value);
|
||||
}
|
||||
|
||||
static void unregister(Object value) {
|
||||
getRegistry().remove(value);
|
||||
}
|
||||
|
||||
private boolean useFieldNames = true;
|
||||
|
||||
private boolean useClassName = true;
|
||||
|
||||
private boolean useShortClassName = false;
|
||||
|
||||
private boolean useIdentityHashCode = true;
|
||||
|
||||
private String contentStart = "[";
|
||||
|
||||
private String contentEnd = "]";
|
||||
|
||||
private String fieldNameValueSeparator = "=";
|
||||
|
||||
private boolean fieldSeparatorAtStart = false;
|
||||
|
||||
private boolean fieldSeparatorAtEnd = false;
|
||||
|
||||
private String fieldSeparator = ",";
|
||||
|
||||
private String arrayStart = "{";
|
||||
|
||||
private String arraySeparator = ",";
|
||||
|
||||
private boolean arrayContentDetail = true;
|
||||
|
||||
private String arrayEnd = "}";
|
||||
|
||||
private boolean defaultFullDetail = true;
|
||||
|
||||
private String nullText = "<null>";
|
||||
|
||||
private String sizeStartText = "<size=";
|
||||
|
||||
private String sizeEndText = ">";
|
||||
|
||||
private String summaryObjectStartText = "<";
|
||||
|
||||
private String summaryObjectEndText = ">";
|
||||
|
||||
public void appendSuper(StringBuffer buffer, String superToString) {
|
||||
appendToString(buffer, superToString);
|
||||
}
|
||||
|
||||
public void appendToString(StringBuffer buffer, String toString) {
|
||||
if (toString != null) {
|
||||
int pos1 = toString.indexOf(this.contentStart) + this.contentStart.length();
|
||||
int pos2 = toString.lastIndexOf(this.contentEnd);
|
||||
if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) {
|
||||
String data = toString.substring(pos1, pos2);
|
||||
if (this.fieldSeparatorAtStart)
|
||||
removeLastFieldSeparator(buffer);
|
||||
buffer.append(data);
|
||||
appendFieldSeparator(buffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void appendStart(StringBuffer buffer, Object object) {
|
||||
if (object != null) {
|
||||
appendClassName(buffer, object);
|
||||
appendIdentityHashCode(buffer, object);
|
||||
appendContentStart(buffer);
|
||||
if (this.fieldSeparatorAtStart)
|
||||
appendFieldSeparator(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public void appendEnd(StringBuffer buffer, Object object) {
|
||||
if (!this.fieldSeparatorAtEnd)
|
||||
removeLastFieldSeparator(buffer);
|
||||
appendContentEnd(buffer);
|
||||
unregister(object);
|
||||
}
|
||||
|
||||
protected void removeLastFieldSeparator(StringBuffer buffer) {
|
||||
int len = buffer.length();
|
||||
int sepLen = this.fieldSeparator.length();
|
||||
if (len > 0 && sepLen > 0 && len >= sepLen) {
|
||||
boolean match = true;
|
||||
for (int i = 0; i < sepLen; i++) {
|
||||
if (buffer.charAt(len - 1 - i) != this.fieldSeparator.charAt(sepLen - 1 - i)) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match)
|
||||
buffer.setLength(len - sepLen);
|
||||
}
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
if (value == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else {
|
||||
appendInternal(buffer, fieldName, value, isFullDetail(fullDetail));
|
||||
}
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) {
|
||||
if (isRegistered(value) && !(value instanceof Number) && !(value instanceof Boolean) && !(value instanceof Character)) {
|
||||
appendCyclicObject(buffer, fieldName, value);
|
||||
return;
|
||||
}
|
||||
register(value);
|
||||
try {
|
||||
if (value instanceof Collection) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (Collection)value);
|
||||
} else {
|
||||
appendSummarySize(buffer, fieldName, ((Collection)value).size());
|
||||
}
|
||||
} else if (value instanceof Map) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (Map)value);
|
||||
} else {
|
||||
appendSummarySize(buffer, fieldName, ((Map)value).size());
|
||||
}
|
||||
} else if (value instanceof long[]) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (long[])value);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, (long[])value);
|
||||
}
|
||||
} else if (value instanceof int[]) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (int[])value);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, (int[])value);
|
||||
}
|
||||
} else if (value instanceof short[]) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (short[])value);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, (short[])value);
|
||||
}
|
||||
} else if (value instanceof byte[]) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (byte[])value);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, (byte[])value);
|
||||
}
|
||||
} else if (value instanceof char[]) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (char[])value);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, (char[])value);
|
||||
}
|
||||
} else if (value instanceof double[]) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (double[])value);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, (double[])value);
|
||||
}
|
||||
} else if (value instanceof float[]) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (float[])value);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, (float[])value);
|
||||
}
|
||||
} else if (value instanceof boolean[]) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (boolean[])value);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, (boolean[])value);
|
||||
}
|
||||
} else if (value.getClass().isArray()) {
|
||||
if (detail) {
|
||||
appendDetail(buffer, fieldName, (Object[])value);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, (Object[])value);
|
||||
}
|
||||
} else if (detail) {
|
||||
appendDetail(buffer, fieldName, value);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, value);
|
||||
}
|
||||
} finally {
|
||||
unregister(value);
|
||||
}
|
||||
}
|
||||
|
||||
protected void appendCyclicObject(StringBuffer buffer, String fieldName, Object value) {
|
||||
ObjectUtils.appendIdentityToString(buffer, value);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
|
||||
buffer.append(value);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, Collection coll) {
|
||||
buffer.append(coll);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, Map map) {
|
||||
buffer.append(map);
|
||||
}
|
||||
|
||||
protected void appendSummary(StringBuffer buffer, String fieldName, Object value) {
|
||||
buffer.append(this.summaryObjectStartText);
|
||||
buffer.append(getShortClassName(value.getClass()));
|
||||
buffer.append(this.summaryObjectEndText);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, long value) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
appendDetail(buffer, fieldName, value);
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, long value) {
|
||||
buffer.append(value);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, int value) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
appendDetail(buffer, fieldName, value);
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, int value) {
|
||||
buffer.append(value);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, short value) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
appendDetail(buffer, fieldName, value);
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, short value) {
|
||||
buffer.append(value);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, byte value) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
appendDetail(buffer, fieldName, value);
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, byte value) {
|
||||
buffer.append(value);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, char value) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
appendDetail(buffer, fieldName, value);
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, char value) {
|
||||
buffer.append(value);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, double value) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
appendDetail(buffer, fieldName, value);
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, double value) {
|
||||
buffer.append(value);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, float value) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
appendDetail(buffer, fieldName, value);
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, float value) {
|
||||
buffer.append(value);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, boolean value) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
appendDetail(buffer, fieldName, value);
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) {
|
||||
buffer.append(value);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
if (array == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else if (isFullDetail(fullDetail)) {
|
||||
appendDetail(buffer, fieldName, array);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, array);
|
||||
}
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) {
|
||||
buffer.append(this.arrayStart);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
Object item = array[i];
|
||||
if (i > 0)
|
||||
buffer.append(this.arraySeparator);
|
||||
if (item == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else {
|
||||
appendInternal(buffer, fieldName, item, this.arrayContentDetail);
|
||||
}
|
||||
}
|
||||
buffer.append(this.arrayEnd);
|
||||
}
|
||||
|
||||
protected void reflectionAppendArrayDetail(StringBuffer buffer, String fieldName, Object array) {
|
||||
buffer.append(this.arrayStart);
|
||||
int length = Array.getLength(array);
|
||||
for (int i = 0; i < length; i++) {
|
||||
Object item = Array.get(array, i);
|
||||
if (i > 0)
|
||||
buffer.append(this.arraySeparator);
|
||||
if (item == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else {
|
||||
appendInternal(buffer, fieldName, item, this.arrayContentDetail);
|
||||
}
|
||||
}
|
||||
buffer.append(this.arrayEnd);
|
||||
}
|
||||
|
||||
protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) {
|
||||
appendSummarySize(buffer, fieldName, array.length);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
if (array == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else if (isFullDetail(fullDetail)) {
|
||||
appendDetail(buffer, fieldName, array);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, array);
|
||||
}
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) {
|
||||
buffer.append(this.arrayStart);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (i > 0)
|
||||
buffer.append(this.arraySeparator);
|
||||
appendDetail(buffer, fieldName, array[i]);
|
||||
}
|
||||
buffer.append(this.arrayEnd);
|
||||
}
|
||||
|
||||
protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) {
|
||||
appendSummarySize(buffer, fieldName, array.length);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
if (array == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else if (isFullDetail(fullDetail)) {
|
||||
appendDetail(buffer, fieldName, array);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, array);
|
||||
}
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) {
|
||||
buffer.append(this.arrayStart);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (i > 0)
|
||||
buffer.append(this.arraySeparator);
|
||||
appendDetail(buffer, fieldName, array[i]);
|
||||
}
|
||||
buffer.append(this.arrayEnd);
|
||||
}
|
||||
|
||||
protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) {
|
||||
appendSummarySize(buffer, fieldName, array.length);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
if (array == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else if (isFullDetail(fullDetail)) {
|
||||
appendDetail(buffer, fieldName, array);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, array);
|
||||
}
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) {
|
||||
buffer.append(this.arrayStart);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (i > 0)
|
||||
buffer.append(this.arraySeparator);
|
||||
appendDetail(buffer, fieldName, array[i]);
|
||||
}
|
||||
buffer.append(this.arrayEnd);
|
||||
}
|
||||
|
||||
protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) {
|
||||
appendSummarySize(buffer, fieldName, array.length);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
if (array == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else if (isFullDetail(fullDetail)) {
|
||||
appendDetail(buffer, fieldName, array);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, array);
|
||||
}
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) {
|
||||
buffer.append(this.arrayStart);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (i > 0)
|
||||
buffer.append(this.arraySeparator);
|
||||
appendDetail(buffer, fieldName, array[i]);
|
||||
}
|
||||
buffer.append(this.arrayEnd);
|
||||
}
|
||||
|
||||
protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) {
|
||||
appendSummarySize(buffer, fieldName, array.length);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
if (array == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else if (isFullDetail(fullDetail)) {
|
||||
appendDetail(buffer, fieldName, array);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, array);
|
||||
}
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) {
|
||||
buffer.append(this.arrayStart);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (i > 0)
|
||||
buffer.append(this.arraySeparator);
|
||||
appendDetail(buffer, fieldName, array[i]);
|
||||
}
|
||||
buffer.append(this.arrayEnd);
|
||||
}
|
||||
|
||||
protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) {
|
||||
appendSummarySize(buffer, fieldName, array.length);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
if (array == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else if (isFullDetail(fullDetail)) {
|
||||
appendDetail(buffer, fieldName, array);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, array);
|
||||
}
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) {
|
||||
buffer.append(this.arrayStart);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (i > 0)
|
||||
buffer.append(this.arraySeparator);
|
||||
appendDetail(buffer, fieldName, array[i]);
|
||||
}
|
||||
buffer.append(this.arrayEnd);
|
||||
}
|
||||
|
||||
protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) {
|
||||
appendSummarySize(buffer, fieldName, array.length);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
if (array == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else if (isFullDetail(fullDetail)) {
|
||||
appendDetail(buffer, fieldName, array);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, array);
|
||||
}
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) {
|
||||
buffer.append(this.arrayStart);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (i > 0)
|
||||
buffer.append(this.arraySeparator);
|
||||
appendDetail(buffer, fieldName, array[i]);
|
||||
}
|
||||
buffer.append(this.arrayEnd);
|
||||
}
|
||||
|
||||
protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) {
|
||||
appendSummarySize(buffer, fieldName, array.length);
|
||||
}
|
||||
|
||||
public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) {
|
||||
appendFieldStart(buffer, fieldName);
|
||||
if (array == null) {
|
||||
appendNullText(buffer, fieldName);
|
||||
} else if (isFullDetail(fullDetail)) {
|
||||
appendDetail(buffer, fieldName, array);
|
||||
} else {
|
||||
appendSummary(buffer, fieldName, array);
|
||||
}
|
||||
appendFieldEnd(buffer, fieldName);
|
||||
}
|
||||
|
||||
protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) {
|
||||
buffer.append(this.arrayStart);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (i > 0)
|
||||
buffer.append(this.arraySeparator);
|
||||
appendDetail(buffer, fieldName, array[i]);
|
||||
}
|
||||
buffer.append(this.arrayEnd);
|
||||
}
|
||||
|
||||
protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) {
|
||||
appendSummarySize(buffer, fieldName, array.length);
|
||||
}
|
||||
|
||||
protected void appendClassName(StringBuffer buffer, Object object) {
|
||||
if (this.useClassName && object != null) {
|
||||
register(object);
|
||||
if (this.useShortClassName) {
|
||||
buffer.append(getShortClassName(object.getClass()));
|
||||
} else {
|
||||
buffer.append(object.getClass().getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void appendIdentityHashCode(StringBuffer buffer, Object object) {
|
||||
if (isUseIdentityHashCode() && object != null) {
|
||||
register(object);
|
||||
buffer.append('@');
|
||||
buffer.append(Integer.toHexString(System.identityHashCode(object)));
|
||||
}
|
||||
}
|
||||
|
||||
protected void appendContentStart(StringBuffer buffer) {
|
||||
buffer.append(this.contentStart);
|
||||
}
|
||||
|
||||
protected void appendContentEnd(StringBuffer buffer) {
|
||||
buffer.append(this.contentEnd);
|
||||
}
|
||||
|
||||
protected void appendNullText(StringBuffer buffer, String fieldName) {
|
||||
buffer.append(this.nullText);
|
||||
}
|
||||
|
||||
protected void appendFieldSeparator(StringBuffer buffer) {
|
||||
buffer.append(this.fieldSeparator);
|
||||
}
|
||||
|
||||
protected void appendFieldStart(StringBuffer buffer, String fieldName) {
|
||||
if (this.useFieldNames && fieldName != null) {
|
||||
buffer.append(fieldName);
|
||||
buffer.append(this.fieldNameValueSeparator);
|
||||
}
|
||||
}
|
||||
|
||||
protected void appendFieldEnd(StringBuffer buffer, String fieldName) {
|
||||
appendFieldSeparator(buffer);
|
||||
}
|
||||
|
||||
protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) {
|
||||
buffer.append(this.sizeStartText);
|
||||
buffer.append(size);
|
||||
buffer.append(this.sizeEndText);
|
||||
}
|
||||
|
||||
protected boolean isFullDetail(Boolean fullDetailRequest) {
|
||||
if (fullDetailRequest == null)
|
||||
return this.defaultFullDetail;
|
||||
return fullDetailRequest.booleanValue();
|
||||
}
|
||||
|
||||
protected String getShortClassName(Class cls) {
|
||||
return ClassUtils.getShortClassName(cls);
|
||||
}
|
||||
|
||||
protected boolean isUseClassName() {
|
||||
return this.useClassName;
|
||||
}
|
||||
|
||||
protected void setUseClassName(boolean useClassName) {
|
||||
this.useClassName = useClassName;
|
||||
}
|
||||
|
||||
protected boolean isUseShortClassName() {
|
||||
return this.useShortClassName;
|
||||
}
|
||||
|
||||
protected boolean isShortClassName() {
|
||||
return this.useShortClassName;
|
||||
}
|
||||
|
||||
protected void setUseShortClassName(boolean useShortClassName) {
|
||||
this.useShortClassName = useShortClassName;
|
||||
}
|
||||
|
||||
protected void setShortClassName(boolean shortClassName) {
|
||||
this.useShortClassName = shortClassName;
|
||||
}
|
||||
|
||||
protected boolean isUseIdentityHashCode() {
|
||||
return this.useIdentityHashCode;
|
||||
}
|
||||
|
||||
protected void setUseIdentityHashCode(boolean useIdentityHashCode) {
|
||||
this.useIdentityHashCode = useIdentityHashCode;
|
||||
}
|
||||
|
||||
protected boolean isUseFieldNames() {
|
||||
return this.useFieldNames;
|
||||
}
|
||||
|
||||
protected void setUseFieldNames(boolean useFieldNames) {
|
||||
this.useFieldNames = useFieldNames;
|
||||
}
|
||||
|
||||
protected boolean isDefaultFullDetail() {
|
||||
return this.defaultFullDetail;
|
||||
}
|
||||
|
||||
protected void setDefaultFullDetail(boolean defaultFullDetail) {
|
||||
this.defaultFullDetail = defaultFullDetail;
|
||||
}
|
||||
|
||||
protected boolean isArrayContentDetail() {
|
||||
return this.arrayContentDetail;
|
||||
}
|
||||
|
||||
protected void setArrayContentDetail(boolean arrayContentDetail) {
|
||||
this.arrayContentDetail = arrayContentDetail;
|
||||
}
|
||||
|
||||
protected String getArrayStart() {
|
||||
return this.arrayStart;
|
||||
}
|
||||
|
||||
protected void setArrayStart(String arrayStart) {
|
||||
if (arrayStart == null)
|
||||
arrayStart = "";
|
||||
this.arrayStart = arrayStart;
|
||||
}
|
||||
|
||||
protected String getArrayEnd() {
|
||||
return this.arrayEnd;
|
||||
}
|
||||
|
||||
protected void setArrayEnd(String arrayEnd) {
|
||||
if (arrayEnd == null)
|
||||
arrayEnd = "";
|
||||
this.arrayEnd = arrayEnd;
|
||||
}
|
||||
|
||||
protected String getArraySeparator() {
|
||||
return this.arraySeparator;
|
||||
}
|
||||
|
||||
protected void setArraySeparator(String arraySeparator) {
|
||||
if (arraySeparator == null)
|
||||
arraySeparator = "";
|
||||
this.arraySeparator = arraySeparator;
|
||||
}
|
||||
|
||||
protected String getContentStart() {
|
||||
return this.contentStart;
|
||||
}
|
||||
|
||||
protected void setContentStart(String contentStart) {
|
||||
if (contentStart == null)
|
||||
contentStart = "";
|
||||
this.contentStart = contentStart;
|
||||
}
|
||||
|
||||
protected String getContentEnd() {
|
||||
return this.contentEnd;
|
||||
}
|
||||
|
||||
protected void setContentEnd(String contentEnd) {
|
||||
if (contentEnd == null)
|
||||
contentEnd = "";
|
||||
this.contentEnd = contentEnd;
|
||||
}
|
||||
|
||||
protected String getFieldNameValueSeparator() {
|
||||
return this.fieldNameValueSeparator;
|
||||
}
|
||||
|
||||
protected void setFieldNameValueSeparator(String fieldNameValueSeparator) {
|
||||
if (fieldNameValueSeparator == null)
|
||||
fieldNameValueSeparator = "";
|
||||
this.fieldNameValueSeparator = fieldNameValueSeparator;
|
||||
}
|
||||
|
||||
protected String getFieldSeparator() {
|
||||
return this.fieldSeparator;
|
||||
}
|
||||
|
||||
protected void setFieldSeparator(String fieldSeparator) {
|
||||
if (fieldSeparator == null)
|
||||
fieldSeparator = "";
|
||||
this.fieldSeparator = fieldSeparator;
|
||||
}
|
||||
|
||||
protected boolean isFieldSeparatorAtStart() {
|
||||
return this.fieldSeparatorAtStart;
|
||||
}
|
||||
|
||||
protected void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) {
|
||||
this.fieldSeparatorAtStart = fieldSeparatorAtStart;
|
||||
}
|
||||
|
||||
protected boolean isFieldSeparatorAtEnd() {
|
||||
return this.fieldSeparatorAtEnd;
|
||||
}
|
||||
|
||||
protected void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) {
|
||||
this.fieldSeparatorAtEnd = fieldSeparatorAtEnd;
|
||||
}
|
||||
|
||||
protected String getNullText() {
|
||||
return this.nullText;
|
||||
}
|
||||
|
||||
protected void setNullText(String nullText) {
|
||||
if (nullText == null)
|
||||
nullText = "";
|
||||
this.nullText = nullText;
|
||||
}
|
||||
|
||||
protected String getSizeStartText() {
|
||||
return this.sizeStartText;
|
||||
}
|
||||
|
||||
protected void setSizeStartText(String sizeStartText) {
|
||||
if (sizeStartText == null)
|
||||
sizeStartText = "";
|
||||
this.sizeStartText = sizeStartText;
|
||||
}
|
||||
|
||||
protected String getSizeEndText() {
|
||||
return this.sizeEndText;
|
||||
}
|
||||
|
||||
protected void setSizeEndText(String sizeEndText) {
|
||||
if (sizeEndText == null)
|
||||
sizeEndText = "";
|
||||
this.sizeEndText = sizeEndText;
|
||||
}
|
||||
|
||||
protected String getSummaryObjectStartText() {
|
||||
return this.summaryObjectStartText;
|
||||
}
|
||||
|
||||
protected void setSummaryObjectStartText(String summaryObjectStartText) {
|
||||
if (summaryObjectStartText == null)
|
||||
summaryObjectStartText = "";
|
||||
this.summaryObjectStartText = summaryObjectStartText;
|
||||
}
|
||||
|
||||
protected String getSummaryObjectEndText() {
|
||||
return this.summaryObjectEndText;
|
||||
}
|
||||
|
||||
protected void setSummaryObjectEndText(String summaryObjectEndText) {
|
||||
if (summaryObjectEndText == null)
|
||||
summaryObjectEndText = "";
|
||||
this.summaryObjectEndText = summaryObjectEndText;
|
||||
}
|
||||
|
||||
private static final class DefaultToStringStyle extends ToStringStyle {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Object readResolve() {
|
||||
return ToStringStyle.DEFAULT_STYLE;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class NoFieldNameToStringStyle extends ToStringStyle {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
NoFieldNameToStringStyle() {
|
||||
setUseFieldNames(false);
|
||||
}
|
||||
|
||||
private Object readResolve() {
|
||||
return ToStringStyle.NO_FIELD_NAMES_STYLE;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ShortPrefixToStringStyle extends ToStringStyle {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
ShortPrefixToStringStyle() {
|
||||
setUseShortClassName(true);
|
||||
setUseIdentityHashCode(false);
|
||||
}
|
||||
|
||||
private Object readResolve() {
|
||||
return ToStringStyle.SHORT_PREFIX_STYLE;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class SimpleToStringStyle extends ToStringStyle {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
SimpleToStringStyle() {
|
||||
setUseClassName(false);
|
||||
setUseIdentityHashCode(false);
|
||||
setUseFieldNames(false);
|
||||
setContentStart("");
|
||||
setContentEnd("");
|
||||
}
|
||||
|
||||
private Object readResolve() {
|
||||
return ToStringStyle.SIMPLE_STYLE;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class MultiLineToStringStyle extends ToStringStyle {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
MultiLineToStringStyle() {
|
||||
setContentStart("[");
|
||||
setFieldSeparator(SystemUtils.LINE_SEPARATOR + " ");
|
||||
setFieldSeparatorAtStart(true);
|
||||
setContentEnd(SystemUtils.LINE_SEPARATOR + "]");
|
||||
}
|
||||
|
||||
private Object readResolve() {
|
||||
return ToStringStyle.MULTI_LINE_STYLE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,204 @@
|
|||
package org.apache.commons.lang.enum;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.WeakHashMap;
|
||||
import org.apache.commons.lang.ClassUtils;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
public abstract class Enum implements Comparable, Serializable {
|
||||
private static final long serialVersionUID = -487045951170455942L;
|
||||
|
||||
private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap(0));
|
||||
|
||||
private static Map cEnumClasses = new WeakHashMap();
|
||||
|
||||
private final String iName;
|
||||
|
||||
private final transient int iHashCode;
|
||||
|
||||
protected transient String iToString = null;
|
||||
|
||||
private static class Entry {
|
||||
final Map map = new HashMap();
|
||||
|
||||
final Map unmodifiableMap = Collections.unmodifiableMap(this.map);
|
||||
|
||||
final List list = new ArrayList(25);
|
||||
|
||||
final List unmodifiableList = Collections.unmodifiableList(this.list);
|
||||
}
|
||||
|
||||
protected Enum(String name) {
|
||||
init(name);
|
||||
this.iName = name;
|
||||
this.iHashCode = 7 + getEnumClass().hashCode() + 3 * name.hashCode();
|
||||
}
|
||||
|
||||
private void init(String name) {
|
||||
Entry entry;
|
||||
if (StringUtils.isEmpty(name))
|
||||
throw new IllegalArgumentException("The Enum name must not be empty or null");
|
||||
Class enumClass = getEnumClass();
|
||||
if (enumClass == null)
|
||||
throw new IllegalArgumentException("getEnumClass() must not be null");
|
||||
Class cls = getClass();
|
||||
boolean ok = false;
|
||||
while (cls != null) {
|
||||
if (cls != Enum.class) {
|
||||
if (cls != ValuedEnum.class) {
|
||||
if (cls == enumClass) {
|
||||
ok = true;
|
||||
break;
|
||||
}
|
||||
cls = cls.getSuperclass();
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (!ok)
|
||||
throw new IllegalArgumentException("getEnumClass() must return a superclass of this class");
|
||||
synchronized (Enum.class) {
|
||||
entry = (Entry)cEnumClasses.get(enumClass);
|
||||
if (entry == null) {
|
||||
entry = createEntry(enumClass);
|
||||
Map myMap = new WeakHashMap();
|
||||
myMap.putAll(cEnumClasses);
|
||||
myMap.put(enumClass, entry);
|
||||
cEnumClasses = myMap;
|
||||
}
|
||||
}
|
||||
if (entry.map.containsKey(name))
|
||||
throw new IllegalArgumentException("The Enum name must be unique, '" + name + "' has already been added");
|
||||
entry.map.put(name, this);
|
||||
entry.list.add(this);
|
||||
}
|
||||
|
||||
protected Object readResolve() {
|
||||
Entry entry = (Entry)cEnumClasses.get(getEnumClass());
|
||||
if (entry == null)
|
||||
return null;
|
||||
return entry.map.get(getName());
|
||||
}
|
||||
|
||||
protected static Enum getEnum(Class enumClass, String name) {
|
||||
Entry entry = getEntry(enumClass);
|
||||
if (entry == null)
|
||||
return null;
|
||||
return (Enum)entry.map.get(name);
|
||||
}
|
||||
|
||||
protected static Map getEnumMap(Class enumClass) {
|
||||
Entry entry = getEntry(enumClass);
|
||||
if (entry == null)
|
||||
return EMPTY_MAP;
|
||||
return entry.unmodifiableMap;
|
||||
}
|
||||
|
||||
protected static List getEnumList(Class enumClass) {
|
||||
Entry entry = getEntry(enumClass);
|
||||
if (entry == null)
|
||||
return Collections.EMPTY_LIST;
|
||||
return entry.unmodifiableList;
|
||||
}
|
||||
|
||||
protected static Iterator iterator(Class enumClass) {
|
||||
return getEnumList(enumClass).iterator();
|
||||
}
|
||||
|
||||
private static Entry getEntry(Class enumClass) {
|
||||
if (enumClass == null)
|
||||
throw new IllegalArgumentException("The Enum Class must not be null");
|
||||
if (!Enum.class.isAssignableFrom(enumClass))
|
||||
throw new IllegalArgumentException("The Class must be a subclass of Enum");
|
||||
Entry entry = (Entry)cEnumClasses.get(enumClass);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static Entry createEntry(Class enumClass) {
|
||||
Entry entry = new Entry();
|
||||
Class cls = enumClass.getSuperclass();
|
||||
while (cls != null) {
|
||||
if (cls != Enum.class) {
|
||||
if (cls != ValuedEnum.class) {
|
||||
Entry loopEntry = (Entry)cEnumClasses.get(cls);
|
||||
if (loopEntry != null) {
|
||||
entry.list.addAll(loopEntry.list);
|
||||
entry.map.putAll(loopEntry.map);
|
||||
break;
|
||||
}
|
||||
cls = cls.getSuperclass();
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
public final String getName() {
|
||||
return this.iName;
|
||||
}
|
||||
|
||||
public Class getEnumClass() {
|
||||
return getClass();
|
||||
}
|
||||
|
||||
public final boolean equals(Object other) {
|
||||
if (other == this)
|
||||
return true;
|
||||
if (other == null)
|
||||
return false;
|
||||
if (other.getClass() == getClass())
|
||||
return this.iName.equals(((Enum)other).iName);
|
||||
if (!other.getClass().getName().equals(getClass().getName()))
|
||||
return false;
|
||||
return this.iName.equals(getNameInOtherClassLoader(other));
|
||||
}
|
||||
|
||||
public final int hashCode() {
|
||||
return this.iHashCode;
|
||||
}
|
||||
|
||||
public int compareTo(Object other) {
|
||||
if (other == this)
|
||||
return 0;
|
||||
if (other.getClass() != getClass()) {
|
||||
if (other.getClass().getName().equals(getClass().getName()))
|
||||
return this.iName.compareTo(getNameInOtherClassLoader(other));
|
||||
throw new ClassCastException("Different enum class '" + ClassUtils.getShortClassName(other.getClass()) + "'");
|
||||
}
|
||||
return this.iName.compareTo(((Enum)other).iName);
|
||||
}
|
||||
|
||||
private String getNameInOtherClassLoader(Object other) {
|
||||
try {
|
||||
Method mth = other.getClass().getMethod("getName", null);
|
||||
String name = (String)mth.invoke(other, null);
|
||||
return name;
|
||||
} catch (NoSuchMethodException e) {
|
||||
|
||||
} catch (IllegalAccessException e) {
|
||||
|
||||
} catch (InvocationTargetException e) {}
|
||||
throw new IllegalStateException("This should not happen");
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.iToString == null) {
|
||||
String shortName = ClassUtils.getShortClassName(getEnumClass());
|
||||
this.iToString = shortName + "[" + getName() + "]";
|
||||
}
|
||||
return this.iToString;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package org.apache.commons.lang.enum;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class EnumUtils {
|
||||
public static Enum getEnum(Class enumClass, String name) {
|
||||
return Enum.getEnum(enumClass, name);
|
||||
}
|
||||
|
||||
public static ValuedEnum getEnum(Class enumClass, int value) {
|
||||
return (ValuedEnum)ValuedEnum.getEnum(enumClass, value);
|
||||
}
|
||||
|
||||
public static Map getEnumMap(Class enumClass) {
|
||||
return Enum.getEnumMap(enumClass);
|
||||
}
|
||||
|
||||
public static List getEnumList(Class enumClass) {
|
||||
return Enum.getEnumList(enumClass);
|
||||
}
|
||||
|
||||
public static Iterator iterator(Class enumClass) {
|
||||
return Enum.getEnumList(enumClass).iterator();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
package org.apache.commons.lang.enum;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang.ClassUtils;
|
||||
|
||||
public abstract class ValuedEnum extends Enum {
|
||||
private static final long serialVersionUID = -7129650521543789085L;
|
||||
|
||||
private final int iValue;
|
||||
|
||||
protected ValuedEnum(String name, int value) {
|
||||
super(name);
|
||||
this.iValue = value;
|
||||
}
|
||||
|
||||
protected static Enum getEnum(Class enumClass, int value) {
|
||||
if (enumClass == null)
|
||||
throw new IllegalArgumentException("The Enum Class must not be null");
|
||||
List list = Enum.getEnumList(enumClass);
|
||||
for (Iterator it = list.iterator(); it.hasNext(); ) {
|
||||
ValuedEnum enumeration = (ValuedEnum)it.next();
|
||||
if (enumeration.getValue() == value)
|
||||
return enumeration;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public final int getValue() {
|
||||
return this.iValue;
|
||||
}
|
||||
|
||||
public int compareTo(Object other) {
|
||||
return this.iValue - ((ValuedEnum)other).iValue;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.iToString == null) {
|
||||
String shortName = ClassUtils.getShortClassName(getEnumClass());
|
||||
this.iToString = shortName + "[" + getName() + "=" + getValue() + "]";
|
||||
}
|
||||
return this.iToString;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,204 @@
|
|||
package org.apache.commons.lang.enums;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.WeakHashMap;
|
||||
import org.apache.commons.lang.ClassUtils;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
public abstract class Enum implements Comparable, Serializable {
|
||||
private static final long serialVersionUID = -487045951170455942L;
|
||||
|
||||
private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap(0));
|
||||
|
||||
private static Map cEnumClasses = new WeakHashMap();
|
||||
|
||||
private final String iName;
|
||||
|
||||
private final transient int iHashCode;
|
||||
|
||||
protected transient String iToString = null;
|
||||
|
||||
private static class Entry {
|
||||
final Map map = new HashMap();
|
||||
|
||||
final Map unmodifiableMap = Collections.unmodifiableMap(this.map);
|
||||
|
||||
final List list = new ArrayList(25);
|
||||
|
||||
final List unmodifiableList = Collections.unmodifiableList(this.list);
|
||||
}
|
||||
|
||||
protected Enum(String name) {
|
||||
init(name);
|
||||
this.iName = name;
|
||||
this.iHashCode = 7 + getEnumClass().hashCode() + 3 * name.hashCode();
|
||||
}
|
||||
|
||||
private void init(String name) {
|
||||
Entry entry;
|
||||
if (StringUtils.isEmpty(name))
|
||||
throw new IllegalArgumentException("The Enum name must not be empty or null");
|
||||
Class enumClass = getEnumClass();
|
||||
if (enumClass == null)
|
||||
throw new IllegalArgumentException("getEnumClass() must not be null");
|
||||
Class cls = getClass();
|
||||
boolean ok = false;
|
||||
while (cls != null) {
|
||||
if (cls != Enum.class) {
|
||||
if (cls != ValuedEnum.class) {
|
||||
if (cls == enumClass) {
|
||||
ok = true;
|
||||
break;
|
||||
}
|
||||
cls = cls.getSuperclass();
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (!ok)
|
||||
throw new IllegalArgumentException("getEnumClass() must return a superclass of this class");
|
||||
synchronized (Enum.class) {
|
||||
entry = (Entry)cEnumClasses.get(enumClass);
|
||||
if (entry == null) {
|
||||
entry = createEntry(enumClass);
|
||||
Map myMap = new WeakHashMap();
|
||||
myMap.putAll(cEnumClasses);
|
||||
myMap.put(enumClass, entry);
|
||||
cEnumClasses = myMap;
|
||||
}
|
||||
}
|
||||
if (entry.map.containsKey(name))
|
||||
throw new IllegalArgumentException("The Enum name must be unique, '" + name + "' has already been added");
|
||||
entry.map.put(name, this);
|
||||
entry.list.add(this);
|
||||
}
|
||||
|
||||
protected Object readResolve() {
|
||||
Entry entry = (Entry)cEnumClasses.get(getEnumClass());
|
||||
if (entry == null)
|
||||
return null;
|
||||
return entry.map.get(getName());
|
||||
}
|
||||
|
||||
protected static Enum getEnum(Class enumClass, String name) {
|
||||
Entry entry = getEntry(enumClass);
|
||||
if (entry == null)
|
||||
return null;
|
||||
return (Enum)entry.map.get(name);
|
||||
}
|
||||
|
||||
protected static Map getEnumMap(Class enumClass) {
|
||||
Entry entry = getEntry(enumClass);
|
||||
if (entry == null)
|
||||
return EMPTY_MAP;
|
||||
return entry.unmodifiableMap;
|
||||
}
|
||||
|
||||
protected static List getEnumList(Class enumClass) {
|
||||
Entry entry = getEntry(enumClass);
|
||||
if (entry == null)
|
||||
return Collections.EMPTY_LIST;
|
||||
return entry.unmodifiableList;
|
||||
}
|
||||
|
||||
protected static Iterator iterator(Class enumClass) {
|
||||
return getEnumList(enumClass).iterator();
|
||||
}
|
||||
|
||||
private static Entry getEntry(Class enumClass) {
|
||||
if (enumClass == null)
|
||||
throw new IllegalArgumentException("The Enum Class must not be null");
|
||||
if (!Enum.class.isAssignableFrom(enumClass))
|
||||
throw new IllegalArgumentException("The Class must be a subclass of Enum");
|
||||
Entry entry = (Entry)cEnumClasses.get(enumClass);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static Entry createEntry(Class enumClass) {
|
||||
Entry entry = new Entry();
|
||||
Class cls = enumClass.getSuperclass();
|
||||
while (cls != null) {
|
||||
if (cls != Enum.class) {
|
||||
if (cls != ValuedEnum.class) {
|
||||
Entry loopEntry = (Entry)cEnumClasses.get(cls);
|
||||
if (loopEntry != null) {
|
||||
entry.list.addAll(loopEntry.list);
|
||||
entry.map.putAll(loopEntry.map);
|
||||
break;
|
||||
}
|
||||
cls = cls.getSuperclass();
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
public final String getName() {
|
||||
return this.iName;
|
||||
}
|
||||
|
||||
public Class getEnumClass() {
|
||||
return getClass();
|
||||
}
|
||||
|
||||
public final boolean equals(Object other) {
|
||||
if (other == this)
|
||||
return true;
|
||||
if (other == null)
|
||||
return false;
|
||||
if (other.getClass() == getClass())
|
||||
return this.iName.equals(((Enum)other).iName);
|
||||
if (!other.getClass().getName().equals(getClass().getName()))
|
||||
return false;
|
||||
return this.iName.equals(getNameInOtherClassLoader(other));
|
||||
}
|
||||
|
||||
public final int hashCode() {
|
||||
return this.iHashCode;
|
||||
}
|
||||
|
||||
public int compareTo(Object other) {
|
||||
if (other == this)
|
||||
return 0;
|
||||
if (other.getClass() != getClass()) {
|
||||
if (other.getClass().getName().equals(getClass().getName()))
|
||||
return this.iName.compareTo(getNameInOtherClassLoader(other));
|
||||
throw new ClassCastException("Different enum class '" + ClassUtils.getShortClassName(other.getClass()) + "'");
|
||||
}
|
||||
return this.iName.compareTo(((Enum)other).iName);
|
||||
}
|
||||
|
||||
private String getNameInOtherClassLoader(Object other) {
|
||||
try {
|
||||
Method mth = other.getClass().getMethod("getName", null);
|
||||
String name = (String)mth.invoke(other, null);
|
||||
return name;
|
||||
} catch (NoSuchMethodException e) {
|
||||
|
||||
} catch (IllegalAccessException e) {
|
||||
|
||||
} catch (InvocationTargetException e) {}
|
||||
throw new IllegalStateException("This should not happen");
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.iToString == null) {
|
||||
String shortName = ClassUtils.getShortClassName(getEnumClass());
|
||||
this.iToString = shortName + "[" + getName() + "]";
|
||||
}
|
||||
return this.iToString;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package org.apache.commons.lang.enums;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class EnumUtils {
|
||||
public static Enum getEnum(Class enumClass, String name) {
|
||||
return Enum.getEnum(enumClass, name);
|
||||
}
|
||||
|
||||
public static ValuedEnum getEnum(Class enumClass, int value) {
|
||||
return (ValuedEnum)ValuedEnum.getEnum(enumClass, value);
|
||||
}
|
||||
|
||||
public static Map getEnumMap(Class enumClass) {
|
||||
return Enum.getEnumMap(enumClass);
|
||||
}
|
||||
|
||||
public static List getEnumList(Class enumClass) {
|
||||
return Enum.getEnumList(enumClass);
|
||||
}
|
||||
|
||||
public static Iterator iterator(Class enumClass) {
|
||||
return Enum.getEnumList(enumClass).iterator();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
package org.apache.commons.lang.enums;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang.ClassUtils;
|
||||
|
||||
public abstract class ValuedEnum extends Enum {
|
||||
private static final long serialVersionUID = -7129650521543789085L;
|
||||
|
||||
private final int iValue;
|
||||
|
||||
protected ValuedEnum(String name, int value) {
|
||||
super(name);
|
||||
this.iValue = value;
|
||||
}
|
||||
|
||||
protected static Enum getEnum(Class enumClass, int value) {
|
||||
if (enumClass == null)
|
||||
throw new IllegalArgumentException("The Enum Class must not be null");
|
||||
List list = Enum.getEnumList(enumClass);
|
||||
for (Iterator it = list.iterator(); it.hasNext(); ) {
|
||||
ValuedEnum enumeration = (ValuedEnum)it.next();
|
||||
if (enumeration.getValue() == value)
|
||||
return enumeration;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public final int getValue() {
|
||||
return this.iValue;
|
||||
}
|
||||
|
||||
public int compareTo(Object other) {
|
||||
if (other == this)
|
||||
return 0;
|
||||
if (other.getClass() != getClass()) {
|
||||
if (other.getClass().getName().equals(getClass().getName()))
|
||||
return this.iValue - getValueInOtherClassLoader(other);
|
||||
throw new ClassCastException("Different enum class '" + ClassUtils.getShortClassName(other.getClass()) + "'");
|
||||
}
|
||||
return this.iValue - ((ValuedEnum)other).iValue;
|
||||
}
|
||||
|
||||
private int getValueInOtherClassLoader(Object other) {
|
||||
try {
|
||||
Method mth = other.getClass().getMethod("getValue", null);
|
||||
Integer value = (Integer)mth.invoke(other, null);
|
||||
return value.intValue();
|
||||
} catch (NoSuchMethodException e) {
|
||||
|
||||
} catch (IllegalAccessException e) {
|
||||
|
||||
} catch (InvocationTargetException e) {}
|
||||
throw new IllegalStateException("This should not happen");
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.iToString == null) {
|
||||
String shortName = ClassUtils.getShortClassName(getEnumClass());
|
||||
this.iToString = shortName + "[" + getName() + "=" + getValue() + "]";
|
||||
}
|
||||
return this.iToString;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,411 @@
|
|||
package org.apache.commons.lang.exception;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.StringTokenizer;
|
||||
import org.apache.commons.lang.ArrayUtils;
|
||||
import org.apache.commons.lang.ClassUtils;
|
||||
import org.apache.commons.lang.NullArgumentException;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.lang.SystemUtils;
|
||||
|
||||
public class ExceptionUtils {
|
||||
static final String WRAPPED_MARKER = " [wrapped] ";
|
||||
|
||||
private static String[] CAUSE_METHOD_NAMES = new String[] {
|
||||
"getCause", "getNextException", "getTargetException", "getException", "getSourceException", "getRootCause", "getCausedByException", "getNested", "getLinkedException", "getNestedException",
|
||||
"getLinkedCause", "getThrowable" };
|
||||
|
||||
private static final Method THROWABLE_CAUSE_METHOD;
|
||||
|
||||
private static final Method THROWABLE_INITCAUSE_METHOD;
|
||||
|
||||
static {
|
||||
Method causeMethod;
|
||||
try {
|
||||
causeMethod = Throwable.class.getMethod("getCause", null);
|
||||
} catch (Exception e) {
|
||||
causeMethod = null;
|
||||
}
|
||||
THROWABLE_CAUSE_METHOD = causeMethod;
|
||||
try {
|
||||
causeMethod = Throwable.class.getMethod("initCause", new Class[] { Throwable.class });
|
||||
} catch (Exception e) {
|
||||
causeMethod = null;
|
||||
}
|
||||
THROWABLE_INITCAUSE_METHOD = causeMethod;
|
||||
}
|
||||
|
||||
public static void addCauseMethodName(String methodName) {
|
||||
if (StringUtils.isNotEmpty(methodName) && !isCauseMethodName(methodName)) {
|
||||
List list = getCauseMethodNameList();
|
||||
if (list.add(methodName))
|
||||
synchronized (CAUSE_METHOD_NAMES) {
|
||||
CAUSE_METHOD_NAMES = toArray(list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeCauseMethodName(String methodName) {
|
||||
if (StringUtils.isNotEmpty(methodName)) {
|
||||
List list = getCauseMethodNameList();
|
||||
if (list.remove(methodName))
|
||||
synchronized (CAUSE_METHOD_NAMES) {
|
||||
CAUSE_METHOD_NAMES = toArray(list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean setCause(Throwable target, Throwable cause) {
|
||||
if (target == null)
|
||||
throw new NullArgumentException("target");
|
||||
Object[] causeArgs = { cause };
|
||||
boolean modifiedTarget = false;
|
||||
if (THROWABLE_INITCAUSE_METHOD != null)
|
||||
try {
|
||||
THROWABLE_INITCAUSE_METHOD.invoke(target, causeArgs);
|
||||
modifiedTarget = true;
|
||||
} catch (IllegalAccessException ignored) {
|
||||
|
||||
} catch (InvocationTargetException ignored) {}
|
||||
try {
|
||||
Method setCauseMethod = target.getClass().getMethod("setCause", new Class[] { Throwable.class });
|
||||
setCauseMethod.invoke(target, causeArgs);
|
||||
modifiedTarget = true;
|
||||
} catch (NoSuchMethodException ignored) {
|
||||
|
||||
} catch (IllegalAccessException ignored) {
|
||||
|
||||
} catch (InvocationTargetException ignored) {}
|
||||
return modifiedTarget;
|
||||
}
|
||||
|
||||
private static String[] toArray(List list) {
|
||||
return (String[])list.toArray(new String[list.size()]);
|
||||
}
|
||||
|
||||
private static ArrayList getCauseMethodNameList() {
|
||||
synchronized (CAUSE_METHOD_NAMES) {
|
||||
return new ArrayList(Arrays.asList(CAUSE_METHOD_NAMES));
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isCauseMethodName(String methodName) {
|
||||
synchronized (CAUSE_METHOD_NAMES) {
|
||||
return (ArrayUtils.indexOf(CAUSE_METHOD_NAMES, methodName) >= 0);
|
||||
}
|
||||
}
|
||||
|
||||
public static Throwable getCause(Throwable throwable) {
|
||||
synchronized (CAUSE_METHOD_NAMES) {
|
||||
return getCause(throwable, CAUSE_METHOD_NAMES);
|
||||
}
|
||||
}
|
||||
|
||||
public static Throwable getCause(Throwable throwable, String[] methodNames) {
|
||||
if (throwable == null)
|
||||
return null;
|
||||
Throwable cause = getCauseUsingWellKnownTypes(throwable);
|
||||
if (cause == null) {
|
||||
if (methodNames == null)
|
||||
synchronized (CAUSE_METHOD_NAMES) {
|
||||
methodNames = CAUSE_METHOD_NAMES;
|
||||
}
|
||||
for (int i = 0; i < methodNames.length; i++) {
|
||||
String methodName = methodNames[i];
|
||||
if (methodName != null) {
|
||||
cause = getCauseUsingMethodName(throwable, methodName);
|
||||
if (cause != null)
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (cause == null)
|
||||
cause = getCauseUsingFieldName(throwable, "detail");
|
||||
}
|
||||
return cause;
|
||||
}
|
||||
|
||||
public static Throwable getRootCause(Throwable throwable) {
|
||||
List list = getThrowableList(throwable);
|
||||
return (list.size() < 2) ? null : (Throwable)list.get(list.size() - 1);
|
||||
}
|
||||
|
||||
private static Throwable getCauseUsingWellKnownTypes(Throwable throwable) {
|
||||
if (throwable instanceof Nestable)
|
||||
return ((Nestable)throwable).getCause();
|
||||
if (throwable instanceof SQLException)
|
||||
return ((SQLException)throwable).getNextException();
|
||||
if (throwable instanceof InvocationTargetException)
|
||||
return ((InvocationTargetException)throwable).getTargetException();
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Throwable getCauseUsingMethodName(Throwable throwable, String methodName) {
|
||||
Method method = null;
|
||||
try {
|
||||
method = throwable.getClass().getMethod(methodName, null);
|
||||
} catch (NoSuchMethodException ignored) {
|
||||
|
||||
} catch (SecurityException ignored) {}
|
||||
if (method != null && Throwable.class.isAssignableFrom(method.getReturnType()))
|
||||
try {
|
||||
return (Throwable)method.invoke(throwable, ArrayUtils.EMPTY_OBJECT_ARRAY);
|
||||
} catch (IllegalAccessException ignored) {
|
||||
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
|
||||
} catch (InvocationTargetException ignored) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Throwable getCauseUsingFieldName(Throwable throwable, String fieldName) {
|
||||
Field field = null;
|
||||
try {
|
||||
field = throwable.getClass().getField(fieldName);
|
||||
} catch (NoSuchFieldException ignored) {
|
||||
|
||||
} catch (SecurityException ignored) {}
|
||||
if (field != null && Throwable.class.isAssignableFrom(field.getType()))
|
||||
try {
|
||||
return (Throwable)field.get(throwable);
|
||||
} catch (IllegalAccessException ignored) {
|
||||
|
||||
} catch (IllegalArgumentException ignored) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean isThrowableNested() {
|
||||
return (THROWABLE_CAUSE_METHOD != null);
|
||||
}
|
||||
|
||||
public static boolean isNestedThrowable(Throwable throwable) {
|
||||
if (throwable == null)
|
||||
return false;
|
||||
if (throwable instanceof Nestable)
|
||||
return true;
|
||||
if (throwable instanceof SQLException)
|
||||
return true;
|
||||
if (throwable instanceof InvocationTargetException)
|
||||
return true;
|
||||
if (isThrowableNested())
|
||||
return true;
|
||||
Class cls = throwable.getClass();
|
||||
synchronized (CAUSE_METHOD_NAMES) {
|
||||
for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
|
||||
try {
|
||||
Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], null);
|
||||
if (method != null && Throwable.class.isAssignableFrom(method.getReturnType()))
|
||||
return true;
|
||||
} catch (NoSuchMethodException ignored) {
|
||||
|
||||
} catch (SecurityException ignored) {}
|
||||
}
|
||||
}
|
||||
try {
|
||||
Field field = cls.getField("detail");
|
||||
if (field != null)
|
||||
return true;
|
||||
} catch (NoSuchFieldException ignored) {
|
||||
|
||||
} catch (SecurityException ignored) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static int getThrowableCount(Throwable throwable) {
|
||||
return getThrowableList(throwable).size();
|
||||
}
|
||||
|
||||
public static Throwable[] getThrowables(Throwable throwable) {
|
||||
List list = getThrowableList(throwable);
|
||||
return (Throwable[])list.toArray(new Throwable[list.size()]);
|
||||
}
|
||||
|
||||
public static List getThrowableList(Throwable throwable) {
|
||||
List list = new ArrayList();
|
||||
while (throwable != null && !list.contains(throwable)) {
|
||||
list.add(throwable);
|
||||
throwable = getCause(throwable);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static int indexOfThrowable(Throwable throwable, Class clazz) {
|
||||
return indexOf(throwable, clazz, 0, false);
|
||||
}
|
||||
|
||||
public static int indexOfThrowable(Throwable throwable, Class clazz, int fromIndex) {
|
||||
return indexOf(throwable, clazz, fromIndex, false);
|
||||
}
|
||||
|
||||
public static int indexOfType(Throwable throwable, Class type) {
|
||||
return indexOf(throwable, type, 0, true);
|
||||
}
|
||||
|
||||
public static int indexOfType(Throwable throwable, Class type, int fromIndex) {
|
||||
return indexOf(throwable, type, fromIndex, true);
|
||||
}
|
||||
|
||||
private static int indexOf(Throwable throwable, Class type, int fromIndex, boolean subclass) {
|
||||
if (throwable == null || type == null)
|
||||
return -1;
|
||||
if (fromIndex < 0)
|
||||
fromIndex = 0;
|
||||
Throwable[] throwables = getThrowables(throwable);
|
||||
if (fromIndex >= throwables.length)
|
||||
return -1;
|
||||
if (subclass) {
|
||||
for (int i = fromIndex; i < throwables.length; i++) {
|
||||
if (type.isAssignableFrom(throwables[i].getClass()))
|
||||
return i;
|
||||
}
|
||||
} else {
|
||||
for (int i = fromIndex; i < throwables.length; i++) {
|
||||
if (type.equals(throwables[i].getClass()))
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static void printRootCauseStackTrace(Throwable throwable) {
|
||||
printRootCauseStackTrace(throwable, System.err);
|
||||
}
|
||||
|
||||
public static void printRootCauseStackTrace(Throwable throwable, PrintStream stream) {
|
||||
if (throwable == null)
|
||||
return;
|
||||
if (stream == null)
|
||||
throw new IllegalArgumentException("The PrintStream must not be null");
|
||||
String[] trace = getRootCauseStackTrace(throwable);
|
||||
for (int i = 0; i < trace.length; i++)
|
||||
stream.println(trace[i]);
|
||||
stream.flush();
|
||||
}
|
||||
|
||||
public static void printRootCauseStackTrace(Throwable throwable, PrintWriter writer) {
|
||||
if (throwable == null)
|
||||
return;
|
||||
if (writer == null)
|
||||
throw new IllegalArgumentException("The PrintWriter must not be null");
|
||||
String[] trace = getRootCauseStackTrace(throwable);
|
||||
for (int i = 0; i < trace.length; i++)
|
||||
writer.println(trace[i]);
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
public static String[] getRootCauseStackTrace(Throwable throwable) {
|
||||
if (throwable == null)
|
||||
return ArrayUtils.EMPTY_STRING_ARRAY;
|
||||
Throwable[] throwables = getThrowables(throwable);
|
||||
int count = throwables.length;
|
||||
ArrayList frames = new ArrayList();
|
||||
List nextTrace = getStackFrameList(throwables[count - 1]);
|
||||
for (int i = count; --i >= 0; ) {
|
||||
List trace = nextTrace;
|
||||
if (i != 0) {
|
||||
nextTrace = getStackFrameList(throwables[i - 1]);
|
||||
removeCommonFrames(trace, nextTrace);
|
||||
}
|
||||
if (i == count - 1) {
|
||||
frames.add(throwables[i].toString());
|
||||
} else {
|
||||
frames.add(" [wrapped] " + throwables[i].toString());
|
||||
}
|
||||
for (int j = 0; j < trace.size(); j++)
|
||||
frames.add(trace.get(j));
|
||||
}
|
||||
return (String[])frames.toArray(new String[0]);
|
||||
}
|
||||
|
||||
public static void removeCommonFrames(List causeFrames, List wrapperFrames) {
|
||||
if (causeFrames == null || wrapperFrames == null)
|
||||
throw new IllegalArgumentException("The List must not be null");
|
||||
int causeFrameIndex = causeFrames.size() - 1;
|
||||
int wrapperFrameIndex = wrapperFrames.size() - 1;
|
||||
while (causeFrameIndex >= 0 && wrapperFrameIndex >= 0) {
|
||||
String causeFrame = (String)causeFrames.get(causeFrameIndex);
|
||||
String wrapperFrame = (String)wrapperFrames.get(wrapperFrameIndex);
|
||||
if (causeFrame.equals(wrapperFrame))
|
||||
causeFrames.remove(causeFrameIndex);
|
||||
causeFrameIndex--;
|
||||
wrapperFrameIndex--;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getFullStackTrace(Throwable throwable) {
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter((Writer)sw, true);
|
||||
Throwable[] ts = getThrowables(throwable);
|
||||
for (int i = 0; i < ts.length; i++) {
|
||||
ts[i].printStackTrace(pw);
|
||||
if (isNestedThrowable(ts[i]))
|
||||
break;
|
||||
}
|
||||
return sw.getBuffer().toString();
|
||||
}
|
||||
|
||||
public static String getStackTrace(Throwable throwable) {
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter((Writer)sw, true);
|
||||
throwable.printStackTrace(pw);
|
||||
return sw.getBuffer().toString();
|
||||
}
|
||||
|
||||
public static String[] getStackFrames(Throwable throwable) {
|
||||
if (throwable == null)
|
||||
return ArrayUtils.EMPTY_STRING_ARRAY;
|
||||
return getStackFrames(getStackTrace(throwable));
|
||||
}
|
||||
|
||||
static String[] getStackFrames(String stackTrace) {
|
||||
String linebreak = SystemUtils.LINE_SEPARATOR;
|
||||
StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
|
||||
List list = new ArrayList();
|
||||
while (frames.hasMoreTokens())
|
||||
list.add(frames.nextToken());
|
||||
return toArray(list);
|
||||
}
|
||||
|
||||
static List getStackFrameList(Throwable t) {
|
||||
String stackTrace = getStackTrace(t);
|
||||
String linebreak = SystemUtils.LINE_SEPARATOR;
|
||||
StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
|
||||
List list = new ArrayList();
|
||||
boolean traceStarted = false;
|
||||
while (frames.hasMoreTokens()) {
|
||||
String token = frames.nextToken();
|
||||
int at = token.indexOf("at");
|
||||
if (at != -1 && token.substring(0, at).trim().length() == 0) {
|
||||
traceStarted = true;
|
||||
list.add(token);
|
||||
continue;
|
||||
}
|
||||
if (traceStarted)
|
||||
break;
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static String getMessage(Throwable th) {
|
||||
if (th == null)
|
||||
return "";
|
||||
String clsName = ClassUtils.getShortClassName(th, null);
|
||||
String msg = th.getMessage();
|
||||
return clsName + ": " + StringUtils.defaultString(msg);
|
||||
}
|
||||
|
||||
public static String getRootCauseMessage(Throwable th) {
|
||||
Throwable root = getRootCause(th);
|
||||
root = (root == null) ? th : root;
|
||||
return getMessage(root);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package org.apache.commons.lang.exception;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
public interface Nestable {
|
||||
Throwable getCause();
|
||||
|
||||
String getMessage();
|
||||
|
||||
String getMessage(int paramInt);
|
||||
|
||||
String[] getMessages();
|
||||
|
||||
Throwable getThrowable(int paramInt);
|
||||
|
||||
int getThrowableCount();
|
||||
|
||||
Throwable[] getThrowables();
|
||||
|
||||
int indexOfThrowable(Class paramClass);
|
||||
|
||||
int indexOfThrowable(Class paramClass, int paramInt);
|
||||
|
||||
void printStackTrace(PrintWriter paramPrintWriter);
|
||||
|
||||
void printStackTrace(PrintStream paramPrintStream);
|
||||
|
||||
void printPartialStackTrace(PrintWriter paramPrintWriter);
|
||||
}
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
package org.apache.commons.lang.exception;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.Serializable;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class NestableDelegate implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static final transient String MUST_BE_THROWABLE = "The Nestable implementation passed to the NestableDelegate(Nestable) constructor must extend java.lang.Throwable";
|
||||
|
||||
private Throwable nestable = null;
|
||||
|
||||
public static boolean topDown = true;
|
||||
|
||||
public static boolean trimStackFrames = true;
|
||||
|
||||
public static boolean matchSubclasses = true;
|
||||
|
||||
public NestableDelegate(Nestable nestable) {
|
||||
if (nestable instanceof Throwable) {
|
||||
this.nestable = (Throwable)nestable;
|
||||
} else {
|
||||
throw new IllegalArgumentException("The Nestable implementation passed to the NestableDelegate(Nestable) constructor must extend java.lang.Throwable");
|
||||
}
|
||||
}
|
||||
|
||||
public String getMessage(int index) {
|
||||
Throwable t = getThrowable(index);
|
||||
if (Nestable.class.isInstance(t))
|
||||
return ((Nestable)t).getMessage(0);
|
||||
return t.getMessage();
|
||||
}
|
||||
|
||||
public String getMessage(String baseMsg) {
|
||||
Throwable nestedCause = ExceptionUtils.getCause(this.nestable);
|
||||
String causeMsg = (nestedCause == null) ? null : nestedCause.getMessage();
|
||||
if (nestedCause == null || causeMsg == null)
|
||||
return baseMsg;
|
||||
if (baseMsg == null)
|
||||
return causeMsg;
|
||||
return baseMsg + ": " + causeMsg;
|
||||
}
|
||||
|
||||
public String[] getMessages() {
|
||||
Throwable[] throwables = getThrowables();
|
||||
String[] msgs = new String[throwables.length];
|
||||
for (int i = 0; i < throwables.length; i++)
|
||||
msgs[i] = Nestable.class.isInstance(throwables[i]) ? ((Nestable)throwables[i]).getMessage(0) : throwables[i].getMessage();
|
||||
return msgs;
|
||||
}
|
||||
|
||||
public Throwable getThrowable(int index) {
|
||||
if (index == 0)
|
||||
return this.nestable;
|
||||
Throwable[] throwables = getThrowables();
|
||||
return throwables[index];
|
||||
}
|
||||
|
||||
public int getThrowableCount() {
|
||||
return ExceptionUtils.getThrowableCount(this.nestable);
|
||||
}
|
||||
|
||||
public Throwable[] getThrowables() {
|
||||
return ExceptionUtils.getThrowables(this.nestable);
|
||||
}
|
||||
|
||||
public int indexOfThrowable(Class type, int fromIndex) {
|
||||
if (type == null)
|
||||
return -1;
|
||||
if (fromIndex < 0)
|
||||
throw new IndexOutOfBoundsException("The start index was out of bounds: " + fromIndex);
|
||||
Throwable[] throwables = ExceptionUtils.getThrowables(this.nestable);
|
||||
if (fromIndex >= throwables.length)
|
||||
throw new IndexOutOfBoundsException("The start index was out of bounds: " + fromIndex + " >= " + throwables.length);
|
||||
if (matchSubclasses) {
|
||||
for (int i = fromIndex; i < throwables.length; i++) {
|
||||
if (type.isAssignableFrom(throwables[i].getClass()))
|
||||
return i;
|
||||
}
|
||||
} else {
|
||||
for (int i = fromIndex; i < throwables.length; i++) {
|
||||
if (type.equals(throwables[i].getClass()))
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public void printStackTrace() {
|
||||
printStackTrace(System.err);
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintStream out) {
|
||||
synchronized (out) {
|
||||
PrintWriter pw = new PrintWriter(out, false);
|
||||
printStackTrace(pw);
|
||||
pw.flush();
|
||||
}
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintWriter out) {
|
||||
Throwable throwable = this.nestable;
|
||||
if (ExceptionUtils.isThrowableNested()) {
|
||||
if (throwable instanceof Nestable) {
|
||||
((Nestable)throwable).printPartialStackTrace(out);
|
||||
} else {
|
||||
throwable.printStackTrace(out);
|
||||
}
|
||||
return;
|
||||
}
|
||||
List stacks = new ArrayList();
|
||||
while (throwable != null) {
|
||||
String[] st = getStackFrames(throwable);
|
||||
stacks.add(st);
|
||||
throwable = ExceptionUtils.getCause(throwable);
|
||||
}
|
||||
String separatorLine = "Caused by: ";
|
||||
if (!topDown) {
|
||||
separatorLine = "Rethrown as: ";
|
||||
Collections.reverse(stacks);
|
||||
}
|
||||
if (trimStackFrames)
|
||||
trimStackFrames(stacks);
|
||||
synchronized (out) {
|
||||
for (Iterator iter = stacks.iterator(); iter.hasNext(); ) {
|
||||
String[] st = (String[])iter.next();
|
||||
for (int i = 0, len = st.length; i < len; i++)
|
||||
out.println(st[i]);
|
||||
if (iter.hasNext())
|
||||
out.print(separatorLine);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected String[] getStackFrames(Throwable t) {
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter((Writer)sw, true);
|
||||
if (t instanceof Nestable) {
|
||||
((Nestable)t).printPartialStackTrace(pw);
|
||||
} else {
|
||||
t.printStackTrace(pw);
|
||||
}
|
||||
return ExceptionUtils.getStackFrames(sw.getBuffer().toString());
|
||||
}
|
||||
|
||||
protected void trimStackFrames(List stacks) {
|
||||
for (int size = stacks.size(), i = size - 1; i > 0; i--) {
|
||||
String[] curr = (String[])stacks.get(i);
|
||||
String[] next = (String[])stacks.get(i - 1);
|
||||
List currList = new ArrayList(Arrays.asList(curr));
|
||||
List nextList = new ArrayList(Arrays.asList(next));
|
||||
ExceptionUtils.removeCommonFrames(currList, nextList);
|
||||
int trimmed = curr.length - currList.size();
|
||||
if (trimmed > 0) {
|
||||
currList.add("\t... " + trimmed + " more");
|
||||
stacks.set(i, currList.toArray(new String[currList.size()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
package org.apache.commons.lang.exception;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
public class NestableError extends Error implements Nestable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
protected NestableDelegate delegate = new NestableDelegate(this);
|
||||
|
||||
private Throwable cause = null;
|
||||
|
||||
public NestableError() {}
|
||||
|
||||
public NestableError(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public NestableError(Throwable cause) {
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
public NestableError(String msg, Throwable cause) {
|
||||
super(msg);
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
public Throwable getCause() {
|
||||
return this.cause;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
if (super.getMessage() != null)
|
||||
return super.getMessage();
|
||||
if (this.cause != null)
|
||||
return this.cause.toString();
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getMessage(int index) {
|
||||
if (index == 0)
|
||||
return super.getMessage();
|
||||
return this.delegate.getMessage(index);
|
||||
}
|
||||
|
||||
public String[] getMessages() {
|
||||
return this.delegate.getMessages();
|
||||
}
|
||||
|
||||
public Throwable getThrowable(int index) {
|
||||
return this.delegate.getThrowable(index);
|
||||
}
|
||||
|
||||
public int getThrowableCount() {
|
||||
return this.delegate.getThrowableCount();
|
||||
}
|
||||
|
||||
public Throwable[] getThrowables() {
|
||||
return this.delegate.getThrowables();
|
||||
}
|
||||
|
||||
public int indexOfThrowable(Class type) {
|
||||
return this.delegate.indexOfThrowable(type, 0);
|
||||
}
|
||||
|
||||
public int indexOfThrowable(Class type, int fromIndex) {
|
||||
return this.delegate.indexOfThrowable(type, fromIndex);
|
||||
}
|
||||
|
||||
public void printStackTrace() {
|
||||
this.delegate.printStackTrace();
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintStream out) {
|
||||
this.delegate.printStackTrace(out);
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintWriter out) {
|
||||
this.delegate.printStackTrace(out);
|
||||
}
|
||||
|
||||
public final void printPartialStackTrace(PrintWriter out) {
|
||||
super.printStackTrace(out);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
package org.apache.commons.lang.exception;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
public class NestableException extends Exception implements Nestable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
protected NestableDelegate delegate = new NestableDelegate(this);
|
||||
|
||||
private Throwable cause = null;
|
||||
|
||||
public NestableException() {}
|
||||
|
||||
public NestableException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public NestableException(Throwable cause) {
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
public NestableException(String msg, Throwable cause) {
|
||||
super(msg);
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
public Throwable getCause() {
|
||||
return this.cause;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
if (super.getMessage() != null)
|
||||
return super.getMessage();
|
||||
if (this.cause != null)
|
||||
return this.cause.toString();
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getMessage(int index) {
|
||||
if (index == 0)
|
||||
return super.getMessage();
|
||||
return this.delegate.getMessage(index);
|
||||
}
|
||||
|
||||
public String[] getMessages() {
|
||||
return this.delegate.getMessages();
|
||||
}
|
||||
|
||||
public Throwable getThrowable(int index) {
|
||||
return this.delegate.getThrowable(index);
|
||||
}
|
||||
|
||||
public int getThrowableCount() {
|
||||
return this.delegate.getThrowableCount();
|
||||
}
|
||||
|
||||
public Throwable[] getThrowables() {
|
||||
return this.delegate.getThrowables();
|
||||
}
|
||||
|
||||
public int indexOfThrowable(Class type) {
|
||||
return this.delegate.indexOfThrowable(type, 0);
|
||||
}
|
||||
|
||||
public int indexOfThrowable(Class type, int fromIndex) {
|
||||
return this.delegate.indexOfThrowable(type, fromIndex);
|
||||
}
|
||||
|
||||
public void printStackTrace() {
|
||||
this.delegate.printStackTrace();
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintStream out) {
|
||||
this.delegate.printStackTrace(out);
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintWriter out) {
|
||||
this.delegate.printStackTrace(out);
|
||||
}
|
||||
|
||||
public final void printPartialStackTrace(PrintWriter out) {
|
||||
super.printStackTrace(out);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
package org.apache.commons.lang.exception;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
public class NestableRuntimeException extends RuntimeException implements Nestable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
protected NestableDelegate delegate = new NestableDelegate(this);
|
||||
|
||||
private Throwable cause = null;
|
||||
|
||||
public NestableRuntimeException() {}
|
||||
|
||||
public NestableRuntimeException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public NestableRuntimeException(Throwable cause) {
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
public NestableRuntimeException(String msg, Throwable cause) {
|
||||
super(msg);
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
public Throwable getCause() {
|
||||
return this.cause;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
if (super.getMessage() != null)
|
||||
return super.getMessage();
|
||||
if (this.cause != null)
|
||||
return this.cause.toString();
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getMessage(int index) {
|
||||
if (index == 0)
|
||||
return super.getMessage();
|
||||
return this.delegate.getMessage(index);
|
||||
}
|
||||
|
||||
public String[] getMessages() {
|
||||
return this.delegate.getMessages();
|
||||
}
|
||||
|
||||
public Throwable getThrowable(int index) {
|
||||
return this.delegate.getThrowable(index);
|
||||
}
|
||||
|
||||
public int getThrowableCount() {
|
||||
return this.delegate.getThrowableCount();
|
||||
}
|
||||
|
||||
public Throwable[] getThrowables() {
|
||||
return this.delegate.getThrowables();
|
||||
}
|
||||
|
||||
public int indexOfThrowable(Class type) {
|
||||
return this.delegate.indexOfThrowable(type, 0);
|
||||
}
|
||||
|
||||
public int indexOfThrowable(Class type, int fromIndex) {
|
||||
return this.delegate.indexOfThrowable(type, fromIndex);
|
||||
}
|
||||
|
||||
public void printStackTrace() {
|
||||
this.delegate.printStackTrace();
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintStream out) {
|
||||
this.delegate.printStackTrace(out);
|
||||
}
|
||||
|
||||
public void printStackTrace(PrintWriter out) {
|
||||
this.delegate.printStackTrace(out);
|
||||
}
|
||||
|
||||
public final void printPartialStackTrace(PrintWriter out) {
|
||||
super.printStackTrace(out);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,175 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public final class DoubleRange extends Range implements Serializable {
|
||||
private static final long serialVersionUID = 71849363892740L;
|
||||
|
||||
private final double min;
|
||||
|
||||
private final double max;
|
||||
|
||||
private transient Double minObject = null;
|
||||
|
||||
private transient Double maxObject = null;
|
||||
|
||||
private transient int hashCode = 0;
|
||||
|
||||
private transient String toString = null;
|
||||
|
||||
public DoubleRange(double number) {
|
||||
if (Double.isNaN(number))
|
||||
throw new IllegalArgumentException("The number must not be NaN");
|
||||
this.min = number;
|
||||
this.max = number;
|
||||
}
|
||||
|
||||
public DoubleRange(Number number) {
|
||||
if (number == null)
|
||||
throw new IllegalArgumentException("The number must not be null");
|
||||
this.min = number.doubleValue();
|
||||
this.max = number.doubleValue();
|
||||
if (Double.isNaN(this.min) || Double.isNaN(this.max))
|
||||
throw new IllegalArgumentException("The number must not be NaN");
|
||||
if (number instanceof Double) {
|
||||
this.minObject = (Double)number;
|
||||
this.maxObject = (Double)number;
|
||||
}
|
||||
}
|
||||
|
||||
public DoubleRange(double number1, double number2) {
|
||||
if (Double.isNaN(number1) || Double.isNaN(number2))
|
||||
throw new IllegalArgumentException("The numbers must not be NaN");
|
||||
if (number2 < number1) {
|
||||
this.min = number2;
|
||||
this.max = number1;
|
||||
} else {
|
||||
this.min = number1;
|
||||
this.max = number2;
|
||||
}
|
||||
}
|
||||
|
||||
public DoubleRange(Number number1, Number number2) {
|
||||
if (number1 == null || number2 == null)
|
||||
throw new IllegalArgumentException("The numbers must not be null");
|
||||
double number1val = number1.doubleValue();
|
||||
double number2val = number2.doubleValue();
|
||||
if (Double.isNaN(number1val) || Double.isNaN(number2val))
|
||||
throw new IllegalArgumentException("The numbers must not be NaN");
|
||||
if (number2val < number1val) {
|
||||
this.min = number2val;
|
||||
this.max = number1val;
|
||||
if (number2 instanceof Double)
|
||||
this.minObject = (Double)number2;
|
||||
if (number1 instanceof Double)
|
||||
this.maxObject = (Double)number1;
|
||||
} else {
|
||||
this.min = number1val;
|
||||
this.max = number2val;
|
||||
if (number1 instanceof Double)
|
||||
this.minObject = (Double)number1;
|
||||
if (number2 instanceof Double)
|
||||
this.maxObject = (Double)number2;
|
||||
}
|
||||
}
|
||||
|
||||
public Number getMinimumNumber() {
|
||||
if (this.minObject == null)
|
||||
this.minObject = new Double(this.min);
|
||||
return this.minObject;
|
||||
}
|
||||
|
||||
public long getMinimumLong() {
|
||||
return (long)this.min;
|
||||
}
|
||||
|
||||
public int getMinimumInteger() {
|
||||
return (int)this.min;
|
||||
}
|
||||
|
||||
public double getMinimumDouble() {
|
||||
return this.min;
|
||||
}
|
||||
|
||||
public float getMinimumFloat() {
|
||||
return (float)this.min;
|
||||
}
|
||||
|
||||
public Number getMaximumNumber() {
|
||||
if (this.maxObject == null)
|
||||
this.maxObject = new Double(this.max);
|
||||
return this.maxObject;
|
||||
}
|
||||
|
||||
public long getMaximumLong() {
|
||||
return (long)this.max;
|
||||
}
|
||||
|
||||
public int getMaximumInteger() {
|
||||
return (int)this.max;
|
||||
}
|
||||
|
||||
public double getMaximumDouble() {
|
||||
return this.max;
|
||||
}
|
||||
|
||||
public float getMaximumFloat() {
|
||||
return (float)this.max;
|
||||
}
|
||||
|
||||
public boolean containsNumber(Number number) {
|
||||
if (number == null)
|
||||
return false;
|
||||
return containsDouble(number.doubleValue());
|
||||
}
|
||||
|
||||
public boolean containsDouble(double value) {
|
||||
return (value >= this.min && value <= this.max);
|
||||
}
|
||||
|
||||
public boolean containsRange(Range range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (containsDouble(range.getMinimumDouble()) && containsDouble(range.getMaximumDouble()));
|
||||
}
|
||||
|
||||
public boolean overlapsRange(Range range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (range.containsDouble(this.min) || range.containsDouble(this.max) || containsDouble(range.getMinimumDouble()));
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (!(obj instanceof DoubleRange))
|
||||
return false;
|
||||
DoubleRange range = (DoubleRange)obj;
|
||||
return (Double.doubleToLongBits(this.min) == Double.doubleToLongBits(range.min) && Double.doubleToLongBits(this.max) == Double.doubleToLongBits(range.max));
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
if (this.hashCode == 0) {
|
||||
this.hashCode = 17;
|
||||
this.hashCode = 37 * this.hashCode + getClass().hashCode();
|
||||
long lng = Double.doubleToLongBits(this.min);
|
||||
this.hashCode = 37 * this.hashCode + (int)(lng ^ lng >> 32L);
|
||||
lng = Double.doubleToLongBits(this.max);
|
||||
this.hashCode = 37 * this.hashCode + (int)(lng ^ lng >> 32L);
|
||||
}
|
||||
return this.hashCode;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.toString == null) {
|
||||
StringBuffer buf = new StringBuffer(32);
|
||||
buf.append("Range[");
|
||||
buf.append(this.min);
|
||||
buf.append(',');
|
||||
buf.append(this.max);
|
||||
buf.append(']');
|
||||
this.toString = buf.toString();
|
||||
}
|
||||
return this.toString;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,173 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public final class FloatRange extends Range implements Serializable {
|
||||
private static final long serialVersionUID = 71849363892750L;
|
||||
|
||||
private final float min;
|
||||
|
||||
private final float max;
|
||||
|
||||
private transient Float minObject = null;
|
||||
|
||||
private transient Float maxObject = null;
|
||||
|
||||
private transient int hashCode = 0;
|
||||
|
||||
private transient String toString = null;
|
||||
|
||||
public FloatRange(float number) {
|
||||
if (Float.isNaN(number))
|
||||
throw new IllegalArgumentException("The number must not be NaN");
|
||||
this.min = number;
|
||||
this.max = number;
|
||||
}
|
||||
|
||||
public FloatRange(Number number) {
|
||||
if (number == null)
|
||||
throw new IllegalArgumentException("The number must not be null");
|
||||
this.min = number.floatValue();
|
||||
this.max = number.floatValue();
|
||||
if (Float.isNaN(this.min) || Float.isNaN(this.max))
|
||||
throw new IllegalArgumentException("The number must not be NaN");
|
||||
if (number instanceof Float) {
|
||||
this.minObject = (Float)number;
|
||||
this.maxObject = (Float)number;
|
||||
}
|
||||
}
|
||||
|
||||
public FloatRange(float number1, float number2) {
|
||||
if (Float.isNaN(number1) || Float.isNaN(number2))
|
||||
throw new IllegalArgumentException("The numbers must not be NaN");
|
||||
if (number2 < number1) {
|
||||
this.min = number2;
|
||||
this.max = number1;
|
||||
} else {
|
||||
this.min = number1;
|
||||
this.max = number2;
|
||||
}
|
||||
}
|
||||
|
||||
public FloatRange(Number number1, Number number2) {
|
||||
if (number1 == null || number2 == null)
|
||||
throw new IllegalArgumentException("The numbers must not be null");
|
||||
float number1val = number1.floatValue();
|
||||
float number2val = number2.floatValue();
|
||||
if (Float.isNaN(number1val) || Float.isNaN(number2val))
|
||||
throw new IllegalArgumentException("The numbers must not be NaN");
|
||||
if (number2val < number1val) {
|
||||
this.min = number2val;
|
||||
this.max = number1val;
|
||||
if (number2 instanceof Float)
|
||||
this.minObject = (Float)number2;
|
||||
if (number1 instanceof Float)
|
||||
this.maxObject = (Float)number1;
|
||||
} else {
|
||||
this.min = number1val;
|
||||
this.max = number2val;
|
||||
if (number1 instanceof Float)
|
||||
this.minObject = (Float)number1;
|
||||
if (number2 instanceof Float)
|
||||
this.maxObject = (Float)number2;
|
||||
}
|
||||
}
|
||||
|
||||
public Number getMinimumNumber() {
|
||||
if (this.minObject == null)
|
||||
this.minObject = new Float(this.min);
|
||||
return this.minObject;
|
||||
}
|
||||
|
||||
public long getMinimumLong() {
|
||||
return (long)this.min;
|
||||
}
|
||||
|
||||
public int getMinimumInteger() {
|
||||
return (int)this.min;
|
||||
}
|
||||
|
||||
public double getMinimumDouble() {
|
||||
return (double)this.min;
|
||||
}
|
||||
|
||||
public float getMinimumFloat() {
|
||||
return this.min;
|
||||
}
|
||||
|
||||
public Number getMaximumNumber() {
|
||||
if (this.maxObject == null)
|
||||
this.maxObject = new Float(this.max);
|
||||
return this.maxObject;
|
||||
}
|
||||
|
||||
public long getMaximumLong() {
|
||||
return (long)this.max;
|
||||
}
|
||||
|
||||
public int getMaximumInteger() {
|
||||
return (int)this.max;
|
||||
}
|
||||
|
||||
public double getMaximumDouble() {
|
||||
return (double)this.max;
|
||||
}
|
||||
|
||||
public float getMaximumFloat() {
|
||||
return this.max;
|
||||
}
|
||||
|
||||
public boolean containsNumber(Number number) {
|
||||
if (number == null)
|
||||
return false;
|
||||
return containsFloat(number.floatValue());
|
||||
}
|
||||
|
||||
public boolean containsFloat(float value) {
|
||||
return (value >= this.min && value <= this.max);
|
||||
}
|
||||
|
||||
public boolean containsRange(Range range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (containsFloat(range.getMinimumFloat()) && containsFloat(range.getMaximumFloat()));
|
||||
}
|
||||
|
||||
public boolean overlapsRange(Range range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (range.containsFloat(this.min) || range.containsFloat(this.max) || containsFloat(range.getMinimumFloat()));
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (!(obj instanceof FloatRange))
|
||||
return false;
|
||||
FloatRange range = (FloatRange)obj;
|
||||
return (Float.floatToIntBits(this.min) == Float.floatToIntBits(range.min) && Float.floatToIntBits(this.max) == Float.floatToIntBits(range.max));
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
if (this.hashCode == 0) {
|
||||
this.hashCode = 17;
|
||||
this.hashCode = 37 * this.hashCode + getClass().hashCode();
|
||||
this.hashCode = 37 * this.hashCode + Float.floatToIntBits(this.min);
|
||||
this.hashCode = 37 * this.hashCode + Float.floatToIntBits(this.max);
|
||||
}
|
||||
return this.hashCode;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.toString == null) {
|
||||
StringBuffer buf = new StringBuffer(32);
|
||||
buf.append("Range[");
|
||||
buf.append(this.min);
|
||||
buf.append(',');
|
||||
buf.append(this.max);
|
||||
buf.append(']');
|
||||
this.toString = buf.toString();
|
||||
}
|
||||
return this.toString;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,411 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public final class Fraction extends Number implements Comparable {
|
||||
private static final long serialVersionUID = 65382027393090L;
|
||||
|
||||
public static final Fraction ZERO = new Fraction(0, 1);
|
||||
|
||||
public static final Fraction ONE = new Fraction(1, 1);
|
||||
|
||||
public static final Fraction ONE_HALF = new Fraction(1, 2);
|
||||
|
||||
public static final Fraction ONE_THIRD = new Fraction(1, 3);
|
||||
|
||||
public static final Fraction TWO_THIRDS = new Fraction(2, 3);
|
||||
|
||||
public static final Fraction ONE_QUARTER = new Fraction(1, 4);
|
||||
|
||||
public static final Fraction TWO_QUARTERS = new Fraction(2, 4);
|
||||
|
||||
public static final Fraction THREE_QUARTERS = new Fraction(3, 4);
|
||||
|
||||
public static final Fraction ONE_FIFTH = new Fraction(1, 5);
|
||||
|
||||
public static final Fraction TWO_FIFTHS = new Fraction(2, 5);
|
||||
|
||||
public static final Fraction THREE_FIFTHS = new Fraction(3, 5);
|
||||
|
||||
public static final Fraction FOUR_FIFTHS = new Fraction(4, 5);
|
||||
|
||||
private final int numerator;
|
||||
|
||||
private final int denominator;
|
||||
|
||||
private transient int hashCode = 0;
|
||||
|
||||
private transient String toString = null;
|
||||
|
||||
private transient String toProperString = null;
|
||||
|
||||
private Fraction(int numerator, int denominator) {
|
||||
this.numerator = numerator;
|
||||
this.denominator = denominator;
|
||||
}
|
||||
|
||||
public static Fraction getFraction(int numerator, int denominator) {
|
||||
if (denominator == 0)
|
||||
throw new ArithmeticException("The denominator must not be zero");
|
||||
if (denominator < 0) {
|
||||
if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE)
|
||||
throw new ArithmeticException("overflow: can't negate");
|
||||
numerator = -numerator;
|
||||
denominator = -denominator;
|
||||
}
|
||||
return new Fraction(numerator, denominator);
|
||||
}
|
||||
|
||||
public static Fraction getFraction(int whole, int numerator, int denominator) {
|
||||
long numeratorValue;
|
||||
if (denominator == 0)
|
||||
throw new ArithmeticException("The denominator must not be zero");
|
||||
if (denominator < 0)
|
||||
throw new ArithmeticException("The denominator must not be negative");
|
||||
if (numerator < 0)
|
||||
throw new ArithmeticException("The numerator must not be negative");
|
||||
if (whole < 0) {
|
||||
numeratorValue = (long)whole * (long)denominator - (long)numerator;
|
||||
} else {
|
||||
numeratorValue = (long)whole * (long)denominator + (long)numerator;
|
||||
}
|
||||
if (numeratorValue < Integer.MIN_VALUE || numeratorValue > Integer.MAX_VALUE)
|
||||
throw new ArithmeticException("Numerator too large to represent as an Integer.");
|
||||
return new Fraction((int)numeratorValue, denominator);
|
||||
}
|
||||
|
||||
public static Fraction getReducedFraction(int numerator, int denominator) {
|
||||
if (denominator == 0)
|
||||
throw new ArithmeticException("The denominator must not be zero");
|
||||
if (numerator == 0)
|
||||
return ZERO;
|
||||
if (denominator == Integer.MIN_VALUE && (numerator & 0x1) == 0) {
|
||||
numerator /= 2;
|
||||
denominator /= 2;
|
||||
}
|
||||
if (denominator < 0) {
|
||||
if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE)
|
||||
throw new ArithmeticException("overflow: can't negate");
|
||||
numerator = -numerator;
|
||||
denominator = -denominator;
|
||||
}
|
||||
int gcd = greatestCommonDivisor(numerator, denominator);
|
||||
numerator /= gcd;
|
||||
denominator /= gcd;
|
||||
return new Fraction(numerator, denominator);
|
||||
}
|
||||
|
||||
public static Fraction getFraction(double value) {
|
||||
double delta1;
|
||||
int sign = (value < 0.0D) ? -1 : 1;
|
||||
value = Math.abs(value);
|
||||
if (value > Integer.MAX_VALUE || Double.isNaN(value))
|
||||
throw new ArithmeticException("The value must not be greater than Integer.MAX_VALUE or NaN");
|
||||
int wholeNumber = (int)value;
|
||||
value -= (double)wholeNumber;
|
||||
int numer0 = 0;
|
||||
int denom0 = 1;
|
||||
int numer1 = 1;
|
||||
int denom1 = 0;
|
||||
int numer2 = 0;
|
||||
int denom2 = 0;
|
||||
int a1 = (int)value;
|
||||
int a2 = 0;
|
||||
double x1 = 1.0D;
|
||||
double x2 = 0.0D;
|
||||
double y1 = value - (double)a1;
|
||||
double y2 = 0.0D;
|
||||
double delta2 = Double.MAX_VALUE;
|
||||
int i = 1;
|
||||
do {
|
||||
delta1 = delta2;
|
||||
a2 = (int)(x1 / y1);
|
||||
x2 = y1;
|
||||
y2 = x1 - (double)a2 * y1;
|
||||
numer2 = a1 * numer1 + numer0;
|
||||
denom2 = a1 * denom1 + denom0;
|
||||
double fraction = (double)numer2 / (double)denom2;
|
||||
delta2 = Math.abs(value - fraction);
|
||||
a1 = a2;
|
||||
x1 = x2;
|
||||
y1 = y2;
|
||||
numer0 = numer1;
|
||||
denom0 = denom1;
|
||||
numer1 = numer2;
|
||||
denom1 = denom2;
|
||||
i++;
|
||||
} while (delta1 > delta2 && denom2 <= 10000 && denom2 > 0 && i < 25);
|
||||
if (i == 25)
|
||||
throw new ArithmeticException("Unable to convert double to fraction");
|
||||
return getReducedFraction((numer0 + wholeNumber * denom0) * sign, denom0);
|
||||
}
|
||||
|
||||
public static Fraction getFraction(String str) {
|
||||
if (str == null)
|
||||
throw new IllegalArgumentException("The string must not be null");
|
||||
int pos = str.indexOf('.');
|
||||
if (pos >= 0)
|
||||
return getFraction(Double.parseDouble(str));
|
||||
pos = str.indexOf(' ');
|
||||
if (pos > 0) {
|
||||
int whole = Integer.parseInt(str.substring(0, pos));
|
||||
str = str.substring(pos + 1);
|
||||
pos = str.indexOf('/');
|
||||
if (pos < 0)
|
||||
throw new NumberFormatException("The fraction could not be parsed as the format X Y/Z");
|
||||
int i = Integer.parseInt(str.substring(0, pos));
|
||||
int j = Integer.parseInt(str.substring(pos + 1));
|
||||
return getFraction(whole, i, j);
|
||||
}
|
||||
pos = str.indexOf('/');
|
||||
if (pos < 0)
|
||||
return getFraction(Integer.parseInt(str), 1);
|
||||
int numer = Integer.parseInt(str.substring(0, pos));
|
||||
int denom = Integer.parseInt(str.substring(pos + 1));
|
||||
return getFraction(numer, denom);
|
||||
}
|
||||
|
||||
public int getNumerator() {
|
||||
return this.numerator;
|
||||
}
|
||||
|
||||
public int getDenominator() {
|
||||
return this.denominator;
|
||||
}
|
||||
|
||||
public int getProperNumerator() {
|
||||
return Math.abs(this.numerator % this.denominator);
|
||||
}
|
||||
|
||||
public int getProperWhole() {
|
||||
return this.numerator / this.denominator;
|
||||
}
|
||||
|
||||
public int intValue() {
|
||||
return this.numerator / this.denominator;
|
||||
}
|
||||
|
||||
public long longValue() {
|
||||
return (long)this.numerator / (long)this.denominator;
|
||||
}
|
||||
|
||||
public float floatValue() {
|
||||
return (float)this.numerator / (float)this.denominator;
|
||||
}
|
||||
|
||||
public double doubleValue() {
|
||||
return (double)this.numerator / (double)this.denominator;
|
||||
}
|
||||
|
||||
public Fraction reduce() {
|
||||
if (this.numerator == 0)
|
||||
return equals(ZERO) ? this : ZERO;
|
||||
int gcd = greatestCommonDivisor(Math.abs(this.numerator), this.denominator);
|
||||
if (gcd == 1)
|
||||
return this;
|
||||
return getFraction(this.numerator / gcd, this.denominator / gcd);
|
||||
}
|
||||
|
||||
public Fraction invert() {
|
||||
if (this.numerator == 0)
|
||||
throw new ArithmeticException("Unable to invert zero.");
|
||||
if (this.numerator == Integer.MIN_VALUE)
|
||||
throw new ArithmeticException("overflow: can't negate numerator");
|
||||
if (this.numerator < 0)
|
||||
return new Fraction(-this.denominator, -this.numerator);
|
||||
return new Fraction(this.denominator, this.numerator);
|
||||
}
|
||||
|
||||
public Fraction negate() {
|
||||
if (this.numerator == Integer.MIN_VALUE)
|
||||
throw new ArithmeticException("overflow: too large to negate");
|
||||
return new Fraction(-this.numerator, this.denominator);
|
||||
}
|
||||
|
||||
public Fraction abs() {
|
||||
if (this.numerator >= 0)
|
||||
return this;
|
||||
return negate();
|
||||
}
|
||||
|
||||
public Fraction pow(int power) {
|
||||
if (power == 1)
|
||||
return this;
|
||||
if (power == 0)
|
||||
return ONE;
|
||||
if (power < 0) {
|
||||
if (power == Integer.MIN_VALUE)
|
||||
return invert().pow(2).pow(-(power / 2));
|
||||
return invert().pow(-power);
|
||||
}
|
||||
Fraction f = multiplyBy(this);
|
||||
if (power % 2 == 0)
|
||||
return f.pow(power / 2);
|
||||
return f.pow(power / 2).multiplyBy(this);
|
||||
}
|
||||
|
||||
private static int greatestCommonDivisor(int u, int v) {
|
||||
if (Math.abs(u) <= 1 || Math.abs(v) <= 1)
|
||||
return 1;
|
||||
if (u > 0)
|
||||
u = -u;
|
||||
if (v > 0)
|
||||
v = -v;
|
||||
int k = 0;
|
||||
while ((u & 0x1) == 0 && (v & 0x1) == 0 && k < 31) {
|
||||
u /= 2;
|
||||
v /= 2;
|
||||
k++;
|
||||
}
|
||||
if (k == 31)
|
||||
throw new ArithmeticException("overflow: gcd is 2^31");
|
||||
int t = ((u & 0x1) == 1) ? v : -(u / 2);
|
||||
while (true) {
|
||||
while ((t & 0x1) == 0)
|
||||
t /= 2;
|
||||
if (t > 0) {
|
||||
u = -t;
|
||||
} else {
|
||||
v = t;
|
||||
}
|
||||
t = (v - u) / 2;
|
||||
if (t == 0)
|
||||
return -u * (1 << k);
|
||||
}
|
||||
}
|
||||
|
||||
private static int mulAndCheck(int x, int y) {
|
||||
long m = (long)x * (long)y;
|
||||
if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE)
|
||||
throw new ArithmeticException("overflow: mul");
|
||||
return (int)m;
|
||||
}
|
||||
|
||||
private static int mulPosAndCheck(int x, int y) {
|
||||
long m = (long)x * (long)y;
|
||||
if (m > Integer.MAX_VALUE)
|
||||
throw new ArithmeticException("overflow: mulPos");
|
||||
return (int)m;
|
||||
}
|
||||
|
||||
private static int addAndCheck(int x, int y) {
|
||||
long s = (long)x + (long)y;
|
||||
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE)
|
||||
throw new ArithmeticException("overflow: add");
|
||||
return (int)s;
|
||||
}
|
||||
|
||||
private static int subAndCheck(int x, int y) {
|
||||
long s = (long)x - (long)y;
|
||||
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE)
|
||||
throw new ArithmeticException("overflow: add");
|
||||
return (int)s;
|
||||
}
|
||||
|
||||
public Fraction add(Fraction fraction) {
|
||||
return addSub(fraction, true);
|
||||
}
|
||||
|
||||
public Fraction subtract(Fraction fraction) {
|
||||
return addSub(fraction, false);
|
||||
}
|
||||
|
||||
private Fraction addSub(Fraction fraction, boolean isAdd) {
|
||||
if (fraction == null)
|
||||
throw new IllegalArgumentException("The fraction must not be null");
|
||||
if (this.numerator == 0)
|
||||
return isAdd ? fraction : fraction.negate();
|
||||
if (fraction.numerator == 0)
|
||||
return this;
|
||||
int d1 = greatestCommonDivisor(this.denominator, fraction.denominator);
|
||||
if (d1 == 1) {
|
||||
int i = mulAndCheck(this.numerator, fraction.denominator);
|
||||
int j = mulAndCheck(fraction.numerator, this.denominator);
|
||||
return new Fraction(isAdd ? addAndCheck(i, j) : subAndCheck(i, j), mulPosAndCheck(this.denominator, fraction.denominator));
|
||||
}
|
||||
BigInteger uvp = BigInteger.valueOf((long)this.numerator).multiply(BigInteger.valueOf((long)(fraction.denominator / d1)));
|
||||
BigInteger upv = BigInteger.valueOf((long)fraction.numerator).multiply(BigInteger.valueOf((long)(this.denominator / d1)));
|
||||
BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv);
|
||||
int tmodd1 = t.mod(BigInteger.valueOf((long)d1)).intValue();
|
||||
int d2 = (tmodd1 == 0) ? d1 : greatestCommonDivisor(tmodd1, d1);
|
||||
BigInteger w = t.divide(BigInteger.valueOf((long)d2));
|
||||
if (w.bitLength() > 31)
|
||||
throw new ArithmeticException("overflow: numerator too large after multiply");
|
||||
return new Fraction(w.intValue(), mulPosAndCheck(this.denominator / d1, fraction.denominator / d2));
|
||||
}
|
||||
|
||||
public Fraction multiplyBy(Fraction fraction) {
|
||||
if (fraction == null)
|
||||
throw new IllegalArgumentException("The fraction must not be null");
|
||||
if (this.numerator == 0 || fraction.numerator == 0)
|
||||
return ZERO;
|
||||
int d1 = greatestCommonDivisor(this.numerator, fraction.denominator);
|
||||
int d2 = greatestCommonDivisor(fraction.numerator, this.denominator);
|
||||
return getReducedFraction(mulAndCheck(this.numerator / d1, fraction.numerator / d2), mulPosAndCheck(this.denominator / d2, fraction.denominator / d1));
|
||||
}
|
||||
|
||||
public Fraction divideBy(Fraction fraction) {
|
||||
if (fraction == null)
|
||||
throw new IllegalArgumentException("The fraction must not be null");
|
||||
if (fraction.numerator == 0)
|
||||
throw new ArithmeticException("The fraction to divide by must not be zero");
|
||||
return multiplyBy(fraction.invert());
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (!(obj instanceof Fraction))
|
||||
return false;
|
||||
Fraction other = (Fraction)obj;
|
||||
return (getNumerator() == other.getNumerator() && getDenominator() == other.getDenominator());
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
if (this.hashCode == 0)
|
||||
this.hashCode = 37 * (629 + getNumerator()) + getDenominator();
|
||||
return this.hashCode;
|
||||
}
|
||||
|
||||
public int compareTo(Object object) {
|
||||
Fraction other = (Fraction)object;
|
||||
if (this == other)
|
||||
return 0;
|
||||
if (this.numerator == other.numerator && this.denominator == other.denominator)
|
||||
return 0;
|
||||
long first = (long)this.numerator * (long)other.denominator;
|
||||
long second = (long)other.numerator * (long)this.denominator;
|
||||
if (first == second)
|
||||
return 0;
|
||||
if (first < second)
|
||||
return -1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.toString == null)
|
||||
this.toString = new StringBuffer(32).append(getNumerator()).append('/').append(getDenominator()).toString();
|
||||
return this.toString;
|
||||
}
|
||||
|
||||
public String toProperString() {
|
||||
if (this.toProperString == null)
|
||||
if (this.numerator == 0) {
|
||||
this.toProperString = "0";
|
||||
} else if (this.numerator == this.denominator) {
|
||||
this.toProperString = "1";
|
||||
} else if (this.numerator == -1 * this.denominator) {
|
||||
this.toProperString = "-1";
|
||||
} else if (((this.numerator > 0) ? -this.numerator : this.numerator) < -this.denominator) {
|
||||
int properNumerator = getProperNumerator();
|
||||
if (properNumerator == 0) {
|
||||
this.toProperString = Integer.toString(getProperWhole());
|
||||
} else {
|
||||
this.toProperString = new StringBuffer(32).append(getProperWhole()).append(' ').append(properNumerator).append('/').append(getDenominator()).toString();
|
||||
}
|
||||
} else {
|
||||
this.toProperString = new StringBuffer(32).append(getNumerator()).append('/').append(getDenominator()).toString();
|
||||
}
|
||||
return this.toProperString;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
public class IEEE754rUtils {
|
||||
public static double min(double[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
double min = array[0];
|
||||
for (int i = 1; i < array.length; i++)
|
||||
min = min(array[i], min);
|
||||
return min;
|
||||
}
|
||||
|
||||
public static float min(float[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
float min = array[0];
|
||||
for (int i = 1; i < array.length; i++)
|
||||
min = min(array[i], min);
|
||||
return min;
|
||||
}
|
||||
|
||||
public static double min(double a, double b, double c) {
|
||||
return min(min(a, b), c);
|
||||
}
|
||||
|
||||
public static double min(double a, double b) {
|
||||
if (Double.isNaN(a))
|
||||
return b;
|
||||
if (Double.isNaN(b))
|
||||
return a;
|
||||
return Math.min(a, b);
|
||||
}
|
||||
|
||||
public static float min(float a, float b, float c) {
|
||||
return min(min(a, b), c);
|
||||
}
|
||||
|
||||
public static float min(float a, float b) {
|
||||
if (Float.isNaN(a))
|
||||
return b;
|
||||
if (Float.isNaN(b))
|
||||
return a;
|
||||
return Math.min(a, b);
|
||||
}
|
||||
|
||||
public static double max(double[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
double max = array[0];
|
||||
for (int j = 1; j < array.length; j++)
|
||||
max = max(array[j], max);
|
||||
return max;
|
||||
}
|
||||
|
||||
public static float max(float[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
float max = array[0];
|
||||
for (int j = 1; j < array.length; j++)
|
||||
max = max(array[j], max);
|
||||
return max;
|
||||
}
|
||||
|
||||
public static double max(double a, double b, double c) {
|
||||
return max(max(a, b), c);
|
||||
}
|
||||
|
||||
public static double max(double a, double b) {
|
||||
if (Double.isNaN(a))
|
||||
return b;
|
||||
if (Double.isNaN(b))
|
||||
return a;
|
||||
return Math.max(a, b);
|
||||
}
|
||||
|
||||
public static float max(float a, float b, float c) {
|
||||
return max(max(a, b), c);
|
||||
}
|
||||
|
||||
public static float max(float a, float b) {
|
||||
if (Float.isNaN(a))
|
||||
return b;
|
||||
if (Float.isNaN(b))
|
||||
return a;
|
||||
return Math.max(a, b);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,172 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public final class IntRange extends Range implements Serializable {
|
||||
private static final long serialVersionUID = 71849363892730L;
|
||||
|
||||
private final int min;
|
||||
|
||||
private final int max;
|
||||
|
||||
private transient Integer minObject = null;
|
||||
|
||||
private transient Integer maxObject = null;
|
||||
|
||||
private transient int hashCode = 0;
|
||||
|
||||
private transient String toString = null;
|
||||
|
||||
public IntRange(int number) {
|
||||
this.min = number;
|
||||
this.max = number;
|
||||
}
|
||||
|
||||
public IntRange(Number number) {
|
||||
if (number == null)
|
||||
throw new IllegalArgumentException("The number must not be null");
|
||||
this.min = number.intValue();
|
||||
this.max = number.intValue();
|
||||
if (number instanceof Integer) {
|
||||
this.minObject = (Integer)number;
|
||||
this.maxObject = (Integer)number;
|
||||
}
|
||||
}
|
||||
|
||||
public IntRange(int number1, int number2) {
|
||||
if (number2 < number1) {
|
||||
this.min = number2;
|
||||
this.max = number1;
|
||||
} else {
|
||||
this.min = number1;
|
||||
this.max = number2;
|
||||
}
|
||||
}
|
||||
|
||||
public IntRange(Number number1, Number number2) {
|
||||
if (number1 == null || number2 == null)
|
||||
throw new IllegalArgumentException("The numbers must not be null");
|
||||
int number1val = number1.intValue();
|
||||
int number2val = number2.intValue();
|
||||
if (number2val < number1val) {
|
||||
this.min = number2val;
|
||||
this.max = number1val;
|
||||
if (number2 instanceof Integer)
|
||||
this.minObject = (Integer)number2;
|
||||
if (number1 instanceof Integer)
|
||||
this.maxObject = (Integer)number1;
|
||||
} else {
|
||||
this.min = number1val;
|
||||
this.max = number2val;
|
||||
if (number1 instanceof Integer)
|
||||
this.minObject = (Integer)number1;
|
||||
if (number2 instanceof Integer)
|
||||
this.maxObject = (Integer)number2;
|
||||
}
|
||||
}
|
||||
|
||||
public Number getMinimumNumber() {
|
||||
if (this.minObject == null)
|
||||
this.minObject = new Integer(this.min);
|
||||
return this.minObject;
|
||||
}
|
||||
|
||||
public long getMinimumLong() {
|
||||
return (long)this.min;
|
||||
}
|
||||
|
||||
public int getMinimumInteger() {
|
||||
return this.min;
|
||||
}
|
||||
|
||||
public double getMinimumDouble() {
|
||||
return (double)this.min;
|
||||
}
|
||||
|
||||
public float getMinimumFloat() {
|
||||
return (float)this.min;
|
||||
}
|
||||
|
||||
public Number getMaximumNumber() {
|
||||
if (this.maxObject == null)
|
||||
this.maxObject = new Integer(this.max);
|
||||
return this.maxObject;
|
||||
}
|
||||
|
||||
public long getMaximumLong() {
|
||||
return (long)this.max;
|
||||
}
|
||||
|
||||
public int getMaximumInteger() {
|
||||
return this.max;
|
||||
}
|
||||
|
||||
public double getMaximumDouble() {
|
||||
return (double)this.max;
|
||||
}
|
||||
|
||||
public float getMaximumFloat() {
|
||||
return (float)this.max;
|
||||
}
|
||||
|
||||
public boolean containsNumber(Number number) {
|
||||
if (number == null)
|
||||
return false;
|
||||
return containsInteger(number.intValue());
|
||||
}
|
||||
|
||||
public boolean containsInteger(int value) {
|
||||
return (value >= this.min && value <= this.max);
|
||||
}
|
||||
|
||||
public boolean containsRange(Range range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (containsInteger(range.getMinimumInteger()) && containsInteger(range.getMaximumInteger()));
|
||||
}
|
||||
|
||||
public boolean overlapsRange(Range range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (range.containsInteger(this.min) || range.containsInteger(this.max) || containsInteger(range.getMinimumInteger()));
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (!(obj instanceof IntRange))
|
||||
return false;
|
||||
IntRange range = (IntRange)obj;
|
||||
return (this.min == range.min && this.max == range.max);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
if (this.hashCode == 0) {
|
||||
this.hashCode = 17;
|
||||
this.hashCode = 37 * this.hashCode + getClass().hashCode();
|
||||
this.hashCode = 37 * this.hashCode + this.min;
|
||||
this.hashCode = 37 * this.hashCode + this.max;
|
||||
}
|
||||
return this.hashCode;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.toString == null) {
|
||||
StringBuffer buf = new StringBuffer(32);
|
||||
buf.append("Range[");
|
||||
buf.append(this.min);
|
||||
buf.append(',');
|
||||
buf.append(this.max);
|
||||
buf.append(']');
|
||||
this.toString = buf.toString();
|
||||
}
|
||||
return this.toString;
|
||||
}
|
||||
|
||||
public int[] toArray() {
|
||||
int[] array = new int[this.max - this.min + 1];
|
||||
for (int i = 0; i < array.length; i++)
|
||||
array[i] = this.min + i;
|
||||
return array;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public final class JVMRandom extends Random {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private boolean constructed = false;
|
||||
|
||||
public JVMRandom() {
|
||||
this.constructed = true;
|
||||
}
|
||||
|
||||
public synchronized void setSeed(long seed) {
|
||||
if (this.constructed)
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public synchronized double nextGaussian() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void nextBytes(byte[] byteArray) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public int nextInt() {
|
||||
return nextInt(Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
public int nextInt(int n) {
|
||||
if (n <= 0)
|
||||
throw new IllegalArgumentException("Upper bound for nextInt must be positive");
|
||||
return (int)(Math.random() * (double)n);
|
||||
}
|
||||
|
||||
public long nextLong() {
|
||||
return nextLong(Long.MAX_VALUE);
|
||||
}
|
||||
|
||||
public static long nextLong(long n) {
|
||||
if (n <= 0L)
|
||||
throw new IllegalArgumentException("Upper bound for nextInt must be positive");
|
||||
return (long)(Math.random() * (double)n);
|
||||
}
|
||||
|
||||
public boolean nextBoolean() {
|
||||
return (Math.random() > 0.5D);
|
||||
}
|
||||
|
||||
public float nextFloat() {
|
||||
return (float)Math.random();
|
||||
}
|
||||
|
||||
public double nextDouble() {
|
||||
return Math.random();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,172 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public final class LongRange extends Range implements Serializable {
|
||||
private static final long serialVersionUID = 71849363892720L;
|
||||
|
||||
private final long min;
|
||||
|
||||
private final long max;
|
||||
|
||||
private transient Long minObject = null;
|
||||
|
||||
private transient Long maxObject = null;
|
||||
|
||||
private transient int hashCode = 0;
|
||||
|
||||
private transient String toString = null;
|
||||
|
||||
public LongRange(long number) {
|
||||
this.min = number;
|
||||
this.max = number;
|
||||
}
|
||||
|
||||
public LongRange(Number number) {
|
||||
if (number == null)
|
||||
throw new IllegalArgumentException("The number must not be null");
|
||||
this.min = number.longValue();
|
||||
this.max = number.longValue();
|
||||
if (number instanceof Long) {
|
||||
this.minObject = (Long)number;
|
||||
this.maxObject = (Long)number;
|
||||
}
|
||||
}
|
||||
|
||||
public LongRange(long number1, long number2) {
|
||||
if (number2 < number1) {
|
||||
this.min = number2;
|
||||
this.max = number1;
|
||||
} else {
|
||||
this.min = number1;
|
||||
this.max = number2;
|
||||
}
|
||||
}
|
||||
|
||||
public LongRange(Number number1, Number number2) {
|
||||
if (number1 == null || number2 == null)
|
||||
throw new IllegalArgumentException("The numbers must not be null");
|
||||
long number1val = number1.longValue();
|
||||
long number2val = number2.longValue();
|
||||
if (number2val < number1val) {
|
||||
this.min = number2val;
|
||||
this.max = number1val;
|
||||
if (number2 instanceof Long)
|
||||
this.minObject = (Long)number2;
|
||||
if (number1 instanceof Long)
|
||||
this.maxObject = (Long)number1;
|
||||
} else {
|
||||
this.min = number1val;
|
||||
this.max = number2val;
|
||||
if (number1 instanceof Long)
|
||||
this.minObject = (Long)number1;
|
||||
if (number2 instanceof Long)
|
||||
this.maxObject = (Long)number2;
|
||||
}
|
||||
}
|
||||
|
||||
public Number getMinimumNumber() {
|
||||
if (this.minObject == null)
|
||||
this.minObject = new Long(this.min);
|
||||
return this.minObject;
|
||||
}
|
||||
|
||||
public long getMinimumLong() {
|
||||
return this.min;
|
||||
}
|
||||
|
||||
public int getMinimumInteger() {
|
||||
return (int)this.min;
|
||||
}
|
||||
|
||||
public double getMinimumDouble() {
|
||||
return (double)this.min;
|
||||
}
|
||||
|
||||
public float getMinimumFloat() {
|
||||
return (float)this.min;
|
||||
}
|
||||
|
||||
public Number getMaximumNumber() {
|
||||
if (this.maxObject == null)
|
||||
this.maxObject = new Long(this.max);
|
||||
return this.maxObject;
|
||||
}
|
||||
|
||||
public long getMaximumLong() {
|
||||
return this.max;
|
||||
}
|
||||
|
||||
public int getMaximumInteger() {
|
||||
return (int)this.max;
|
||||
}
|
||||
|
||||
public double getMaximumDouble() {
|
||||
return (double)this.max;
|
||||
}
|
||||
|
||||
public float getMaximumFloat() {
|
||||
return (float)this.max;
|
||||
}
|
||||
|
||||
public boolean containsNumber(Number number) {
|
||||
if (number == null)
|
||||
return false;
|
||||
return containsLong(number.longValue());
|
||||
}
|
||||
|
||||
public boolean containsLong(long value) {
|
||||
return (value >= this.min && value <= this.max);
|
||||
}
|
||||
|
||||
public boolean containsRange(Range range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (containsLong(range.getMinimumLong()) && containsLong(range.getMaximumLong()));
|
||||
}
|
||||
|
||||
public boolean overlapsRange(Range range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (range.containsLong(this.min) || range.containsLong(this.max) || containsLong(range.getMinimumLong()));
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (!(obj instanceof LongRange))
|
||||
return false;
|
||||
LongRange range = (LongRange)obj;
|
||||
return (this.min == range.min && this.max == range.max);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
if (this.hashCode == 0) {
|
||||
this.hashCode = 17;
|
||||
this.hashCode = 37 * this.hashCode + getClass().hashCode();
|
||||
this.hashCode = 37 * this.hashCode + (int)(this.min ^ this.min >> 32L);
|
||||
this.hashCode = 37 * this.hashCode + (int)(this.max ^ this.max >> 32L);
|
||||
}
|
||||
return this.hashCode;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.toString == null) {
|
||||
StringBuffer buf = new StringBuffer(32);
|
||||
buf.append("Range[");
|
||||
buf.append(this.min);
|
||||
buf.append(',');
|
||||
buf.append(this.max);
|
||||
buf.append(']');
|
||||
this.toString = buf.toString();
|
||||
}
|
||||
return this.toString;
|
||||
}
|
||||
|
||||
public long[] toArray() {
|
||||
long[] array = new long[(int)(this.max - this.min + 1L)];
|
||||
for (int i = 0; i < array.length; i++)
|
||||
array[i] = this.min + (long)i;
|
||||
return array;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public final class NumberRange extends Range implements Serializable {
|
||||
private static final long serialVersionUID = 71849363892710L;
|
||||
|
||||
private final Number min;
|
||||
|
||||
private final Number max;
|
||||
|
||||
private transient int hashCode = 0;
|
||||
|
||||
private transient String toString = null;
|
||||
|
||||
public NumberRange(Number num) {
|
||||
if (num == null)
|
||||
throw new IllegalArgumentException("The number must not be null");
|
||||
if (!(num instanceof Comparable))
|
||||
throw new IllegalArgumentException("The number must implement Comparable");
|
||||
if (num instanceof Double && ((Double)num).isNaN())
|
||||
throw new IllegalArgumentException("The number must not be NaN");
|
||||
if (num instanceof Float && ((Float)num).isNaN())
|
||||
throw new IllegalArgumentException("The number must not be NaN");
|
||||
this.min = num;
|
||||
this.max = num;
|
||||
}
|
||||
|
||||
public NumberRange(Number num1, Number num2) {
|
||||
if (num1 == null || num2 == null)
|
||||
throw new IllegalArgumentException("The numbers must not be null");
|
||||
if (num1.getClass() != num2.getClass())
|
||||
throw new IllegalArgumentException("The numbers must be of the same type");
|
||||
if (!(num1 instanceof Comparable))
|
||||
throw new IllegalArgumentException("The numbers must implement Comparable");
|
||||
if (num1 instanceof Double) {
|
||||
if (((Double)num1).isNaN() || ((Double)num2).isNaN())
|
||||
throw new IllegalArgumentException("The number must not be NaN");
|
||||
} else if (num1 instanceof Float && ((
|
||||
(Float)num1).isNaN() || ((Float)num2).isNaN())) {
|
||||
throw new IllegalArgumentException("The number must not be NaN");
|
||||
}
|
||||
int compare = ((Comparable)num1).compareTo(num2);
|
||||
if (compare == 0) {
|
||||
this.min = num1;
|
||||
this.max = num1;
|
||||
} else if (compare > 0) {
|
||||
this.min = num2;
|
||||
this.max = num1;
|
||||
} else {
|
||||
this.min = num1;
|
||||
this.max = num2;
|
||||
}
|
||||
}
|
||||
|
||||
public Number getMinimumNumber() {
|
||||
return this.min;
|
||||
}
|
||||
|
||||
public Number getMaximumNumber() {
|
||||
return this.max;
|
||||
}
|
||||
|
||||
public boolean containsNumber(Number number) {
|
||||
if (number == null)
|
||||
return false;
|
||||
if (number.getClass() != this.min.getClass())
|
||||
throw new IllegalArgumentException("The number must be of the same type as the range numbers");
|
||||
int compareMin = ((Comparable)this.min).compareTo(number);
|
||||
int compareMax = ((Comparable)this.max).compareTo(number);
|
||||
return (compareMin <= 0 && compareMax >= 0);
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (!(obj instanceof NumberRange))
|
||||
return false;
|
||||
NumberRange range = (NumberRange)obj;
|
||||
return (this.min.equals(range.min) && this.max.equals(range.max));
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
if (this.hashCode == 0) {
|
||||
this.hashCode = 17;
|
||||
this.hashCode = 37 * this.hashCode + getClass().hashCode();
|
||||
this.hashCode = 37 * this.hashCode + this.min.hashCode();
|
||||
this.hashCode = 37 * this.hashCode + this.max.hashCode();
|
||||
}
|
||||
return this.hashCode;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.toString == null) {
|
||||
StringBuffer buf = new StringBuffer(32);
|
||||
buf.append("Range[");
|
||||
buf.append(this.min);
|
||||
buf.append(',');
|
||||
buf.append(this.max);
|
||||
buf.append(']');
|
||||
this.toString = buf.toString();
|
||||
}
|
||||
return this.toString;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,598 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
public class NumberUtils {
|
||||
public static final Long LONG_ZERO = new Long(0L);
|
||||
|
||||
public static final Long LONG_ONE = new Long(1L);
|
||||
|
||||
public static final Long LONG_MINUS_ONE = new Long(-1L);
|
||||
|
||||
public static final Integer INTEGER_ZERO = new Integer(0);
|
||||
|
||||
public static final Integer INTEGER_ONE = new Integer(1);
|
||||
|
||||
public static final Integer INTEGER_MINUS_ONE = new Integer(-1);
|
||||
|
||||
public static final Short SHORT_ZERO = new Short((short)0);
|
||||
|
||||
public static final Short SHORT_ONE = new Short((short)1);
|
||||
|
||||
public static final Short SHORT_MINUS_ONE = new Short((short)-1);
|
||||
|
||||
public static final Byte BYTE_ZERO = new Byte((byte)0);
|
||||
|
||||
public static final Byte BYTE_ONE = new Byte((byte)1);
|
||||
|
||||
public static final Byte BYTE_MINUS_ONE = new Byte((byte)-1);
|
||||
|
||||
public static final Double DOUBLE_ZERO = new Double(0.0D);
|
||||
|
||||
public static final Double DOUBLE_ONE = new Double(1.0D);
|
||||
|
||||
public static final Double DOUBLE_MINUS_ONE = new Double(-1.0D);
|
||||
|
||||
public static final Float FLOAT_ZERO = new Float(0.0F);
|
||||
|
||||
public static final Float FLOAT_ONE = new Float(1.0F);
|
||||
|
||||
public static final Float FLOAT_MINUS_ONE = new Float(-1.0F);
|
||||
|
||||
public static int stringToInt(String str) {
|
||||
return toInt(str);
|
||||
}
|
||||
|
||||
public static int toInt(String str) {
|
||||
return toInt(str, 0);
|
||||
}
|
||||
|
||||
public static int stringToInt(String str, int defaultValue) {
|
||||
return toInt(str, defaultValue);
|
||||
}
|
||||
|
||||
public static int toInt(String str, int defaultValue) {
|
||||
if (str == null)
|
||||
return defaultValue;
|
||||
try {
|
||||
return Integer.parseInt(str);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static long toLong(String str) {
|
||||
return toLong(str, 0L);
|
||||
}
|
||||
|
||||
public static long toLong(String str, long defaultValue) {
|
||||
if (str == null)
|
||||
return defaultValue;
|
||||
try {
|
||||
return Long.parseLong(str);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static float toFloat(String str) {
|
||||
return toFloat(str, 0.0F);
|
||||
}
|
||||
|
||||
public static float toFloat(String str, float defaultValue) {
|
||||
if (str == null)
|
||||
return defaultValue;
|
||||
try {
|
||||
return Float.parseFloat(str);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static double toDouble(String str) {
|
||||
return toDouble(str, 0.0D);
|
||||
}
|
||||
|
||||
public static double toDouble(String str, double defaultValue) {
|
||||
if (str == null)
|
||||
return defaultValue;
|
||||
try {
|
||||
return Double.parseDouble(str);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static Number createNumber(String str) throws NumberFormatException {
|
||||
String mant, dec, exp;
|
||||
if (str == null)
|
||||
return null;
|
||||
if (StringUtils.isBlank(str))
|
||||
throw new NumberFormatException("A blank string is not a valid number");
|
||||
if (str.startsWith("--"))
|
||||
return null;
|
||||
if (str.startsWith("0x") || str.startsWith("-0x"))
|
||||
return createInteger(str);
|
||||
char lastChar = str.charAt(str.length() - 1);
|
||||
int decPos = str.indexOf('.');
|
||||
int expPos = str.indexOf('e') + str.indexOf('E') + 1;
|
||||
if (decPos > -1) {
|
||||
if (expPos > -1) {
|
||||
if (expPos < decPos)
|
||||
throw new NumberFormatException(str + " is not a valid number.");
|
||||
dec = str.substring(decPos + 1, expPos);
|
||||
} else {
|
||||
dec = str.substring(decPos + 1);
|
||||
}
|
||||
mant = str.substring(0, decPos);
|
||||
} else {
|
||||
if (expPos > -1) {
|
||||
mant = str.substring(0, expPos);
|
||||
} else {
|
||||
mant = str;
|
||||
}
|
||||
dec = null;
|
||||
}
|
||||
if (!Character.isDigit(lastChar)) {
|
||||
if (expPos > -1 && expPos < str.length() - 1) {
|
||||
exp = str.substring(expPos + 1, str.length() - 1);
|
||||
} else {
|
||||
exp = null;
|
||||
}
|
||||
String numeric = str.substring(0, str.length() - 1);
|
||||
boolean bool = (isAllZeros(mant) && isAllZeros(exp));
|
||||
switch (lastChar) {
|
||||
case 'L':
|
||||
case 'l':
|
||||
if (dec == null && exp == null && ((numeric.charAt(0) == '-' && isDigits(numeric.substring(1))) || isDigits(numeric)))
|
||||
try {
|
||||
return createLong(numeric);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return createBigInteger(numeric);
|
||||
}
|
||||
throw new NumberFormatException(str + " is not a valid number.");
|
||||
case 'F':
|
||||
case 'f':
|
||||
try {
|
||||
Float f = createFloat(numeric);
|
||||
if (!f.isInfinite() && (f.floatValue() != 0.0F || bool))
|
||||
return f;
|
||||
} catch (NumberFormatException nfe) {}
|
||||
case 'D':
|
||||
case 'd':
|
||||
try {
|
||||
Double d = createDouble(numeric);
|
||||
if (!d.isInfinite() && ((double)d.floatValue() != 0.0D || bool))
|
||||
return d;
|
||||
} catch (NumberFormatException nfe) {}
|
||||
try {
|
||||
return createBigDecimal(numeric);
|
||||
} catch (NumberFormatException e) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw new NumberFormatException(str + " is not a valid number.");
|
||||
}
|
||||
if (expPos > -1 && expPos < str.length() - 1) {
|
||||
exp = str.substring(expPos + 1, str.length());
|
||||
} else {
|
||||
exp = null;
|
||||
}
|
||||
if (dec == null && exp == null)
|
||||
try {
|
||||
return createInteger(str);
|
||||
} catch (NumberFormatException nfe) {
|
||||
try {
|
||||
return createLong(str);
|
||||
} catch (NumberFormatException numberFormatException) {
|
||||
return createBigInteger(str);
|
||||
}
|
||||
}
|
||||
boolean allZeros = (isAllZeros(mant) && isAllZeros(exp));
|
||||
try {
|
||||
Float f = createFloat(str);
|
||||
if (!f.isInfinite() && (f.floatValue() != 0.0F || allZeros))
|
||||
return f;
|
||||
} catch (NumberFormatException nfe) {}
|
||||
try {
|
||||
Double d = createDouble(str);
|
||||
if (!d.isInfinite() && (d.doubleValue() != 0.0D || allZeros))
|
||||
return d;
|
||||
} catch (NumberFormatException nfe) {}
|
||||
return createBigDecimal(str);
|
||||
}
|
||||
|
||||
private static boolean isAllZeros(String str) {
|
||||
if (str == null)
|
||||
return true;
|
||||
for (int i = str.length() - 1; i >= 0; i--) {
|
||||
if (str.charAt(i) != '0')
|
||||
return false;
|
||||
}
|
||||
return (str.length() > 0);
|
||||
}
|
||||
|
||||
public static Float createFloat(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
return Float.valueOf(str);
|
||||
}
|
||||
|
||||
public static Double createDouble(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
return Double.valueOf(str);
|
||||
}
|
||||
|
||||
public static Integer createInteger(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
return Integer.decode(str);
|
||||
}
|
||||
|
||||
public static Long createLong(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
return Long.valueOf(str);
|
||||
}
|
||||
|
||||
public static BigInteger createBigInteger(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
return new BigInteger(str);
|
||||
}
|
||||
|
||||
public static BigDecimal createBigDecimal(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
if (StringUtils.isBlank(str))
|
||||
throw new NumberFormatException("A blank string is not a valid number");
|
||||
return new BigDecimal(str);
|
||||
}
|
||||
|
||||
public static long min(long[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
long min = array[0];
|
||||
for (int i = 1; i < array.length; i++) {
|
||||
if (array[i] < min)
|
||||
min = array[i];
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
public static int min(int[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
int min = array[0];
|
||||
for (int j = 1; j < array.length; j++) {
|
||||
if (array[j] < min)
|
||||
min = array[j];
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
public static short min(short[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
short min = array[0];
|
||||
for (int i = 1; i < array.length; i++) {
|
||||
if (array[i] < min)
|
||||
min = array[i];
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
public static byte min(byte[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
byte min = array[0];
|
||||
for (int i = 1; i < array.length; i++) {
|
||||
if (array[i] < min)
|
||||
min = array[i];
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
public static double min(double[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
double min = array[0];
|
||||
for (int i = 1; i < array.length; i++) {
|
||||
if (Double.isNaN(array[i]))
|
||||
return Double.NaN;
|
||||
if (array[i] < min)
|
||||
min = array[i];
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
public static float min(float[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
float min = array[0];
|
||||
for (int i = 1; i < array.length; i++) {
|
||||
if (Float.isNaN(array[i]))
|
||||
return Float.NaN;
|
||||
if (array[i] < min)
|
||||
min = array[i];
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
public static long max(long[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
long max = array[0];
|
||||
for (int j = 1; j < array.length; j++) {
|
||||
if (array[j] > max)
|
||||
max = array[j];
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
public static int max(int[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
int max = array[0];
|
||||
for (int j = 1; j < array.length; j++) {
|
||||
if (array[j] > max)
|
||||
max = array[j];
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
public static short max(short[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
short max = array[0];
|
||||
for (int i = 1; i < array.length; i++) {
|
||||
if (array[i] > max)
|
||||
max = array[i];
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
public static byte max(byte[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
byte max = array[0];
|
||||
for (int i = 1; i < array.length; i++) {
|
||||
if (array[i] > max)
|
||||
max = array[i];
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
public static double max(double[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
double max = array[0];
|
||||
for (int j = 1; j < array.length; j++) {
|
||||
if (Double.isNaN(array[j]))
|
||||
return Double.NaN;
|
||||
if (array[j] > max)
|
||||
max = array[j];
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
public static float max(float[] array) {
|
||||
if (array == null)
|
||||
throw new IllegalArgumentException("The Array must not be null");
|
||||
if (array.length == 0)
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
float max = array[0];
|
||||
for (int j = 1; j < array.length; j++) {
|
||||
if (Float.isNaN(array[j]))
|
||||
return Float.NaN;
|
||||
if (array[j] > max)
|
||||
max = array[j];
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
public static long min(long a, long b, long c) {
|
||||
if (b < a)
|
||||
a = b;
|
||||
if (c < a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static int min(int a, int b, int c) {
|
||||
if (b < a)
|
||||
a = b;
|
||||
if (c < a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static short min(short a, short b, short c) {
|
||||
if (b < a)
|
||||
a = b;
|
||||
if (c < a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static byte min(byte a, byte b, byte c) {
|
||||
if (b < a)
|
||||
a = b;
|
||||
if (c < a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static double min(double a, double b, double c) {
|
||||
return Math.min(Math.min(a, b), c);
|
||||
}
|
||||
|
||||
public static float min(float a, float b, float c) {
|
||||
return Math.min(Math.min(a, b), c);
|
||||
}
|
||||
|
||||
public static long max(long a, long b, long c) {
|
||||
if (b > a)
|
||||
a = b;
|
||||
if (c > a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static int max(int a, int b, int c) {
|
||||
if (b > a)
|
||||
a = b;
|
||||
if (c > a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static short max(short a, short b, short c) {
|
||||
if (b > a)
|
||||
a = b;
|
||||
if (c > a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static byte max(byte a, byte b, byte c) {
|
||||
if (b > a)
|
||||
a = b;
|
||||
if (c > a)
|
||||
a = c;
|
||||
return a;
|
||||
}
|
||||
|
||||
public static double max(double a, double b, double c) {
|
||||
return Math.max(Math.max(a, b), c);
|
||||
}
|
||||
|
||||
public static float max(float a, float b, float c) {
|
||||
return Math.max(Math.max(a, b), c);
|
||||
}
|
||||
|
||||
public static int compare(double lhs, double rhs) {
|
||||
if (lhs < rhs)
|
||||
return -1;
|
||||
if (lhs > rhs)
|
||||
return 1;
|
||||
long lhsBits = Double.doubleToLongBits(lhs);
|
||||
long rhsBits = Double.doubleToLongBits(rhs);
|
||||
if (lhsBits == rhsBits)
|
||||
return 0;
|
||||
if (lhsBits < rhsBits)
|
||||
return -1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static int compare(float lhs, float rhs) {
|
||||
if (lhs < rhs)
|
||||
return -1;
|
||||
if (lhs > rhs)
|
||||
return 1;
|
||||
int lhsBits = Float.floatToIntBits(lhs);
|
||||
int rhsBits = Float.floatToIntBits(rhs);
|
||||
if (lhsBits == rhsBits)
|
||||
return 0;
|
||||
if (lhsBits < rhsBits)
|
||||
return -1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static boolean isDigits(String str) {
|
||||
if (StringUtils.isEmpty(str))
|
||||
return false;
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
if (!Character.isDigit(str.charAt(i)))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isNumber(String str) {
|
||||
if (StringUtils.isEmpty(str))
|
||||
return false;
|
||||
char[] chars = str.toCharArray();
|
||||
int sz = chars.length;
|
||||
boolean hasExp = false;
|
||||
boolean hasDecPoint = false;
|
||||
boolean allowSigns = false;
|
||||
boolean foundDigit = false;
|
||||
int start = (chars[0] == '-') ? 1 : 0;
|
||||
if (sz > start + 1 &&
|
||||
chars[start] == '0' && chars[start + 1] == 'x') {
|
||||
int j = start + 2;
|
||||
if (j == sz)
|
||||
return false;
|
||||
for (; j < chars.length; j++) {
|
||||
if ((chars[j] < '0' || chars[j] > '9') && (chars[j] < 'a' || chars[j] > 'f') && (chars[j] < 'A' || chars[j] > 'F'))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
sz--;
|
||||
int i = start;
|
||||
while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
|
||||
if (chars[i] >= '0' && chars[i] <= '9') {
|
||||
foundDigit = true;
|
||||
allowSigns = false;
|
||||
} else if (chars[i] == '.') {
|
||||
if (hasDecPoint || hasExp)
|
||||
return false;
|
||||
hasDecPoint = true;
|
||||
} else if (chars[i] == 'e' || chars[i] == 'E') {
|
||||
if (hasExp)
|
||||
return false;
|
||||
if (!foundDigit)
|
||||
return false;
|
||||
hasExp = true;
|
||||
allowSigns = true;
|
||||
} else if (chars[i] == '+' || chars[i] == '-') {
|
||||
if (!allowSigns)
|
||||
return false;
|
||||
allowSigns = false;
|
||||
foundDigit = false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if (i < chars.length) {
|
||||
if (chars[i] >= '0' && chars[i] <= '9')
|
||||
return true;
|
||||
if (chars[i] == 'e' || chars[i] == 'E')
|
||||
return false;
|
||||
if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F'))
|
||||
return foundDigit;
|
||||
if (chars[i] == 'l' || chars[i] == 'L')
|
||||
return (foundDigit && !hasExp);
|
||||
return false;
|
||||
}
|
||||
return (!allowSigns && foundDigit);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class RandomUtils {
|
||||
public static final Random JVM_RANDOM = new JVMRandom();
|
||||
|
||||
public static int nextInt() {
|
||||
return nextInt(JVM_RANDOM);
|
||||
}
|
||||
|
||||
public static int nextInt(Random random) {
|
||||
return random.nextInt();
|
||||
}
|
||||
|
||||
public static int nextInt(int n) {
|
||||
return nextInt(JVM_RANDOM, n);
|
||||
}
|
||||
|
||||
public static int nextInt(Random random, int n) {
|
||||
return random.nextInt(n);
|
||||
}
|
||||
|
||||
public static long nextLong() {
|
||||
return nextLong(JVM_RANDOM);
|
||||
}
|
||||
|
||||
public static long nextLong(Random random) {
|
||||
return random.nextLong();
|
||||
}
|
||||
|
||||
public static boolean nextBoolean() {
|
||||
return nextBoolean(JVM_RANDOM);
|
||||
}
|
||||
|
||||
public static boolean nextBoolean(Random random) {
|
||||
return random.nextBoolean();
|
||||
}
|
||||
|
||||
public static float nextFloat() {
|
||||
return nextFloat(JVM_RANDOM);
|
||||
}
|
||||
|
||||
public static float nextFloat(Random random) {
|
||||
return random.nextFloat();
|
||||
}
|
||||
|
||||
public static double nextDouble() {
|
||||
return nextDouble(JVM_RANDOM);
|
||||
}
|
||||
|
||||
public static double nextDouble(Random random) {
|
||||
return random.nextDouble();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
package org.apache.commons.lang.math;
|
||||
|
||||
public abstract class Range {
|
||||
public abstract Number getMinimumNumber();
|
||||
|
||||
public long getMinimumLong() {
|
||||
return getMinimumNumber().longValue();
|
||||
}
|
||||
|
||||
public int getMinimumInteger() {
|
||||
return getMinimumNumber().intValue();
|
||||
}
|
||||
|
||||
public double getMinimumDouble() {
|
||||
return getMinimumNumber().doubleValue();
|
||||
}
|
||||
|
||||
public float getMinimumFloat() {
|
||||
return getMinimumNumber().floatValue();
|
||||
}
|
||||
|
||||
public abstract Number getMaximumNumber();
|
||||
|
||||
public long getMaximumLong() {
|
||||
return getMaximumNumber().longValue();
|
||||
}
|
||||
|
||||
public int getMaximumInteger() {
|
||||
return getMaximumNumber().intValue();
|
||||
}
|
||||
|
||||
public double getMaximumDouble() {
|
||||
return getMaximumNumber().doubleValue();
|
||||
}
|
||||
|
||||
public float getMaximumFloat() {
|
||||
return getMaximumNumber().floatValue();
|
||||
}
|
||||
|
||||
public abstract boolean containsNumber(Number paramNumber);
|
||||
|
||||
public boolean containsLong(Number value) {
|
||||
if (value == null)
|
||||
return false;
|
||||
return containsLong(value.longValue());
|
||||
}
|
||||
|
||||
public boolean containsLong(long value) {
|
||||
return (value >= getMinimumLong() && value <= getMaximumLong());
|
||||
}
|
||||
|
||||
public boolean containsInteger(Number value) {
|
||||
if (value == null)
|
||||
return false;
|
||||
return containsInteger(value.intValue());
|
||||
}
|
||||
|
||||
public boolean containsInteger(int value) {
|
||||
return (value >= getMinimumInteger() && value <= getMaximumInteger());
|
||||
}
|
||||
|
||||
public boolean containsDouble(Number value) {
|
||||
if (value == null)
|
||||
return false;
|
||||
return containsDouble(value.doubleValue());
|
||||
}
|
||||
|
||||
public boolean containsDouble(double value) {
|
||||
int compareMin = NumberUtils.compare(getMinimumDouble(), value);
|
||||
int compareMax = NumberUtils.compare(getMaximumDouble(), value);
|
||||
return (compareMin <= 0 && compareMax >= 0);
|
||||
}
|
||||
|
||||
public boolean containsFloat(Number value) {
|
||||
if (value == null)
|
||||
return false;
|
||||
return containsFloat(value.floatValue());
|
||||
}
|
||||
|
||||
public boolean containsFloat(float value) {
|
||||
int compareMin = NumberUtils.compare(getMinimumFloat(), value);
|
||||
int compareMax = NumberUtils.compare(getMaximumFloat(), value);
|
||||
return (compareMin <= 0 && compareMax >= 0);
|
||||
}
|
||||
|
||||
public boolean containsRange(Range range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (containsNumber(range.getMinimumNumber()) && containsNumber(range.getMaximumNumber()));
|
||||
}
|
||||
|
||||
public boolean overlapsRange(Range range) {
|
||||
if (range == null)
|
||||
return false;
|
||||
return (range.containsNumber(getMinimumNumber()) || range.containsNumber(getMaximumNumber()) || containsNumber(range.getMinimumNumber()));
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (obj == null || obj.getClass() != getClass())
|
||||
return false;
|
||||
Range range = (Range)obj;
|
||||
return (getMinimumNumber().equals(range.getMinimumNumber()) && getMaximumNumber().equals(range.getMaximumNumber()));
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
int result = 17;
|
||||
result = 37 * result + getClass().hashCode();
|
||||
result = 37 * result + getMinimumNumber().hashCode();
|
||||
result = 37 * result + getMaximumNumber().hashCode();
|
||||
return result;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer buf = new StringBuffer(32);
|
||||
buf.append("Range[");
|
||||
buf.append(getMinimumNumber());
|
||||
buf.append(',');
|
||||
buf.append(getMaximumNumber());
|
||||
buf.append(']');
|
||||
return buf.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
package org.apache.commons.lang.mutable;
|
||||
|
||||
public interface Mutable {
|
||||
Object getValue();
|
||||
|
||||
void setValue(Object paramObject);
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
package org.apache.commons.lang.mutable;
|
||||
|
||||
import java.io.Serializable;
|
||||
import org.apache.commons.lang.BooleanUtils;
|
||||
|
||||
public class MutableBoolean implements Mutable, Serializable, Comparable {
|
||||
private static final long serialVersionUID = -4830728138360036487L;
|
||||
|
||||
private boolean value;
|
||||
|
||||
public MutableBoolean() {}
|
||||
|
||||
public MutableBoolean(boolean value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public MutableBoolean(Boolean value) {
|
||||
this.value = value.booleanValue();
|
||||
}
|
||||
|
||||
public boolean booleanValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public int compareTo(Object obj) {
|
||||
MutableBoolean other = (MutableBoolean)obj;
|
||||
boolean anotherVal = other.value;
|
||||
return (this.value == anotherVal) ? 0 : (this.value ? 1 : -1);
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof MutableBoolean)
|
||||
return (this.value == ((MutableBoolean)obj).booleanValue());
|
||||
return false;
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return BooleanUtils.toBooleanObject(this.value);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.value ? Boolean.TRUE.hashCode() : Boolean.FALSE.hashCode();
|
||||
}
|
||||
|
||||
public void setValue(boolean value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public void setValue(Object value) {
|
||||
setValue(((Boolean)value).booleanValue());
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return String.valueOf(this.value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
package org.apache.commons.lang.mutable;
|
||||
|
||||
public class MutableByte extends Number implements Comparable, Mutable {
|
||||
private static final long serialVersionUID = -1585823265L;
|
||||
|
||||
private byte value;
|
||||
|
||||
public MutableByte() {}
|
||||
|
||||
public MutableByte(byte value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public MutableByte(Number value) {
|
||||
this.value = value.byteValue();
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return new Byte(this.value);
|
||||
}
|
||||
|
||||
public void setValue(byte value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public void setValue(Object value) {
|
||||
setValue(((Number)value).byteValue());
|
||||
}
|
||||
|
||||
public byte byteValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public int intValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public long longValue() {
|
||||
return (long)this.value;
|
||||
}
|
||||
|
||||
public float floatValue() {
|
||||
return (float)this.value;
|
||||
}
|
||||
|
||||
public double doubleValue() {
|
||||
return (double)this.value;
|
||||
}
|
||||
|
||||
public Byte toByte() {
|
||||
return new Byte(byteValue());
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
this.value = (byte)(this.value + 1);
|
||||
}
|
||||
|
||||
public void decrement() {
|
||||
this.value = (byte)(this.value - 1);
|
||||
}
|
||||
|
||||
public void add(byte operand) {
|
||||
this.value = (byte)(this.value + operand);
|
||||
}
|
||||
|
||||
public void add(Number operand) {
|
||||
this.value = (byte)(this.value + operand.byteValue());
|
||||
}
|
||||
|
||||
public void subtract(byte operand) {
|
||||
this.value = (byte)(this.value - operand);
|
||||
}
|
||||
|
||||
public void subtract(Number operand) {
|
||||
this.value = (byte)(this.value - operand.byteValue());
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof MutableByte)
|
||||
return (this.value == ((MutableByte)obj).byteValue());
|
||||
return false;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public int compareTo(Object obj) {
|
||||
MutableByte other = (MutableByte)obj;
|
||||
byte anotherVal = other.value;
|
||||
return (this.value < anotherVal) ? -1 : ((this.value == anotherVal) ? 0 : 1);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return String.valueOf(this.value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
package org.apache.commons.lang.mutable;
|
||||
|
||||
import org.apache.commons.lang.math.NumberUtils;
|
||||
|
||||
public class MutableDouble extends Number implements Comparable, Mutable {
|
||||
private static final long serialVersionUID = 1587163916L;
|
||||
|
||||
private double value;
|
||||
|
||||
public MutableDouble() {}
|
||||
|
||||
public MutableDouble(double value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public MutableDouble(Number value) {
|
||||
this.value = value.doubleValue();
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return new Double(this.value);
|
||||
}
|
||||
|
||||
public void setValue(double value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public void setValue(Object value) {
|
||||
setValue(((Number)value).doubleValue());
|
||||
}
|
||||
|
||||
public int intValue() {
|
||||
return (int)this.value;
|
||||
}
|
||||
|
||||
public long longValue() {
|
||||
return (long)this.value;
|
||||
}
|
||||
|
||||
public float floatValue() {
|
||||
return (float)this.value;
|
||||
}
|
||||
|
||||
public double doubleValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public boolean isNaN() {
|
||||
return Double.isNaN(this.value);
|
||||
}
|
||||
|
||||
public boolean isInfinite() {
|
||||
return Double.isInfinite(this.value);
|
||||
}
|
||||
|
||||
public Double toDouble() {
|
||||
return new Double(doubleValue());
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
this.value++;
|
||||
}
|
||||
|
||||
public void decrement() {
|
||||
this.value--;
|
||||
}
|
||||
|
||||
public void add(double operand) {
|
||||
this.value += operand;
|
||||
}
|
||||
|
||||
public void add(Number operand) {
|
||||
this.value += operand.doubleValue();
|
||||
}
|
||||
|
||||
public void subtract(double operand) {
|
||||
this.value -= operand;
|
||||
}
|
||||
|
||||
public void subtract(Number operand) {
|
||||
this.value -= operand.doubleValue();
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
return (obj instanceof MutableDouble && Double.doubleToLongBits(((MutableDouble)obj).value) == Double.doubleToLongBits(this.value));
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
long bits = Double.doubleToLongBits(this.value);
|
||||
return (int)(bits ^ bits >>> 32L);
|
||||
}
|
||||
|
||||
public int compareTo(Object obj) {
|
||||
MutableDouble other = (MutableDouble)obj;
|
||||
double anotherVal = other.value;
|
||||
return NumberUtils.compare(this.value, anotherVal);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return String.valueOf(this.value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
package org.apache.commons.lang.mutable;
|
||||
|
||||
import org.apache.commons.lang.math.NumberUtils;
|
||||
|
||||
public class MutableFloat extends Number implements Comparable, Mutable {
|
||||
private static final long serialVersionUID = 5787169186L;
|
||||
|
||||
private float value;
|
||||
|
||||
public MutableFloat() {}
|
||||
|
||||
public MutableFloat(float value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public MutableFloat(Number value) {
|
||||
this.value = value.floatValue();
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return new Float(this.value);
|
||||
}
|
||||
|
||||
public void setValue(float value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public void setValue(Object value) {
|
||||
setValue(((Number)value).floatValue());
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
this.value++;
|
||||
}
|
||||
|
||||
public void decrement() {
|
||||
this.value--;
|
||||
}
|
||||
|
||||
public void add(float operand) {
|
||||
this.value += operand;
|
||||
}
|
||||
|
||||
public void add(Number operand) {
|
||||
this.value += operand.floatValue();
|
||||
}
|
||||
|
||||
public void subtract(float operand) {
|
||||
this.value -= operand;
|
||||
}
|
||||
|
||||
public void subtract(Number operand) {
|
||||
this.value -= operand.floatValue();
|
||||
}
|
||||
|
||||
public int intValue() {
|
||||
return (int)this.value;
|
||||
}
|
||||
|
||||
public long longValue() {
|
||||
return (long)this.value;
|
||||
}
|
||||
|
||||
public float floatValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public double doubleValue() {
|
||||
return (double)this.value;
|
||||
}
|
||||
|
||||
public boolean isNaN() {
|
||||
return Float.isNaN(this.value);
|
||||
}
|
||||
|
||||
public boolean isInfinite() {
|
||||
return Float.isInfinite(this.value);
|
||||
}
|
||||
|
||||
public Float toFloat() {
|
||||
return new Float(floatValue());
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
return (obj instanceof MutableFloat && Float.floatToIntBits(((MutableFloat)obj).value) == Float.floatToIntBits(this.value));
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return Float.floatToIntBits(this.value);
|
||||
}
|
||||
|
||||
public int compareTo(Object obj) {
|
||||
MutableFloat other = (MutableFloat)obj;
|
||||
float anotherVal = other.value;
|
||||
return NumberUtils.compare(this.value, anotherVal);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return String.valueOf(this.value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
package org.apache.commons.lang.mutable;
|
||||
|
||||
public class MutableInt extends Number implements Comparable, Mutable {
|
||||
private static final long serialVersionUID = 512176391864L;
|
||||
|
||||
private int value;
|
||||
|
||||
public MutableInt() {}
|
||||
|
||||
public MutableInt(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public MutableInt(Number value) {
|
||||
this.value = value.intValue();
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return new Integer(this.value);
|
||||
}
|
||||
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public void setValue(Object value) {
|
||||
setValue(((Number)value).intValue());
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
this.value++;
|
||||
}
|
||||
|
||||
public void decrement() {
|
||||
this.value--;
|
||||
}
|
||||
|
||||
public void add(int operand) {
|
||||
this.value += operand;
|
||||
}
|
||||
|
||||
public void add(Number operand) {
|
||||
this.value += operand.intValue();
|
||||
}
|
||||
|
||||
public void subtract(int operand) {
|
||||
this.value -= operand;
|
||||
}
|
||||
|
||||
public void subtract(Number operand) {
|
||||
this.value -= operand.intValue();
|
||||
}
|
||||
|
||||
public int intValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public long longValue() {
|
||||
return (long)this.value;
|
||||
}
|
||||
|
||||
public float floatValue() {
|
||||
return (float)this.value;
|
||||
}
|
||||
|
||||
public double doubleValue() {
|
||||
return (double)this.value;
|
||||
}
|
||||
|
||||
public Integer toInteger() {
|
||||
return new Integer(intValue());
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof MutableInt)
|
||||
return (this.value == ((MutableInt)obj).intValue());
|
||||
return false;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public int compareTo(Object obj) {
|
||||
MutableInt other = (MutableInt)obj;
|
||||
int anotherVal = other.value;
|
||||
return (this.value < anotherVal) ? -1 : ((this.value == anotherVal) ? 0 : 1);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return String.valueOf(this.value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
package org.apache.commons.lang.mutable;
|
||||
|
||||
public class MutableLong extends Number implements Comparable, Mutable {
|
||||
private static final long serialVersionUID = 62986528375L;
|
||||
|
||||
private long value;
|
||||
|
||||
public MutableLong() {}
|
||||
|
||||
public MutableLong(long value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public MutableLong(Number value) {
|
||||
this.value = value.longValue();
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return new Long(this.value);
|
||||
}
|
||||
|
||||
public void setValue(long value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public void setValue(Object value) {
|
||||
setValue(((Number)value).longValue());
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
this.value++;
|
||||
}
|
||||
|
||||
public void decrement() {
|
||||
this.value--;
|
||||
}
|
||||
|
||||
public void add(long operand) {
|
||||
this.value += operand;
|
||||
}
|
||||
|
||||
public void add(Number operand) {
|
||||
this.value += operand.longValue();
|
||||
}
|
||||
|
||||
public void subtract(long operand) {
|
||||
this.value -= operand;
|
||||
}
|
||||
|
||||
public void subtract(Number operand) {
|
||||
this.value -= operand.longValue();
|
||||
}
|
||||
|
||||
public int intValue() {
|
||||
return (int)this.value;
|
||||
}
|
||||
|
||||
public long longValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public float floatValue() {
|
||||
return (float)this.value;
|
||||
}
|
||||
|
||||
public double doubleValue() {
|
||||
return (double)this.value;
|
||||
}
|
||||
|
||||
public Long toLong() {
|
||||
return new Long(longValue());
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof MutableLong)
|
||||
return (this.value == ((MutableLong)obj).longValue());
|
||||
return false;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return (int)(this.value ^ this.value >>> 32L);
|
||||
}
|
||||
|
||||
public int compareTo(Object obj) {
|
||||
MutableLong other = (MutableLong)obj;
|
||||
long anotherVal = other.value;
|
||||
return (this.value < anotherVal) ? -1 : ((this.value == anotherVal) ? 0 : 1);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return String.valueOf(this.value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
package org.apache.commons.lang.mutable;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class MutableObject implements Mutable, Serializable {
|
||||
private static final long serialVersionUID = 86241875189L;
|
||||
|
||||
private Object value;
|
||||
|
||||
public MutableObject() {}
|
||||
|
||||
public MutableObject(Object value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public void setValue(Object value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof MutableObject) {
|
||||
Object other = ((MutableObject)obj).value;
|
||||
return (this.value == other || (this.value != null && this.value.equals(other)));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return (this.value == null) ? 0 : this.value.hashCode();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return (this.value == null) ? "null" : this.value.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
package org.apache.commons.lang.mutable;
|
||||
|
||||
public class MutableShort extends Number implements Comparable, Mutable {
|
||||
private static final long serialVersionUID = -2135791679L;
|
||||
|
||||
private short value;
|
||||
|
||||
public MutableShort() {}
|
||||
|
||||
public MutableShort(short value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public MutableShort(Number value) {
|
||||
this.value = value.shortValue();
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return new Short(this.value);
|
||||
}
|
||||
|
||||
public void setValue(short value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public void setValue(Object value) {
|
||||
setValue(((Number)value).shortValue());
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
this.value = (short)(this.value + 1);
|
||||
}
|
||||
|
||||
public void decrement() {
|
||||
this.value = (short)(this.value - 1);
|
||||
}
|
||||
|
||||
public void add(short operand) {
|
||||
this.value = (short)(this.value + operand);
|
||||
}
|
||||
|
||||
public void add(Number operand) {
|
||||
this.value = (short)(this.value + operand.shortValue());
|
||||
}
|
||||
|
||||
public void subtract(short operand) {
|
||||
this.value = (short)(this.value - operand);
|
||||
}
|
||||
|
||||
public void subtract(Number operand) {
|
||||
this.value = (short)(this.value - operand.shortValue());
|
||||
}
|
||||
|
||||
public short shortValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public int intValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public long longValue() {
|
||||
return (long)this.value;
|
||||
}
|
||||
|
||||
public float floatValue() {
|
||||
return (float)this.value;
|
||||
}
|
||||
|
||||
public double doubleValue() {
|
||||
return (double)this.value;
|
||||
}
|
||||
|
||||
public Short toShort() {
|
||||
return new Short(shortValue());
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof MutableShort)
|
||||
return (this.value == ((MutableShort)obj).shortValue());
|
||||
return false;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public int compareTo(Object obj) {
|
||||
MutableShort other = (MutableShort)obj;
|
||||
short anotherVal = other.value;
|
||||
return (this.value < anotherVal) ? -1 : ((this.value == anotherVal) ? 0 : 1);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return String.valueOf(this.value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
package org.apache.commons.lang.text;
|
||||
|
||||
import java.text.FieldPosition;
|
||||
import java.text.Format;
|
||||
import java.text.ParseException;
|
||||
import java.text.ParsePosition;
|
||||
|
||||
public class CompositeFormat extends Format {
|
||||
private static final long serialVersionUID = -4329119827877627683L;
|
||||
|
||||
private final Format parser;
|
||||
|
||||
private final Format formatter;
|
||||
|
||||
public CompositeFormat(Format parser, Format formatter) {
|
||||
this.parser = parser;
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
|
||||
return this.formatter.format(obj, toAppendTo, pos);
|
||||
}
|
||||
|
||||
public Object parseObject(String source, ParsePosition pos) {
|
||||
return this.parser.parseObject(source, pos);
|
||||
}
|
||||
|
||||
public Format getParser() {
|
||||
return this.parser;
|
||||
}
|
||||
|
||||
public Format getFormatter() {
|
||||
return this.formatter;
|
||||
}
|
||||
|
||||
public String reformat(String input) throws ParseException {
|
||||
return format(parseObject(input));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,280 @@
|
|||
package org.apache.commons.lang.text;
|
||||
|
||||
import java.text.Format;
|
||||
import java.text.MessageFormat;
|
||||
import java.text.ParsePosition;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.apache.commons.lang.Validate;
|
||||
|
||||
public class ExtendedMessageFormat extends MessageFormat {
|
||||
private static final long serialVersionUID = -2362048321261811743L;
|
||||
|
||||
private static final String DUMMY_PATTERN = "";
|
||||
|
||||
private static final String ESCAPED_QUOTE = "''";
|
||||
|
||||
private static final char START_FMT = ',';
|
||||
|
||||
private static final char END_FE = '}';
|
||||
|
||||
private static final char START_FE = '{';
|
||||
|
||||
private static final char QUOTE = '\'';
|
||||
|
||||
private String toPattern;
|
||||
|
||||
private Map registry;
|
||||
|
||||
public ExtendedMessageFormat(String pattern) {
|
||||
this(pattern, Locale.getDefault());
|
||||
}
|
||||
|
||||
public ExtendedMessageFormat(String pattern, Locale locale) {
|
||||
this(pattern, locale, null);
|
||||
}
|
||||
|
||||
public ExtendedMessageFormat(String pattern, Map registry) {
|
||||
this(pattern, Locale.getDefault(), registry);
|
||||
}
|
||||
|
||||
public ExtendedMessageFormat(String pattern, Locale locale, Map registry) {
|
||||
super("");
|
||||
setLocale(locale);
|
||||
this.registry = registry;
|
||||
applyPattern(pattern);
|
||||
}
|
||||
|
||||
public String toPattern() {
|
||||
return this.toPattern;
|
||||
}
|
||||
|
||||
public final void applyPattern(String pattern) {
|
||||
if (this.registry == null) {
|
||||
super.applyPattern(pattern);
|
||||
this.toPattern = super.toPattern();
|
||||
return;
|
||||
}
|
||||
ArrayList foundFormats = new ArrayList();
|
||||
ArrayList foundDescriptions = new ArrayList();
|
||||
StringBuffer stripCustom = new StringBuffer(pattern.length());
|
||||
ParsePosition pos = new ParsePosition(0);
|
||||
char[] c = pattern.toCharArray();
|
||||
int fmtCount = 0;
|
||||
while (pos.getIndex() < pattern.length()) {
|
||||
int start, index;
|
||||
Format format;
|
||||
String formatDescription;
|
||||
switch (c[pos.getIndex()]) {
|
||||
case '\'':
|
||||
appendQuotedString(pattern, pos, stripCustom, true);
|
||||
continue;
|
||||
case '{':
|
||||
fmtCount++;
|
||||
seekNonWs(pattern, pos);
|
||||
start = pos.getIndex();
|
||||
index = readArgumentIndex(pattern, next(pos));
|
||||
stripCustom.append('{').append(index);
|
||||
seekNonWs(pattern, pos);
|
||||
format = null;
|
||||
formatDescription = null;
|
||||
if (c[pos.getIndex()] == ',') {
|
||||
formatDescription = parseFormatDescription(pattern, next(pos));
|
||||
format = getFormat(formatDescription);
|
||||
if (format == null)
|
||||
stripCustom.append(',').append(formatDescription);
|
||||
}
|
||||
foundFormats.add(format);
|
||||
foundDescriptions.add((format == null) ? null : formatDescription);
|
||||
Validate.isTrue((foundFormats.size() == fmtCount));
|
||||
Validate.isTrue((foundDescriptions.size() == fmtCount));
|
||||
if (c[pos.getIndex()] != '}')
|
||||
throw new IllegalArgumentException("Unreadable format element at position " + start);
|
||||
break;
|
||||
}
|
||||
stripCustom.append(c[pos.getIndex()]);
|
||||
next(pos);
|
||||
}
|
||||
super.applyPattern(stripCustom.toString());
|
||||
this.toPattern = insertFormats(super.toPattern(), foundDescriptions);
|
||||
if (containsElements(foundFormats)) {
|
||||
Format[] origFormats = getFormats();
|
||||
int i = 0;
|
||||
for (Iterator it = foundFormats.iterator(); it.hasNext(); i++) {
|
||||
Format f = (Format)it.next();
|
||||
if (f != null)
|
||||
origFormats[i] = f;
|
||||
}
|
||||
super.setFormats(origFormats);
|
||||
}
|
||||
}
|
||||
|
||||
public void setFormat(int formatElementIndex, Format newFormat) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setFormatByArgumentIndex(int argumentIndex, Format newFormat) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setFormats(Format[] newFormats) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setFormatsByArgumentIndex(Format[] newFormats) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
private Format getFormat(String desc) {
|
||||
if (this.registry != null) {
|
||||
String name = desc;
|
||||
String args = null;
|
||||
int i = desc.indexOf(',');
|
||||
if (i > 0) {
|
||||
name = desc.substring(0, i).trim();
|
||||
args = desc.substring(i + 1).trim();
|
||||
}
|
||||
FormatFactory factory = (FormatFactory)this.registry.get(name);
|
||||
if (factory != null)
|
||||
return factory.getFormat(name, args, getLocale());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private int readArgumentIndex(String pattern, ParsePosition pos) {
|
||||
int start = pos.getIndex();
|
||||
seekNonWs(pattern, pos);
|
||||
StringBuffer result = new StringBuffer();
|
||||
boolean error = false;
|
||||
for (; !error && pos.getIndex() < pattern.length(); next(pos)) {
|
||||
char c = pattern.charAt(pos.getIndex());
|
||||
if (Character.isWhitespace(c)) {
|
||||
seekNonWs(pattern, pos);
|
||||
c = pattern.charAt(pos.getIndex());
|
||||
if (c != ',' && c != '}') {
|
||||
error = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((c == ',' || c == '}') && result.length() > 0)
|
||||
try {
|
||||
return Integer.parseInt(result.toString());
|
||||
} catch (NumberFormatException e) {}
|
||||
error = !Character.isDigit(c);
|
||||
result.append(c);
|
||||
}
|
||||
if (error)
|
||||
throw new IllegalArgumentException("Invalid format argument index at position " + start + ": " + pattern.substring(start, pos.getIndex()));
|
||||
throw new IllegalArgumentException("Unterminated format element at position " + start);
|
||||
}
|
||||
|
||||
private String parseFormatDescription(String pattern, ParsePosition pos) {
|
||||
int start = pos.getIndex();
|
||||
seekNonWs(pattern, pos);
|
||||
int text = pos.getIndex();
|
||||
int depth = 1;
|
||||
for (; pos.getIndex() < pattern.length(); next(pos)) {
|
||||
switch (pattern.charAt(pos.getIndex())) {
|
||||
case '{':
|
||||
depth++;
|
||||
break;
|
||||
case '}':
|
||||
depth--;
|
||||
if (depth == 0)
|
||||
return pattern.substring(text, pos.getIndex());
|
||||
break;
|
||||
case '\'':
|
||||
getQuotedString(pattern, pos, false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unterminated format element at position " + start);
|
||||
}
|
||||
|
||||
private String insertFormats(String pattern, ArrayList customPatterns) {
|
||||
if (!containsElements(customPatterns))
|
||||
return pattern;
|
||||
StringBuffer sb = new StringBuffer(pattern.length() * 2);
|
||||
ParsePosition pos = new ParsePosition(0);
|
||||
int fe = -1;
|
||||
int depth = 0;
|
||||
while (pos.getIndex() < pattern.length()) {
|
||||
char c = pattern.charAt(pos.getIndex());
|
||||
switch (c) {
|
||||
case '\'':
|
||||
appendQuotedString(pattern, pos, sb, false);
|
||||
continue;
|
||||
case '{':
|
||||
depth++;
|
||||
if (depth == 1) {
|
||||
fe++;
|
||||
sb.append('{').append(readArgumentIndex(pattern, next(pos)));
|
||||
String customPattern = (String)customPatterns.get(fe);
|
||||
if (customPattern != null)
|
||||
sb.append(',').append(customPattern);
|
||||
}
|
||||
continue;
|
||||
case '}':
|
||||
depth--;
|
||||
break;
|
||||
}
|
||||
sb.append(c);
|
||||
next(pos);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void seekNonWs(String pattern, ParsePosition pos) {
|
||||
int len = 0;
|
||||
char[] buffer = pattern.toCharArray();
|
||||
do {
|
||||
len = StrMatcher.splitMatcher().isMatch(buffer, pos.getIndex());
|
||||
pos.setIndex(pos.getIndex() + len);
|
||||
} while (len > 0 && pos.getIndex() < pattern.length());
|
||||
}
|
||||
|
||||
private ParsePosition next(ParsePosition pos) {
|
||||
pos.setIndex(pos.getIndex() + 1);
|
||||
return pos;
|
||||
}
|
||||
|
||||
private StringBuffer appendQuotedString(String pattern, ParsePosition pos, StringBuffer appendTo, boolean escapingOn) {
|
||||
int start = pos.getIndex();
|
||||
char[] c = pattern.toCharArray();
|
||||
if (escapingOn && c[start] == '\'')
|
||||
return (appendTo == null) ? null : appendTo.append('\'');
|
||||
int lastHold = start;
|
||||
for (int i = pos.getIndex(); i < pattern.length(); i++) {
|
||||
if (escapingOn && pattern.substring(i).startsWith("''")) {
|
||||
appendTo.append(c, lastHold, pos.getIndex() - lastHold).append('\'');
|
||||
pos.setIndex(i + "''".length());
|
||||
lastHold = pos.getIndex();
|
||||
} else {
|
||||
switch (c[pos.getIndex()]) {
|
||||
case '\'':
|
||||
next(pos);
|
||||
return (appendTo == null) ? null : appendTo.append(c, lastHold, pos.getIndex() - lastHold);
|
||||
}
|
||||
next(pos);
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unterminated quoted string at position " + start);
|
||||
}
|
||||
|
||||
private void getQuotedString(String pattern, ParsePosition pos, boolean escapingOn) {
|
||||
appendQuotedString(pattern, pos, null, escapingOn);
|
||||
}
|
||||
|
||||
private boolean containsElements(Collection coll) {
|
||||
if (coll == null || coll.size() == 0)
|
||||
return false;
|
||||
for (Iterator iter = coll.iterator(); iter.hasNext();) {
|
||||
if (iter.next() != null)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
package org.apache.commons.lang.text;
|
||||
|
||||
import java.text.Format;
|
||||
import java.util.Locale;
|
||||
|
||||
public interface FormatFactory {
|
||||
Format getFormat(String paramString1, String paramString2, Locale paramLocale);
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,50 @@
|
|||
package org.apache.commons.lang.text;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public abstract class StrLookup {
|
||||
private static final StrLookup NONE_LOOKUP = new MapStrLookup(null);
|
||||
|
||||
private static final StrLookup SYSTEM_PROPERTIES_LOOKUP;
|
||||
|
||||
static {
|
||||
StrLookup lookup = null;
|
||||
try {
|
||||
lookup = new MapStrLookup(System.getProperties());
|
||||
} catch (SecurityException ex) {
|
||||
lookup = NONE_LOOKUP;
|
||||
}
|
||||
SYSTEM_PROPERTIES_LOOKUP = lookup;
|
||||
}
|
||||
|
||||
public static StrLookup noneLookup() {
|
||||
return NONE_LOOKUP;
|
||||
}
|
||||
|
||||
public static StrLookup systemPropertiesLookup() {
|
||||
return SYSTEM_PROPERTIES_LOOKUP;
|
||||
}
|
||||
|
||||
public static StrLookup mapLookup(Map map) {
|
||||
return new MapStrLookup(map);
|
||||
}
|
||||
|
||||
public abstract String lookup(String paramString);
|
||||
|
||||
static class MapStrLookup extends StrLookup {
|
||||
private final Map map;
|
||||
|
||||
MapStrLookup(Map map) {
|
||||
this.map = map;
|
||||
}
|
||||
|
||||
public String lookup(String key) {
|
||||
if (this.map == null)
|
||||
return null;
|
||||
Object obj = this.map.get(key);
|
||||
if (obj == null)
|
||||
return null;
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,147 @@
|
|||
package org.apache.commons.lang.text;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public abstract class StrMatcher {
|
||||
private static final StrMatcher COMMA_MATCHER = new CharMatcher(',');
|
||||
|
||||
private static final StrMatcher TAB_MATCHER = new CharMatcher('\t');
|
||||
|
||||
private static final StrMatcher SPACE_MATCHER = new CharMatcher(' ');
|
||||
|
||||
private static final StrMatcher SPLIT_MATCHER = new CharSetMatcher(" \t\n\r\f".toCharArray());
|
||||
|
||||
private static final StrMatcher TRIM_MATCHER = new TrimMatcher();
|
||||
|
||||
private static final StrMatcher SINGLE_QUOTE_MATCHER = new CharMatcher('\'');
|
||||
|
||||
private static final StrMatcher DOUBLE_QUOTE_MATCHER = new CharMatcher('"');
|
||||
|
||||
private static final StrMatcher QUOTE_MATCHER = new CharSetMatcher("'\"".toCharArray());
|
||||
|
||||
private static final StrMatcher NONE_MATCHER = new NoMatcher();
|
||||
|
||||
public static StrMatcher commaMatcher() {
|
||||
return COMMA_MATCHER;
|
||||
}
|
||||
|
||||
public static StrMatcher tabMatcher() {
|
||||
return TAB_MATCHER;
|
||||
}
|
||||
|
||||
public static StrMatcher spaceMatcher() {
|
||||
return SPACE_MATCHER;
|
||||
}
|
||||
|
||||
public static StrMatcher splitMatcher() {
|
||||
return SPLIT_MATCHER;
|
||||
}
|
||||
|
||||
public static StrMatcher trimMatcher() {
|
||||
return TRIM_MATCHER;
|
||||
}
|
||||
|
||||
public static StrMatcher singleQuoteMatcher() {
|
||||
return SINGLE_QUOTE_MATCHER;
|
||||
}
|
||||
|
||||
public static StrMatcher doubleQuoteMatcher() {
|
||||
return DOUBLE_QUOTE_MATCHER;
|
||||
}
|
||||
|
||||
public static StrMatcher quoteMatcher() {
|
||||
return QUOTE_MATCHER;
|
||||
}
|
||||
|
||||
public static StrMatcher noneMatcher() {
|
||||
return NONE_MATCHER;
|
||||
}
|
||||
|
||||
public static StrMatcher charMatcher(char ch) {
|
||||
return new CharMatcher(ch);
|
||||
}
|
||||
|
||||
public static StrMatcher charSetMatcher(char[] chars) {
|
||||
if (chars == null || chars.length == 0)
|
||||
return NONE_MATCHER;
|
||||
if (chars.length == 1)
|
||||
return new CharMatcher(chars[0]);
|
||||
return new CharSetMatcher(chars);
|
||||
}
|
||||
|
||||
public static StrMatcher charSetMatcher(String chars) {
|
||||
if (chars == null || chars.length() == 0)
|
||||
return NONE_MATCHER;
|
||||
if (chars.length() == 1)
|
||||
return new CharMatcher(chars.charAt(0));
|
||||
return new CharSetMatcher(chars.toCharArray());
|
||||
}
|
||||
|
||||
public static StrMatcher stringMatcher(String str) {
|
||||
if (str == null || str.length() == 0)
|
||||
return NONE_MATCHER;
|
||||
return new StringMatcher(str);
|
||||
}
|
||||
|
||||
public abstract int isMatch(char[] paramArrayOfchar, int paramInt1, int paramInt2, int paramInt3);
|
||||
|
||||
public int isMatch(char[] buffer, int pos) {
|
||||
return isMatch(buffer, pos, 0, buffer.length);
|
||||
}
|
||||
|
||||
static final class CharSetMatcher extends StrMatcher {
|
||||
private char[] chars;
|
||||
|
||||
CharSetMatcher(char[] chars) {
|
||||
this.chars = (char[])chars.clone();
|
||||
Arrays.sort(this.chars);
|
||||
}
|
||||
|
||||
public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
|
||||
return (Arrays.binarySearch(this.chars, buffer[pos]) >= 0) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
static final class CharMatcher extends StrMatcher {
|
||||
private char ch;
|
||||
|
||||
CharMatcher(char ch) {
|
||||
this.ch = ch;
|
||||
}
|
||||
|
||||
public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
|
||||
return (this.ch == buffer[pos]) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
static final class StringMatcher extends StrMatcher {
|
||||
private char[] chars;
|
||||
|
||||
StringMatcher(String str) {
|
||||
this.chars = str.toCharArray();
|
||||
}
|
||||
|
||||
public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
|
||||
int len = this.chars.length;
|
||||
if (pos + len > bufferEnd)
|
||||
return 0;
|
||||
for (int i = 0; i < this.chars.length; i++, pos++) {
|
||||
if (this.chars[i] != buffer[pos])
|
||||
return 0;
|
||||
}
|
||||
return len;
|
||||
}
|
||||
}
|
||||
|
||||
static final class NoMatcher extends StrMatcher {
|
||||
public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static final class TrimMatcher extends StrMatcher {
|
||||
public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
|
||||
return (buffer[pos] <= ' ') ? 1 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,312 @@
|
|||
package org.apache.commons.lang.text;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class StrSubstitutor {
|
||||
public static final char DEFAULT_ESCAPE = '$';
|
||||
|
||||
public static final StrMatcher DEFAULT_PREFIX = StrMatcher.stringMatcher("${");
|
||||
|
||||
public static final StrMatcher DEFAULT_SUFFIX = StrMatcher.stringMatcher("}");
|
||||
|
||||
private char escapeChar;
|
||||
|
||||
private StrMatcher prefixMatcher;
|
||||
|
||||
private StrMatcher suffixMatcher;
|
||||
|
||||
private StrLookup variableResolver;
|
||||
|
||||
public static String replace(Object source, Map valueMap) {
|
||||
return new StrSubstitutor(valueMap).replace(source);
|
||||
}
|
||||
|
||||
public static String replace(Object source, Map valueMap, String prefix, String suffix) {
|
||||
return new StrSubstitutor(valueMap, prefix, suffix).replace(source);
|
||||
}
|
||||
|
||||
public static String replaceSystemProperties(Object source) {
|
||||
return new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(source);
|
||||
}
|
||||
|
||||
public StrSubstitutor() {
|
||||
this((StrLookup)null, DEFAULT_PREFIX, DEFAULT_SUFFIX, '$');
|
||||
}
|
||||
|
||||
public StrSubstitutor(Map valueMap) {
|
||||
this(StrLookup.mapLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, '$');
|
||||
}
|
||||
|
||||
public StrSubstitutor(Map valueMap, String prefix, String suffix) {
|
||||
this(StrLookup.mapLookup(valueMap), prefix, suffix, '$');
|
||||
}
|
||||
|
||||
public StrSubstitutor(Map valueMap, String prefix, String suffix, char escape) {
|
||||
this(StrLookup.mapLookup(valueMap), prefix, suffix, escape);
|
||||
}
|
||||
|
||||
public StrSubstitutor(StrLookup variableResolver) {
|
||||
this(variableResolver, DEFAULT_PREFIX, DEFAULT_SUFFIX, '$');
|
||||
}
|
||||
|
||||
public StrSubstitutor(StrLookup variableResolver, String prefix, String suffix, char escape) {
|
||||
setVariableResolver(variableResolver);
|
||||
setVariablePrefix(prefix);
|
||||
setVariableSuffix(suffix);
|
||||
setEscapeChar(escape);
|
||||
}
|
||||
|
||||
public StrSubstitutor(StrLookup variableResolver, StrMatcher prefixMatcher, StrMatcher suffixMatcher, char escape) {
|
||||
setVariableResolver(variableResolver);
|
||||
setVariablePrefixMatcher(prefixMatcher);
|
||||
setVariableSuffixMatcher(suffixMatcher);
|
||||
setEscapeChar(escape);
|
||||
}
|
||||
|
||||
public String replace(String source) {
|
||||
if (source == null)
|
||||
return null;
|
||||
StrBuilder buf = new StrBuilder(source);
|
||||
if (!substitute(buf, 0, source.length()))
|
||||
return source;
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public String replace(String source, int offset, int length) {
|
||||
if (source == null)
|
||||
return null;
|
||||
StrBuilder buf = new StrBuilder(length).append(source, offset, length);
|
||||
if (!substitute(buf, 0, length))
|
||||
return source.substring(offset, offset + length);
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public String replace(char[] source) {
|
||||
if (source == null)
|
||||
return null;
|
||||
StrBuilder buf = new StrBuilder(source.length).append(source);
|
||||
substitute(buf, 0, source.length);
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public String replace(char[] source, int offset, int length) {
|
||||
if (source == null)
|
||||
return null;
|
||||
StrBuilder buf = new StrBuilder(length).append(source, offset, length);
|
||||
substitute(buf, 0, length);
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public String replace(StringBuffer source) {
|
||||
if (source == null)
|
||||
return null;
|
||||
StrBuilder buf = new StrBuilder(source.length()).append(source);
|
||||
substitute(buf, 0, buf.length());
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public String replace(StringBuffer source, int offset, int length) {
|
||||
if (source == null)
|
||||
return null;
|
||||
StrBuilder buf = new StrBuilder(length).append(source, offset, length);
|
||||
substitute(buf, 0, length);
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public String replace(StrBuilder source) {
|
||||
if (source == null)
|
||||
return null;
|
||||
StrBuilder buf = new StrBuilder(source.length()).append(source);
|
||||
substitute(buf, 0, buf.length());
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public String replace(StrBuilder source, int offset, int length) {
|
||||
if (source == null)
|
||||
return null;
|
||||
StrBuilder buf = new StrBuilder(length).append(source, offset, length);
|
||||
substitute(buf, 0, length);
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public String replace(Object source) {
|
||||
if (source == null)
|
||||
return null;
|
||||
StrBuilder buf = new StrBuilder().append(source);
|
||||
substitute(buf, 0, buf.length());
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public boolean replaceIn(StringBuffer source) {
|
||||
if (source == null)
|
||||
return false;
|
||||
return replaceIn(source, 0, source.length());
|
||||
}
|
||||
|
||||
public boolean replaceIn(StringBuffer source, int offset, int length) {
|
||||
if (source == null)
|
||||
return false;
|
||||
StrBuilder buf = new StrBuilder(length).append(source, offset, length);
|
||||
if (!substitute(buf, 0, length))
|
||||
return false;
|
||||
source.replace(offset, offset + length, buf.toString());
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean replaceIn(StrBuilder source) {
|
||||
if (source == null)
|
||||
return false;
|
||||
return substitute(source, 0, source.length());
|
||||
}
|
||||
|
||||
public boolean replaceIn(StrBuilder source, int offset, int length) {
|
||||
if (source == null)
|
||||
return false;
|
||||
return substitute(source, offset, length);
|
||||
}
|
||||
|
||||
protected boolean substitute(StrBuilder buf, int offset, int length) {
|
||||
return (substitute(buf, offset, length, null) > 0);
|
||||
}
|
||||
|
||||
private int substitute(StrBuilder buf, int offset, int length, List priorVariables) {
|
||||
StrMatcher prefixMatcher = getVariablePrefixMatcher();
|
||||
StrMatcher suffixMatcher = getVariableSuffixMatcher();
|
||||
char escape = getEscapeChar();
|
||||
boolean top = (priorVariables == null);
|
||||
boolean altered = false;
|
||||
int lengthChange = 0;
|
||||
char[] chars = buf.buffer;
|
||||
int bufEnd = offset + length;
|
||||
int pos = offset;
|
||||
while (pos < bufEnd) {
|
||||
int startMatchLen = prefixMatcher.isMatch(chars, pos, offset, bufEnd);
|
||||
if (startMatchLen == 0) {
|
||||
pos++;
|
||||
continue;
|
||||
}
|
||||
if (pos > offset && chars[pos - 1] == escape) {
|
||||
buf.deleteCharAt(pos - 1);
|
||||
chars = buf.buffer;
|
||||
lengthChange--;
|
||||
altered = true;
|
||||
bufEnd--;
|
||||
continue;
|
||||
}
|
||||
int startPos = pos;
|
||||
pos += startMatchLen;
|
||||
int endMatchLen = 0;
|
||||
label36: while (pos < bufEnd) {
|
||||
endMatchLen = suffixMatcher.isMatch(chars, pos, offset, bufEnd);
|
||||
if (endMatchLen == 0) {
|
||||
pos++;
|
||||
continue;
|
||||
}
|
||||
String varName = new String(chars, startPos + startMatchLen, pos - startPos - startMatchLen);
|
||||
pos += endMatchLen;
|
||||
int endPos = pos;
|
||||
if (priorVariables == null) {
|
||||
priorVariables = new ArrayList();
|
||||
priorVariables.add(new String(chars, offset, length));
|
||||
}
|
||||
checkCyclicSubstitution(varName, priorVariables);
|
||||
priorVariables.add(varName);
|
||||
String varValue = resolveVariable(varName, buf, startPos, endPos);
|
||||
if (varValue != null) {
|
||||
int varLen = varValue.length();
|
||||
buf.replace(startPos, endPos, varValue);
|
||||
altered = true;
|
||||
int change = substitute(buf, startPos, varLen, priorVariables);
|
||||
change += varLen - (endPos - startPos);
|
||||
pos += change;
|
||||
bufEnd += change;
|
||||
lengthChange += change;
|
||||
chars = buf.buffer;
|
||||
break label36;
|
||||
}
|
||||
priorVariables.remove(priorVariables.size() - 1);
|
||||
}
|
||||
}
|
||||
if (top)
|
||||
return altered ? 1 : 0;
|
||||
return lengthChange;
|
||||
}
|
||||
|
||||
private void checkCyclicSubstitution(String varName, List priorVariables) {
|
||||
if (!priorVariables.contains(varName))
|
||||
return;
|
||||
StrBuilder buf = new StrBuilder(256);
|
||||
buf.append("Infinite loop in property interpolation of ");
|
||||
buf.append(priorVariables.remove(0));
|
||||
buf.append(": ");
|
||||
buf.appendWithSeparators(priorVariables, "->");
|
||||
throw new IllegalStateException(buf.toString());
|
||||
}
|
||||
|
||||
protected String resolveVariable(String variableName, StrBuilder buf, int startPos, int endPos) {
|
||||
StrLookup resolver = getVariableResolver();
|
||||
if (resolver == null)
|
||||
return null;
|
||||
return resolver.lookup(variableName);
|
||||
}
|
||||
|
||||
public char getEscapeChar() {
|
||||
return this.escapeChar;
|
||||
}
|
||||
|
||||
public void setEscapeChar(char escapeCharacter) {
|
||||
this.escapeChar = escapeCharacter;
|
||||
}
|
||||
|
||||
public StrMatcher getVariablePrefixMatcher() {
|
||||
return this.prefixMatcher;
|
||||
}
|
||||
|
||||
public StrSubstitutor setVariablePrefixMatcher(StrMatcher prefixMatcher) {
|
||||
if (prefixMatcher == null)
|
||||
throw new IllegalArgumentException("Variable prefix matcher must not be null!");
|
||||
this.prefixMatcher = prefixMatcher;
|
||||
return this;
|
||||
}
|
||||
|
||||
public StrSubstitutor setVariablePrefix(char prefix) {
|
||||
return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix));
|
||||
}
|
||||
|
||||
public StrSubstitutor setVariablePrefix(String prefix) {
|
||||
if (prefix == null)
|
||||
throw new IllegalArgumentException("Variable prefix must not be null!");
|
||||
return setVariablePrefixMatcher(StrMatcher.stringMatcher(prefix));
|
||||
}
|
||||
|
||||
public StrMatcher getVariableSuffixMatcher() {
|
||||
return this.suffixMatcher;
|
||||
}
|
||||
|
||||
public StrSubstitutor setVariableSuffixMatcher(StrMatcher suffixMatcher) {
|
||||
if (suffixMatcher == null)
|
||||
throw new IllegalArgumentException("Variable suffix matcher must not be null!");
|
||||
this.suffixMatcher = suffixMatcher;
|
||||
return this;
|
||||
}
|
||||
|
||||
public StrSubstitutor setVariableSuffix(char suffix) {
|
||||
return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix));
|
||||
}
|
||||
|
||||
public StrSubstitutor setVariableSuffix(String suffix) {
|
||||
if (suffix == null)
|
||||
throw new IllegalArgumentException("Variable suffix must not be null!");
|
||||
return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix));
|
||||
}
|
||||
|
||||
public StrLookup getVariableResolver() {
|
||||
return this.variableResolver;
|
||||
}
|
||||
|
||||
public void setVariableResolver(StrLookup variableResolver) {
|
||||
this.variableResolver = variableResolver;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,470 @@
|
|||
package org.apache.commons.lang.text;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
public class StrTokenizer implements ListIterator, Cloneable {
|
||||
private static final StrTokenizer CSV_TOKENIZER_PROTOTYPE = new StrTokenizer();
|
||||
|
||||
static {
|
||||
CSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StrMatcher.commaMatcher());
|
||||
CSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StrMatcher.doubleQuoteMatcher());
|
||||
CSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StrMatcher.noneMatcher());
|
||||
CSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StrMatcher.trimMatcher());
|
||||
CSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false);
|
||||
CSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
|
||||
}
|
||||
|
||||
private static final StrTokenizer TSV_TOKENIZER_PROTOTYPE = new StrTokenizer();
|
||||
|
||||
private char[] chars;
|
||||
|
||||
private String[] tokens;
|
||||
|
||||
private int tokenPos;
|
||||
|
||||
static {
|
||||
TSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StrMatcher.tabMatcher());
|
||||
TSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StrMatcher.doubleQuoteMatcher());
|
||||
TSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StrMatcher.noneMatcher());
|
||||
TSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StrMatcher.trimMatcher());
|
||||
TSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false);
|
||||
TSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
|
||||
}
|
||||
|
||||
private StrMatcher delimMatcher = StrMatcher.splitMatcher();
|
||||
|
||||
private StrMatcher quoteMatcher = StrMatcher.noneMatcher();
|
||||
|
||||
private StrMatcher ignoredMatcher = StrMatcher.noneMatcher();
|
||||
|
||||
private StrMatcher trimmerMatcher = StrMatcher.noneMatcher();
|
||||
|
||||
private boolean emptyAsNull = false;
|
||||
|
||||
private boolean ignoreEmptyTokens = true;
|
||||
|
||||
private static StrTokenizer getCSVClone() {
|
||||
return (StrTokenizer)CSV_TOKENIZER_PROTOTYPE.clone();
|
||||
}
|
||||
|
||||
public static StrTokenizer getCSVInstance() {
|
||||
return getCSVClone();
|
||||
}
|
||||
|
||||
public static StrTokenizer getCSVInstance(String input) {
|
||||
StrTokenizer tok = getCSVClone();
|
||||
tok.reset(input);
|
||||
return tok;
|
||||
}
|
||||
|
||||
public static StrTokenizer getCSVInstance(char[] input) {
|
||||
StrTokenizer tok = getCSVClone();
|
||||
tok.reset(input);
|
||||
return tok;
|
||||
}
|
||||
|
||||
private static StrTokenizer getTSVClone() {
|
||||
return (StrTokenizer)TSV_TOKENIZER_PROTOTYPE.clone();
|
||||
}
|
||||
|
||||
public static StrTokenizer getTSVInstance() {
|
||||
return getTSVClone();
|
||||
}
|
||||
|
||||
public static StrTokenizer getTSVInstance(String input) {
|
||||
StrTokenizer tok = getTSVClone();
|
||||
tok.reset(input);
|
||||
return tok;
|
||||
}
|
||||
|
||||
public static StrTokenizer getTSVInstance(char[] input) {
|
||||
StrTokenizer tok = getTSVClone();
|
||||
tok.reset(input);
|
||||
return tok;
|
||||
}
|
||||
|
||||
public StrTokenizer() {
|
||||
this.chars = null;
|
||||
}
|
||||
|
||||
public StrTokenizer(String input) {
|
||||
if (input != null) {
|
||||
this.chars = input.toCharArray();
|
||||
} else {
|
||||
this.chars = null;
|
||||
}
|
||||
}
|
||||
|
||||
public StrTokenizer(String input, char delim) {
|
||||
this(input);
|
||||
setDelimiterChar(delim);
|
||||
}
|
||||
|
||||
public StrTokenizer(String input, String delim) {
|
||||
this(input);
|
||||
setDelimiterString(delim);
|
||||
}
|
||||
|
||||
public StrTokenizer(String input, StrMatcher delim) {
|
||||
this(input);
|
||||
setDelimiterMatcher(delim);
|
||||
}
|
||||
|
||||
public StrTokenizer(String input, char delim, char quote) {
|
||||
this(input, delim);
|
||||
setQuoteChar(quote);
|
||||
}
|
||||
|
||||
public StrTokenizer(String input, StrMatcher delim, StrMatcher quote) {
|
||||
this(input, delim);
|
||||
setQuoteMatcher(quote);
|
||||
}
|
||||
|
||||
public StrTokenizer(char[] input) {
|
||||
this.chars = input;
|
||||
}
|
||||
|
||||
public StrTokenizer(char[] input, char delim) {
|
||||
this(input);
|
||||
setDelimiterChar(delim);
|
||||
}
|
||||
|
||||
public StrTokenizer(char[] input, String delim) {
|
||||
this(input);
|
||||
setDelimiterString(delim);
|
||||
}
|
||||
|
||||
public StrTokenizer(char[] input, StrMatcher delim) {
|
||||
this(input);
|
||||
setDelimiterMatcher(delim);
|
||||
}
|
||||
|
||||
public StrTokenizer(char[] input, char delim, char quote) {
|
||||
this(input, delim);
|
||||
setQuoteChar(quote);
|
||||
}
|
||||
|
||||
public StrTokenizer(char[] input, StrMatcher delim, StrMatcher quote) {
|
||||
this(input, delim);
|
||||
setQuoteMatcher(quote);
|
||||
}
|
||||
|
||||
public int size() {
|
||||
checkTokenized();
|
||||
return this.tokens.length;
|
||||
}
|
||||
|
||||
public String nextToken() {
|
||||
if (hasNext())
|
||||
return this.tokens[this.tokenPos++];
|
||||
return null;
|
||||
}
|
||||
|
||||
public String previousToken() {
|
||||
if (hasPrevious())
|
||||
return this.tokens[--this.tokenPos];
|
||||
return null;
|
||||
}
|
||||
|
||||
public String[] getTokenArray() {
|
||||
checkTokenized();
|
||||
return (String[])this.tokens.clone();
|
||||
}
|
||||
|
||||
public List getTokenList() {
|
||||
checkTokenized();
|
||||
List list = new ArrayList(this.tokens.length);
|
||||
for (int i = 0; i < this.tokens.length; i++)
|
||||
list.add(this.tokens[i]);
|
||||
return list;
|
||||
}
|
||||
|
||||
public StrTokenizer reset() {
|
||||
this.tokenPos = 0;
|
||||
this.tokens = null;
|
||||
return this;
|
||||
}
|
||||
|
||||
public StrTokenizer reset(String input) {
|
||||
reset();
|
||||
if (input != null) {
|
||||
this.chars = input.toCharArray();
|
||||
} else {
|
||||
this.chars = null;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public StrTokenizer reset(char[] input) {
|
||||
reset();
|
||||
this.chars = input;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
checkTokenized();
|
||||
return (this.tokenPos < this.tokens.length);
|
||||
}
|
||||
|
||||
public Object next() {
|
||||
if (hasNext())
|
||||
return this.tokens[this.tokenPos++];
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
|
||||
public int nextIndex() {
|
||||
return this.tokenPos;
|
||||
}
|
||||
|
||||
public boolean hasPrevious() {
|
||||
checkTokenized();
|
||||
return (this.tokenPos > 0);
|
||||
}
|
||||
|
||||
public Object previous() {
|
||||
if (hasPrevious())
|
||||
return this.tokens[--this.tokenPos];
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
|
||||
public int previousIndex() {
|
||||
return this.tokenPos - 1;
|
||||
}
|
||||
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException("remove() is unsupported");
|
||||
}
|
||||
|
||||
public void set(Object obj) {
|
||||
throw new UnsupportedOperationException("set() is unsupported");
|
||||
}
|
||||
|
||||
public void add(Object obj) {
|
||||
throw new UnsupportedOperationException("add() is unsupported");
|
||||
}
|
||||
|
||||
private void checkTokenized() {
|
||||
if (this.tokens == null)
|
||||
if (this.chars == null) {
|
||||
List split = tokenize(null, 0, 0);
|
||||
this.tokens = (String[])split.toArray(new String[split.size()]);
|
||||
} else {
|
||||
List split = tokenize(this.chars, 0, this.chars.length);
|
||||
this.tokens = (String[])split.toArray(new String[split.size()]);
|
||||
}
|
||||
}
|
||||
|
||||
protected List tokenize(char[] chars, int offset, int count) {
|
||||
if (chars == null || count == 0)
|
||||
return Collections.EMPTY_LIST;
|
||||
StrBuilder buf = new StrBuilder();
|
||||
List tokens = new ArrayList();
|
||||
int pos = offset;
|
||||
while (pos >= 0 && pos < count) {
|
||||
pos = readNextToken(chars, pos, count, buf, tokens);
|
||||
if (pos >= count)
|
||||
addToken(tokens, "");
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private void addToken(List list, String tok) {
|
||||
if (tok == null || tok.length() == 0) {
|
||||
if (isIgnoreEmptyTokens())
|
||||
return;
|
||||
if (isEmptyTokenAsNull())
|
||||
tok = null;
|
||||
}
|
||||
list.add(tok);
|
||||
}
|
||||
|
||||
private int readNextToken(char[] chars, int start, int len, StrBuilder workArea, List tokens) {
|
||||
while (start < len) {
|
||||
int removeLen = Math.max(getIgnoredMatcher().isMatch(chars, start, start, len), getTrimmerMatcher().isMatch(chars, start, start, len));
|
||||
if (removeLen == 0 || getDelimiterMatcher().isMatch(chars, start, start, len) > 0 || getQuoteMatcher().isMatch(chars, start, start, len) > 0)
|
||||
break;
|
||||
start += removeLen;
|
||||
}
|
||||
if (start >= len) {
|
||||
addToken(tokens, "");
|
||||
return -1;
|
||||
}
|
||||
int delimLen = getDelimiterMatcher().isMatch(chars, start, start, len);
|
||||
if (delimLen > 0) {
|
||||
addToken(tokens, "");
|
||||
return start + delimLen;
|
||||
}
|
||||
int quoteLen = getQuoteMatcher().isMatch(chars, start, start, len);
|
||||
if (quoteLen > 0)
|
||||
return readWithQuotes(chars, start + quoteLen, len, workArea, tokens, start, quoteLen);
|
||||
return readWithQuotes(chars, start, len, workArea, tokens, 0, 0);
|
||||
}
|
||||
|
||||
private int readWithQuotes(char[] chars, int start, int len, StrBuilder workArea, List tokens, int quoteStart, int quoteLen) {
|
||||
workArea.clear();
|
||||
int pos = start;
|
||||
boolean quoting = (quoteLen > 0);
|
||||
int trimStart = 0;
|
||||
while (pos < len) {
|
||||
if (quoting) {
|
||||
if (isQuote(chars, pos, len, quoteStart, quoteLen)) {
|
||||
if (isQuote(chars, pos + quoteLen, len, quoteStart, quoteLen)) {
|
||||
workArea.append(chars, pos, quoteLen);
|
||||
pos += quoteLen * 2;
|
||||
trimStart = workArea.size();
|
||||
continue;
|
||||
}
|
||||
quoting = false;
|
||||
pos += quoteLen;
|
||||
continue;
|
||||
}
|
||||
workArea.append(chars[pos++]);
|
||||
trimStart = workArea.size();
|
||||
continue;
|
||||
}
|
||||
int delimLen = getDelimiterMatcher().isMatch(chars, pos, start, len);
|
||||
if (delimLen > 0) {
|
||||
addToken(tokens, workArea.substring(0, trimStart));
|
||||
return pos + delimLen;
|
||||
}
|
||||
if (quoteLen > 0 &&
|
||||
isQuote(chars, pos, len, quoteStart, quoteLen)) {
|
||||
quoting = true;
|
||||
pos += quoteLen;
|
||||
continue;
|
||||
}
|
||||
int ignoredLen = getIgnoredMatcher().isMatch(chars, pos, start, len);
|
||||
if (ignoredLen > 0) {
|
||||
pos += ignoredLen;
|
||||
continue;
|
||||
}
|
||||
int trimmedLen = getTrimmerMatcher().isMatch(chars, pos, start, len);
|
||||
if (trimmedLen > 0) {
|
||||
workArea.append(chars, pos, trimmedLen);
|
||||
pos += trimmedLen;
|
||||
continue;
|
||||
}
|
||||
workArea.append(chars[pos++]);
|
||||
trimStart = workArea.size();
|
||||
}
|
||||
addToken(tokens, workArea.substring(0, trimStart));
|
||||
return -1;
|
||||
}
|
||||
|
||||
private boolean isQuote(char[] chars, int pos, int len, int quoteStart, int quoteLen) {
|
||||
for (int i = 0; i < quoteLen; i++) {
|
||||
if (pos + i >= len || chars[pos + i] != chars[quoteStart + i])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public StrMatcher getDelimiterMatcher() {
|
||||
return this.delimMatcher;
|
||||
}
|
||||
|
||||
public StrTokenizer setDelimiterMatcher(StrMatcher delim) {
|
||||
if (delim == null) {
|
||||
this.delimMatcher = StrMatcher.noneMatcher();
|
||||
} else {
|
||||
this.delimMatcher = delim;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public StrTokenizer setDelimiterChar(char delim) {
|
||||
return setDelimiterMatcher(StrMatcher.charMatcher(delim));
|
||||
}
|
||||
|
||||
public StrTokenizer setDelimiterString(String delim) {
|
||||
return setDelimiterMatcher(StrMatcher.stringMatcher(delim));
|
||||
}
|
||||
|
||||
public StrMatcher getQuoteMatcher() {
|
||||
return this.quoteMatcher;
|
||||
}
|
||||
|
||||
public StrTokenizer setQuoteMatcher(StrMatcher quote) {
|
||||
if (quote != null)
|
||||
this.quoteMatcher = quote;
|
||||
return this;
|
||||
}
|
||||
|
||||
public StrTokenizer setQuoteChar(char quote) {
|
||||
return setQuoteMatcher(StrMatcher.charMatcher(quote));
|
||||
}
|
||||
|
||||
public StrMatcher getIgnoredMatcher() {
|
||||
return this.ignoredMatcher;
|
||||
}
|
||||
|
||||
public StrTokenizer setIgnoredMatcher(StrMatcher ignored) {
|
||||
if (ignored != null)
|
||||
this.ignoredMatcher = ignored;
|
||||
return this;
|
||||
}
|
||||
|
||||
public StrTokenizer setIgnoredChar(char ignored) {
|
||||
return setIgnoredMatcher(StrMatcher.charMatcher(ignored));
|
||||
}
|
||||
|
||||
public StrMatcher getTrimmerMatcher() {
|
||||
return this.trimmerMatcher;
|
||||
}
|
||||
|
||||
public StrTokenizer setTrimmerMatcher(StrMatcher trimmer) {
|
||||
if (trimmer != null)
|
||||
this.trimmerMatcher = trimmer;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isEmptyTokenAsNull() {
|
||||
return this.emptyAsNull;
|
||||
}
|
||||
|
||||
public StrTokenizer setEmptyTokenAsNull(boolean emptyAsNull) {
|
||||
this.emptyAsNull = emptyAsNull;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isIgnoreEmptyTokens() {
|
||||
return this.ignoreEmptyTokens;
|
||||
}
|
||||
|
||||
public StrTokenizer setIgnoreEmptyTokens(boolean ignoreEmptyTokens) {
|
||||
this.ignoreEmptyTokens = ignoreEmptyTokens;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
if (this.chars == null)
|
||||
return null;
|
||||
return new String(this.chars);
|
||||
}
|
||||
|
||||
public Object clone() {
|
||||
try {
|
||||
return cloneReset();
|
||||
} catch (CloneNotSupportedException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Object cloneReset() throws CloneNotSupportedException {
|
||||
StrTokenizer cloned = (StrTokenizer)super.clone();
|
||||
if (cloned.chars != null)
|
||||
cloned.chars = (char[])cloned.chars.clone();
|
||||
cloned.reset();
|
||||
return cloned;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if (this.tokens == null)
|
||||
return "StrTokenizer[not tokenized yet]";
|
||||
return "StrTokenizer" + getTokenList();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
package org.apache.commons.lang.time;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class DateFormatUtils {
|
||||
public static final FastDateFormat ISO_DATETIME_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss");
|
||||
|
||||
public static final FastDateFormat ISO_DATETIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZZ");
|
||||
|
||||
public static final FastDateFormat ISO_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd");
|
||||
|
||||
public static final FastDateFormat ISO_DATE_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-ddZZ");
|
||||
|
||||
public static final FastDateFormat ISO_TIME_FORMAT = FastDateFormat.getInstance("'T'HH:mm:ss");
|
||||
|
||||
public static final FastDateFormat ISO_TIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("'T'HH:mm:ssZZ");
|
||||
|
||||
public static final FastDateFormat ISO_TIME_NO_T_FORMAT = FastDateFormat.getInstance("HH:mm:ss");
|
||||
|
||||
public static final FastDateFormat ISO_TIME_NO_T_TIME_ZONE_FORMAT = FastDateFormat.getInstance("HH:mm:ssZZ");
|
||||
|
||||
public static final FastDateFormat SMTP_DATETIME_FORMAT = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
|
||||
|
||||
public static String formatUTC(long millis, String pattern) {
|
||||
return format(new Date(millis), pattern, DateUtils.UTC_TIME_ZONE, null);
|
||||
}
|
||||
|
||||
public static String formatUTC(Date date, String pattern) {
|
||||
return format(date, pattern, DateUtils.UTC_TIME_ZONE, null);
|
||||
}
|
||||
|
||||
public static String formatUTC(long millis, String pattern, Locale locale) {
|
||||
return format(new Date(millis), pattern, DateUtils.UTC_TIME_ZONE, locale);
|
||||
}
|
||||
|
||||
public static String formatUTC(Date date, String pattern, Locale locale) {
|
||||
return format(date, pattern, DateUtils.UTC_TIME_ZONE, locale);
|
||||
}
|
||||
|
||||
public static String format(long millis, String pattern) {
|
||||
return format(new Date(millis), pattern, null, null);
|
||||
}
|
||||
|
||||
public static String format(Date date, String pattern) {
|
||||
return format(date, pattern, null, null);
|
||||
}
|
||||
|
||||
public static String format(Calendar calendar, String pattern) {
|
||||
return format(calendar, pattern, null, null);
|
||||
}
|
||||
|
||||
public static String format(long millis, String pattern, TimeZone timeZone) {
|
||||
return format(new Date(millis), pattern, timeZone, null);
|
||||
}
|
||||
|
||||
public static String format(Date date, String pattern, TimeZone timeZone) {
|
||||
return format(date, pattern, timeZone, null);
|
||||
}
|
||||
|
||||
public static String format(Calendar calendar, String pattern, TimeZone timeZone) {
|
||||
return format(calendar, pattern, timeZone, null);
|
||||
}
|
||||
|
||||
public static String format(long millis, String pattern, Locale locale) {
|
||||
return format(new Date(millis), pattern, null, locale);
|
||||
}
|
||||
|
||||
public static String format(Date date, String pattern, Locale locale) {
|
||||
return format(date, pattern, null, locale);
|
||||
}
|
||||
|
||||
public static String format(Calendar calendar, String pattern, Locale locale) {
|
||||
return format(calendar, pattern, null, locale);
|
||||
}
|
||||
|
||||
public static String format(long millis, String pattern, TimeZone timeZone, Locale locale) {
|
||||
return format(new Date(millis), pattern, timeZone, locale);
|
||||
}
|
||||
|
||||
public static String format(Date date, String pattern, TimeZone timeZone, Locale locale) {
|
||||
FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
public static String format(Calendar calendar, String pattern, TimeZone timeZone, Locale locale) {
|
||||
FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
|
||||
return df.format(calendar);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,519 @@
|
|||
package org.apache.commons.lang.time;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.ParsePosition;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class DateUtils {
|
||||
public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
|
||||
|
||||
public static final long MILLIS_PER_SECOND = 1000L;
|
||||
|
||||
public static final long MILLIS_PER_MINUTE = 60000L;
|
||||
|
||||
public static final long MILLIS_PER_HOUR = 3600000L;
|
||||
|
||||
public static final long MILLIS_PER_DAY = 86400000L;
|
||||
|
||||
public static final int SEMI_MONTH = 1001;
|
||||
|
||||
private static final int[][] fields = new int[][] { new int[] { 14 }, new int[] { 13 }, new int[] { 12 }, new int[] { 11, 10 }, new int[] { 5, 5, 9 }, new int[] { 2, 1001 }, new int[] { 1 }, new int[] { 0 } };
|
||||
|
||||
public static final int RANGE_WEEK_SUNDAY = 1;
|
||||
|
||||
public static final int RANGE_WEEK_MONDAY = 2;
|
||||
|
||||
public static final int RANGE_WEEK_RELATIVE = 3;
|
||||
|
||||
public static final int RANGE_WEEK_CENTER = 4;
|
||||
|
||||
public static final int RANGE_MONTH_SUNDAY = 5;
|
||||
|
||||
public static final int RANGE_MONTH_MONDAY = 6;
|
||||
|
||||
public static final int MILLIS_IN_SECOND = 1000;
|
||||
|
||||
public static final int MILLIS_IN_MINUTE = 60000;
|
||||
|
||||
public static final int MILLIS_IN_HOUR = 3600000;
|
||||
|
||||
public static final int MILLIS_IN_DAY = 86400000;
|
||||
|
||||
public static boolean isSameDay(Date date1, Date date2) {
|
||||
if (date1 == null || date2 == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
Calendar cal1 = Calendar.getInstance();
|
||||
cal1.setTime(date1);
|
||||
Calendar cal2 = Calendar.getInstance();
|
||||
cal2.setTime(date2);
|
||||
return isSameDay(cal1, cal2);
|
||||
}
|
||||
|
||||
public static boolean isSameDay(Calendar cal1, Calendar cal2) {
|
||||
if (cal1 == null || cal2 == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
return (cal1.get(0) == cal2.get(0) && cal1.get(1) == cal2.get(1) && cal1.get(6) == cal2.get(6));
|
||||
}
|
||||
|
||||
public static boolean isSameInstant(Date date1, Date date2) {
|
||||
if (date1 == null || date2 == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
return (date1.getTime() == date2.getTime());
|
||||
}
|
||||
|
||||
public static boolean isSameInstant(Calendar cal1, Calendar cal2) {
|
||||
if (cal1 == null || cal2 == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
return (cal1.getTime().getTime() == cal2.getTime().getTime());
|
||||
}
|
||||
|
||||
public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {
|
||||
if (cal1 == null || cal2 == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
return (cal1.get(14) == cal2.get(14) && cal1.get(13) == cal2.get(13) && cal1.get(12) == cal2.get(12) && cal1.get(10) == cal2.get(10) && cal1.get(6) == cal2.get(6) && cal1.get(1) == cal2.get(1) && cal1.get(0) == cal2.get(0) && cal1.getClass() == cal2.getClass());
|
||||
}
|
||||
|
||||
public static Date parseDate(String str, String[] parsePatterns) throws ParseException {
|
||||
if (str == null || parsePatterns == null)
|
||||
throw new IllegalArgumentException("Date and Patterns must not be null");
|
||||
SimpleDateFormat parser = null;
|
||||
ParsePosition pos = new ParsePosition(0);
|
||||
for (int i = 0; i < parsePatterns.length; i++) {
|
||||
if (i == 0) {
|
||||
parser = new SimpleDateFormat(parsePatterns[0]);
|
||||
} else {
|
||||
parser.applyPattern(parsePatterns[i]);
|
||||
}
|
||||
pos.setIndex(0);
|
||||
Date date = parser.parse(str, pos);
|
||||
if (date != null && pos.getIndex() == str.length())
|
||||
return date;
|
||||
}
|
||||
throw new ParseException("Unable to parse the date: " + str, -1);
|
||||
}
|
||||
|
||||
public static Date addYears(Date date, int amount) {
|
||||
return add(date, 1, amount);
|
||||
}
|
||||
|
||||
public static Date addMonths(Date date, int amount) {
|
||||
return add(date, 2, amount);
|
||||
}
|
||||
|
||||
public static Date addWeeks(Date date, int amount) {
|
||||
return add(date, 3, amount);
|
||||
}
|
||||
|
||||
public static Date addDays(Date date, int amount) {
|
||||
return add(date, 5, amount);
|
||||
}
|
||||
|
||||
public static Date addHours(Date date, int amount) {
|
||||
return add(date, 11, amount);
|
||||
}
|
||||
|
||||
public static Date addMinutes(Date date, int amount) {
|
||||
return add(date, 12, amount);
|
||||
}
|
||||
|
||||
public static Date addSeconds(Date date, int amount) {
|
||||
return add(date, 13, amount);
|
||||
}
|
||||
|
||||
public static Date addMilliseconds(Date date, int amount) {
|
||||
return add(date, 14, amount);
|
||||
}
|
||||
|
||||
public static Date add(Date date, int calendarField, int amount) {
|
||||
if (date == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(date);
|
||||
c.add(calendarField, amount);
|
||||
return c.getTime();
|
||||
}
|
||||
|
||||
public static Date setYears(Date date, int amount) {
|
||||
return set(date, 1, amount);
|
||||
}
|
||||
|
||||
public static Date setMonths(Date date, int amount) {
|
||||
return set(date, 2, amount);
|
||||
}
|
||||
|
||||
public static Date setDays(Date date, int amount) {
|
||||
return set(date, 5, amount);
|
||||
}
|
||||
|
||||
public static Date setHours(Date date, int amount) {
|
||||
return set(date, 11, amount);
|
||||
}
|
||||
|
||||
public static Date setMinutes(Date date, int amount) {
|
||||
return set(date, 12, amount);
|
||||
}
|
||||
|
||||
public static Date setSeconds(Date date, int amount) {
|
||||
return set(date, 13, amount);
|
||||
}
|
||||
|
||||
public static Date setMilliseconds(Date date, int amount) {
|
||||
return set(date, 14, amount);
|
||||
}
|
||||
|
||||
private static Date set(Date date, int calendarField, int amount) {
|
||||
if (date == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setLenient(false);
|
||||
c.setTime(date);
|
||||
c.set(calendarField, amount);
|
||||
return c.getTime();
|
||||
}
|
||||
|
||||
public static Date round(Date date, int field) {
|
||||
if (date == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
Calendar gval = Calendar.getInstance();
|
||||
gval.setTime(date);
|
||||
modify(gval, field, true);
|
||||
return gval.getTime();
|
||||
}
|
||||
|
||||
public static Calendar round(Calendar date, int field) {
|
||||
if (date == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
Calendar rounded = (Calendar)date.clone();
|
||||
modify(rounded, field, true);
|
||||
return rounded;
|
||||
}
|
||||
|
||||
public static Date round(Object date, int field) {
|
||||
if (date == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
if (date instanceof Date)
|
||||
return round((Date)date, field);
|
||||
if (date instanceof Calendar)
|
||||
return round((Calendar)date, field).getTime();
|
||||
throw new ClassCastException("Could not round " + date);
|
||||
}
|
||||
|
||||
public static Date truncate(Date date, int field) {
|
||||
if (date == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
Calendar gval = Calendar.getInstance();
|
||||
gval.setTime(date);
|
||||
modify(gval, field, false);
|
||||
return gval.getTime();
|
||||
}
|
||||
|
||||
public static Calendar truncate(Calendar date, int field) {
|
||||
if (date == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
Calendar truncated = (Calendar)date.clone();
|
||||
modify(truncated, field, false);
|
||||
return truncated;
|
||||
}
|
||||
|
||||
public static Date truncate(Object date, int field) {
|
||||
if (date == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
if (date instanceof Date)
|
||||
return truncate((Date)date, field);
|
||||
if (date instanceof Calendar)
|
||||
return truncate((Calendar)date, field).getTime();
|
||||
throw new ClassCastException("Could not truncate " + date);
|
||||
}
|
||||
|
||||
private static void modify(Calendar val, int field, boolean round) {
|
||||
if (val.get(1) > 280000000)
|
||||
throw new ArithmeticException("Calendar value too large for accurate calculations");
|
||||
if (field == 14)
|
||||
return;
|
||||
Date date = val.getTime();
|
||||
long time = date.getTime();
|
||||
boolean done = false;
|
||||
int millisecs = val.get(14);
|
||||
if (!round || millisecs < 500)
|
||||
time -= (long)millisecs;
|
||||
if (field == 13)
|
||||
done = true;
|
||||
int seconds = val.get(13);
|
||||
if (!done && (!round || seconds < 30))
|
||||
time -= (long)seconds * 1000L;
|
||||
if (field == 12)
|
||||
done = true;
|
||||
int minutes = val.get(12);
|
||||
if (!done && (!round || minutes < 30))
|
||||
time -= (long)minutes * 60000L;
|
||||
if (date.getTime() != time) {
|
||||
date.setTime(time);
|
||||
val.setTime(date);
|
||||
}
|
||||
boolean roundUp = false;
|
||||
for (int i = 0; i < fields.length; i++) {
|
||||
for (int j = 0; j < (fields[i]).length; j++) {
|
||||
if (fields[i][j] == field) {
|
||||
if (round && roundUp)
|
||||
if (field == 1001) {
|
||||
if (val.get(5) == 1) {
|
||||
val.add(5, 15);
|
||||
} else {
|
||||
val.add(5, -15);
|
||||
val.add(2, 1);
|
||||
}
|
||||
} else {
|
||||
val.add(fields[i][0], 1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
int offset = 0;
|
||||
boolean offsetSet = false;
|
||||
switch (field) {
|
||||
case 1001:
|
||||
if (fields[i][0] == 5) {
|
||||
offset = val.get(5) - 1;
|
||||
if (offset >= 15)
|
||||
offset -= 15;
|
||||
roundUp = (offset > 7);
|
||||
offsetSet = true;
|
||||
}
|
||||
break;
|
||||
case 9:
|
||||
if (fields[i][0] == 11) {
|
||||
offset = val.get(11);
|
||||
if (offset >= 12)
|
||||
offset -= 12;
|
||||
roundUp = (offset > 6);
|
||||
offsetSet = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (!offsetSet) {
|
||||
int min = val.getActualMinimum(fields[i][0]);
|
||||
int max = val.getActualMaximum(fields[i][0]);
|
||||
offset = val.get(fields[i][0]) - min;
|
||||
roundUp = (offset > (max - min) / 2);
|
||||
}
|
||||
if (offset != 0)
|
||||
val.set(fields[i][0], val.get(fields[i][0]) - offset);
|
||||
}
|
||||
throw new IllegalArgumentException("The field " + field + " is not supported");
|
||||
}
|
||||
|
||||
public static Iterator iterator(Date focus, int rangeStyle) {
|
||||
if (focus == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
Calendar gval = Calendar.getInstance();
|
||||
gval.setTime(focus);
|
||||
return iterator(gval, rangeStyle);
|
||||
}
|
||||
|
||||
public static Iterator iterator(Calendar focus, int rangeStyle) {
|
||||
if (focus == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
Calendar start = null;
|
||||
Calendar end = null;
|
||||
int startCutoff = 1;
|
||||
int endCutoff = 7;
|
||||
switch (rangeStyle) {
|
||||
case 5:
|
||||
case 6:
|
||||
start = truncate(focus, 2);
|
||||
end = (Calendar)start.clone();
|
||||
end.add(2, 1);
|
||||
end.add(5, -1);
|
||||
if (rangeStyle == 6) {
|
||||
startCutoff = 2;
|
||||
endCutoff = 1;
|
||||
}
|
||||
break;
|
||||
case 1:
|
||||
case 2:
|
||||
case 3:
|
||||
case 4:
|
||||
start = truncate(focus, 5);
|
||||
end = truncate(focus, 5);
|
||||
switch (rangeStyle) {
|
||||
case 2:
|
||||
startCutoff = 2;
|
||||
endCutoff = 1;
|
||||
break;
|
||||
case 3:
|
||||
startCutoff = focus.get(7);
|
||||
endCutoff = startCutoff - 1;
|
||||
break;
|
||||
case 4:
|
||||
startCutoff = focus.get(7) - 3;
|
||||
endCutoff = focus.get(7) + 3;
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("The range style " + rangeStyle + " is not valid.");
|
||||
}
|
||||
if (startCutoff < 1)
|
||||
startCutoff += 7;
|
||||
if (startCutoff > 7)
|
||||
startCutoff -= 7;
|
||||
if (endCutoff < 1)
|
||||
endCutoff += 7;
|
||||
if (endCutoff > 7)
|
||||
endCutoff -= 7;
|
||||
while (start.get(7) != startCutoff)
|
||||
start.add(5, -1);
|
||||
while (end.get(7) != endCutoff)
|
||||
end.add(5, 1);
|
||||
return new DateIterator(start, end);
|
||||
}
|
||||
|
||||
public static Iterator iterator(Object focus, int rangeStyle) {
|
||||
if (focus == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
if (focus instanceof Date)
|
||||
return iterator((Date)focus, rangeStyle);
|
||||
if (focus instanceof Calendar)
|
||||
return iterator((Calendar)focus, rangeStyle);
|
||||
throw new ClassCastException("Could not iterate based on " + focus);
|
||||
}
|
||||
|
||||
public static long getFragmentInMilliseconds(Date date, int fragment) {
|
||||
return getFragment(date, fragment, 14);
|
||||
}
|
||||
|
||||
public static long getFragmentInSeconds(Date date, int fragment) {
|
||||
return getFragment(date, fragment, 13);
|
||||
}
|
||||
|
||||
public static long getFragmentInMinutes(Date date, int fragment) {
|
||||
return getFragment(date, fragment, 12);
|
||||
}
|
||||
|
||||
public static long getFragmentInHours(Date date, int fragment) {
|
||||
return getFragment(date, fragment, 11);
|
||||
}
|
||||
|
||||
public static long getFragmentInDays(Date date, int fragment) {
|
||||
return getFragment(date, fragment, 6);
|
||||
}
|
||||
|
||||
public static long getFragmentInMilliseconds(Calendar calendar, int fragment) {
|
||||
return getFragment(calendar, fragment, 14);
|
||||
}
|
||||
|
||||
public static long getFragmentInSeconds(Calendar calendar, int fragment) {
|
||||
return getFragment(calendar, fragment, 13);
|
||||
}
|
||||
|
||||
public static long getFragmentInMinutes(Calendar calendar, int fragment) {
|
||||
return getFragment(calendar, fragment, 12);
|
||||
}
|
||||
|
||||
public static long getFragmentInHours(Calendar calendar, int fragment) {
|
||||
return getFragment(calendar, fragment, 11);
|
||||
}
|
||||
|
||||
public static long getFragmentInDays(Calendar calendar, int fragment) {
|
||||
return getFragment(calendar, fragment, 6);
|
||||
}
|
||||
|
||||
private static long getFragment(Date date, int fragment, int unit) {
|
||||
if (date == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
return getFragment(calendar, fragment, unit);
|
||||
}
|
||||
|
||||
private static long getFragment(Calendar calendar, int fragment, int unit) {
|
||||
if (calendar == null)
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
long millisPerUnit = getMillisPerUnit(unit);
|
||||
long result = 0L;
|
||||
switch (fragment) {
|
||||
case 1:
|
||||
result += (long)calendar.get(6) * 86400000L / millisPerUnit;
|
||||
break;
|
||||
case 2:
|
||||
result += (long)calendar.get(5) * 86400000L / millisPerUnit;
|
||||
break;
|
||||
}
|
||||
switch (fragment) {
|
||||
case 1:
|
||||
case 2:
|
||||
case 5:
|
||||
case 6:
|
||||
result += (long)calendar.get(11) * 3600000L / millisPerUnit;
|
||||
case 11:
|
||||
result += (long)calendar.get(12) * 60000L / millisPerUnit;
|
||||
case 12:
|
||||
result += (long)calendar.get(13) * 1000L / millisPerUnit;
|
||||
case 13:
|
||||
result += (long)(calendar.get(14) * 1) / millisPerUnit;
|
||||
break;
|
||||
case 14:
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static long getMillisPerUnit(int unit) {
|
||||
long result = Long.MAX_VALUE;
|
||||
switch (unit) {
|
||||
case 5:
|
||||
case 6:
|
||||
result = 86400000L;
|
||||
break;
|
||||
case 11:
|
||||
result = 3600000L;
|
||||
break;
|
||||
case 12:
|
||||
result = 60000L;
|
||||
break;
|
||||
case 13:
|
||||
result = 1000L;
|
||||
break;
|
||||
case 14:
|
||||
result = 1L;
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static class DateIterator implements Iterator {
|
||||
private final Calendar endFinal;
|
||||
|
||||
private final Calendar spot;
|
||||
|
||||
DateIterator(Calendar startFinal, Calendar endFinal) {
|
||||
this.endFinal = endFinal;
|
||||
this.spot = startFinal;
|
||||
this.spot.add(5, -1);
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
return this.spot.before(this.endFinal);
|
||||
}
|
||||
|
||||
public Object next() {
|
||||
if (this.spot.equals(this.endFinal))
|
||||
throw new NoSuchElementException();
|
||||
this.spot.add(5, 1);
|
||||
return this.spot.clone();
|
||||
}
|
||||
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,373 @@
|
|||
package org.apache.commons.lang.time;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
public class DurationFormatUtils {
|
||||
public static final String ISO_EXTENDED_FORMAT_PATTERN = "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.S'S'";
|
||||
|
||||
public static String formatDurationHMS(long durationMillis) {
|
||||
return formatDuration(durationMillis, "H:mm:ss.SSS");
|
||||
}
|
||||
|
||||
public static String formatDurationISO(long durationMillis) {
|
||||
return formatDuration(durationMillis, "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.S'S'", false);
|
||||
}
|
||||
|
||||
public static String formatDuration(long durationMillis, String format) {
|
||||
return formatDuration(durationMillis, format, true);
|
||||
}
|
||||
|
||||
public static String formatDuration(long durationMillis, String format, boolean padWithZeros) {
|
||||
Token[] tokens = lexx(format);
|
||||
int days = 0;
|
||||
int hours = 0;
|
||||
int minutes = 0;
|
||||
int seconds = 0;
|
||||
int milliseconds = 0;
|
||||
if (Token.containsTokenWithValue(tokens, d)) {
|
||||
days = (int)(durationMillis / 86400000L);
|
||||
durationMillis -= (long)days * 86400000L;
|
||||
}
|
||||
if (Token.containsTokenWithValue(tokens, H)) {
|
||||
hours = (int)(durationMillis / 3600000L);
|
||||
durationMillis -= (long)hours * 3600000L;
|
||||
}
|
||||
if (Token.containsTokenWithValue(tokens, m)) {
|
||||
minutes = (int)(durationMillis / 60000L);
|
||||
durationMillis -= (long)minutes * 60000L;
|
||||
}
|
||||
if (Token.containsTokenWithValue(tokens, s)) {
|
||||
seconds = (int)(durationMillis / 1000L);
|
||||
durationMillis -= (long)seconds * 1000L;
|
||||
}
|
||||
if (Token.containsTokenWithValue(tokens, S))
|
||||
milliseconds = (int)durationMillis;
|
||||
return format(tokens, 0, 0, days, hours, minutes, seconds, milliseconds, padWithZeros);
|
||||
}
|
||||
|
||||
public static String formatDurationWords(long durationMillis, boolean suppressLeadingZeroElements, boolean suppressTrailingZeroElements) {
|
||||
String duration = formatDuration(durationMillis, "d' days 'H' hours 'm' minutes 's' seconds'");
|
||||
if (suppressLeadingZeroElements) {
|
||||
duration = " " + duration;
|
||||
String tmp = StringUtils.replaceOnce(duration, " 0 days", "");
|
||||
if (tmp.length() != duration.length()) {
|
||||
duration = tmp;
|
||||
tmp = StringUtils.replaceOnce(duration, " 0 hours", "");
|
||||
if (tmp.length() != duration.length()) {
|
||||
duration = tmp;
|
||||
tmp = StringUtils.replaceOnce(duration, " 0 minutes", "");
|
||||
duration = tmp;
|
||||
if (tmp.length() != duration.length())
|
||||
duration = StringUtils.replaceOnce(tmp, " 0 seconds", "");
|
||||
}
|
||||
}
|
||||
if (duration.length() != 0)
|
||||
duration = duration.substring(1);
|
||||
}
|
||||
if (suppressTrailingZeroElements) {
|
||||
String tmp = StringUtils.replaceOnce(duration, " 0 seconds", "");
|
||||
if (tmp.length() != duration.length()) {
|
||||
duration = tmp;
|
||||
tmp = StringUtils.replaceOnce(duration, " 0 minutes", "");
|
||||
if (tmp.length() != duration.length()) {
|
||||
duration = tmp;
|
||||
tmp = StringUtils.replaceOnce(duration, " 0 hours", "");
|
||||
if (tmp.length() != duration.length())
|
||||
duration = StringUtils.replaceOnce(tmp, " 0 days", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
duration = " " + duration;
|
||||
duration = StringUtils.replaceOnce(duration, " 1 seconds", " 1 second");
|
||||
duration = StringUtils.replaceOnce(duration, " 1 minutes", " 1 minute");
|
||||
duration = StringUtils.replaceOnce(duration, " 1 hours", " 1 hour");
|
||||
duration = StringUtils.replaceOnce(duration, " 1 days", " 1 day");
|
||||
return duration.trim();
|
||||
}
|
||||
|
||||
public static String formatPeriodISO(long startMillis, long endMillis) {
|
||||
return formatPeriod(startMillis, endMillis, "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.S'S'", false, TimeZone.getDefault());
|
||||
}
|
||||
|
||||
public static String formatPeriod(long startMillis, long endMillis, String format) {
|
||||
return formatPeriod(startMillis, endMillis, format, true, TimeZone.getDefault());
|
||||
}
|
||||
|
||||
public static String formatPeriod(long startMillis, long endMillis, String format, boolean padWithZeros, TimeZone timezone) {
|
||||
Token[] tokens = lexx(format);
|
||||
Calendar start = Calendar.getInstance(timezone);
|
||||
start.setTime(new Date(startMillis));
|
||||
Calendar end = Calendar.getInstance(timezone);
|
||||
end.setTime(new Date(endMillis));
|
||||
int milliseconds = end.get(14) - start.get(14);
|
||||
int seconds = end.get(13) - start.get(13);
|
||||
int minutes = end.get(12) - start.get(12);
|
||||
int hours = end.get(11) - start.get(11);
|
||||
int days = end.get(5) - start.get(5);
|
||||
int months = end.get(2) - start.get(2);
|
||||
int years = end.get(1) - start.get(1);
|
||||
while (milliseconds < 0) {
|
||||
milliseconds += 1000;
|
||||
seconds--;
|
||||
}
|
||||
while (seconds < 0) {
|
||||
seconds += 60;
|
||||
minutes--;
|
||||
}
|
||||
while (minutes < 0) {
|
||||
minutes += 60;
|
||||
hours--;
|
||||
}
|
||||
while (hours < 0) {
|
||||
hours += 24;
|
||||
days--;
|
||||
}
|
||||
if (Token.containsTokenWithValue(tokens, M)) {
|
||||
while (days < 0) {
|
||||
days += start.getActualMaximum(5);
|
||||
months--;
|
||||
start.add(2, 1);
|
||||
}
|
||||
while (months < 0) {
|
||||
months += 12;
|
||||
years--;
|
||||
}
|
||||
if (!Token.containsTokenWithValue(tokens, y) && years != 0)
|
||||
while (years != 0) {
|
||||
months += 12 * years;
|
||||
years = 0;
|
||||
}
|
||||
} else {
|
||||
if (!Token.containsTokenWithValue(tokens, y)) {
|
||||
int target = end.get(1);
|
||||
if (months < 0)
|
||||
target--;
|
||||
while (start.get(1) != target) {
|
||||
days += start.getActualMaximum(6) - start.get(6);
|
||||
if (start instanceof java.util.GregorianCalendar &&
|
||||
start.get(2) == 1 && start.get(5) == 29)
|
||||
days++;
|
||||
start.add(1, 1);
|
||||
days += start.get(6);
|
||||
}
|
||||
years = 0;
|
||||
}
|
||||
while (start.get(2) != end.get(2)) {
|
||||
days += start.getActualMaximum(5);
|
||||
start.add(2, 1);
|
||||
}
|
||||
months = 0;
|
||||
while (days < 0) {
|
||||
days += start.getActualMaximum(5);
|
||||
months--;
|
||||
start.add(2, 1);
|
||||
}
|
||||
}
|
||||
if (!Token.containsTokenWithValue(tokens, d)) {
|
||||
hours += 24 * days;
|
||||
days = 0;
|
||||
}
|
||||
if (!Token.containsTokenWithValue(tokens, H)) {
|
||||
minutes += 60 * hours;
|
||||
hours = 0;
|
||||
}
|
||||
if (!Token.containsTokenWithValue(tokens, m)) {
|
||||
seconds += 60 * minutes;
|
||||
minutes = 0;
|
||||
}
|
||||
if (!Token.containsTokenWithValue(tokens, s)) {
|
||||
milliseconds += 1000 * seconds;
|
||||
seconds = 0;
|
||||
}
|
||||
return format(tokens, years, months, days, hours, minutes, seconds, milliseconds, padWithZeros);
|
||||
}
|
||||
|
||||
static String format(Token[] tokens, int years, int months, int days, int hours, int minutes, int seconds, int milliseconds, boolean padWithZeros) {
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
boolean lastOutputSeconds = false;
|
||||
int sz = tokens.length;
|
||||
for (int i = 0; i < sz; i++) {
|
||||
Token token = tokens[i];
|
||||
Object value = token.getValue();
|
||||
int count = token.getCount();
|
||||
if (value instanceof StringBuffer) {
|
||||
buffer.append(value.toString());
|
||||
} else if (value == y) {
|
||||
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(years), count, '0') : Integer.toString(years));
|
||||
lastOutputSeconds = false;
|
||||
} else if (value == M) {
|
||||
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(months), count, '0') : Integer.toString(months));
|
||||
lastOutputSeconds = false;
|
||||
} else if (value == d) {
|
||||
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(days), count, '0') : Integer.toString(days));
|
||||
lastOutputSeconds = false;
|
||||
} else if (value == H) {
|
||||
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(hours), count, '0') : Integer.toString(hours));
|
||||
lastOutputSeconds = false;
|
||||
} else if (value == m) {
|
||||
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(minutes), count, '0') : Integer.toString(minutes));
|
||||
lastOutputSeconds = false;
|
||||
} else if (value == s) {
|
||||
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(seconds), count, '0') : Integer.toString(seconds));
|
||||
lastOutputSeconds = true;
|
||||
} else if (value == S) {
|
||||
if (lastOutputSeconds) {
|
||||
milliseconds += 1000;
|
||||
String str = padWithZeros ? StringUtils.leftPad(Integer.toString(milliseconds), count, '0') : Integer.toString(milliseconds);
|
||||
buffer.append(str.substring(1));
|
||||
} else {
|
||||
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(milliseconds), count, '0') : Integer.toString(milliseconds));
|
||||
}
|
||||
lastOutputSeconds = false;
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
static final Object y = "y";
|
||||
|
||||
static final Object M = "M";
|
||||
|
||||
static final Object d = "d";
|
||||
|
||||
static final Object H = "H";
|
||||
|
||||
static final Object m = "m";
|
||||
|
||||
static final Object s = "s";
|
||||
|
||||
static final Object S = "S";
|
||||
|
||||
static Token[] lexx(String format) {
|
||||
char[] array = format.toCharArray();
|
||||
ArrayList list = new ArrayList(array.length);
|
||||
boolean inLiteral = false;
|
||||
StringBuffer buffer = null;
|
||||
Token previous = null;
|
||||
int sz = array.length;
|
||||
for (int i = 0; i < sz; i++) {
|
||||
char ch = array[i];
|
||||
if (inLiteral && ch != '\'') {
|
||||
buffer.append(ch);
|
||||
} else {
|
||||
Object value = null;
|
||||
switch (ch) {
|
||||
case '\'':
|
||||
if (inLiteral) {
|
||||
buffer = null;
|
||||
inLiteral = false;
|
||||
} else {
|
||||
buffer = new StringBuffer();
|
||||
list.add(new Token(buffer));
|
||||
inLiteral = true;
|
||||
}
|
||||
break;
|
||||
case 'y':
|
||||
value = y;
|
||||
break;
|
||||
case 'M':
|
||||
value = M;
|
||||
break;
|
||||
case 'd':
|
||||
value = d;
|
||||
break;
|
||||
case 'H':
|
||||
value = H;
|
||||
break;
|
||||
case 'm':
|
||||
value = m;
|
||||
break;
|
||||
case 's':
|
||||
value = s;
|
||||
break;
|
||||
case 'S':
|
||||
value = S;
|
||||
break;
|
||||
default:
|
||||
if (buffer == null) {
|
||||
buffer = new StringBuffer();
|
||||
list.add(new Token(buffer));
|
||||
}
|
||||
buffer.append(ch);
|
||||
break;
|
||||
}
|
||||
if (value != null) {
|
||||
if (previous != null && previous.getValue() == value) {
|
||||
previous.increment();
|
||||
} else {
|
||||
Token token = new Token(value);
|
||||
list.add(token);
|
||||
previous = token;
|
||||
}
|
||||
buffer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (Token[])list.toArray(new Token[list.size()]);
|
||||
}
|
||||
|
||||
static class Token {
|
||||
private Object value;
|
||||
|
||||
private int count;
|
||||
|
||||
static boolean containsTokenWithValue(Token[] tokens, Object value) {
|
||||
int sz = tokens.length;
|
||||
for (int i = 0; i < sz; i++) {
|
||||
if (tokens[i].getValue() == value)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Token(Object value) {
|
||||
this.value = value;
|
||||
this.count = 1;
|
||||
}
|
||||
|
||||
Token(Object value, int count) {
|
||||
this.value = value;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
void increment() {
|
||||
this.count++;
|
||||
}
|
||||
|
||||
int getCount() {
|
||||
return this.count;
|
||||
}
|
||||
|
||||
Object getValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj2) {
|
||||
if (obj2 instanceof Token) {
|
||||
Token tok2 = (Token)obj2;
|
||||
if (this.value.getClass() != tok2.value.getClass())
|
||||
return false;
|
||||
if (this.count != tok2.count)
|
||||
return false;
|
||||
if (this.value instanceof StringBuffer)
|
||||
return this.value.toString().equals(tok2.value.toString());
|
||||
if (this.value instanceof Number)
|
||||
return this.value.equals(tok2.value);
|
||||
return (this.value == tok2.value);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.value.hashCode();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return StringUtils.repeat(this.value.toString(), this.count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,903 @@
|
|||
package org.apache.commons.lang.time;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.text.DateFormat;
|
||||
import java.text.DateFormatSymbols;
|
||||
import java.text.FieldPosition;
|
||||
import java.text.Format;
|
||||
import java.text.ParsePosition;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
import org.apache.commons.lang.Validate;
|
||||
|
||||
public class FastDateFormat extends Format {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final int FULL = 0;
|
||||
|
||||
public static final int LONG = 1;
|
||||
|
||||
public static final int MEDIUM = 2;
|
||||
|
||||
public static final int SHORT = 3;
|
||||
|
||||
private static String cDefaultPattern;
|
||||
|
||||
private static final Map cInstanceCache = new HashMap(7);
|
||||
|
||||
private static final Map cDateInstanceCache = new HashMap(7);
|
||||
|
||||
private static final Map cTimeInstanceCache = new HashMap(7);
|
||||
|
||||
private static final Map cDateTimeInstanceCache = new HashMap(7);
|
||||
|
||||
private static final Map cTimeZoneDisplayCache = new HashMap(7);
|
||||
|
||||
private final String mPattern;
|
||||
|
||||
private final TimeZone mTimeZone;
|
||||
|
||||
private final boolean mTimeZoneForced;
|
||||
|
||||
private final Locale mLocale;
|
||||
|
||||
private final boolean mLocaleForced;
|
||||
|
||||
private transient Rule[] mRules;
|
||||
|
||||
private transient int mMaxLengthEstimate;
|
||||
|
||||
public static FastDateFormat getInstance() {
|
||||
return getInstance(getDefaultPattern(), null, null);
|
||||
}
|
||||
|
||||
public static FastDateFormat getInstance(String pattern) {
|
||||
return getInstance(pattern, null, null);
|
||||
}
|
||||
|
||||
public static FastDateFormat getInstance(String pattern, TimeZone timeZone) {
|
||||
return getInstance(pattern, timeZone, null);
|
||||
}
|
||||
|
||||
public static FastDateFormat getInstance(String pattern, Locale locale) {
|
||||
return getInstance(pattern, null, locale);
|
||||
}
|
||||
|
||||
public static synchronized FastDateFormat getInstance(String pattern, TimeZone timeZone, Locale locale) {
|
||||
FastDateFormat emptyFormat = new FastDateFormat(pattern, timeZone, locale);
|
||||
FastDateFormat format = (FastDateFormat)cInstanceCache.get(emptyFormat);
|
||||
if (format == null) {
|
||||
format = emptyFormat;
|
||||
format.init();
|
||||
cInstanceCache.put(format, format);
|
||||
}
|
||||
return format;
|
||||
}
|
||||
|
||||
public static FastDateFormat getDateInstance(int style) {
|
||||
return getDateInstance(style, null, null);
|
||||
}
|
||||
|
||||
public static FastDateFormat getDateInstance(int style, Locale locale) {
|
||||
return getDateInstance(style, null, locale);
|
||||
}
|
||||
|
||||
public static FastDateFormat getDateInstance(int style, TimeZone timeZone) {
|
||||
return getDateInstance(style, timeZone, null);
|
||||
}
|
||||
|
||||
public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) {
|
||||
Object key = new Integer(style);
|
||||
if (timeZone != null)
|
||||
key = new Pair(key, timeZone);
|
||||
if (locale == null)
|
||||
locale = Locale.getDefault();
|
||||
key = new Pair(key, locale);
|
||||
FastDateFormat format = (FastDateFormat)cDateInstanceCache.get(key);
|
||||
if (format == null)
|
||||
try {
|
||||
SimpleDateFormat formatter = (SimpleDateFormat)DateFormat.getDateInstance(style, locale);
|
||||
String pattern = formatter.toPattern();
|
||||
format = getInstance(pattern, timeZone, locale);
|
||||
cDateInstanceCache.put(key, format);
|
||||
} catch (ClassCastException ex) {
|
||||
throw new IllegalArgumentException("No date pattern for locale: " + locale);
|
||||
}
|
||||
return format;
|
||||
}
|
||||
|
||||
public static FastDateFormat getTimeInstance(int style) {
|
||||
return getTimeInstance(style, null, null);
|
||||
}
|
||||
|
||||
public static FastDateFormat getTimeInstance(int style, Locale locale) {
|
||||
return getTimeInstance(style, null, locale);
|
||||
}
|
||||
|
||||
public static FastDateFormat getTimeInstance(int style, TimeZone timeZone) {
|
||||
return getTimeInstance(style, timeZone, null);
|
||||
}
|
||||
|
||||
public static synchronized FastDateFormat getTimeInstance(int style, TimeZone timeZone, Locale locale) {
|
||||
Object key = new Integer(style);
|
||||
if (timeZone != null)
|
||||
key = new Pair(key, timeZone);
|
||||
if (locale != null)
|
||||
key = new Pair(key, locale);
|
||||
FastDateFormat format = (FastDateFormat)cTimeInstanceCache.get(key);
|
||||
if (format == null) {
|
||||
if (locale == null)
|
||||
locale = Locale.getDefault();
|
||||
try {
|
||||
SimpleDateFormat formatter = (SimpleDateFormat)DateFormat.getTimeInstance(style, locale);
|
||||
String pattern = formatter.toPattern();
|
||||
format = getInstance(pattern, timeZone, locale);
|
||||
cTimeInstanceCache.put(key, format);
|
||||
} catch (ClassCastException ex) {
|
||||
throw new IllegalArgumentException("No date pattern for locale: " + locale);
|
||||
}
|
||||
}
|
||||
return format;
|
||||
}
|
||||
|
||||
public static FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle) {
|
||||
return getDateTimeInstance(dateStyle, timeStyle, null, null);
|
||||
}
|
||||
|
||||
public static FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale) {
|
||||
return getDateTimeInstance(dateStyle, timeStyle, null, locale);
|
||||
}
|
||||
|
||||
public static FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone) {
|
||||
return getDateTimeInstance(dateStyle, timeStyle, timeZone, null);
|
||||
}
|
||||
|
||||
public static synchronized FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone, Locale locale) {
|
||||
Object key = new Pair(new Integer(dateStyle), new Integer(timeStyle));
|
||||
if (timeZone != null)
|
||||
key = new Pair(key, timeZone);
|
||||
if (locale == null)
|
||||
locale = Locale.getDefault();
|
||||
key = new Pair(key, locale);
|
||||
FastDateFormat format = (FastDateFormat)cDateTimeInstanceCache.get(key);
|
||||
if (format == null)
|
||||
try {
|
||||
SimpleDateFormat formatter = (SimpleDateFormat)DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
|
||||
String pattern = formatter.toPattern();
|
||||
format = getInstance(pattern, timeZone, locale);
|
||||
cDateTimeInstanceCache.put(key, format);
|
||||
} catch (ClassCastException ex) {
|
||||
throw new IllegalArgumentException("No date time pattern for locale: " + locale);
|
||||
}
|
||||
return format;
|
||||
}
|
||||
|
||||
static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) {
|
||||
Object key = new TimeZoneDisplayKey(tz, daylight, style, locale);
|
||||
String value = (String)cTimeZoneDisplayCache.get(key);
|
||||
if (value == null) {
|
||||
value = tz.getDisplayName(daylight, style, locale);
|
||||
cTimeZoneDisplayCache.put(key, value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static synchronized String getDefaultPattern() {
|
||||
if (cDefaultPattern == null)
|
||||
cDefaultPattern = new SimpleDateFormat().toPattern();
|
||||
return cDefaultPattern;
|
||||
}
|
||||
|
||||
protected FastDateFormat(String pattern, TimeZone timeZone, Locale locale) {
|
||||
if (pattern == null)
|
||||
throw new IllegalArgumentException("The pattern must not be null");
|
||||
this.mPattern = pattern;
|
||||
this.mTimeZoneForced = (timeZone != null);
|
||||
if (timeZone == null)
|
||||
timeZone = TimeZone.getDefault();
|
||||
this.mTimeZone = timeZone;
|
||||
this.mLocaleForced = (locale != null);
|
||||
if (locale == null)
|
||||
locale = Locale.getDefault();
|
||||
this.mLocale = locale;
|
||||
}
|
||||
|
||||
protected void init() {
|
||||
List rulesList = parsePattern();
|
||||
this.mRules = (Rule[])rulesList.toArray(new Rule[rulesList.size()]);
|
||||
int len = 0;
|
||||
for (int i = this.mRules.length; --i >= 0;)
|
||||
len += this.mRules[i].estimateLength();
|
||||
this.mMaxLengthEstimate = len;
|
||||
}
|
||||
|
||||
protected List parsePattern() {
|
||||
DateFormatSymbols symbols = new DateFormatSymbols(this.mLocale);
|
||||
List rules = new ArrayList();
|
||||
String[] ERAs = symbols.getEras();
|
||||
String[] months = symbols.getMonths();
|
||||
String[] shortMonths = symbols.getShortMonths();
|
||||
String[] weekdays = symbols.getWeekdays();
|
||||
String[] shortWeekdays = symbols.getShortWeekdays();
|
||||
String[] AmPmStrings = symbols.getAmPmStrings();
|
||||
int length = this.mPattern.length();
|
||||
int[] indexRef = new int[1];
|
||||
for (int i = 0; i < length; i++) {
|
||||
Rule rule;
|
||||
String sub;
|
||||
indexRef[0] = i;
|
||||
String token = parseToken(this.mPattern, indexRef);
|
||||
i = indexRef[0];
|
||||
int tokenLen = token.length();
|
||||
if (tokenLen == 0)
|
||||
break;
|
||||
char c = token.charAt(0);
|
||||
switch (c) {
|
||||
case 'G':
|
||||
rule = new TextField(0, ERAs);
|
||||
break;
|
||||
case 'y':
|
||||
if (tokenLen >= 4) {
|
||||
rule = selectNumberRule(1, tokenLen);
|
||||
} else {
|
||||
rule = TwoDigitYearField.INSTANCE;
|
||||
}
|
||||
break;
|
||||
case 'M':
|
||||
if (tokenLen >= 4) {
|
||||
rule = new TextField(2, months);
|
||||
} else if (tokenLen == 3) {
|
||||
rule = new TextField(2, shortMonths);
|
||||
} else if (tokenLen == 2) {
|
||||
rule = TwoDigitMonthField.INSTANCE;
|
||||
} else {
|
||||
rule = UnpaddedMonthField.INSTANCE;
|
||||
}
|
||||
break;
|
||||
case 'd':
|
||||
rule = selectNumberRule(5, tokenLen);
|
||||
break;
|
||||
case 'h':
|
||||
rule = new TwelveHourField(selectNumberRule(10, tokenLen));
|
||||
break;
|
||||
case 'H':
|
||||
rule = selectNumberRule(11, tokenLen);
|
||||
break;
|
||||
case 'm':
|
||||
rule = selectNumberRule(12, tokenLen);
|
||||
break;
|
||||
case 's':
|
||||
rule = selectNumberRule(13, tokenLen);
|
||||
break;
|
||||
case 'S':
|
||||
rule = selectNumberRule(14, tokenLen);
|
||||
break;
|
||||
case 'E':
|
||||
rule = new TextField(7, (tokenLen < 4) ? shortWeekdays : weekdays);
|
||||
break;
|
||||
case 'D':
|
||||
rule = selectNumberRule(6, tokenLen);
|
||||
break;
|
||||
case 'F':
|
||||
rule = selectNumberRule(8, tokenLen);
|
||||
break;
|
||||
case 'w':
|
||||
rule = selectNumberRule(3, tokenLen);
|
||||
break;
|
||||
case 'W':
|
||||
rule = selectNumberRule(4, tokenLen);
|
||||
break;
|
||||
case 'a':
|
||||
rule = new TextField(9, AmPmStrings);
|
||||
break;
|
||||
case 'k':
|
||||
rule = new TwentyFourHourField(selectNumberRule(11, tokenLen));
|
||||
break;
|
||||
case 'K':
|
||||
rule = selectNumberRule(10, tokenLen);
|
||||
break;
|
||||
case 'z':
|
||||
if (tokenLen >= 4) {
|
||||
rule = new TimeZoneNameRule(this.mTimeZone, this.mTimeZoneForced, this.mLocale, 1);
|
||||
} else {
|
||||
rule = new TimeZoneNameRule(this.mTimeZone, this.mTimeZoneForced, this.mLocale, 0);
|
||||
}
|
||||
break;
|
||||
case 'Z':
|
||||
if (tokenLen == 1) {
|
||||
rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
|
||||
} else {
|
||||
rule = TimeZoneNumberRule.INSTANCE_COLON;
|
||||
}
|
||||
break;
|
||||
case '\'':
|
||||
sub = token.substring(1);
|
||||
if (sub.length() == 1) {
|
||||
rule = new CharacterLiteral(sub.charAt(0));
|
||||
} else {
|
||||
rule = new StringLiteral(sub);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Illegal pattern component: " + token);
|
||||
}
|
||||
rules.add(rule);
|
||||
}
|
||||
return rules;
|
||||
}
|
||||
|
||||
protected String parseToken(String pattern, int[] indexRef) {
|
||||
StringBuffer buf = new StringBuffer();
|
||||
int i = indexRef[0];
|
||||
int length = pattern.length();
|
||||
char c = pattern.charAt(i);
|
||||
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
|
||||
buf.append(c);
|
||||
while (i + 1 < length) {
|
||||
char peek = pattern.charAt(i + 1);
|
||||
if (peek == c) {
|
||||
buf.append(c);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
buf.append('\'');
|
||||
boolean inLiteral = false;
|
||||
for (; i < length; i++) {
|
||||
c = pattern.charAt(i);
|
||||
if (c == '\'') {
|
||||
if (i + 1 < length && pattern.charAt(i + 1) == '\'') {
|
||||
i++;
|
||||
buf.append(c);
|
||||
} else {
|
||||
inLiteral = !inLiteral;
|
||||
}
|
||||
} else {
|
||||
if (!inLiteral && ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) {
|
||||
i--;
|
||||
break;
|
||||
}
|
||||
buf.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
indexRef[0] = i;
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
protected NumberRule selectNumberRule(int field, int padding) {
|
||||
switch (padding) {
|
||||
case 1:
|
||||
return new UnpaddedNumberField(field);
|
||||
case 2:
|
||||
return new TwoDigitNumberField(field);
|
||||
}
|
||||
return new PaddedNumberField(field, padding);
|
||||
}
|
||||
|
||||
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
|
||||
if (obj instanceof Date)
|
||||
return format((Date)obj, toAppendTo);
|
||||
if (obj instanceof Calendar)
|
||||
return format((Calendar)obj, toAppendTo);
|
||||
if (obj instanceof Long)
|
||||
return format(((Long)obj).longValue(), toAppendTo);
|
||||
throw new IllegalArgumentException("Unknown class: " + ((obj == null) ? "<null>" : obj.getClass().getName()));
|
||||
}
|
||||
|
||||
public String format(long millis) {
|
||||
return format(new Date(millis));
|
||||
}
|
||||
|
||||
public String format(Date date) {
|
||||
Calendar c = new GregorianCalendar(this.mTimeZone);
|
||||
c.setTime(date);
|
||||
return applyRules(c, new StringBuffer(this.mMaxLengthEstimate)).toString();
|
||||
}
|
||||
|
||||
public String format(Calendar calendar) {
|
||||
return format(calendar, new StringBuffer(this.mMaxLengthEstimate)).toString();
|
||||
}
|
||||
|
||||
public StringBuffer format(long millis, StringBuffer buf) {
|
||||
return format(new Date(millis), buf);
|
||||
}
|
||||
|
||||
public StringBuffer format(Date date, StringBuffer buf) {
|
||||
Calendar c = new GregorianCalendar(this.mTimeZone);
|
||||
c.setTime(date);
|
||||
return applyRules(c, buf);
|
||||
}
|
||||
|
||||
public StringBuffer format(Calendar calendar, StringBuffer buf) {
|
||||
if (this.mTimeZoneForced) {
|
||||
calendar = (Calendar)calendar.clone();
|
||||
calendar.setTimeZone(this.mTimeZone);
|
||||
}
|
||||
return applyRules(calendar, buf);
|
||||
}
|
||||
|
||||
protected StringBuffer applyRules(Calendar calendar, StringBuffer buf) {
|
||||
Rule[] rules = this.mRules;
|
||||
int len = this.mRules.length;
|
||||
for (int i = 0; i < len; i++)
|
||||
rules[i].appendTo(buf, calendar);
|
||||
return buf;
|
||||
}
|
||||
|
||||
public Object parseObject(String source, ParsePosition pos) {
|
||||
pos.setIndex(0);
|
||||
pos.setErrorIndex(0);
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getPattern() {
|
||||
return this.mPattern;
|
||||
}
|
||||
|
||||
public TimeZone getTimeZone() {
|
||||
return this.mTimeZone;
|
||||
}
|
||||
|
||||
public boolean getTimeZoneOverridesCalendar() {
|
||||
return this.mTimeZoneForced;
|
||||
}
|
||||
|
||||
public Locale getLocale() {
|
||||
return this.mLocale;
|
||||
}
|
||||
|
||||
public int getMaxLengthEstimate() {
|
||||
return this.mMaxLengthEstimate;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof FastDateFormat))
|
||||
return false;
|
||||
FastDateFormat other = (FastDateFormat)obj;
|
||||
if ((this.mPattern == other.mPattern || this.mPattern.equals(other.mPattern)) && (this.mTimeZone == other.mTimeZone || this.mTimeZone.equals(other.mTimeZone)) && (this.mLocale == other.mLocale || this.mLocale.equals(other.mLocale)) && this.mTimeZoneForced == other.mTimeZoneForced && this.mLocaleForced == other.mLocaleForced)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
int total = 0;
|
||||
total += this.mPattern.hashCode();
|
||||
total += this.mTimeZone.hashCode();
|
||||
total += this.mTimeZoneForced ? 1 : 0;
|
||||
total += this.mLocale.hashCode();
|
||||
total += this.mLocaleForced ? 1 : 0;
|
||||
return total;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "FastDateFormat[" + this.mPattern + "]";
|
||||
}
|
||||
|
||||
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
|
||||
in.defaultReadObject();
|
||||
init();
|
||||
}
|
||||
|
||||
private static interface Rule {
|
||||
int estimateLength();
|
||||
|
||||
void appendTo(StringBuffer param1StringBuffer, Calendar param1Calendar);
|
||||
}
|
||||
|
||||
private static interface NumberRule extends Rule {
|
||||
void appendTo(StringBuffer param1StringBuffer, int param1Int);
|
||||
}
|
||||
|
||||
private static class CharacterLiteral implements Rule {
|
||||
private final char mValue;
|
||||
|
||||
CharacterLiteral(char value) {
|
||||
this.mValue = value;
|
||||
}
|
||||
|
||||
public int estimateLength() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
buffer.append(this.mValue);
|
||||
}
|
||||
}
|
||||
|
||||
private static class StringLiteral implements Rule {
|
||||
private final String mValue;
|
||||
|
||||
StringLiteral(String value) {
|
||||
this.mValue = value;
|
||||
}
|
||||
|
||||
public int estimateLength() {
|
||||
return this.mValue.length();
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
buffer.append(this.mValue);
|
||||
}
|
||||
}
|
||||
|
||||
private static class TextField implements Rule {
|
||||
private final int mField;
|
||||
|
||||
private final String[] mValues;
|
||||
|
||||
TextField(int field, String[] values) {
|
||||
this.mField = field;
|
||||
this.mValues = values;
|
||||
}
|
||||
|
||||
public int estimateLength() {
|
||||
int max = 0;
|
||||
for (int i = this.mValues.length; --i >= 0; ) {
|
||||
int len = this.mValues[i].length();
|
||||
if (len > max)
|
||||
max = len;
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
buffer.append(this.mValues[calendar.get(this.mField)]);
|
||||
}
|
||||
}
|
||||
|
||||
private static class UnpaddedNumberField implements NumberRule {
|
||||
static final UnpaddedNumberField INSTANCE_YEAR = new UnpaddedNumberField(1);
|
||||
|
||||
private final int mField;
|
||||
|
||||
UnpaddedNumberField(int field) {
|
||||
this.mField = field;
|
||||
}
|
||||
|
||||
public int estimateLength() {
|
||||
return 4;
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
appendTo(buffer, calendar.get(this.mField));
|
||||
}
|
||||
|
||||
public final void appendTo(StringBuffer buffer, int value) {
|
||||
if (value < 10) {
|
||||
buffer.append((char)(value + 48));
|
||||
} else if (value < 100) {
|
||||
buffer.append((char)(value / 10 + 48));
|
||||
buffer.append((char)(value % 10 + 48));
|
||||
} else {
|
||||
buffer.append(Integer.toString(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class UnpaddedMonthField implements NumberRule {
|
||||
static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField();
|
||||
|
||||
public int estimateLength() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
appendTo(buffer, calendar.get(2) + 1);
|
||||
}
|
||||
|
||||
public final void appendTo(StringBuffer buffer, int value) {
|
||||
if (value < 10) {
|
||||
buffer.append((char)(value + 48));
|
||||
} else {
|
||||
buffer.append((char)(value / 10 + 48));
|
||||
buffer.append((char)(value % 10 + 48));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class PaddedNumberField implements NumberRule {
|
||||
private final int mField;
|
||||
|
||||
private final int mSize;
|
||||
|
||||
PaddedNumberField(int field, int size) {
|
||||
if (size < 3)
|
||||
throw new IllegalArgumentException();
|
||||
this.mField = field;
|
||||
this.mSize = size;
|
||||
}
|
||||
|
||||
public int estimateLength() {
|
||||
return 4;
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
appendTo(buffer, calendar.get(this.mField));
|
||||
}
|
||||
|
||||
public final void appendTo(StringBuffer buffer, int value) {
|
||||
if (value < 100) {
|
||||
for (int i = this.mSize; --i >= 2;)
|
||||
buffer.append('0');
|
||||
buffer.append((char)(value / 10 + 48));
|
||||
buffer.append((char)(value % 10 + 48));
|
||||
} else {
|
||||
int digits;
|
||||
if (value < 1000) {
|
||||
digits = 3;
|
||||
} else {
|
||||
Validate.isTrue((value > -1), "Negative values should not be possible", (long)value);
|
||||
digits = Integer.toString(value).length();
|
||||
}
|
||||
for (int i = this.mSize; --i >= digits;)
|
||||
buffer.append('0');
|
||||
buffer.append(Integer.toString(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class TwoDigitNumberField implements NumberRule {
|
||||
private final int mField;
|
||||
|
||||
TwoDigitNumberField(int field) {
|
||||
this.mField = field;
|
||||
}
|
||||
|
||||
public int estimateLength() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
appendTo(buffer, calendar.get(this.mField));
|
||||
}
|
||||
|
||||
public final void appendTo(StringBuffer buffer, int value) {
|
||||
if (value < 100) {
|
||||
buffer.append((char)(value / 10 + 48));
|
||||
buffer.append((char)(value % 10 + 48));
|
||||
} else {
|
||||
buffer.append(Integer.toString(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class TwoDigitYearField implements NumberRule {
|
||||
static final TwoDigitYearField INSTANCE = new TwoDigitYearField();
|
||||
|
||||
public int estimateLength() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
appendTo(buffer, calendar.get(1) % 100);
|
||||
}
|
||||
|
||||
public final void appendTo(StringBuffer buffer, int value) {
|
||||
buffer.append((char)(value / 10 + 48));
|
||||
buffer.append((char)(value % 10 + 48));
|
||||
}
|
||||
}
|
||||
|
||||
private static class TwoDigitMonthField implements NumberRule {
|
||||
static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField();
|
||||
|
||||
public int estimateLength() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
appendTo(buffer, calendar.get(2) + 1);
|
||||
}
|
||||
|
||||
public final void appendTo(StringBuffer buffer, int value) {
|
||||
buffer.append((char)(value / 10 + 48));
|
||||
buffer.append((char)(value % 10 + 48));
|
||||
}
|
||||
}
|
||||
|
||||
private static class TwelveHourField implements NumberRule {
|
||||
private final FastDateFormat.NumberRule mRule;
|
||||
|
||||
TwelveHourField(FastDateFormat.NumberRule rule) {
|
||||
this.mRule = rule;
|
||||
}
|
||||
|
||||
public int estimateLength() {
|
||||
return this.mRule.estimateLength();
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
int value = calendar.get(10);
|
||||
if (value == 0)
|
||||
value = calendar.getLeastMaximum(10) + 1;
|
||||
this.mRule.appendTo(buffer, value);
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, int value) {
|
||||
this.mRule.appendTo(buffer, value);
|
||||
}
|
||||
}
|
||||
|
||||
private static class TwentyFourHourField implements NumberRule {
|
||||
private final FastDateFormat.NumberRule mRule;
|
||||
|
||||
TwentyFourHourField(FastDateFormat.NumberRule rule) {
|
||||
this.mRule = rule;
|
||||
}
|
||||
|
||||
public int estimateLength() {
|
||||
return this.mRule.estimateLength();
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
int value = calendar.get(11);
|
||||
if (value == 0)
|
||||
value = calendar.getMaximum(11) + 1;
|
||||
this.mRule.appendTo(buffer, value);
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, int value) {
|
||||
this.mRule.appendTo(buffer, value);
|
||||
}
|
||||
}
|
||||
|
||||
private static class TimeZoneNameRule implements Rule {
|
||||
private final TimeZone mTimeZone;
|
||||
|
||||
private final boolean mTimeZoneForced;
|
||||
|
||||
private final Locale mLocale;
|
||||
|
||||
private final int mStyle;
|
||||
|
||||
private final String mStandard;
|
||||
|
||||
private final String mDaylight;
|
||||
|
||||
TimeZoneNameRule(TimeZone timeZone, boolean timeZoneForced, Locale locale, int style) {
|
||||
this.mTimeZone = timeZone;
|
||||
this.mTimeZoneForced = timeZoneForced;
|
||||
this.mLocale = locale;
|
||||
this.mStyle = style;
|
||||
if (timeZoneForced) {
|
||||
this.mStandard = FastDateFormat.getTimeZoneDisplay(timeZone, false, style, locale);
|
||||
this.mDaylight = FastDateFormat.getTimeZoneDisplay(timeZone, true, style, locale);
|
||||
} else {
|
||||
this.mStandard = null;
|
||||
this.mDaylight = null;
|
||||
}
|
||||
}
|
||||
|
||||
public int estimateLength() {
|
||||
if (this.mTimeZoneForced)
|
||||
return Math.max(this.mStandard.length(), this.mDaylight.length());
|
||||
if (this.mStyle == 0)
|
||||
return 4;
|
||||
return 40;
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
if (this.mTimeZoneForced) {
|
||||
if (this.mTimeZone.useDaylightTime() && calendar.get(16) != 0) {
|
||||
buffer.append(this.mDaylight);
|
||||
} else {
|
||||
buffer.append(this.mStandard);
|
||||
}
|
||||
} else {
|
||||
TimeZone timeZone = calendar.getTimeZone();
|
||||
if (timeZone.useDaylightTime() && calendar.get(16) != 0) {
|
||||
buffer.append(FastDateFormat.getTimeZoneDisplay(timeZone, true, this.mStyle, this.mLocale));
|
||||
} else {
|
||||
buffer.append(FastDateFormat.getTimeZoneDisplay(timeZone, false, this.mStyle, this.mLocale));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class TimeZoneNumberRule implements Rule {
|
||||
static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true);
|
||||
|
||||
static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false);
|
||||
|
||||
final boolean mColon;
|
||||
|
||||
TimeZoneNumberRule(boolean colon) {
|
||||
this.mColon = colon;
|
||||
}
|
||||
|
||||
public int estimateLength() {
|
||||
return 5;
|
||||
}
|
||||
|
||||
public void appendTo(StringBuffer buffer, Calendar calendar) {
|
||||
int offset = calendar.get(15) + calendar.get(16);
|
||||
if (offset < 0) {
|
||||
buffer.append('-');
|
||||
offset = -offset;
|
||||
} else {
|
||||
buffer.append('+');
|
||||
}
|
||||
int hours = offset / 3600000;
|
||||
buffer.append((char)(hours / 10 + 48));
|
||||
buffer.append((char)(hours % 10 + 48));
|
||||
if (this.mColon)
|
||||
buffer.append(':');
|
||||
int minutes = offset / 60000 - 60 * hours;
|
||||
buffer.append((char)(minutes / 10 + 48));
|
||||
buffer.append((char)(minutes % 10 + 48));
|
||||
}
|
||||
}
|
||||
|
||||
private static class TimeZoneDisplayKey {
|
||||
private final TimeZone mTimeZone;
|
||||
|
||||
private final int mStyle;
|
||||
|
||||
private final Locale mLocale;
|
||||
|
||||
TimeZoneDisplayKey(TimeZone timeZone, boolean daylight, int style, Locale locale) {
|
||||
this.mTimeZone = timeZone;
|
||||
if (daylight)
|
||||
style |= Integer.MIN_VALUE;
|
||||
this.mStyle = style;
|
||||
this.mLocale = locale;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.mStyle * 31 + this.mLocale.hashCode();
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj instanceof TimeZoneDisplayKey) {
|
||||
TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj;
|
||||
return (this.mTimeZone.equals(other.mTimeZone) && this.mStyle == other.mStyle && this.mLocale.equals(other.mLocale));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static class Pair {
|
||||
private final Object mObj1;
|
||||
|
||||
private final Object mObj2;
|
||||
|
||||
public Pair(Object obj1, Object obj2) {
|
||||
this.mObj1 = obj1;
|
||||
this.mObj2 = obj2;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (!(obj instanceof Pair))
|
||||
return false;
|
||||
Pair key = (Pair)obj;
|
||||
if ((this.mObj1 == null) ? (key.mObj1 == null) : this.mObj1.equals(key.mObj1))
|
||||
if ((this.mObj2 == null) ? (key.mObj2 == null) : this.mObj2.equals(key.mObj2))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return ((this.mObj1 == null) ? 0 : this.mObj1.hashCode()) + ((this.mObj2 == null) ? 0 : this.mObj2.hashCode());
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "[" + this.mObj1 + ':' + this.mObj2 + ']';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
package org.apache.commons.lang.time;
|
||||
|
||||
public class StopWatch {
|
||||
private static final int STATE_UNSTARTED = 0;
|
||||
|
||||
private static final int STATE_RUNNING = 1;
|
||||
|
||||
private static final int STATE_STOPPED = 2;
|
||||
|
||||
private static final int STATE_SUSPENDED = 3;
|
||||
|
||||
private static final int STATE_UNSPLIT = 10;
|
||||
|
||||
private static final int STATE_SPLIT = 11;
|
||||
|
||||
private int runningState = 0;
|
||||
|
||||
private int splitState = 10;
|
||||
|
||||
private long startTime = -1L;
|
||||
|
||||
private long stopTime = -1L;
|
||||
|
||||
public void start() {
|
||||
if (this.runningState == 2)
|
||||
throw new IllegalStateException("Stopwatch must be reset before being restarted. ");
|
||||
if (this.runningState != 0)
|
||||
throw new IllegalStateException("Stopwatch already started. ");
|
||||
this.stopTime = -1L;
|
||||
this.startTime = System.currentTimeMillis();
|
||||
this.runningState = 1;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (this.runningState != 1 && this.runningState != 3)
|
||||
throw new IllegalStateException("Stopwatch is not running. ");
|
||||
if (this.runningState == 1)
|
||||
this.stopTime = System.currentTimeMillis();
|
||||
this.runningState = 2;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
this.runningState = 0;
|
||||
this.splitState = 10;
|
||||
this.startTime = -1L;
|
||||
this.stopTime = -1L;
|
||||
}
|
||||
|
||||
public void split() {
|
||||
if (this.runningState != 1)
|
||||
throw new IllegalStateException("Stopwatch is not running. ");
|
||||
this.stopTime = System.currentTimeMillis();
|
||||
this.splitState = 11;
|
||||
}
|
||||
|
||||
public void unsplit() {
|
||||
if (this.splitState != 11)
|
||||
throw new IllegalStateException("Stopwatch has not been split. ");
|
||||
this.stopTime = -1L;
|
||||
this.splitState = 10;
|
||||
}
|
||||
|
||||
public void suspend() {
|
||||
if (this.runningState != 1)
|
||||
throw new IllegalStateException("Stopwatch must be running to suspend. ");
|
||||
this.stopTime = System.currentTimeMillis();
|
||||
this.runningState = 3;
|
||||
}
|
||||
|
||||
public void resume() {
|
||||
if (this.runningState != 3)
|
||||
throw new IllegalStateException("Stopwatch must be suspended to resume. ");
|
||||
this.startTime += System.currentTimeMillis() - this.stopTime;
|
||||
this.stopTime = -1L;
|
||||
this.runningState = 1;
|
||||
}
|
||||
|
||||
public long getTime() {
|
||||
if (this.runningState == 2 || this.runningState == 3)
|
||||
return this.stopTime - this.startTime;
|
||||
if (this.runningState == 0)
|
||||
return 0L;
|
||||
if (this.runningState == 1)
|
||||
return System.currentTimeMillis() - this.startTime;
|
||||
throw new RuntimeException("Illegal running state has occured. ");
|
||||
}
|
||||
|
||||
public long getSplitTime() {
|
||||
if (this.splitState != 11)
|
||||
throw new IllegalStateException("Stopwatch must be split to get the split time. ");
|
||||
return this.stopTime - this.startTime;
|
||||
}
|
||||
|
||||
public long getStartTime() {
|
||||
if (this.runningState == 0)
|
||||
throw new IllegalStateException("Stopwatch has not been started");
|
||||
return this.startTime;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return DurationFormatUtils.formatDurationHMS(getTime());
|
||||
}
|
||||
|
||||
public String toSplitString() {
|
||||
return DurationFormatUtils.formatDurationHMS(getSplitTime());
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue