pax_global_header00006660000000000000000000000064116705133000014506gustar00rootroot0000000000000052 comment=893f7b3ed0e4582f156b395445e8c01d7768712e sisu-ioc-2.3.0/000077500000000000000000000000001167051330000132435ustar00rootroot00000000000000sisu-ioc-2.3.0/.gitignore000066400000000000000000000000451167051330000152320ustar00rootroot00000000000000target .project .classpath .settings sisu-ioc-2.3.0/LICENSE-ASL.txt000066400000000000000000000261351167051330000155120ustar00rootroot00000000000000 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. sisu-ioc-2.3.0/LICENSE-EPL.txt000066400000000000000000000257401167051330000155140ustar00rootroot00000000000000Eclipse Public License - v 1.0 THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 1. DEFINITIONS "Contribution" means: a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and b) in the case of each subsequent Contributor: i) changes to the Program, and ii) additions to the Program; where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. "Contributor" means any person or entity that distributes the Program. "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. "Program" means the Contributions distributed in accordance with this Agreement. "Recipient" means anyone who receives the Program under this Agreement, including all Contributors. 2. GRANT OF RIGHTS a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 3. REQUIREMENTS A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: a) it complies with the terms and conditions of this Agreement; and b) its license agreement: i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. When the Program is made available in source code form: a) it must be made available under this Agreement; and b) a copy of this Agreement must be included with each copy of the Program. Contributors may not remove or alter any copyright notices contained within the Program. Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. 4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED 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. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. sisu-ioc-2.3.0/README.md000066400000000000000000000013531167051330000145240ustar00rootroot00000000000000Homepage ======== Wiki ==== Issue Tracker ============= Mailing Lists ============= - Development of sisu: to post mails to subscribe to the list - Usage of sisu: to post mails to subscribe to the list Development =========== Source code uses the Maven code style: License ======= [Apache License, v2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) [Eclipse Public License, v1.0](http://www.eclipse.org/legal/epl-v10.html) sisu-ioc-2.3.0/pom.xml000066400000000000000000000245611167051330000145700ustar00rootroot00000000000000 4.0.0 org.sonatype.forge forge-parent 10 pom org.sonatype.sisu sisu-parent 2.3.0 Sisu http://sisu.sonatype.org/ 2010 Sonatype, Inc. http://www.sonatype.com/ Sisu Developers List sisu-dev-subscribe@sonatype.org sisu-dev-unsubscribe@sonatype.org sisu-dev@sonatype.org Sisu Users List sisu-user-subscribe@sonatype.org sisu-user-unsubscribe@sonatype.org sisu-user@sonatype.org Sisu Commits List sisu-scm-subscribe@sonatype.org sisu-scm-unsubscribe@sonatype.org scm:git:git@github.com:sonatype/sisu.git scm:git:git@github.com:sonatype/sisu.git git@github.com:sonatype/sisu.git jira https://issues.sonatype.org/browse/SISU Hudson https://builds.sonatype.org/job/sisu/ The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo Eclipse Public License, Version 1.0 http://www.eclipse.org/legal/epl-v10.html repo sisu-inject UTF-8 https://repository.sonatype.org/service/local/staging/deploy/maven2 ch.qos.logback logback-classic test junit junit test javax.inject javax.inject 1 aopalliance aopalliance 1.0 javax.annotation jsr250-api 1.0 javax.enterprise cdi-api 1.0 javax.el el-api org.jboss.ejb3 jboss-ejb3-api org.jboss.interceptor jboss-interceptor-api org.slf4j slf4j-api 1.6.2 ch.qos.logback logback-classic 0.9.29 org.osgi org.osgi.core 4.2.0 org.osgi org.osgi.compendium 4.2.0 org.apache.felix org.apache.felix.framework 3.2.2 junit junit 4.9 org.testng testng 6.2 maven-compiler-plugin 2.3.2 1.5 1.5 maven-jar-plugin 2.3.2 org.apache.felix maven-bundle-plugin 2.3.5 ${project.artifactId} Copyright (C) 2010 Sonatype Inc. https://github.com/sonatype/sisu/ Sonatype, Inc. J2SE-1.5,JavaSE-1.6 <_nouses>true <_removeheaders> Embed-Dependency,Embed-Transitive, Built-By,Tool,Created-By,Build-Jdk, Originally-Created-By,Archiver-Version, Include-Resource,Private-Package, Bnd-LastModified maven-dependency-plugin 2.3 maven-javadoc-plugin 2.8 maven-source-plugin 2.1.2 maven-surefire-plugin 2.9 true maven-site-plugin 3.0 maven-gpg-plugin 1.3 maven-release-plugin 2.2.1 true maven-enforcer-plugin 1.0.1 enforce-java enforce 3.0 1.6.0 org.codehaus.mojo animal-sniffer-maven-plugin 1.7 org.codehaus.mojo.signature java15 1.0 javax.annotation.processing.* javax.lang.model.* javax.tools.* check-java-1.5-compat process-classes check maven-project-info-reports-plugin 2.4 maven-javadoc-plugin 2.8 org.codehaus.mojo cobertura-maven-plugin 2.5.1 org.codehaus.mojo findbugs-maven-plugin 2.3.2 sisu-ioc-2.3.0/sisu-examples/000077500000000000000000000000001167051330000160425ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/000077500000000000000000000000001167051330000202635ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/000077500000000000000000000000001167051330000245615ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/pom.xml000066400000000000000000000021201167051330000260710ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.examples guice-swing 2.3.0-SNAPSHOT bundle guice-swing-button-tab Guice - Swing example | button tab sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/src/000077500000000000000000000000001167051330000253505ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/src/main/000077500000000000000000000000001167051330000262745ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/src/main/java/000077500000000000000000000000001167051330000272155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/src/main/java/org/000077500000000000000000000000001167051330000300045ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/src/main/java/org/sonatype/000077500000000000000000000000001167051330000316465ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/src/main/java/org/sonatype/examples/000077500000000000000000000000001167051330000334645ustar00rootroot00000000000000000077500000000000000000000000001167051330000345015ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/src/main/java/org/sonatype/examples/guice000077500000000000000000000000001167051330000356305ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/src/main/java/org/sonatype/examples/guice/swing000077500000000000000000000000001167051330000365715ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/src/main/java/org/sonatype/examples/guice/swing/implButtonTab.java000066400000000000000000000017351167051330000413440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-button-tab/src/main/java/org/sonatype/examples/guice/swing/impl/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.examples.guice.swing.impl; import javax.inject.Named; import javax.swing.JButton; import javax.swing.JPanel; @Named( "Button" ) final class ButtonTab extends JPanel { static int instanceCount; ButtonTab() { add( new JButton( "Button #" + ++instanceCount ) ); } } sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/000077500000000000000000000000001167051330000250345ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/pom.xml000066400000000000000000000021241167051330000263500ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.examples guice-swing 2.3.0-SNAPSHOT bundle guice-swing-checkbox-tab Guice - Swing example | checkbox tab sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/src/000077500000000000000000000000001167051330000256235ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/src/main/000077500000000000000000000000001167051330000265475ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/src/main/java/000077500000000000000000000000001167051330000274705ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/src/main/java/org/000077500000000000000000000000001167051330000302575ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/src/main/java/org/sonatype/000077500000000000000000000000001167051330000321215ustar00rootroot00000000000000000077500000000000000000000000001167051330000336605ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/src/main/java/org/sonatype/examples000077500000000000000000000000001167051330000347545ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/src/main/java/org/sonatype/examples/guice000077500000000000000000000000001167051330000361035ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/src/main/java/org/sonatype/examples/guice/swing000077500000000000000000000000001167051330000370445ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/src/main/java/org/sonatype/examples/guice/swing/implCheckboxTab.java000066400000000000000000000017511167051330000420700ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-checkbox-tab/src/main/java/org/sonatype/examples/guice/swing/impl/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.examples.guice.swing.impl; import javax.inject.Named; import javax.swing.JCheckBox; import javax.swing.JPanel; @Named( "Checkbox" ) final class CheckboxTab extends JPanel { static int instanceCount; CheckboxTab() { add( new JCheckBox( "Checkbox #" + ++instanceCount ) ); } } sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/000077500000000000000000000000001167051330000234265ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/pom.xml000066400000000000000000000076271167051330000247570ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.examples guice-swing 2.3.0-SNAPSHOT guice-swing-main Guice - Swing example | main launcher org.osgi org.osgi.core true org.sonatype.sisu.examples guice-swing-button-tab ${project.version} runtime org.sonatype.sisu.examples guice-swing-checkbox-tab ${project.version} runtime org.sonatype.sisu.examples guice-swing-nested-tab ${project.version} runtime org.sonatype.sisu.examples guice-swing-window ${project.version} runtime org.sonatype.sisu sisu-inject-bean runtime org.apache.felix org.apache.felix.framework runtime org.apache.felix org.apache.felix.shell 1.4.2 runtime org.apache.felix org.apache.felix.shell.tui 1.4.1 runtime main maven-dependency-plugin copy-dependencies package copy-dependencies ${project.build.directory}/lib org.osgi.core,org.osgi.compendium,org.osgi.foundation,aopalliance,javax.inject,javax.servlet runtime maven-jar-plugin org.sonatype.examples.guice.swing.Main lib true sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/src/000077500000000000000000000000001167051330000242155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/src/main/000077500000000000000000000000001167051330000251415ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/src/main/java/000077500000000000000000000000001167051330000260625ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/src/main/java/org/000077500000000000000000000000001167051330000266515ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/src/main/java/org/sonatype/000077500000000000000000000000001167051330000305135ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/src/main/java/org/sonatype/examples/000077500000000000000000000000001167051330000323315ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/src/main/java/org/sonatype/examples/guice/000077500000000000000000000000001167051330000334255ustar00rootroot00000000000000000077500000000000000000000000001167051330000344755ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/src/main/java/org/sonatype/examples/guice/swingMain.java000066400000000000000000000065521167051330000362340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-main/src/main/java/org/sonatype/examples/guice/swing/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.examples.guice.swing; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.imageio.spi.ServiceRegistry; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.launch.Framework; import org.osgi.framework.launch.FrameworkFactory; public final class Main { public static void main( final String[] args ) throws Exception { if ( args.length > 0 && "osgi".equalsIgnoreCase( args[0] ) ) { OSGiLauncher.launch(); } else { ClassicLauncher.launch(); } } static class ClassicLauncher { static void launch() throws Exception { final Class mainClazz = Class.forName( "org.sonatype.guice.bean.containers.Main" ); mainClazz.getMethod( "main", String[].class ).invoke( null, (Object) new String[0] ); } } static class OSGiLauncher { static void launch() throws BundleException { final Map configuration = new HashMap(); configuration.put( Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT ); configuration.put( Constants.FRAMEWORK_STORAGE, "target/bundlecache" ); configuration.putAll( (Map)System.getProperties() ); final FrameworkFactory frameworkFactory = ServiceRegistry.lookupProviders( FrameworkFactory.class ).next(); final Framework framework = frameworkFactory.newFramework( configuration ); framework.start(); final BundleContext ctx = framework.getBundleContext(); final List bundles = new ArrayList(); for ( final File f : new File( getTargetDir(), "lib" ).listFiles() ) { if ( !f.getName().contains( "framework" ) ) { bundles.add( ctx.installBundle( "reference:" + f.toURI() ) ); } } for ( final Bundle bundle : bundles ) { if ( bundle.getHeaders().get( Constants.FRAGMENT_HOST ) == null ) { bundle.start(); } } } } static File getTargetDir() { final String clazz = Main.class.getName().replace( '.', '/' ) + ".class"; final String base = Main.class.getClassLoader().getResource( clazz ).getPath(); return new File( base.substring( 5, base.lastIndexOf( "/main.jar" ) ) ); } } sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/000077500000000000000000000000001167051330000245305ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/pom.xml000066400000000000000000000021201167051330000260400ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.examples guice-swing 2.3.0-SNAPSHOT bundle guice-swing-nested-tab Guice - Swing example | nested tab sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/src/000077500000000000000000000000001167051330000253175ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/src/main/000077500000000000000000000000001167051330000262435ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/src/main/java/000077500000000000000000000000001167051330000271645ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/src/main/java/org/000077500000000000000000000000001167051330000277535ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/src/main/java/org/sonatype/000077500000000000000000000000001167051330000316155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/src/main/java/org/sonatype/examples/000077500000000000000000000000001167051330000334335ustar00rootroot00000000000000000077500000000000000000000000001167051330000344505ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/src/main/java/org/sonatype/examples/guice000077500000000000000000000000001167051330000355775ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/src/main/java/org/sonatype/examples/guice/swing000077500000000000000000000000001167051330000365405ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/src/main/java/org/sonatype/examples/guice/swing/implNestedTab.java000066400000000000000000000030371167051330000412570ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-nested-tab/src/main/java/org/sonatype/examples/guice/swing/impl/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.examples.guice.swing.impl; import java.awt.Graphics; import java.util.Map; import java.util.Map.Entry; import javax.inject.Inject; import javax.inject.Named; import javax.swing.JPanel; import javax.swing.JTabbedPane; @Named( "Nested" ) final class NestedTab extends JPanel { static int instanceCount; final JTabbedPane pane = new JTabbedPane(); @Inject Map tabs; NestedTab() { setName( "NestedTab instance #" + ++instanceCount ); add( pane ); } @Override public void paint( final Graphics g ) { if ( pane.getTabCount() == 0 ) { pane.setPreferredSize( getSize() ); for ( final Entry e : tabs.entrySet() ) { pane.addTab( e.getKey(), e.getValue() ); } } super.paint( g ); } } sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/000077500000000000000000000000001167051330000240115ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/pom.xml000066400000000000000000000021101167051330000253200ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.examples guice-swing 2.3.0-SNAPSHOT bundle guice-swing-window Guice - Swing example | window sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/000077500000000000000000000000001167051330000246005ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/main/000077500000000000000000000000001167051330000255245ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/main/java/000077500000000000000000000000001167051330000264455ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/main/java/org/000077500000000000000000000000001167051330000272345ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/main/java/org/sonatype/000077500000000000000000000000001167051330000310765ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/main/java/org/sonatype/examples/000077500000000000000000000000001167051330000327145ustar00rootroot00000000000000000077500000000000000000000000001167051330000337315ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/main/java/org/sonatype/examples/guice000077500000000000000000000000001167051330000350605ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/main/java/org/sonatype/examples/guice/swing000077500000000000000000000000001167051330000360215ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/main/java/org/sonatype/examples/guice/swing/implWindow.java000066400000000000000000000032731167051330000401400ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/main/java/org/sonatype/examples/guice/swing/impl/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.examples.guice.swing.impl; import java.awt.BorderLayout; import javax.inject.Named; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import org.sonatype.inject.EagerSingleton; @EagerSingleton @Named( "default" ) final class Window implements Runnable { final JTabbedPane pane = new JTabbedPane(); Window() { SwingUtilities.invokeLater( this ); } public void run() { final JFrame frame = new JFrame( "Guice Swing Example" ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.add( pane, BorderLayout.CENTER ); frame.setLocation( 100, 50 ); frame.setSize( 600, 400 ); frame.setName( "Window" ); frame.setVisible( true ); } public void add( final String name, final JPanel panel ) { pane.addTab( name, panel ); } public void remove( final String name ) { pane.removeTabAt( pane.indexOfTab( name ) ); } } WindowMediator.java000066400000000000000000000031541167051330000416230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-examples/guice-swing/guice-swing-window/src/main/java/org/sonatype/examples/guice/swing/impl/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.examples.guice.swing.impl; import javax.inject.Named; import javax.inject.Singleton; import javax.swing.JPanel; import javax.swing.SwingUtilities; import org.sonatype.inject.BeanEntry; import org.sonatype.inject.Mediator; @Named @Singleton final class WindowMediator implements Mediator { public void add( final BeanEntry bean, final Window window ) throws Exception { SwingUtilities.invokeLater( new Runnable() { public void run() { window.add( bean.getKey().value(), bean.getValue() ); } } ); } public void remove( final BeanEntry bean, final Window window ) throws Exception { SwingUtilities.invokeLater( new Runnable() { public void run() { window.remove( bean.getKey().value() ); } } ); } } sisu-ioc-2.3.0/sisu-examples/guice-swing/pom.xml000066400000000000000000000037731167051330000216120ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu sisu-examples 2.3.0-SNAPSHOT pom org.sonatype.sisu.examples guice-swing Guice - Swing example guice-swing-button-tab guice-swing-checkbox-tab guice-swing-nested-tab guice-swing-window guice-swing-main ${project.build.outputDirectory}/META-INF/sisu org.sonatype.sisu sisu-inject-bean org.apache.felix maven-bundle-plugin true $(if;$(dir;${sisu.meta});META-INF/sisu=${sisu.meta}) sisu-ioc-2.3.0/sisu-examples/pom.xml000066400000000000000000000031001167051330000173510ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu sisu-parent 2.3.0-SNAPSHOT pom sisu-examples Sisu - Examples guice-swing guice-rcp org.sonatype.sisu sisu-inject-bean 2.3.0-SNAPSHOT org.sonatype.sisu sisu-inject-eclipse 2.3.0-SNAPSHOT sisu-ioc-2.3.0/sisu-inject/000077500000000000000000000000001167051330000155005ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/000077500000000000000000000000001167051330000176455ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/000077500000000000000000000000001167051330000216445ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/000077500000000000000000000000001167051330000252675ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/pom.xml000066400000000000000000000040741167051330000266110ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-bean 2.3.0 guice-bean-binders Sisu-Inject-Bean : @Inject auto-wiring javax.inject javax.inject aopalliance aopalliance javax.enterprise cdi-api org.sonatype.sisu sisu-guice org.sonatype.sisu.inject guice-bean-reflect org.sonatype.sisu.inject guice-bean-scanners org.sonatype.sisu.inject guice-bean-converters org.sonatype.sisu.inject guice-bean-locators sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/000077500000000000000000000000001167051330000260565ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/000077500000000000000000000000001167051330000270025ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/000077500000000000000000000000001167051330000277235ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/000077500000000000000000000000001167051330000305125ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/000077500000000000000000000000001167051330000323545ustar00rootroot00000000000000000077500000000000000000000000001167051330000333715ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000342765ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000357245ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/bindersBeanListener.java000066400000000000000000000100161167051330000411400ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import org.sonatype.guice.bean.locators.BeanLocator; import org.sonatype.inject.Mediator; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; /** * {@link InjectionListener} that listens for mediated watchers and registers them with the {@link BeanLocator}. */ final class BeanListener implements TypeListener, InjectionListener { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final List> mediation = new ArrayList>(); @Inject private BeanLocator locator; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- /** * Adds a {@link Mediation} record containing the necessary details about a mediated watcher. * * @param key The watched key * @param mediator The bean mediator * @param watcherType The watcher type */ @SuppressWarnings( { "unchecked", "rawtypes" } ) public void mediate( final Key key, final Mediator mediator, final Class watcherType ) { mediation.add( new Mediation( key, mediator, watcherType ) ); } public void hear( final TypeLiteral type, final TypeEncounter encounter ) { for ( final Mediation m : mediation ) { if ( m.watcherType.isAssignableFrom( type.getRawType() ) ) { encounter.register( this ); // look out for watcher instances } } } @SuppressWarnings( { "unchecked", "rawtypes" } ) public void afterInjection( final Object watcher ) { for ( final Mediation m : mediation ) { if ( m.watcherType.isInstance( watcher ) ) { locator.watch( m.watchedKey, m.mediator, watcher ); } } } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Record containing all the necessary details about a mediated watcher. */ private static final class Mediation { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- final Key watchedKey; final Mediator mediator; final Class watcherType; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- Mediation( final Key watchedKey, final Mediator mediator, final Class watcherType ) { this.watchedKey = watchedKey; this.mediator = mediator; this.watcherType = watcherType; } } } BeanProviders.java000066400000000000000000000364621167051330000413450ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; import javax.inject.Singleton; import org.sonatype.guice.bean.locators.BeanLocator; import org.sonatype.guice.bean.locators.EntryListAdapter; import org.sonatype.guice.bean.locators.EntryMapAdapter; import org.sonatype.guice.bean.locators.EntrySetAdapter; import org.sonatype.guice.bean.locators.NamedIterableAdapter; import org.sonatype.guice.bean.locators.ProviderIterableAdapter; import org.sonatype.guice.bean.reflect.TypeParameters; import org.sonatype.inject.BeanEntry; import org.sonatype.inject.Parameters; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; import com.google.inject.name.Names; import com.google.inject.spi.TypeConverter; import com.google.inject.spi.TypeConverterBinding; // ---------------------------------------------------------------------- // BeanLocator-backed Providers that can provide dynamic bean lookups // ---------------------------------------------------------------------- /** * Provides an {@link Iterable} sequence of {@link BeanEntry}s. */ final class BeanEntryProvider implements Provider>> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- @Inject private BeanLocator locator; private final Key key; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BeanEntryProvider( final Key key ) { this.key = key; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterable> get() { return locator.locate( key ); } } // ---------------------------------------------------------------------- /** * Base class for {@link Collection}s of qualified beans. */ class AbstractBeans { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- @Inject private BeanLocator locator; private final Key key; private final boolean isProvider; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- AbstractBeans( final Key key ) { final TypeLiteral type = key.getTypeLiteral(); final Class clazz = type.getRawType(); isProvider = javax.inject.Provider.class == clazz || com.google.inject.Provider.class == clazz; if ( isProvider ) { this.key = key.ofType( TypeParameters.get( type, 0 ) ); } else { this.key = key; } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @SuppressWarnings( { "rawtypes", "unchecked" } ) protected final Iterable> beans() { final Iterable beans = locator.locate( key ); return isProvider ? new ProviderIterableAdapter( beans ) : beans; } } // ---------------------------------------------------------------------- /** * Provides a {@link List} of qualified beans. */ final class BeanListProvider extends AbstractBeans implements Provider> { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BeanListProvider( final Key key ) { super( key ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public List get() { return new EntryListAdapter( beans() ); } } // ---------------------------------------------------------------------- /** * Provides a {@link Set} of qualified beans. */ final class BeanSetProvider extends AbstractBeans implements Provider> { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BeanSetProvider( final Key key ) { super( key ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Set get() { return new EntrySetAdapter( beans() ); } } // ---------------------------------------------------------------------- /** * Provides a {@link Map} of qualified beans. */ final class BeanMapProvider extends AbstractBeans implements Provider> { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BeanMapProvider( final Key key ) { super( key ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Map get() { return new EntryMapAdapter( beans() ); } } // ---------------------------------------------------------------------- /** * Provides a {@link Map} of named beans. */ final class NamedBeanMapProvider extends AbstractBeans implements Provider> { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- NamedBeanMapProvider( final TypeLiteral type ) { super( Key.get( type, Named.class ) ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Map get() { return new EntryMapAdapter( new NamedIterableAdapter( beans() ) ); } } // ---------------------------------------------------------------------- /** * Provides a single qualified bean. */ final class BeanProvider implements Provider { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- @Inject private BeanLocator locator; private final Key key; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BeanProvider( final Key key ) { this.key = key; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public V get() { return get( locator, key ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- static T get( final BeanLocator locator, final Key key ) { final Iterator> i = locator.locate( key ).iterator(); return i.hasNext() ? i.next().getValue() : null; // TODO: dynamic proxy?? } } // ---------------------------------------------------------------------- /** * Lazy cache of known {@link TypeConverter}s. */ @Singleton final class TypeConverterMap { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- @Inject private Injector injector; private final Map, TypeConverter> converterMap = new ConcurrentHashMap, TypeConverter>( 16, 0.75f, 1 ); // ---------------------------------------------------------------------- // Shared methods // ---------------------------------------------------------------------- TypeConverter getTypeConverter( final TypeLiteral type ) { TypeConverter converter = converterMap.get( type ); if ( null == converter ) { for ( final TypeConverterBinding b : injector.getTypeConverterBindings() ) { if ( b.getTypeMatcher().matches( type ) ) { converter = b.getTypeConverter(); converterMap.put( type, converter ); break; } } } return converter; } } // ---------------------------------------------------------------------- /** * Provides a single bean; the name used to lookup/convert the bean is selected at runtime. */ final class PlaceholderBeanProvider implements Provider { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final int EXPRESSION_RECURSION_LIMIT = 8; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- @Inject @Parameters @SuppressWarnings( "rawtypes" ) private Map properties; @Inject private TypeConverterMap converterMap; @Inject private BeanLocator locator; private final Key placeholderKey; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- PlaceholderBeanProvider( final Key key ) { placeholderKey = key; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @SuppressWarnings( "unchecked" ) public V get() { final String template = ( (Named) placeholderKey.getAnnotation() ).value(); final TypeLiteral expectedType = placeholderKey.getTypeLiteral(); // ---------------- INTERPOLATION ---------------- final Class clazz = expectedType.getRawType(); Object value = interpolate( template, clazz ); if ( false == value instanceof String ) { return (V) value; // found non-String mapping } // ------------------- LOOKUP -------------------- final Key lookupKey = Key.get( expectedType, Names.named( (String) value ) ); if ( String.class != clazz ) { final V bean = BeanProvider.get( locator, lookupKey ); if ( null != bean ) { return bean; // found non-String binding } } // ----------------- CONVERSION ------------------ if ( template == value ) { // same reference, so no interpolation occurred; is this perhaps a Guice constant? value = normalize( BeanProvider.get( locator, lookupKey.ofType( String.class ) ) ); } if ( value instanceof String ) { if ( String.class == clazz ) { return (V) value; // no conversion required } final TypeConverter converter = converterMap.getTypeConverter( expectedType ); if ( null != converter ) { return (V) converter.convert( (String) value, expectedType ); } } return null; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static T normalize( final T value ) { return "null".equals( value ) ? null : value; } private Object interpolate( final String template, final Class clazz ) { final StringBuilder buf; if ( template.contains( "${" ) ) { buf = new StringBuilder( template ); } else if ( properties.containsKey( template ) ) { // handle situations where someone missed out the main brackets buf = new StringBuilder( "${" ).append( template ).append( '}' ); } else { return template; // nothing to interpolate, maintain reference } int x = 0, y, expressionEnd = 0, expressionNum = 0; while ( ( x = buf.indexOf( "${", x ) ) >= 0 && ( y = buf.indexOf( "}", x ) + 1 ) > 0 ) { if ( y > expressionEnd ) // making progress { expressionNum = 0; expressionEnd = y; } final String key = buf.substring( x + 2, y - 1 ); final int anchor = key.indexOf( ":-" ); Object value = properties.get( anchor < 0 ? key : key.substring( 0, anchor ) ); if ( value == null && anchor >= 0 ) { value = key.substring( anchor + 2 ); } if ( expressionNum++ >= EXPRESSION_RECURSION_LIMIT ) { throw new ProvisionException( "Recursive configuration: " + template + " stopped at: " + buf ); } final int len = buf.length(); if ( 0 == x && len == y && String.class != clazz && clazz.isInstance( value ) ) { return value; // found compatible (non-String) instance in the properties! } buf.replace( x, y, String.valueOf( value ) ); expressionEnd += buf.length() - len; } return normalize( buf.toString() ); } } // ---------------------------------------------------------------------- ChildWireModule.java000066400000000000000000000046611167051330000416160ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.Arrays; import java.util.List; import org.sonatype.guice.bean.locators.DefaultBeanLocator; import com.google.inject.Binder; import com.google.inject.Injector; import com.google.inject.Module; /** * Child {@link WireModule} that avoids wiring dependencies that already exist in a parent {@link Injector}. */ public class ChildWireModule extends WireModule { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- final Injector parent; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public ChildWireModule( final Injector parent, final Module... modules ) { this( parent, Arrays.asList( modules ) ); } public ChildWireModule( final Injector parent, final List modules ) { super( modules ); this.parent = parent; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- @Override ElementAnalyzer getAnalyzer( final Binder binder ) { // make sure we're added to locator as early as possible binder.requestStaticInjection( DefaultBeanLocator.class ); // ignore any inherited bindings/dependencies final ElementAnalyzer analyzer = super.getAnalyzer( binder ); for ( Injector i = parent; i != null; i = i.getParent() ) { analyzer.ignoreKeys( i.getAllBindings().keySet() ); } return analyzer; } } DependencyAnalyzer.java000066400000000000000000000261711167051330000423620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import org.sonatype.guice.bean.reflect.DeferredProvider; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.reflect.TypeParameters; import com.google.inject.AbstractModule; import com.google.inject.Binder; import com.google.inject.Binding; import com.google.inject.ImplementedBy; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.MembersInjector; import com.google.inject.Module; import com.google.inject.ProvidedBy; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.TypeLiteral; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.Dependency; import com.google.inject.spi.HasDependencies; import com.google.inject.spi.InjectionPoint; import com.google.inject.spi.InjectionRequest; import com.google.inject.spi.LinkedKeyBinding; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderKeyBinding; import com.google.inject.spi.ProviderLookup; import com.google.inject.spi.StaticInjectionRequest; import com.google.inject.spi.UntargettedBinding; /** * {@link BindingTargetVisitor} that collects the {@link Key}s of any injected dependencies. */ final class DependencyAnalyzer extends DefaultBindingTargetVisitor { // ---------------------------------------------------------------------- // Static initialization // ---------------------------------------------------------------------- static { RESTRICTED_CLASSES = new HashSet>( Arrays.> asList( AbstractModule.class, Binder.class, Binding.class, Injector.class, Key.class, Logger.class, MembersInjector.class, Module.class, Provider.class, Scope.class, TypeLiteral.class ) ); } // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final Set> RESTRICTED_CLASSES; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Map, Boolean> analyzedTypes = new HashMap, Boolean>(); private final Set> requiredKeys = new HashSet>(); // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- DependencyAnalyzer() { // properties parameter is implicitly required requiredKeys.add( ParameterKeys.PROPERTIES ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Set> findMissingKeys( final Set> localKeys ) { final Set> missingKeys = new HashSet>(); while ( requiredKeys.size() > 0 ) { final List> candidateKeys = new ArrayList>( requiredKeys ); requiredKeys.clear(); // reset so we can detect any implicit requirements for ( final Key key : candidateKeys ) { if ( !localKeys.contains( key ) && missingKeys.add( key ) ) { analyzeImplicitBindings( key.getTypeLiteral() ); } } } return missingKeys; } @Override public Boolean visit( final UntargettedBinding binding ) { return analyzeImplementation( binding.getKey().getTypeLiteral(), true ); } @Override public Boolean visit( final LinkedKeyBinding binding ) { final Key linkedKey = binding.getLinkedKey(); if ( linkedKey.getAnnotationType() == null ) { return analyzeImplementation( linkedKey.getTypeLiteral(), true ); } return Boolean.TRUE; // indirect binding, don't scan } @Override public Boolean visit( final ProviderKeyBinding binding ) { final Key providerKey = binding.getProviderKey(); if ( providerKey.getAnnotationType() == null ) { return analyzeImplementation( providerKey.getTypeLiteral(), true ); } return Boolean.TRUE; // indirect binding, don't scan } @Override public Boolean visit( final ProviderInstanceBinding binding ) { final javax.inject.Provider provider = binding.getProviderInstance(); if ( provider instanceof DeferredProvider ) { try { final Class clazz = ( (DeferredProvider) provider ).getImplementationClass().load(); analyzeImplementation( TypeLiteral.get( clazz ), false ); } catch ( final TypeNotPresentException e ) // NOPMD { // deferred provider, so we also defer any errors until someone actually tries to use it } return Boolean.TRUE; } return Boolean.valueOf( analyzeDependencies( binding.getDependencies() ) ); } @Override public Boolean visitOther( final Binding binding ) { if ( binding instanceof HasDependencies ) { return Boolean.valueOf( analyzeDependencies( ( (HasDependencies) binding ).getDependencies() ) ); } return Boolean.TRUE; } public Boolean visit( final ProviderLookup lookup ) { requireKey( lookup.getKey() ); return Boolean.TRUE; } public Boolean visit( final StaticInjectionRequest request ) { return Boolean.valueOf( analyzeInjectionPoints( request.getInjectionPoints() ) ); } public Boolean visit( final InjectionRequest request ) { return Boolean.valueOf( analyzeInjectionPoints( request.getInjectionPoints() ) ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private void requireKey( final Key key ) { if ( !requiredKeys.contains( key ) ) { final Class clazz = key.getTypeLiteral().getRawType(); if ( javax.inject.Provider.class == clazz || com.google.inject.Provider.class == clazz ) { requireKey( key.ofType( TypeParameters.get( key.getTypeLiteral(), 0 ) ) ); } else if ( !RESTRICTED_CLASSES.contains( clazz ) ) { requiredKeys.add( key ); } } } private Boolean analyzeImplementation( final TypeLiteral type, final boolean reportErrors ) { Boolean applyBinding = analyzedTypes.get( type ); if ( null == applyBinding ) { applyBinding = Boolean.TRUE; if ( TypeParameters.isConcrete( type ) && !type.toString().startsWith( "java" ) ) { try { // check methods+fields first and avoid short-circuiting to maximize dependency analysis results final boolean rhs = analyzeInjectionPoints( InjectionPoint.forInstanceMethodsAndFields( type ) ); if ( !analyzeDependencies( InjectionPoint.forConstructorOf( type ).getDependencies() ) || !rhs ) { applyBinding = Boolean.FALSE; } } catch ( final RuntimeException e ) { if ( reportErrors ) { Logs.debug( "Potential problem: {}", type, e ); } applyBinding = Boolean.FALSE; } catch ( final LinkageError e ) { if ( reportErrors ) { Logs.debug( "Potential problem: {}", type, e ); } applyBinding = Boolean.FALSE; } } analyzedTypes.put( type, applyBinding ); } return applyBinding; } private boolean analyzeInjectionPoints( final Set points ) { boolean applyBinding = true; for ( final InjectionPoint p : points ) { applyBinding &= analyzeDependencies( p.getDependencies() ); } return applyBinding; } private boolean analyzeDependencies( final Collection> dependencies ) { boolean applyBinding = true; for ( final Dependency d : dependencies ) { final Key key = d.getKey(); if ( key.hasAttributes() && "Assisted".equals( key.getAnnotationType().getSimpleName() ) ) { applyBinding = false; // avoid directly binding AssistedInject based components } else { requireKey( key ); } } return applyBinding; } private void analyzeImplicitBindings( final TypeLiteral type ) { if ( !analyzedTypes.containsKey( type ) ) { final Class clazz = type.getRawType(); if ( TypeParameters.isConcrete( clazz ) ) { analyzeImplementation( type, false ); } else { analyzedTypes.put( type, Boolean.TRUE ); final ImplementedBy implementedBy = clazz.getAnnotation( ImplementedBy.class ); if ( null != implementedBy ) { requireKey( Key.get( implementedBy.value() ) ); } else { final ProvidedBy providedBy = clazz.getAnnotation( ProvidedBy.class ); if ( null != providedBy ) { requireKey( Key.get( providedBy.value() ) ); } } } } } } DependencyVerifier.java000066400000000000000000000060161167051330000423440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.reflect.TypeParameters; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.InjectionPoint; import com.google.inject.spi.LinkedKeyBinding; import com.google.inject.spi.UntargettedBinding; /** * {@link BindingTargetVisitor} that verifies any injected dependencies. */ final class DependencyVerifier extends DefaultBindingTargetVisitor { // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public Boolean visit( final UntargettedBinding binding ) { return verifyImplementation( binding.getKey().getTypeLiteral() ); } @Override public Boolean visit( final LinkedKeyBinding binding ) { final Key linkedKey = binding.getLinkedKey(); if ( linkedKey.getAnnotationType() == null ) { return verifyImplementation( linkedKey.getTypeLiteral() ); } return Boolean.TRUE; // indirect binding, don't scan } @Override public Boolean visitOther( final Binding binding ) { return Boolean.TRUE; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static Boolean verifyImplementation( final TypeLiteral type ) { if ( TypeParameters.isConcrete( type ) && !type.toString().startsWith( "java" ) ) { try { InjectionPoint.forInstanceMethodsAndFields( type ); InjectionPoint.forConstructorOf( type ); } catch ( final RuntimeException e ) { Logs.debug( "Potential problem: {}", type, e ); return Boolean.FALSE; } catch ( final LinkageError e ) { Logs.debug( "Potential problem: {}", type, e ); return Boolean.FALSE; } } return Boolean.TRUE; } } ElementAnalyzer.java000066400000000000000000000174771167051330000417060ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.reflect.TypeParameters; import org.sonatype.inject.Parameters; import com.google.inject.Binder; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.PrivateBinder; import com.google.inject.TypeLiteral; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.Element; import com.google.inject.spi.ElementVisitor; import com.google.inject.spi.InjectionRequest; import com.google.inject.spi.InstanceBinding; import com.google.inject.spi.PrivateElements; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderLookup; import com.google.inject.spi.StaticInjectionRequest; /** * {@link ElementVisitor} that analyzes linked {@link Binding}s for non-local injection dependencies. */ final class ElementAnalyzer extends DefaultElementVisitor { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Set> localKeys = new HashSet>(); private final DependencyAnalyzer analyzer = new DependencyAnalyzer(); private final List privateAnalyzers = new ArrayList(); private final List> properties = new ArrayList>(); private final List arguments = new ArrayList(); private final Binder binder; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ElementAnalyzer( final Binder binder ) { this.binder = binder; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void ignoreKeys( final Set> keys ) { localKeys.addAll( keys ); } public void apply( final Wiring wiring ) { // calculate which dependencies are missing from the module elements final Set> missingKeys = analyzer.findMissingKeys( localKeys ); final Map mergedProperties = new MergedProperties( properties ); for ( final Key key : missingKeys ) { if ( Parameters.class == key.getAnnotationType() ) { wireParameters( key, mergedProperties ); } else { wiring.wire( key ); } } for ( final ElementAnalyzer privateAnalyzer : privateAnalyzers ) { // ignore parent local/wired dependencies privateAnalyzer.ignoreKeys( localKeys ); privateAnalyzer.ignoreKeys( missingKeys ); privateAnalyzer.apply( wiring ); } } @Override public Void visit( final Binding binding ) { final Key key = binding.getKey(); if ( !localKeys.contains( key ) ) { if ( Parameters.class == key.getAnnotationType() ) { mergeParameters( binding ); } else if ( binding.acceptTargetVisitor( analyzer ).booleanValue() ) { localKeys.add( key ); binding.applyTo( binder ); } else { Logs.debug( "Discard binding: {}", binding, null ); } } return null; } @Override public Void visit( final PrivateElements elements ) { // based on private module introspection code from the Guice SPI final PrivateBinder privateBinder = binder.withSource( elements.getSource() ).newPrivateBinder(); final ElementAnalyzer privateAnalyzer = new ElementAnalyzer( privateBinder ); privateAnalyzers.add( privateAnalyzer ); // ignore bindings already in the parent privateAnalyzer.ignoreKeys( localKeys ); for ( final Element e : elements.getElements() ) { e.acceptVisitor( privateAnalyzer ); } for ( final Key k : elements.getExposedKeys() ) { // only expose valid bindings that won't conflict with existing ones if ( privateAnalyzer.localKeys.contains( k ) && localKeys.add( k ) ) { privateBinder.withSource( elements.getExposedSource( k ) ).expose( k ); } } return null; } @Override public Void visit( final ProviderLookup lookup ) { analyzer.visit( lookup ); lookup.applyTo( binder ); return null; } @Override public Void visit( final StaticInjectionRequest request ) { analyzer.visit( request ); request.applyTo( binder ); return null; } @Override public Void visit( final InjectionRequest request ) { analyzer.visit( request ); request.applyTo( binder ); return null; } @Override public Void visitOther( final Element element ) { element.applyTo( binder ); return null; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private void mergeParameters( final Binding binding ) { Object parameters = null; if ( binding instanceof InstanceBinding ) { parameters = ( (InstanceBinding) binding ).getInstance(); } else if ( binding instanceof ProviderInstanceBinding ) { parameters = ( (ProviderInstanceBinding) binding ).getProviderInstance().get(); } if ( parameters instanceof Map ) { properties.add( (Map) parameters ); } else if ( parameters instanceof String[] ) { Collections.addAll( arguments, (String[]) parameters ); } else { Logs.warn( "Ignoring incompatible @Parameters binding: {}", binding, null ); } } @SuppressWarnings( { "rawtypes", "unchecked" } ) private void wireParameters( final Key key, final Map mergedProperties ) { final TypeLiteral type = key.getTypeLiteral(); final Class clazz = type.getRawType(); if ( Map.class == clazz ) { final TypeLiteral[] constraints = TypeParameters.get( type ); if ( constraints.length == 2 && String.class == constraints[1].getRawType() ) { binder.bind( key ).toInstance( new StringProperties( mergedProperties ) ); } else { binder.bind( key ).toInstance( mergedProperties ); } } else if ( String[].class == clazz ) { binder.bind( key ).toInstance( arguments.toArray( new String[arguments.size()] ) ); } } } ElementMerger.java000066400000000000000000000047151167051330000413310ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.HashSet; import java.util.Set; import org.sonatype.guice.bean.reflect.Logs; import com.google.inject.Binder; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.Element; final class ElementMerger extends DefaultElementVisitor { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final DependencyVerifier verifier = new DependencyVerifier(); private final Set> localKeys = new HashSet>(); private final Binder binder; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ElementMerger( final Binder binder ) { this.binder = binder; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public Void visit( final Binding binding ) { final Key key = binding.getKey(); if ( !localKeys.contains( key ) ) { if ( binding.acceptTargetVisitor( verifier ).booleanValue() ) { localKeys.add( key ); binding.applyTo( binder ); } else { Logs.debug( "Discard binding: {}", binding, null ); } } return null; } @Override public Void visitOther( final Element element ) { element.applyTo( binder ); return null; } } LocatorWiring.java000066400000000000000000000215121167051330000413530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Member; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Qualifier; import org.sonatype.guice.bean.locators.BeanLocator; import org.sonatype.guice.bean.locators.HiddenBinding; import org.sonatype.guice.bean.locators.Implicit; import org.sonatype.guice.bean.reflect.TypeParameters; import org.sonatype.inject.BeanEntry; import com.google.inject.Binder; import com.google.inject.ImplementedBy; import com.google.inject.Key; import com.google.inject.ProvidedBy; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; import com.google.inject.spi.InjectionPoint; /** * Adds {@link BeanLocator}-backed bindings for non-local bean dependencies. */ @SuppressWarnings( { "unchecked", "rawtypes" } ) final class LocatorWiring implements Wiring { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final HiddenBinding HIDDEN_SOURCE = new HiddenBinding() { @Override public String toString() { return LocatorWiring.class.getName(); } }; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Binder binder; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- LocatorWiring( final Binder binder ) { this.binder = binder.withSource( HIDDEN_SOURCE ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean wire( final Key key ) { final Class clazz = key.getTypeLiteral().getRawType(); if ( Map.class == clazz ) { bindMapImport( key ); } else if ( List.class == clazz || Iterable.class == clazz ) { bindListImport( key ); } else if ( Set.class == clazz ) { bindSetImport( key ); } else if ( !isRestricted( clazz ) ) { bindBeanImport( key ); } return true; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Adds an imported {@link Map} binding; uses the generic type parameters to determine the search details. * * @param key The dependency key */ private void bindMapImport( final Key key ) { final TypeLiteral[] parameters = TypeParameters.get( key.getTypeLiteral() ); if ( 2 == parameters.length && null == key.getAnnotation() ) { final Class qualifierType = parameters[0].getRawType(); if ( String.class == qualifierType ) { binder.bind( key ).toProvider( new NamedBeanMapProvider( parameters[1] ) ); } else if ( qualifierType.isAnnotationPresent( Qualifier.class ) ) { binder.bind( key ).toProvider( new BeanMapProvider( Key.get( parameters[1], qualifierType ) ) ); } } } /** * Adds an imported {@link List} binding; uses the generic type parameters to determine the search details. * * @param key The dependency key */ private void bindListImport( final Key key ) { TypeLiteral[] parameters = TypeParameters.get( key.getTypeLiteral() ); if ( 1 == parameters.length && null == key.getAnnotation() ) { final TypeLiteral elementType = parameters[0]; if ( BeanEntry.class == elementType.getRawType() ) { parameters = TypeParameters.get( elementType ); if ( 2 == parameters.length ) { final Class qualifierType = parameters[0].getRawType(); if ( qualifierType.isAnnotationPresent( Qualifier.class ) ) { binder.bind( key ).toProvider( new BeanEntryProvider( Key.get( parameters[1], qualifierType ) ) ); } } } else { binder.bind( key ).toProvider( new BeanListProvider( Key.get( elementType ) ) ); } } } /** * Adds an imported {@link Set} binding; uses the generic type parameters to determine the search details. * * @param key The dependency key */ private void bindSetImport( final Key key ) { final TypeLiteral[] parameters = TypeParameters.get( key.getTypeLiteral() ); if ( 1 == parameters.length && null == key.getAnnotation() ) { binder.bind( key ).toProvider( new BeanSetProvider( Key.get( parameters[0] ) ) ); } } /** * Adds an imported bean binding; uses the type and {@link Qualifier} annotation to determine the search details. * * @param key The dependency key */ private void bindBeanImport( final Key key ) { final Annotation qualifier = key.getAnnotation(); if ( qualifier instanceof Named ) { if ( ( (Named) qualifier ).value().length() == 0 ) { // special case for wildcard @Named dependencies: match any @Named bean regardless of actual name binder.bind( key ).toProvider( new BeanProvider( Key.get( key.getTypeLiteral(), Named.class ) ) ); } else { binder.bind( key ).toProvider( new PlaceholderBeanProvider( key ) ); } } else { binder.bind( key ).toProvider( new BeanProvider( key ) ); // capture original implicit binding? if ( null == key.getAnnotationType() ) { bindImplicitType( key.getTypeLiteral() ); } } } /** * Captures the original implicit binding that would have been used by Guice; see the {@link BeanLocator} code. * * @param type The implicit type */ private void bindImplicitType( final TypeLiteral type ) { try { final Class clazz = type.getRawType(); if ( TypeParameters.isConcrete( clazz ) ) { final Member ctor = InjectionPoint.forConstructorOf( type ).getMember(); binder.bind( Key.get( clazz, Implicit.class ) ).toConstructor( (Constructor) ctor ); } else { final ImplementedBy implementedBy = clazz.getAnnotation( ImplementedBy.class ); if ( null != implementedBy ) { binder.bind( Key.get( clazz, Implicit.class ) ).to( (Class) implementedBy.value() ); } else { final ProvidedBy providedBy = clazz.getAnnotation( ProvidedBy.class ); if ( null != providedBy ) { binder.bind( Key.get( clazz, Implicit.class ) ).toProvider( (Class) providedBy.value() ); } } } } catch ( final RuntimeException e ) // NOPMD { // can safely ignore } catch ( final LinkageError e ) // NOPMD { // can safely ignore } } /** * Determines whether the given type is restricted and therefore can never be overridden by the import binder. * * @param clazz The binding type * @return {@code true} if the given type is restricted; otherwise {@code false} */ private static boolean isRestricted( final Class clazz ) { return "org.slf4j.Logger".equals( clazz.getName() ) || BeanLocator.class.isAssignableFrom( clazz ); } } MergedModule.java000066400000000000000000000040451167051330000411430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.Arrays; import java.util.List; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.spi.Element; import com.google.inject.spi.Elements; public final class MergedModule implements Module { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final List modules; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public MergedModule( final Module... modules ) { this.modules = Arrays.asList( modules ); } public MergedModule( final List modules ) { this.modules = modules; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void configure( final Binder binder ) { final ElementMerger merger = new ElementMerger( binder ); for ( final Module m : modules ) { for ( final Element e : Elements.getElements( m ) ) { e.acceptVisitor( merger ); } } } } MergedProperties.java000066400000000000000000000047241167051330000420560ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.AbstractMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; final class MergedProperties extends AbstractMap { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Map[] properties; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- MergedProperties( final List> properties ) { this.properties = properties.toArray( new Map[properties.size()] ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public Object get( final Object key ) { for ( final Map p : properties ) { final Object value = p.get( key ); if ( null != value ) { return value; } } return null; } @Override public boolean containsKey( final Object key ) { for ( final Map p : properties ) { if ( p.containsKey( key ) ) { return true; } } return false; } @Override @SuppressWarnings( { "unchecked", "rawtypes" } ) public Set> entrySet() { final Set entries = new LinkedHashSet(); for ( final Map p : properties ) { entries.addAll( p.entrySet() ); } return entries; } } ParameterKeys.java000066400000000000000000000017731167051330000413530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.Map; import org.sonatype.inject.Parameters; import com.google.inject.Key; @SuppressWarnings( "rawtypes" ) public interface ParameterKeys { Key PROPERTIES = Key.get( Map.class, Parameters.class ); Key ARGUMENTS = Key.get( String[].class, Parameters.class ); } QualifiedTypeBinder.java000066400000000000000000000267361167051330000424760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.lang.annotation.Annotation; import java.lang.annotation.IncompleteAnnotationException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import javax.enterprise.inject.Typed; import javax.inject.Provider; import org.sonatype.guice.bean.locators.BeanLocator; import org.sonatype.guice.bean.locators.WildcardKey; import org.sonatype.guice.bean.reflect.TypeParameters; import org.sonatype.guice.bean.scanners.QualifiedTypeListener; import org.sonatype.inject.EagerSingleton; import org.sonatype.inject.Mediator; import com.google.inject.Binder; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.binder.ScopedBindingBuilder; import com.google.inject.matcher.Matchers; import com.google.inject.name.Named; import com.google.inject.name.Names; /** * {@link QualifiedTypeListener} that installs {@link Module}s, registers {@link Mediator}s, and binds types. */ public final class QualifiedTypeBinder implements QualifiedTypeListener { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final TypeLiteral OBJECT_TYPE_LITERAL = TypeLiteral.get( Object.class ); // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Binder rootBinder; private BeanListener beanListener; private Object currentSource; private Binder binder; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public QualifiedTypeBinder( final Binder binder ) { rootBinder = binder; this.binder = binder; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @SuppressWarnings( { "unchecked", "rawtypes" } ) public void hear( final Annotation qualifier, final Class qualifiedType, final Object source ) { if ( currentSource != source ) { if ( null != source ) { binder = rootBinder.withSource( source ); currentSource = source; } else { binder = rootBinder; currentSource = null; } } if ( !TypeParameters.isConcrete( qualifiedType ) ) { return; } else if ( Module.class.isAssignableFrom( qualifiedType ) ) { installModule( qualifiedType ); } else if ( Mediator.class.isAssignableFrom( qualifiedType ) ) { registerMediator( qualifiedType ); } else if ( Provider.class.isAssignableFrom( qualifiedType ) ) { bindProviderType( qualifiedType ); } else { bindQualifiedType( qualifiedType ); } } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Installs an instance of the given {@link Module}. * * @param moduleType The module type */ private void installModule( final Class moduleType ) { final Module module = newInstance( moduleType ); if ( null != module ) { binder.install( module ); } } /** * Registers an instance of the given {@link Mediator} using its generic type parameters as configuration. * * @param mediatorType The mediator type */ @SuppressWarnings( { "unchecked", "rawtypes" } ) private void registerMediator( final Class mediatorType ) { final TypeLiteral[] params = getSuperTypeParameters( mediatorType, Mediator.class ); if ( params.length != 3 ) { binder.addError( mediatorType + " has wrong number of type arguments" ); } else { final Mediator mediator = newInstance( mediatorType ); if ( null != mediator ) { mediate( Key.get( params[1], (Class) params[0].getRawType() ), mediator, params[2].getRawType() ); } } } /** * Uses the given mediator to mediate updates between the {@link BeanLocator} and associated watchers. * * @param key The watched key * @param mediator The bean mediator * @param watcherType The watcher type */ @SuppressWarnings( "rawtypes" ) private void mediate( final Key key, final Mediator mediator, final Class watcherType ) { if ( null == beanListener ) { beanListener = new BeanListener(); binder.bindListener( Matchers.any(), beanListener ); binder.requestInjection( beanListener ); } beanListener.mediate( key, mediator, watcherType ); } /** * Binds the given provider type using a binding key determined by common-use heuristics. * * @param providerType The provider type */ @SuppressWarnings( { "unchecked", "rawtypes" } ) private void bindProviderType( final Class providerType ) { final TypeLiteral[] params = getSuperTypeParameters( providerType, javax.inject.Provider.class ); if ( params.length != 1 ) { binder.addError( providerType + " has wrong number of type arguments" ); } else { final Key key = getBindingKey( params[0], getBindingName( providerType ) ); final ScopedBindingBuilder sbb = binder.bind( key ).toProvider( providerType ); if ( providerType.isAnnotationPresent( EagerSingleton.class ) ) { sbb.asEagerSingleton(); } else if ( providerType.isAnnotationPresent( javax.inject.Singleton.class ) || providerType.isAnnotationPresent( com.google.inject.Singleton.class ) ) { sbb.in( Scopes.SINGLETON ); } final Class[] types = getBindingTypes( providerType ); if ( null != types ) { for ( final Class bindingType : types ) { binder.bind( key.ofType( bindingType ) ).to( key ); } } } } /** * Binds the given qualified type using a binding key determined by common-use heuristics. * * @param qualifiedType The qualified type */ @SuppressWarnings( { "unchecked", "rawtypes" } ) private void bindQualifiedType( final Class qualifiedType ) { final ScopedBindingBuilder sbb = binder.bind( qualifiedType ); if ( qualifiedType.isAnnotationPresent( EagerSingleton.class ) ) { sbb.asEagerSingleton(); } final Named bindingName = getBindingName( qualifiedType ); final Class[] types = getBindingTypes( qualifiedType ); if ( null != types ) { final Key key = getBindingKey( OBJECT_TYPE_LITERAL, bindingName ); for ( final Class bindingType : types ) { binder.bind( key.ofType( bindingType ) ).to( qualifiedType ); } } else { binder.bind( new WildcardKey( qualifiedType, bindingName ) ).to( qualifiedType ); } } /** * Attempts to create a new instance of the given type. * * @param type The instance type * @return New instance; {@code null} if the instance couldn't be created */ private T newInstance( final Class type ) { try { // slightly roundabout approach, but it might be private final Constructor ctor = type.getDeclaredConstructor(); ctor.setAccessible( true ); return ctor.newInstance(); } catch ( final Exception e ) { final Throwable cause = e instanceof InvocationTargetException ? e.getCause() : e; binder.addError( "Error creating instance of: " + type + " reason: " + cause ); return null; } catch ( final LinkageError e ) { binder.addError( "Error creating instance of: " + type + " reason: " + e ); return null; } } /** * Resolves the type parameters of a super type based on the given concrete type. * * @param type The concrete type * @param superType The generic super type * @return Resolved super type parameters */ private static TypeLiteral[] getSuperTypeParameters( final Class type, final Class superType ) { return TypeParameters.get( TypeLiteral.get( type ).getSupertype( superType ) ); } private static Key getBindingKey( final TypeLiteral bindingType, final Annotation qualifier ) { return null != qualifier ? Key.get( bindingType, qualifier ) : Key.get( bindingType ); } private static Named getBindingName( final Class qualifiedType ) { final javax.inject.Named jsr330 = qualifiedType.getAnnotation( javax.inject.Named.class ); if ( null != jsr330 ) { try { final String name = jsr330.value(); if ( name.length() > 0 ) { return "default".equals( name ) ? null : Names.named( name ); } } catch ( final IncompleteAnnotationException e ) // NOPMD { // early prototypes of JSR330 @Named declared no default value } } else { final Named guice = qualifiedType.getAnnotation( Named.class ); if ( null != guice ) { final String name = guice.value(); if ( name.length() > 0 ) { return "default".equals( name ) ? null : guice; } } } if ( qualifiedType.getSimpleName().startsWith( "Default" ) ) { return null; } return Names.named( qualifiedType.getName() ); } private static Class[] getBindingTypes( final Class clazz ) { for ( Class c = clazz; c != Object.class; c = c.getSuperclass() ) { final Typed typed = c.getAnnotation( Typed.class ); if ( null != typed ) { return typed.value().length > 0 ? typed.value() : c.getInterfaces(); } } return null; } } SpaceModule.java000066400000000000000000000123721167051330000407750ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Qualifier; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.scanners.ClassSpaceScanner; import org.sonatype.guice.bean.scanners.ClassSpaceVisitor; import org.sonatype.guice.bean.scanners.QualifiedTypeVisitor; import org.sonatype.guice.bean.scanners.index.SisuIndexFinder; import org.sonatype.inject.BeanScanning; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.spi.Element; import com.google.inject.spi.Elements; import com.google.inject.spi.MembersInjectorLookup; import com.google.inject.spi.ProviderLookup; /** * Guice {@link Module} that automatically binds types annotated with {@link Qualifier} annotations. */ public class SpaceModule implements Module { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private static Map> cachedElementsMap; final ClassSpace space; private final BeanScanning scanning; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public SpaceModule( final ClassSpace space ) { this( space, BeanScanning.ON ); } public SpaceModule( final ClassSpace space, final BeanScanning scanning ) { this.space = space; this.scanning = scanning; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public final void configure( final Binder binder ) { binder.bind( ClassSpace.class ).toInstance( space ); final ClassSpaceScanner scanner; switch ( scanning ) { default: case ON: scanner = new ClassSpaceScanner( space ); break; case INDEX: scanner = new ClassSpaceScanner( new SisuIndexFinder( false ), space ); break; case GLOBAL_INDEX: scanner = new ClassSpaceScanner( new SisuIndexFinder( true ), space ); break; case CACHE: replayCachedElements( binder ); return; case OFF: return; } scanner.accept( visitor( binder ) ); } // ---------------------------------------------------------------------- // Customizable methods // ---------------------------------------------------------------------- protected ClassSpaceVisitor visitor( final Binder binder ) { return new QualifiedTypeVisitor( new QualifiedTypeBinder( binder ) ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private final synchronized void replayCachedElements( final Binder binder ) { if ( null == cachedElementsMap ) { cachedElementsMap = new HashMap>(); } /* * Scan and cache elements */ final String key = space.toString(); List elements = cachedElementsMap.get( key ); boolean replaying = true; if ( null == elements ) { replaying = false; elements = Elements.getElements( new Module() { public void configure( final Binder recorder ) { new ClassSpaceScanner( space ).accept( visitor( recorder ) ); } } ); cachedElementsMap.put( key, elements ); } /* * Replay cached elements */ for ( final Element e : elements ) { if ( replaying ) { // lookups have state so we replace them with duplicates when replaying... if ( e instanceof ProviderLookup ) { binder.getProvider( ( (ProviderLookup) e ).getKey() ); continue; } if ( e instanceof MembersInjectorLookup ) { binder.getMembersInjector( ( (MembersInjectorLookup) e ).getType() ); continue; } } e.applyTo( binder ); } } } StringProperties.java000066400000000000000000000050411167051330000421120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.AbstractMap; import java.util.HashSet; import java.util.Map; import java.util.Set; final class StringProperties extends AbstractMap { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Map delegate; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- StringProperties( final Map delegate ) { this.delegate = delegate; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public String get( final Object key ) { final Object value = delegate.get( key ); if ( value instanceof String ) { return (String) value; } return null; } @Override public boolean containsKey( final Object key ) { final Object value = delegate.get( key ); if ( null == value ) { return delegate.containsKey( key ); } return value instanceof String; } @Override @SuppressWarnings( { "unchecked", "rawtypes" } ) public Set> entrySet() { final Set entries = new HashSet(); for ( final Entry e : delegate.entrySet() ) { if ( e.getKey() instanceof String ) { final Object value = e.getValue(); if ( null == value || value instanceof String ) { entries.add( e ); } } } return entries; } } WireModule.java000066400000000000000000000060421167051330000406450ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.Arrays; import java.util.List; import org.sonatype.guice.bean.converters.FileTypeConverter; import org.sonatype.guice.bean.converters.URLTypeConverter; import org.sonatype.guice.bean.locators.BeanLocator; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.spi.Element; import com.google.inject.spi.Elements; /** * Guice {@link Module} that automatically adds {@link BeanLocator}-backed bindings for non-local bean dependencies. */ public class WireModule implements Module { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final List modules; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public WireModule( final Module... modules ) { this( Arrays.asList( modules ) ); } public WireModule( final List modules ) { this.modules = modules; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void configure( final Binder binder ) { final ElementAnalyzer analyzer = getAnalyzer( binder ); for ( final Module m : modules ) { for ( final Element e : Elements.getElements( m ) ) { e.acceptVisitor( analyzer ); } } analyzer.apply( wiring( binder ) ); } // ---------------------------------------------------------------------- // Customizable methods // ---------------------------------------------------------------------- protected Wiring wiring( final Binder binder ) { binder.install( new FileTypeConverter() ); binder.install( new URLTypeConverter() ); return new LocatorWiring( binder ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- ElementAnalyzer getAnalyzer( final Binder binder ) { return new ElementAnalyzer( binder ); } } Wiring.java000066400000000000000000000015471167051330000400350ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import com.google.inject.Key; /** * Supplies bindings for given dependency {@link Key}s. */ public interface Wiring { boolean wire( Key key ); } package-info.java000066400000000000000000000022051167051330000411120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * Automatic bean binding. * *

The principal members of this package are: *

*
{@link org.sonatype.guice.bean.binders.SpaceModule} *
Scans a {@link org.sonatype.guice.bean.reflect.ClassSpace} for beans and adds any qualified bindings. *
{@link org.sonatype.guice.bean.binders.WireModule} *
Adds {@link org.sonatype.guice.bean.locators.BeanLocator} bindings for any non-local bean dependencies. *
*/ package org.sonatype.guice.bean.binders; 000077500000000000000000000000001167051330000335515ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/injectBeanScanning.java000066400000000000000000000017641167051330000367520ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/inject/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.inject; public enum BeanScanning { /** * Always scan */ ON, /** * Never scan */ OFF, /** * Scan once and cache results */ CACHE, /** * Use local index (plug-ins) */ INDEX, /** * Use global index (application) */ GLOBAL_INDEX } EagerSingleton.java000066400000000000000000000021341167051330000373220ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/inject/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.inject; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Identifies beans that should be created as soon as the Injector starts. */ @Target( value = { ElementType.TYPE } ) @Retention( RetentionPolicy.RUNTIME ) @Documented public @interface EagerSingleton { } Nullable.java000066400000000000000000000021311167051330000361470ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/inject/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.inject; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks dependencies that allow {@code null} values. */ @Target( value = { ElementType.FIELD, ElementType.PARAMETER } ) @Retention( RetentionPolicy.RUNTIME ) @Documented public @interface Nullable { } Parameters.java000066400000000000000000000024211167051330000365160ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/inject/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.inject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier; /** * Marks dependencies to external runtime parameters, for example: * *
 * @Inject
 * @Parameters
 * String[] args;
 * 
 * @Inject
 * @Parameters
 * Map<String, String> properties;
 * 
*/ @Target( value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD } ) @Retention( RetentionPolicy.RUNTIME ) @Qualifier public @interface Parameters { } package-info.java000066400000000000000000000014451167051330000367440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/main/java/org/sonatype/inject/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * Optional Sonatype extensions to JSR330. */ package org.sonatype.inject; sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/000077500000000000000000000000001167051330000270355ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/000077500000000000000000000000001167051330000277565ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/000077500000000000000000000000001167051330000305455ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/000077500000000000000000000000001167051330000324075ustar00rootroot00000000000000000077500000000000000000000000001167051330000334245ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000343315ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000357575ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/guice/bean/bindersBeanImportTest.java000066400000000000000000000570041167051330000415300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import junit.framework.TestCase; import org.slf4j.Logger; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.TypeParameters; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.inject.BeanEntry; import org.sonatype.inject.Nullable; import com.google.inject.AbstractModule; import com.google.inject.BindingAnnotation; import com.google.inject.CreationException; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.ProvidedBy; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; import com.google.inject.matcher.Matchers; import com.google.inject.name.Names; public class BeanImportTest extends TestCase { @Target( FIELD ) @Retention( RUNTIME ) @BindingAnnotation public @interface Fuzzy { } static class FuzzyImpl implements Fuzzy { public Class annotationType() { return Fuzzy.class; } @Override public boolean equals( final Object rhs ) { return rhs instanceof Fuzzy; } @Override public int hashCode() { return 0; } } interface X { } interface Y { } interface Z { } @ProvidedBy( XProvider.class ) interface ImplicitX extends X { } @ImplementedBy( YImpl.class ) interface ImplicitY extends Y { } static class XProvider implements Provider { public ImplicitX get() { return new ImplicitX() { }; } } static abstract class AbstractY implements Y { } static class YImpl extends AbstractY implements ImplicitY { } static class ZImpl implements Z { T element; } static abstract class AbstractX implements X { @Inject Injector injector; @Inject Logger logger; @Inject ImplicitX implicitX; @Inject ImplicitY implicitY; @Inject YImpl concreteY; @Inject @Nullable AbstractY abstractY; @Inject @Fuzzy Y fuzzy; @Inject @Named( "fixed" ) Y fixed; @Inject Map namedMap; @Inject Map> namedProviderMap; } static class UnrestrictedInstance extends AbstractX { final Y single; @Inject UnrestrictedInstance( @Nullable final Y single, @Named( "fixed" ) final Y fixed ) { this.single = single; this.fixed = fixed; } } static class UnrestrictedList extends AbstractX { @Inject List list; @Inject Iterable iterable; @Inject List> providerList; } static class UnrestrictedSet extends AbstractX { @Inject Set set; @Inject Set> providerSet; } static class NamedType extends AbstractX { final Y single; @Inject NamedType( @Named( "fixed" ) final Y fixed, @Nullable @Named final Y single ) { this.single = single; this.fixed = fixed; } } static class NamedInstance extends AbstractX { final Y single; @Inject NamedInstance( @Nullable @Named( "TEST" ) final Y single ) { this.single = single; } @Inject void setFixed( final @Named( "fixed" ) Y fixed ) { this.fixed = fixed; } } static class HintMap extends AbstractX { @Inject Map map; @Inject Map> providerMap; } static class BeanEntries implements X { @Inject Iterable> entries; } static class PlaceholderInstance extends AbstractX { @Inject @Nullable @Named( "${name}" ) Y single; } static class PlaceholderString extends AbstractX { @Inject @Nullable @Named( "${text}" ) String config; @Inject @Nullable @Named( "text" ) String plain; } static class PlaceholderConfig extends AbstractX { @Inject @Nullable @Named( "4${value}2" ) int single; } static class BadMap implements X { @Inject Map map; } static class RawList implements X { @Inject @SuppressWarnings( "rawtypes" ) List list; } static class RawMap implements X { @Inject @SuppressWarnings( "rawtypes" ) Map map; } static class MissingList implements X { @Inject @Named( "missing" ) List list; } static class MissingSet implements X { @Inject @Named( "missing" ) Set set; } static class MissingMap implements X { @Inject @Named( "missing" ) Map map; } static class GenericInstance implements X { @Inject Z number; @Inject Z chars; @Inject Z random; } static Map PROPS = new HashMap(); class TestModule extends AbstractModule { @Override protected void configure() { bind( ClassSpace.class ).toInstance( new URLClassSpace( BeanImportTest.class.getClassLoader() ) ); bindInterceptor( Matchers.subclassesOf( X.class ), Matchers.any() ); requestInjection( BeanImportTest.this ); bind( X.class ).annotatedWith( Names.named( "UI" ) ).to( UnrestrictedInstance.class ); bind( X.class ).annotatedWith( Names.named( "UL" ) ).to( UnrestrictedList.class ); bind( X.class ).annotatedWith( Names.named( "US" ) ).to( UnrestrictedSet.class ); bind( X.class ).annotatedWith( Names.named( "NT" ) ).to( NamedType.class ); bind( X.class ).annotatedWith( Names.named( "NI" ) ).to( NamedInstance.class ); bind( X.class ).annotatedWith( Names.named( "HM" ) ).to( HintMap.class ); bind( X.class ).annotatedWith( Names.named( "BE" ) ).to( BeanEntries.class ); bind( X.class ).annotatedWith( Names.named( "PI" ) ).to( PlaceholderInstance.class ); bind( X.class ).annotatedWith( Names.named( "PS" ) ).to( PlaceholderString.class ); bind( X.class ).annotatedWith( Names.named( "PC" ) ).to( PlaceholderConfig.class ); bind( X.class ).annotatedWith( Names.named( "GI" ) ).to( GenericInstance.class ); bind( Y.class ).annotatedWith( Names.named( "fixed" ) ).toInstance( new YImpl() ); bind( Y.class ).annotatedWith( Names.named( "unscoped" ) ).to( YImpl.class ); bind( Y.class ).annotatedWith( new FuzzyImpl() ).toInstance( new YImpl() ); bind( Z.class ).annotatedWith( Names.named( "integer" ) ).toInstance( new ZImpl() { } ); bind( Z.class ).annotatedWith( Names.named( "string" ) ).toInstance( new ZImpl() { } ); bind( Z.class ).annotatedWith( Names.named( "raw" ) ).to( ZImpl.class ); bind( ParameterKeys.PROPERTIES ).toInstance( PROPS ); } } public void testUnrestrictedImport() { final Injector injector = Guice.createInjector( new WireModule( new TestModule() ) ); final UnrestrictedInstance unrestrictedInstance = (UnrestrictedInstance) injector.getInstance( Key.get( X.class, Names.named( "UI" ) ) ); assertSame( unrestrictedInstance.fixed, unrestrictedInstance.single ); final UnrestrictedList unrestrictedList = (UnrestrictedList) injector.getInstance( Key.get( X.class, Names.named( "UL" ) ) ); assertEquals( 3, unrestrictedList.list.size() ); assertSame( unrestrictedInstance.fixed, unrestrictedList.list.get( 0 ) ); assertSame( unrestrictedList.fixed, unrestrictedList.list.get( 0 ) ); assertSame( unrestrictedInstance.fuzzy, unrestrictedList.list.get( 2 ) ); assertSame( unrestrictedList.fuzzy, unrestrictedList.list.get( 2 ) ); assertNotSame( unrestrictedList.list.get( 0 ), unrestrictedList.list.get( 2 ) ); final Iterator iterator = unrestrictedList.iterable.iterator(); assertTrue( iterator.hasNext() ); assertSame( unrestrictedList.list.get( 0 ), iterator.next() ); iterator.next(); assertSame( unrestrictedList.list.get( 2 ), iterator.next() ); assertFalse( iterator.hasNext() ); final UnrestrictedSet unrestrictedSet = (UnrestrictedSet) injector.getInstance( Key.get( X.class, Names.named( "US" ) ) ); assertEquals( 3, unrestrictedSet.set.size() ); assertTrue( unrestrictedSet.set.contains( unrestrictedInstance.fixed ) ); assertTrue( unrestrictedSet.set.contains( unrestrictedList.fixed ) ); assertTrue( unrestrictedSet.set.contains( unrestrictedInstance.fuzzy ) ); assertTrue( unrestrictedSet.set.contains( unrestrictedList.fuzzy ) ); } public void testNamedImports() { final Injector injector = Guice.createInjector( new WireModule( new TestModule() ) ); final NamedType namedType = (NamedType) injector.getInstance( Key.get( X.class, Names.named( "NT" ) ) ); final NamedInstance namedInstance = (NamedInstance) injector.getInstance( Key.get( X.class, Names.named( "NI" ) ) ); assertNotNull( namedType.single ); assertSame( namedType.fixed, namedType.single ); assertNull( namedInstance.single ); final HintMap hintMap = (HintMap) injector.getInstance( Key.get( X.class, Names.named( "HM" ) ) ); assertSame( namedType.fixed, hintMap.map.get( "fixed" ) ); assertSame( hintMap.fixed, hintMap.map.get( "fixed" ) ); assertNotSame( namedType.fixed, hintMap.map.get( "unscoped" ) ); assertNotSame( hintMap.fixed, hintMap.map.get( "unscoped" ) ); assertEquals( 2, hintMap.map.size() ); } public void testProviderImports() { final Injector injector = Guice.createInjector( new WireModule( new TestModule() ) ); final UnrestrictedList unrestrictedList = (UnrestrictedList) injector.getInstance( Key.get( X.class, Names.named( "UL" ) ) ); final UnrestrictedSet unrestrictedSet = (UnrestrictedSet) injector.getInstance( Key.get( X.class, Names.named( "US" ) ) ); final HintMap hintMap = (HintMap) injector.getInstance( Key.get( X.class, Names.named( "HM" ) ) ); Provider provider; provider = unrestrictedList.providerList.get( 0 ); assertTrue( provider.get() instanceof YImpl ); assertSame( provider.get(), provider.get() ); provider = unrestrictedList.providerList.get( 1 ); assertTrue( provider.get() instanceof YImpl ); assertNotSame( provider.get(), provider.get() ); assertEquals( 3, unrestrictedList.providerList.size() ); final Iterator> itr = unrestrictedSet.providerSet.iterator(); provider = itr.next(); assertTrue( provider.get() instanceof YImpl ); assertSame( provider.get(), provider.get() ); provider = itr.next(); assertTrue( provider.get() instanceof YImpl ); assertNotSame( provider.get(), provider.get() ); assertEquals( 3, unrestrictedList.providerList.size() ); provider = hintMap.providerMap.get( "unscoped" ); assertTrue( provider.get() instanceof YImpl ); assertNotSame( provider.get(), provider.get() ); assertEquals( 2, hintMap.providerMap.size() ); provider = hintMap.namedProviderMap.get( Names.named( "unscoped" ) ); assertTrue( provider.get() instanceof YImpl ); assertNotSame( provider.get(), provider.get() ); assertEquals( 2, hintMap.namedProviderMap.size() ); provider = hintMap.providerMap.get( "fixed" ); assertTrue( provider.get() instanceof YImpl ); assertSame( provider.get(), provider.get() ); assertEquals( 2, hintMap.providerMap.size() ); provider = hintMap.namedProviderMap.get( Names.named( "fixed" ) ); assertTrue( provider.get() instanceof YImpl ); assertSame( provider.get(), provider.get() ); assertEquals( 2, hintMap.namedProviderMap.size() ); } public void testBeanEntries() { final Injector injector = Guice.createInjector( new WireModule( new TestModule() ) ); final BeanEntries beans = (BeanEntries) injector.getInstance( Key.get( X.class, Names.named( "BE" ) ) ); final HintMap hintMap = (HintMap) injector.getInstance( Key.get( X.class, Names.named( "HM" ) ) ); final Iterator> i = beans.entries.iterator(); assertTrue( i.hasNext() ); assertSame( hintMap.map.get( "fixed" ), i.next().getValue() ); assertNotSame( hintMap.map.get( "unscoped" ), i.next().getValue() ); assertFalse( i.hasNext() ); } public void testPlaceholderImports() { final Injector injector = Guice.createInjector( new WireModule( new TestModule() ) ); PlaceholderInstance placeholderInstance; placeholderInstance = (PlaceholderInstance) injector.getInstance( Key.get( X.class, Names.named( "PI" ) ) ); assertNull( placeholderInstance.single ); final Y why = new YImpl(); PROPS.put( "name", why ); placeholderInstance = (PlaceholderInstance) injector.getInstance( Key.get( X.class, Names.named( "PI" ) ) ); assertSame( why, placeholderInstance.single ); PROPS.put( "name", "fixed" ); placeholderInstance = (PlaceholderInstance) injector.getInstance( Key.get( X.class, Names.named( "PI" ) ) ); assertSame( placeholderInstance.fixed, placeholderInstance.single ); PlaceholderString placeholderString; placeholderString = (PlaceholderString) injector.getInstance( Key.get( X.class, Names.named( "PS" ) ) ); assertNull( placeholderString.config ); assertNull( placeholderString.plain ); PROPS.put( "text", "Hello, world!" ); placeholderString = (PlaceholderString) injector.getInstance( Key.get( X.class, Names.named( "PS" ) ) ); assertEquals( "Hello, world!", placeholderString.config ); assertEquals( "Hello, world!", placeholderString.plain ); PROPS.put( "text", "text" ); placeholderString = (PlaceholderString) injector.getInstance( Key.get( X.class, Names.named( "PS" ) ) ); assertEquals( "text", placeholderString.config ); assertEquals( "text", placeholderString.plain ); PROPS.put( "text", "${text}" ); try { placeholderString = (PlaceholderString) injector.getInstance( Key.get( X.class, Names.named( "PS" ) ) ); fail( "Expected ProvisionException" ); } catch ( final ProvisionException e ) { assertTrue( e.getMessage().contains( "${text}" ) ); } PROPS.put( "text", ">${one}{" ); PROPS.put( "one", "-${two}=" ); PROPS.put( "two", "<${three}}" ); PROPS.put( "three", "|${text}|" ); try { placeholderString = (PlaceholderString) injector.getInstance( Key.get( X.class, Names.named( "PS" ) ) ); fail( "Expected ProvisionException" ); } catch ( final ProvisionException e ) { assertTrue( e.getMessage().contains( ">-<|>-<|${text}|}={|}={" ) ); } PROPS.put( "text", ">${text" ); placeholderString = (PlaceholderString) injector.getInstance( Key.get( X.class, Names.named( "PS" ) ) ); assertEquals( ">${text", placeholderString.config ); assertEquals( ">${text", placeholderString.plain ); PROPS.put( "text", "${key:-default}" ); placeholderString = (PlaceholderString) injector.getInstance( Key.get( X.class, Names.named( "PS" ) ) ); assertEquals( "default", placeholderString.config ); assertEquals( "default", placeholderString.plain ); PROPS.put( "key", "configured" ); placeholderString = (PlaceholderString) injector.getInstance( Key.get( X.class, Names.named( "PS" ) ) ); assertEquals( "configured", placeholderString.config ); assertEquals( "configured", placeholderString.plain ); PROPS.put( "text", "${:-some:-default:-value:-}" ); placeholderString = (PlaceholderString) injector.getInstance( Key.get( X.class, Names.named( "PS" ) ) ); assertEquals( "some:-default:-value:-", placeholderString.config ); assertEquals( "some:-default:-value:-", placeholderString.plain ); try { injector.getInstance( Key.get( X.class, Names.named( "PC" ) ) ); fail( "Expected RuntimeException" ); } catch ( final RuntimeException e ) { System.out.println( e ); } PROPS.put( "value", "53" ); assertEquals( 4532, ( (PlaceholderConfig) injector.getInstance( Key.get( X.class, Names.named( "PC" ) ) ) ).single ); } public void testDuplicatesAreIgnored() { Guice.createInjector( new WireModule( new TestModule(), new TestModule(), new TestModule() ) ); } public void testImportSource() { final Injector injector = Guice.createInjector( new WireModule( new TestModule() ) ); assertEquals( LocatorWiring.class.getName(), injector.getBinding( Y.class ).getSource().toString() ); } public void testInvalidTypeParameters() { try { Guice.createInjector( new WireModule( new AbstractModule() { @Override protected void configure() { bind( X.class ).annotatedWith( Names.named( "BM" ) ).to( BadMap.class ); } } ) ); fail( "Expected CreationException" ); } catch ( final CreationException e ) { } try { Guice.createInjector( new WireModule( new AbstractModule() { @Override protected void configure() { bind( X.class ).annotatedWith( Names.named( "RL" ) ).to( RawList.class ); } } ) ); fail( "Expected CreationException" ); } catch ( final CreationException e ) { } try { Guice.createInjector( new WireModule( new AbstractModule() { @Override protected void configure() { bind( X.class ).annotatedWith( Names.named( "RM" ) ).to( RawMap.class ); } } ) ); fail( "Expected CreationException" ); } catch ( final CreationException e ) { } try { Guice.createInjector( new WireModule( new AbstractModule() { @Override protected void configure() { bind( X.class ).annotatedWith( Names.named( "ML" ) ).to( MissingList.class ); } } ) ); fail( "Expected CreationException" ); } catch ( final CreationException e ) { } try { Guice.createInjector( new WireModule( new AbstractModule() { @Override protected void configure() { bind( X.class ).annotatedWith( Names.named( "MS" ) ).to( MissingSet.class ); } } ) ); fail( "Expected CreationException" ); } catch ( final CreationException e ) { } try { Guice.createInjector( new WireModule( new AbstractModule() { @Override protected void configure() { bind( X.class ).annotatedWith( Names.named( "MM" ) ).to( MissingMap.class ); } } ) ); fail( "Expected CreationException" ); } catch ( final CreationException e ) { } } public void testGenericInjection() { final Injector injector = Guice.createInjector( new WireModule( new TestModule() ) ); final GenericInstance genericInstance = (GenericInstance) injector.getInstance( Key.get( X.class, Names.named( "GI" ) ) ); assertEquals( TypeLiteral.get( Integer.class ), TypeParameters.get( TypeLiteral.get( genericInstance.number.getClass() ).getSupertype( Z.class ), 0 ) ); assertEquals( TypeLiteral.get( String.class ), TypeParameters.get( TypeLiteral.get( genericInstance.chars.getClass() ).getSupertype( Z.class ), 0 ) ); assertEquals( ZImpl.class, genericInstance.random.getClass() ); } public void testChildWiring() { final Y y = new YImpl(); final Injector parent = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Y.class ).annotatedWith( Names.named( "fixed" ) ).toInstance( y ); } } ); final Injector child = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { bind( Y.class ).annotatedWith( new FuzzyImpl() ).toInstance( y ); } } ); final Injector grandchild = child.createChildInjector( new ChildWireModule( child, new TestModule() ) ); assertSame( y, ( (PlaceholderString) grandchild.getInstance( Key.get( X.class, Names.named( "PS" ) ) ) ).fixed ); assertSame( y, ( (PlaceholderString) grandchild.getInstance( Key.get( X.class, Names.named( "PS" ) ) ) ).fuzzy ); } } BeanWatcherTest.java000066400000000000000000000121261167051330000416470ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import javax.inject.Qualifier; import junit.framework.TestCase; import org.sonatype.guice.bean.locators.MutableBeanLocator; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.inject.BeanEntry; import org.sonatype.inject.EagerSingleton; import org.sonatype.inject.Mediator; import com.google.inject.Guice; import com.google.inject.Injector; public class BeanWatcherTest extends TestCase { @Qualifier @Retention( RetentionPolicy.RUNTIME ) public @interface Marked { int value(); } static abstract class Item { } static abstract class SomeItem extends Item { } @javax.inject.Named static class AItem extends SomeItem { } @Marked( 0 ) @javax.inject.Named static class BItem extends SomeItem { } @EagerSingleton @javax.inject.Named static class CItem extends SomeItem { static boolean initialized; public CItem() { initialized = true; } } @Marked( 1 ) static class DItem extends SomeItem { } @javax.inject.Named static class NamedItemWatcher { Map items = new HashMap(); } @javax.inject.Named static class MarkedItemWatcher { Map items = new HashMap(); } @javax.inject.Named static class NamedItemMediator implements Mediator { public void add( final BeanEntry bean, final NamedItemWatcher watcher ) throws Exception { assertNull( watcher.items.put( bean.getKey().value(), bean.getValue() ) ); } public void remove( final BeanEntry bean, final NamedItemWatcher watcher ) throws Exception { assertEquals( watcher.items.remove( bean.getKey().value() ), bean.getValue() ); } } @javax.inject.Named static class MarkedItemMediator implements Mediator { public void add( final BeanEntry bean, final MarkedItemWatcher watcher ) throws Exception { assertNull( watcher.items.put( Integer.valueOf( bean.getKey().value() ), bean.getValue() ) ); } public void remove( final BeanEntry bean, final MarkedItemWatcher watcher ) throws Exception { assertEquals( watcher.items.remove( Integer.valueOf( bean.getKey().value() ) ), bean.getValue() ); } } @Inject private NamedItemWatcher namedItemWatcher; @Inject private MarkedItemWatcher markedItemWatcher; @Inject private Injector injector; @Override protected void setUp() throws Exception { final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); Guice.createInjector( new SpaceModule( space ) ).injectMembers( this ); } public void testNamedWatcher() { assertTrue( CItem.initialized ); assertEquals( 4, namedItemWatcher.items.size() ); assertEquals( 2, markedItemWatcher.items.size() ); assertTrue( namedItemWatcher.items.get( AItem.class.getName() ) instanceof AItem ); assertTrue( namedItemWatcher.items.get( BItem.class.getName() ) instanceof BItem ); assertTrue( namedItemWatcher.items.get( CItem.class.getName() ) instanceof CItem ); assertTrue( namedItemWatcher.items.get( DItem.class.getName() ) instanceof DItem ); assertNotSame( namedItemWatcher.items.get( AItem.class.getName() ), injector.getInstance( AItem.class ) ); assertSame( namedItemWatcher.items.get( CItem.class.getName() ), injector.getInstance( CItem.class ) ); assertTrue( markedItemWatcher.items.get( Integer.valueOf( 0 ) ) instanceof BItem ); assertTrue( markedItemWatcher.items.get( Integer.valueOf( 1 ) ) instanceof DItem ); injector.getInstance( MutableBeanLocator.class ).remove( injector ); assertEquals( 0, namedItemWatcher.items.size() ); assertEquals( 0, markedItemWatcher.items.size() ); } } CachingModuleTest.java000066400000000000000000000032371167051330000421710ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import javax.inject.Named; import junit.framework.TestCase; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.inject.BeanScanning; import com.google.inject.AbstractModule; import com.google.inject.Guice; public class CachingModuleTest extends TestCase { @Named static class CustomModule extends AbstractModule { @Override protected void configure() { requireBinding( CachingModuleTest.class ); getMembersInjector( CachingModuleTest.class ); } } public void testQualifiedModule() { final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); Guice.createInjector( new SpaceModule( space, BeanScanning.CACHE ) ); Guice.createInjector( new SpaceModule( space, BeanScanning.CACHE ) ); Guice.createInjector( new SpaceModule( space, BeanScanning.CACHE ) ); } } ParametersTest.java000066400000000000000000000045231167051330000415710ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.Arrays; import java.util.Map; import javax.inject.Inject; import junit.framework.TestCase; import org.sonatype.inject.Parameters; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Provides; public class ParametersTest extends TestCase { @Inject @Parameters String[] arguments; @Inject @Parameters Map properties; public void testDefaultParameters() { Guice.createInjector( new WireModule( new AbstractModule() { @Override protected void configure() { bind( ParametersTest.class ); } } ) ).injectMembers( this ); assertTrue( properties.isEmpty() ); assertEquals( 0, arguments.length ); } @SuppressWarnings( { "unchecked", "rawtypes", "unused" } ) public void testCustomParameters() { Guice.createInjector( new WireModule( new AbstractModule() { @Override protected void configure() { bind( ParametersTest.class ); } @Provides @Parameters String[] arguments() { return new String[] { "Hello", "World" }; } @Provides @Parameters Map properties() { return (Map) System.getProperties(); } } ) ).injectMembers( this ); assertEquals( System.getProperties(), properties ); assertTrue( Arrays.equals( new String[] { "Hello", "World" }, arguments ) ); } } QualifiedModuleTest.java000066400000000000000000000033471167051330000425420ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import javax.inject.Inject; import junit.framework.TestCase; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.URLClassSpace; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.name.Names; public class QualifiedModuleTest extends TestCase { @javax.inject.Named static class CustomModule extends AbstractModule { @Override protected void configure() { bindConstant().annotatedWith( Names.named( "CustomConstant" ) ).to( "CustomValue" ); } } @Inject @javax.inject.Named( "CustomConstant" ) private String value; @Inject private ClassSpace surroundingSpace; public void testQualifiedModule() { final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); Guice.createInjector( new SpaceModule( space ) ).injectMembers( this ); assertEquals( surroundingSpace, space ); assertEquals( "CustomValue", value ); } } QualifiedProviderTest.java000066400000000000000000000064521167051330000431070ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.util.concurrent.atomic.AtomicInteger; import javax.enterprise.inject.Typed; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import junit.framework.TestCase; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.URLClassSpace; import com.google.inject.Guice; public class QualifiedProviderTest extends TestCase { @Named( "jsr330-counting" ) static class JSR330CountingThreadProvider implements javax.inject.Provider { @Inject @Named( "counting" ) Runnable runnable; static int count; public Thread get() { count++; return new Thread( runnable ); } } @Named( "guice-counting" ) static class GuiceCountingThreadProvider implements com.google.inject.Provider { @Inject @Named( "counting" ) Runnable runnable; static int count; public Thread get() { count++; return new Thread( runnable ); } } @Named( "counting" ) @Typed static class CountingRunnable implements Runnable { static final AtomicInteger count = new AtomicInteger(); public void run() { count.incrementAndGet(); } } @Inject @Named( "jsr330-counting" ) Provider jsr330ThreadProvider; @Inject @Named( "guice-counting" ) Provider guiceThreadProvider; public void testQualifiedProvider() { final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); Guice.createInjector( new SpaceModule( space ) ).injectMembers( this ); final Thread[] ts = new Thread[8]; assertEquals( 0, JSR330CountingThreadProvider.count ); assertEquals( 0, GuiceCountingThreadProvider.count ); for ( int i = 0; i < ts.length; i++ ) { ts[i] = i % 2 == 0 ? jsr330ThreadProvider.get() : guiceThreadProvider.get(); } assertEquals( 4, JSR330CountingThreadProvider.count ); assertEquals( 4, GuiceCountingThreadProvider.count ); assertEquals( 0, CountingRunnable.count.get() ); for ( final Thread t : ts ) { t.start(); } for ( final Thread t : ts ) { try { t.join(); } catch ( final InterruptedException e ) { e.printStackTrace(); } } assertEquals( 8, CountingRunnable.count.get() ); } } QualifiedTypesTest.java000066400000000000000000000221261167051330000424150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-binders/src/test/java/org/sonatype/guice/bean/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.binders; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.EventListener; import java.util.RandomAccess; import java.util.concurrent.Callable; import javax.enterprise.inject.Typed; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Qualifier; import junit.framework.TestCase; import org.sonatype.guice.bean.locators.BeanLocator; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.guice.bean.scanners.QualifiedTypeListener; import org.sonatype.inject.BeanEntry; import org.sonatype.inject.EagerSingleton; import org.sonatype.inject.Mediator; import com.google.inject.AbstractModule; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.name.Names; public class QualifiedTypesTest extends TestCase { @Named static class DefaultB01 { } @Named( "default" ) static class B01 extends Thread { } @Named @Typed static class DefaultB02 implements RandomAccess, EventListener { } @Named @Typed( EventListener.class ) static class B02 implements RandomAccess, EventListener { } @Named static class B03 implements EventListener { } @Named @EagerSingleton static class DefaultB03 { static boolean initialized; @Inject void initialize() { initialized = true; } } @Named( "TEST" ) static class DefaultB04 { } @Named( "TEST" ) static class B04 { } @Named static class B05EventListener implements Callable, EventListener, Serializable { private static final long serialVersionUID = 1L; public String call() { return "GO"; } } @Named @Typed( { EventListener.class, Callable.class } ) static class B06 implements Callable, EventListener, Serializable { private static final long serialVersionUID = 1L; public String call() { return "GO"; } } static abstract class AbstractB01 { } @Typed( { AbstractB02.class, EventListener.class } ) static abstract class AbstractB02 implements RandomAccess, EventListener { } static abstract class AbstractB03 implements EventListener { } @Named static class SubclassB00 extends B01 { } @Named static class SubclassB01 extends AbstractB01 { } @Named static class SubclassB02 extends AbstractB02 { } @Named static class SubclassB03EventListener extends AbstractB03 { } @Named( "RENAME" ) static class SubclassB04EventListener extends AbstractB03 { } @Named @Typed( B02.class ) static class SubclassB06 extends B02 { } @Named @Typed( Serializable.class ) static class SubclassB07 extends B02 implements Callable, Serializable { private static final long serialVersionUID = 1L; public String call() { return "GO"; } } @Named @Typed static class SubclassB08 extends B02 implements Serializable { private static final long serialVersionUID = 1L; } @Qualifier @Retention( RetentionPolicy.RUNTIME ) public @interface Legacy { } static class LegacyImpl implements Legacy { public Class annotationType() { return Legacy.class; } } @Legacy static class LegacyCallable implements Callable { public String call() { return "GO"; } } private BeanLocator locator; private Injector injector; @Override protected void setUp() throws Exception { final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); injector = Guice.createInjector( new SpaceModule( space ) ); locator = injector.getInstance( BeanLocator.class ); assertTrue( DefaultB03.initialized ); } private void checkDefaultBinding( final Class api, final Class imp ) { final Annotation defaultName = Names.named( "default" ); assertSame( imp, locator.locate( Key.get( api ) ).iterator().next().getImplementationClass() ); assertSame( imp, locator.locate( Key.get( api, Named.class ) ).iterator().next().getImplementationClass() ); assertSame( imp, locator.locate( Key.get( api, defaultName ) ).iterator().next().getImplementationClass() ); } private void checkNamedBinding( final Class api, final String name, final Class imp ) { assertSame( imp, locator.locate( Key.get( api, Names.named( name ) ) ).iterator().next().getImplementationClass() ); } private void checkLegacyBinding( final Class api, final Class imp ) { assertSame( imp, locator.locate( Key.get( api, Legacy.class ) ).iterator().next().getImplementationClass() ); } public void testQualifiedBindings() { checkDefaultBinding( DefaultB01.class, DefaultB01.class ); checkDefaultBinding( DefaultB02.class, DefaultB02.class ); checkDefaultBinding( DefaultB03.class, DefaultB03.class ); checkDefaultBinding( DefaultB04.class, DefaultB04.class ); checkDefaultBinding( Thread.class, B01.class ); checkDefaultBinding( B04.class, B04.class ); checkNamedBinding( EventListener.class, B02.class.getName(), B02.class ); checkNamedBinding( EventListener.class, B03.class.getName(), B03.class ); checkNamedBinding( EventListener.class, B05EventListener.class.getName(), B05EventListener.class ); checkNamedBinding( EventListener.class, B06.class.getName(), B06.class ); checkNamedBinding( B01.class, SubclassB00.class.getName(), SubclassB00.class ); checkNamedBinding( AbstractB01.class, SubclassB01.class.getName(), SubclassB01.class ); checkNamedBinding( AbstractB02.class, SubclassB02.class.getName(), SubclassB02.class ); checkNamedBinding( EventListener.class, SubclassB03EventListener.class.getName(), SubclassB03EventListener.class ); checkNamedBinding( EventListener.class, "RENAME", SubclassB04EventListener.class ); checkNamedBinding( B02.class, SubclassB06.class.getName(), SubclassB06.class ); checkNamedBinding( Serializable.class, SubclassB07.class.getName(), SubclassB07.class ); checkNamedBinding( Serializable.class, SubclassB08.class.getName(), SubclassB08.class ); checkLegacyBinding( Callable.class, LegacyCallable.class ); } @ImplementedBy( AImpl.class ) interface A { } static class AImpl implements A { } static class Ambiguous implements Serializable, EventListener { private static final long serialVersionUID = 1L; } @SuppressWarnings( "rawtypes" ) static class RawMediator implements Mediator { public void add( final BeanEntry bean, final Object watcher ) throws Exception { } public void remove( final BeanEntry bean, final Object watcher ) throws Exception { } } abstract class AbstractNamedMediator implements Mediator { } static class BadBindings implements Module { public void configure( final Binder binder ) { final QualifiedTypeListener listener = new QualifiedTypeBinder( binder ); listener.hear( null, Ambiguous.class, null ); listener.hear( null, RawMediator.class, null ); listener.hear( null, AbstractNamedMediator.class, null ); listener.hear( null, AbstractModule.class, null ); } } public void testBadBindings() { try { Guice.createInjector( new BadBindings() ); } catch ( final Exception e ) { e.printStackTrace(); } } } sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/000077500000000000000000000000001167051330000260065ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/pom.xml000066400000000000000000000062311167051330000273250ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-bean 2.3.0 guice-bean-containers Sisu-Inject-Bean : Container API javax.inject javax.inject org.sonatype.sisu sisu-guice org.sonatype.sisu.inject guice-bean-reflect org.sonatype.sisu.inject guice-bean-inject org.sonatype.sisu.inject guice-bean-locators org.sonatype.sisu.inject guice-bean-binders org.osgi org.osgi.core true org.osgi org.osgi.compendium true junit junit true org.testng testng true org.sonatype.sisu.inject guice-assistedinject ${sisu.guice.version} test maven-surefire-plugin org.apache.maven.surefire surefire-junit4 2.8.1 org.apache.maven.surefire surefire-testng 2.8.1 sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/000077500000000000000000000000001167051330000265755ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/000077500000000000000000000000001167051330000275215ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/000077500000000000000000000000001167051330000304425ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/000077500000000000000000000000001167051330000312315ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/000077500000000000000000000000001167051330000330735ustar00rootroot00000000000000000077500000000000000000000000001167051330000341105ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000350155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000371625ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/guice/bean/containersInjectedTest.java000066400000000000000000000122251167051330000424140ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import java.io.File; import java.lang.annotation.Annotation; import java.util.Iterator; import java.util.Map.Entry; import java.util.Properties; import javax.inject.Inject; import org.junit.After; import org.junit.Before; import org.sonatype.guice.bean.binders.ParameterKeys; import org.sonatype.guice.bean.binders.SpaceModule; import org.sonatype.guice.bean.binders.WireModule; import org.sonatype.guice.bean.locators.MutableBeanLocator; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.inject.BeanScanning; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.name.Names; /** * Abstract TestNG/JUnit4 test that automatically binds and injects itself. */ public abstract class InjectedTest implements Module { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private String basedir; @Inject private MutableBeanLocator locator; // ---------------------------------------------------------------------- // Setup // ---------------------------------------------------------------------- @Before @BeforeMethod public void setUp() { Guice.createInjector( new WireModule( new SetUpModule(), new SpaceModule( space(), scanning() ) ) ); } @After @AfterMethod public void tearDown() { locator.clear(); } final class SetUpModule implements Module { public void configure( final Binder binder ) { binder.install( InjectedTest.this ); final Properties properties = new Properties(); properties.put( "basedir", getBasedir() ); InjectedTest.this.configure( properties ); binder.bind( ParameterKeys.PROPERTIES ).toInstance( properties ); binder.requestInjection( InjectedTest.this ); } } public ClassSpace space() { return new URLClassSpace( getClass().getClassLoader() ); } public BeanScanning scanning() { return BeanScanning.CACHE; } // ---------------------------------------------------------------------- // Container configuration methods // ---------------------------------------------------------------------- /** * Custom injection bindings. * * @param binder The Guice binder */ public void configure( final Binder binder ) { // place any per-test bindings here... } /** * Custom property values. * * @param properties The test properties */ public void configure( final Properties properties ) { // put any per-test properties here... } // ---------------------------------------------------------------------- // Container lookup methods // ---------------------------------------------------------------------- public final T lookup( final Class type ) { return lookup( Key.get( type ) ); } public final T lookup( final Class type, final String name ) { return lookup( type, Names.named( name ) ); } public final T lookup( final Class type, final Class qualifier ) { return lookup( Key.get( type, qualifier ) ); } public final T lookup( final Class type, final Annotation qualifier ) { return lookup( Key.get( type, qualifier ) ); } // ---------------------------------------------------------------------- // Container resource methods // ---------------------------------------------------------------------- public final String getBasedir() { if ( null == basedir ) { basedir = System.getProperty( "basedir", new File( "" ).getAbsolutePath() ); } return basedir; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private final T lookup( final Key key ) { final Iterator> i = locator.locate( key ).iterator(); return i.hasNext() ? i.next().getValue() : null; } } InjectedTestCase.java000066400000000000000000000121631167051330000432110ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import java.io.File; import java.lang.annotation.Annotation; import java.util.Iterator; import java.util.Map.Entry; import java.util.Properties; import javax.inject.Inject; import junit.framework.TestCase; import org.sonatype.guice.bean.binders.ParameterKeys; import org.sonatype.guice.bean.binders.SpaceModule; import org.sonatype.guice.bean.binders.WireModule; import org.sonatype.guice.bean.locators.MutableBeanLocator; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.inject.BeanScanning; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.name.Names; /** * Abstract JUnit3 {@link TestCase} that automatically binds and injects itself. */ public abstract class InjectedTestCase extends TestCase implements Module { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private String basedir; @Inject private MutableBeanLocator locator; // ---------------------------------------------------------------------- // Setup // ---------------------------------------------------------------------- @Override protected void setUp() throws Exception { Guice.createInjector( new WireModule( new SetUpModule(), new SpaceModule( space(), scanning() ) ) ); } @Override protected void tearDown() throws Exception { locator.clear(); } final class SetUpModule implements Module { public void configure( final Binder binder ) { binder.install( InjectedTestCase.this ); final Properties properties = new Properties(); properties.put( "basedir", getBasedir() ); InjectedTestCase.this.configure( properties ); binder.bind( ParameterKeys.PROPERTIES ).toInstance( properties ); binder.requestInjection( InjectedTestCase.this ); } } public ClassSpace space() { return new URLClassSpace( getClass().getClassLoader() ); } public BeanScanning scanning() { return BeanScanning.CACHE; } // ---------------------------------------------------------------------- // Container configuration methods // ---------------------------------------------------------------------- /** * Custom injection bindings. * * @param binder The Guice binder */ public void configure( final Binder binder ) { // place any per-test bindings here... } /** * Custom property values. * * @param properties The test properties */ public void configure( final Properties properties ) { // put any per-test properties here... } // ---------------------------------------------------------------------- // Container lookup methods // ---------------------------------------------------------------------- public final T lookup( final Class type ) { return lookup( Key.get( type ) ); } public final T lookup( final Class type, final String name ) { return lookup( type, Names.named( name ) ); } public final T lookup( final Class type, final Class qualifier ) { return lookup( Key.get( type, qualifier ) ); } public final T lookup( final Class type, final Annotation qualifier ) { return lookup( Key.get( type, qualifier ) ); } // ---------------------------------------------------------------------- // Container resource methods // ---------------------------------------------------------------------- public final String getBasedir() { if ( null == basedir ) { basedir = System.getProperty( "basedir", new File( "" ).getAbsolutePath() ); } return basedir; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private final T lookup( final Key key ) { final Iterator> i = locator.locate( key ).iterator(); return i.hasNext() ? i.next().getValue() : null; } } Main.java000066400000000000000000000121431167051330000407120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import java.util.Collections; import java.util.Map; import javax.inject.Inject; import org.sonatype.guice.bean.binders.ParameterKeys; import org.sonatype.guice.bean.binders.SpaceModule; import org.sonatype.guice.bean.binders.WireModule; import org.sonatype.guice.bean.locators.MutableBeanLocator; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.inject.BeanScanning; import org.sonatype.inject.Parameters; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Provides; /** * Bootstrap class that creates a static {@link Injector} by scanning the current class-path for beans. */ public final class Main implements Module { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Map properties; private final String[] args; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private Main( final Map properties, final String... args ) { this.properties = Collections.unmodifiableMap( properties ); this.args = args; } // ---------------------------------------------------------------------- // Public entry points // ---------------------------------------------------------------------- public static void main( final String... args ) { boot( System.getProperties(), args ); } public static T boot( final Class type, final String... args ) { return boot( System.getProperties(), args ).getInstance( type ); } public static Injector boot( final Map properties, final String... args ) { final BeanScanning scanning = selectScanning( properties ); final Module app = wire( scanning, new Main( properties, args ) ); final Injector injector = Guice.createInjector( app ); return injector; } public static Module wire( final BeanScanning scanning, final Module... bindings ) { final Module[] modules = new Module[bindings.length + 1]; System.arraycopy( bindings, 0, modules, 0, bindings.length ); final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); modules[bindings.length] = new SpaceModule( new URLClassSpace( tccl ), scanning ); return new WireModule( modules ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void configure( final Binder binder ) { binder.requestStaticInjection( SisuGuice.class ); binder.bind( ParameterKeys.PROPERTIES ).toInstance( properties ); binder.bind( ShutdownThread.class ).asEagerSingleton(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- @Provides @Parameters String[] parameters() { return args.clone(); } static BeanScanning selectScanning( final Map properties ) { final String option = (String) properties.get( BeanScanning.class.getName() ); if ( null == option || option.length() == 0 ) { return BeanScanning.ON; } for ( final BeanScanning value : BeanScanning.values() ) { if ( value.name().equalsIgnoreCase( option ) ) { return value; } } throw new IllegalArgumentException( "Unknown BeanScanning option: " + option ); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- static final class ShutdownThread extends Thread { private final MutableBeanLocator locator; @Inject ShutdownThread( final MutableBeanLocator locator ) { this.locator = locator; Runtime.getRuntime().addShutdownHook( this ); } @Override public void run() { locator.clear(); } } } SisuActivator.java000066400000000000000000000244361167051330000426360ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import java.util.AbstractMap; import java.util.Collections; import java.util.Dictionary; import java.util.Hashtable; import java.util.Map; import java.util.Set; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.BundleTracker; import org.osgi.util.tracker.BundleTrackerCustomizer; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.sonatype.guice.bean.binders.ParameterKeys; import org.sonatype.guice.bean.binders.SpaceModule; import org.sonatype.guice.bean.binders.WireModule; import org.sonatype.guice.bean.locators.DefaultBeanLocator; import org.sonatype.guice.bean.locators.MutableBeanLocator; import org.sonatype.guice.bean.reflect.BundleClassSpace; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.inject.BeanScanning; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; /** * {@link BundleActivator} that maintains a dynamic {@link Injector} graph by scanning bundles as they come and go. */ public final class SisuActivator implements BundleActivator, BundleTrackerCustomizer, ServiceTrackerCustomizer { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- static final String CONTAINER_SYMBOLIC_NAME = "org.sonatype.inject"; static final String BUNDLE_INJECTOR_CLASS_NAME = BundleInjector.class.getName(); // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- static final MutableBeanLocator locator = new DefaultBeanLocator(); private BundleContext bundleContext; private ServiceTracker serviceTracker; private BundleTracker bundleTracker; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void start( final BundleContext context ) { bundleContext = context; serviceTracker = new ServiceTracker( context, BUNDLE_INJECTOR_CLASS_NAME, this ); serviceTracker.open(); bundleTracker = new BundleTracker( context, Bundle.STARTING | Bundle.ACTIVE, this ); bundleTracker.open(); } public void stop( final BundleContext context ) { bundleTracker.close(); serviceTracker.close(); locator.clear(); } // ---------------------------------------------------------------------- // Bundle tracking // ---------------------------------------------------------------------- public Object addingBundle( final Bundle bundle, final BundleEvent event ) { if ( CONTAINER_SYMBOLIC_NAME.equals( bundle.getSymbolicName() ) ) { return null; // this is our container, ignore it to avoid circularity errors } if ( needsScanning( bundle ) && getBundleInjectorService( bundle ) == null ) { try { new BundleInjector( bundle ); } catch ( final RuntimeException e ) { Logs.warn( "Problem starting: {}", bundle, e ); } } return null; } public void modifiedBundle( final Bundle bundle, final BundleEvent event, final Object object ) { // nothing to do } public void removedBundle( final Bundle bundle, final BundleEvent event, final Object object ) { // nothing to do } // ---------------------------------------------------------------------- // Service tracking // ---------------------------------------------------------------------- @SuppressWarnings( "deprecation" ) public Object addingService( final ServiceReference reference ) { final Object service = bundleContext.getService( reference ); locator.add( ( (BundleInjector) service ).getInjector(), 0 ); return service; } public void modifiedService( final ServiceReference reference, final Object service ) { // nothing to do } public void removedService( final ServiceReference reference, final Object service ) { locator.remove( ( (BundleInjector) service ).getInjector() ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static boolean needsScanning( final Bundle bundle ) { final Dictionary headers = bundle.getHeaders(); final String host = (String) headers.get( Constants.FRAGMENT_HOST ); if ( null != host ) { return false; // fragment, we'll scan it when we process the host } final String imports = (String) headers.get( Constants.IMPORT_PACKAGE ); if ( null == imports ) { return false; // doesn't import any interesting injection packages } return imports.contains( "javax.inject" ) || imports.contains( "com.google.inject" ); } private static ServiceReference getBundleInjectorService( final Bundle bundle ) { final ServiceReference[] serviceReferences = bundle.getRegisteredServices(); if ( null != serviceReferences ) { for ( final ServiceReference ref : serviceReferences ) { for ( final String name : (String[]) ref.getProperty( Constants.OBJECTCLASS ) ) { if ( BUNDLE_INJECTOR_CLASS_NAME.equals( name ) ) { return ref; } } } } return null; } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- private static final class BundleInjector implements /* TODO:ManagedService, */Module { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String[] API = { BUNDLE_INJECTOR_CLASS_NAME /* TODO:, ManagedService.class.getName() */}; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Map properties; private final Injector injector; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BundleInjector( final Bundle bundle ) { properties = new BundleProperties( bundle.getBundleContext() ); final ClassSpace space = new BundleClassSpace( bundle ); final BeanScanning scanning = Main.selectScanning( properties ); injector = Guice.createInjector( new WireModule( this, new SpaceModule( space, scanning ) ) ); final Dictionary metadata = new Hashtable(); metadata.put( Constants.SERVICE_PID, CONTAINER_SYMBOLIC_NAME ); bundle.getBundleContext().registerService( API, this, metadata ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void configure( final Binder binder ) { binder.requestStaticInjection( SisuGuice.class ); binder.bind( ParameterKeys.PROPERTIES ).toInstance( properties ); binder.bind( MutableBeanLocator.class ).toInstance( locator ); } public Injector getInjector() { return injector; } } private static final class BundleProperties extends AbstractMap { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private transient final BundleContext context; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BundleProperties( final BundleContext context ) { this.context = context; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public Object get( final Object key ) { return context.getProperty( String.valueOf( key ) ); } @Override public boolean containsKey( final Object key ) { return null != get( key ); } @Override public Set> entrySet() { return Collections.emptySet(); } @Override public int size() { return 0; } } } SisuGuice.java000066400000000000000000000121231167051330000417240ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Iterator; import java.util.Map.Entry; import javax.inject.Inject; import org.sonatype.guice.bean.binders.WireModule; import org.sonatype.guice.bean.locators.BeanLocator; import org.sonatype.guice.bean.reflect.Logs; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.util.Providers; public final class SisuGuice { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private static final ThreadLocal LOCATOR = new InheritableThreadLocal(); private static volatile BeanLocator latest; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private SisuGuice() { // static utility class, not allowed to create instances } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Inject public static void setBeanLocator( final BeanLocator locator ) { if ( null != locator ) { LOCATOR.set( locator ); } else { LOCATOR.remove(); } latest = locator; } public static BeanLocator getBeanLocator() { final BeanLocator locator = LOCATOR.get(); return null != locator ? locator : latest; } public static T lookup( final Key key ) { final BeanLocator locator = getBeanLocator(); if ( null != locator ) { final Iterator> i = locator.locate( key ).iterator(); if ( i.hasNext() ) { return i.next().getValue(); } } else { Logs.debug( "No BeanLocator found for thread {}", Thread.currentThread(), null ); } return null; } public static void inject( final Object that ) { final BeanLocator locator = getBeanLocator(); if ( null != locator ) { Guice.createInjector( new WireModule() { @Override public void configure( final Binder binder ) { binder.bind( BeanLocator.class ).toProvider( Providers.of( locator ) ); binder.requestInjection( that ); } } ); } else { Logs.debug( "No BeanLocator found for thread {}", Thread.currentThread(), null ); } } public static Injector enhance( final Injector injector ) { final Class[] api = { Injector.class }; return (Injector) Proxy.newProxyInstance( api[0].getClassLoader(), api, new InvocationHandler() { @SuppressWarnings( { "rawtypes", "unchecked" } ) public Object invoke( final Object proxy, final Method method, final Object[] args ) throws Throwable { final String methodName = method.getName(); if ( "getInstance".equals( methodName ) ) { final Key key = args[0] instanceof Key ? (Key) args[0] : Key.get( (Class) args[0] ); final Iterator i = injector.getInstance( BeanLocator.class ).locate( key ).iterator(); return i.hasNext() ? i.next().getValue() : null; } if ( "injectMembers".equals( methodName ) ) { Guice.createInjector( new WireModule( new Module() { public void configure( final Binder binder ) { binder.bind( BeanLocator.class ).toProvider( injector.getProvider( BeanLocator.class ) ); binder.requestInjection( args[0] ); } } ) ); return null; } return method.invoke( injector, args ); } } ); } } package-info.java000066400000000000000000000024611167051330000423540ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * Bean containers. * *

The principal members of this package are: *

*
{@link org.sonatype.guice.bean.containers.Main} *
Classic main entry point that creates a static {@link com.google.inject.Injector} for the current class-path. *
{@link org.sonatype.guice.bean.containers.SisuActivator} *
OSGi {@link org.osgi.framework.BundleActivator} that maintains a dynamic injector graph as bundles come and go. *
{@link org.sonatype.guice.bean.containers.InjectedTestCase} *
JUnit {@link junit.framework.TestCase} that automatically binds and injects itself. *
*/ package org.sonatype.guice.bean.containers; 000077500000000000000000000000001167051330000342705ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/injectSisu.java000066400000000000000000000040101167051330000360510ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/main/java/org/sonatype/inject/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.inject; import java.lang.annotation.Annotation; import org.sonatype.guice.bean.containers.SisuGuice; import com.google.inject.Key; import com.google.inject.name.Names; public final class Sisu { // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public static T lookup( final Class type ) { return SisuGuice.lookup( Key.get( type ) ); } public static T lookup( final Class type, final String name ) { return SisuGuice.lookup( Key.get( type, Names.named( name ) ) ); } public static T lookup( final Class type, final Annotation qualifier ) { return SisuGuice.lookup( Key.get( type, qualifier ) ); } public static T lookup( final Class type, final Class qualifier ) { return SisuGuice.lookup( Key.get( type, qualifier ) ); } public static void inject( final Object that ) { SisuGuice.inject( that ); } // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private Sisu() { // static utility class, not allowed to create instances } } sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/000077500000000000000000000000001167051330000275545ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/000077500000000000000000000000001167051330000304755ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/000077500000000000000000000000001167051330000312645ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/000077500000000000000000000000001167051330000331265ustar00rootroot00000000000000000077500000000000000000000000001167051330000341435ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000350505ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000372155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/guice/bean/containersAssistedTestCase.java000066400000000000000000000047771167051330000433120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import java.util.Properties; import javax.inject.Inject; import javax.inject.Named; import org.sonatype.guice.bean.locators.BeanLocator; import com.google.inject.Binder; import com.google.inject.Key; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.FactoryModuleBuilder; public final class AssistedTestCase extends InjectedTestCase { interface FooFactory { Foo create( int port ); } @Named static class AssistedFoo implements Foo { final int port; final String host; @Inject public AssistedFoo( @Assisted final int port, @Named( "${host}" ) final String host ) { this.port = port; this.host = host; } } @Override public void configure( final Binder binder ) { binder.install( new FactoryModuleBuilder().implement( Foo.class, AssistedFoo.class ).build( FooFactory.class ) ); } @Override public void configure( final Properties properties ) { properties.setProperty( "host", "localhost" ); } @Inject FooFactory beanFactory; @Inject BeanLocator beanLocator; public void testAssistedInject() { Foo bean = beanFactory.create( 8080 ); assertTrue( bean instanceof AssistedFoo ); assertEquals( 8080, ( (AssistedFoo) bean ).port ); assertEquals( "localhost", ( (AssistedFoo) bean ).host ); bean = beanLocator.locate( Key.get( FooFactory.class ) ).iterator().next().getValue().create( 42 ); assertEquals( 42, ( (AssistedFoo) bean ).port ); assertEquals( "localhost", ( (AssistedFoo) bean ).host ); bean = beanLocator.locate( Key.get( Foo.class ) ).iterator().next().getValue(); assertTrue( bean instanceof DefaultFoo ); } } Custom1TestCase.java000066400000000000000000000022011167051330000430420ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import javax.inject.Inject; import com.google.inject.Binder; public final class Custom1TestCase extends InjectedTestCase { @Override public void configure( final Binder binder ) { // override automatic binding binder.bind( Foo.class ).to( NamedFoo.class ); } @Inject Foo bean; public void testPerTestCaseCustomization() { assertTrue( bean instanceof NamedFoo ); } } Custom2Test.java000066400000000000000000000023221167051330000422530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import javax.inject.Inject; import org.testng.Assert; import com.google.inject.Binder; public final class Custom2Test extends InjectedTest { @Override public void configure( final Binder binder ) { // override automatic binding binder.bind( Foo.class ).to( TaggedFoo.class ); } @Inject Foo bean; @org.junit.Test @org.testng.annotations.Test public void testPerTestCaseCustomization() { Assert.assertTrue( bean instanceof TaggedFoo ); } } Custom3TestCase.java000066400000000000000000000024231167051330000430520ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import java.util.Properties; import javax.inject.Inject; import javax.inject.Named; public final class Custom3TestCase extends InjectedTestCase { @Override public void configure( final Properties properties ) { properties.put( "hint", "NameTag" ); properties.put( "port", "8080" ); } @Inject @Named( "${hint}" ) Foo bean; @Inject @Named( "${port}" ) int port; public void testPerTestCaseCustomization() { assertTrue( bean instanceof NamedAndTaggedFoo ); assertEquals( 8080, port ); } } ExampleTestCase.java000066400000000000000000000046331167051330000431150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import java.io.File; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import com.google.inject.name.Names; public final class ExampleTestCase extends InjectedTestCase { @Inject @Named( "${basedir}" ) String basedir; @Inject @Named( "${basedir}/target/test-classes/inject.properties" ) File propertiesFile; public void testBasedir() { assertEquals( getBasedir(), basedir ); assertTrue( propertiesFile.isFile() ); } @Inject Foo bean; @Inject Map beans; public void testInjection() { assertTrue( bean instanceof DefaultFoo ); assertEquals( 4, beans.size() ); assertTrue( beans.get( "default" ) instanceof DefaultFoo ); assertTrue( beans.get( NamedFoo.class.getName() ) instanceof NamedFoo ); assertTrue( beans.get( TaggedFoo.class.getName() ) instanceof TaggedFoo ); assertTrue( beans.get( "NameTag" ) instanceof NamedAndTaggedFoo ); assertTrue( bean == beans.get( "default" ) ); } public void testContainerLookup() { assertTrue( lookup( Foo.class ) instanceof DefaultFoo ); assertTrue( lookup( Foo.class, Named.class ) instanceof DefaultFoo ); assertTrue( lookup( Foo.class, "NameTag" ) instanceof NamedAndTaggedFoo ); assertTrue( lookup( Foo.class, Names.named( "NameTag" ) ) instanceof NamedAndTaggedFoo ); assertTrue( lookup( Foo.class, Tag.class ).getClass().isAnnotationPresent( Tag.class ) ); assertTrue( lookup( Foo.class, new TagImpl( "A" ) ) instanceof TaggedFoo ); assertNull( lookup( Foo.class, new TagImpl( "X" ) ) ); assertNull( lookup( Integer.class ) ); } } ExampleTypes.java000066400000000000000000000041361167051330000425040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.inject.Named; import javax.inject.Qualifier; import javax.inject.Singleton; // various qualified types for testing interface Foo { } @Qualifier @Retention( RetentionPolicy.RUNTIME ) @interface Tag { String value(); } @Named class NamedFoo implements Foo { } @Tag( "A" ) class TaggedFoo implements Foo { } @Tag( "B" ) @Named( "NameTag" ) class NamedAndTaggedFoo implements Foo { } @Named @Singleton class DefaultFoo implements Foo { } class TagImpl implements Tag { private final String value; public TagImpl( final String value ) { this.value = value; } public String value() { return value; } @Override public int hashCode() { return 127 * "value".hashCode() ^ value.hashCode(); } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof Tag ) { return value.equals( ( (Tag) rhs ).value() ); } return false; } @Override public String toString() { return "@" + Tag.class.getName() + "(value=" + value + ")"; } public Class annotationType() { return Tag.class; } } PrivateModuleTestCase.java000066400000000000000000000064361167051330000443050ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/java/org/sonatype/guice/bean/containers/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.containers; import java.util.Properties; import javax.inject.Inject; import javax.inject.Named; import com.google.inject.Binder; import com.google.inject.PrivateModule; import com.google.inject.name.Names; public final class PrivateModuleTestCase extends InjectedTestCase { static class PrivateFoo implements Foo { final String host; final int port; @Inject public PrivateFoo( @Named( "${host}" ) final String host, @Named( "port" ) final int port ) { this.host = host; this.port = port; } } @Override public void configure( final Binder binder ) { binder.install( new PrivateModule() { @Override protected void configure() { bind( Foo.class ).to( PrivateFoo.class ); bindConstant().annotatedWith( Names.named( "port" ) ).to( 8081 ); expose( Foo.class ); } } ); binder.install( new PrivateModule() { @Override protected void configure() { bind( Foo.class ).annotatedWith( Names.named( "A" ) ).to( PrivateFoo.class ); bindConstant().annotatedWith( Names.named( "port" ) ).to( 1234 ); expose( Foo.class ).annotatedWith( Names.named( "A" ) ); } } ); binder.install( new PrivateModule() { @Override protected void configure() { bind( Foo.class ).annotatedWith( Names.named( "B" ) ).to( PrivateFoo.class ); bindConstant().annotatedWith( Names.named( "port" ) ).to( 4321 ); expose( Foo.class ).annotatedWith( Names.named( "B" ) ); } } ); } @Override public void configure( final Properties properties ) { properties.setProperty( "host", "127.0.0.1" ); } @Inject Foo bean; @Inject @Named( "A" ) Foo beanA; @Inject @Named( "B" ) Foo beanB; public void testAssistedInject() { assertTrue( bean instanceof PrivateFoo ); assertEquals( "127.0.0.1", ( (PrivateFoo) bean ).host ); assertEquals( 8081, ( (PrivateFoo) bean ).port ); assertTrue( beanA instanceof PrivateFoo ); assertEquals( "127.0.0.1", ( (PrivateFoo) beanA ).host ); assertEquals( 1234, ( (PrivateFoo) beanA ).port ); assertTrue( beanB instanceof PrivateFoo ); assertEquals( "127.0.0.1", ( (PrivateFoo) beanB ).host ); assertEquals( 4321, ( (PrivateFoo) beanB ).port ); } } sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/resources/000077500000000000000000000000001167051330000315665ustar00rootroot00000000000000inject.properties000066400000000000000000000000001167051330000350670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-containers/src/test/resourcessisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/000077500000000000000000000000001167051330000260335ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/pom.xml000066400000000000000000000025051167051330000273520ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-bean 2.3.0 guice-bean-converters Sisu-Inject-Bean : Type conversion org.sonatype.sisu sisu-guice org.sonatype.sisu.inject guice-bean-reflect sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/000077500000000000000000000000001167051330000266225ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/000077500000000000000000000000001167051330000275465ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/java/000077500000000000000000000000001167051330000304675ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/java/org/000077500000000000000000000000001167051330000312565ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/java/org/sonatype/000077500000000000000000000000001167051330000331205ustar00rootroot00000000000000000077500000000000000000000000001167051330000341355ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000350425ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000372345ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/java/org/sonatype/guice/bean/convertersAbstractTypeConverter.java000066400000000000000000000030341167051330000443740ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/java/org/sonatype/guice/bean/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.converters; import org.sonatype.guice.bean.reflect.TypeParameters; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.google.inject.matcher.Matchers; import com.google.inject.spi.TypeConverter; /** * Abstract {@link TypeConverter} {@link Module} that automatically registers the converter based on the type parameter. */ public abstract class AbstractTypeConverter implements TypeConverter, Module { public final void configure( final Binder binder ) { // make sure we pick up the right super type parameter, i.e. Foo from AbstractTypeConverter final TypeLiteral superType = TypeLiteral.get( getClass() ).getSupertype( AbstractTypeConverter.class ); binder.convertToTypes( Matchers.only( TypeParameters.get( superType, 0 ) ), this ); } } FileTypeConverter.java000066400000000000000000000021771167051330000435170ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/java/org/sonatype/guice/bean/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.converters; import java.io.File; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.google.inject.spi.TypeConverter; /** * {@link TypeConverter} {@link Module} that converts constants to {@link File}s. */ public final class FileTypeConverter extends AbstractTypeConverter { public Object convert( final String value, final TypeLiteral toType ) { return new File( value ); } } URLTypeConverter.java000066400000000000000000000025611167051330000432770ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/java/org/sonatype/guice/bean/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.converters; import java.net.MalformedURLException; import java.net.URL; import com.google.inject.Module; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; import com.google.inject.spi.TypeConverter; /** * {@link TypeConverter} {@link Module} that converts constants to {@link URL}s. */ public final class URLTypeConverter extends AbstractTypeConverter { public Object convert( final String value, final TypeLiteral toType ) { try { return new URL( value ); } catch ( final MalformedURLException e ) { throw new ProvisionException( e.toString() ); } } } package-info.java000066400000000000000000000023161167051330000424250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/main/java/org/sonatype/guice/bean/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * Additional type converters. * *

The principal members of this package are: *

*
{@link org.sonatype.guice.bean.converters.FileTypeConverter} *
{@link com.google.inject.spi.TypeConverter} {@link com.google.inject.Module} that converts constants to {@link java.io.File}s. *
{@link org.sonatype.guice.bean.converters.URLTypeConverter} *
{@link com.google.inject.spi.TypeConverter} {@link com.google.inject.Module} that converts constants to {@link java.net.URL}s. *
*/ package org.sonatype.guice.bean.converters; sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/test/000077500000000000000000000000001167051330000276015ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/test/java/000077500000000000000000000000001167051330000305225ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/test/java/org/000077500000000000000000000000001167051330000313115ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/test/java/org/sonatype/000077500000000000000000000000001167051330000331535ustar00rootroot00000000000000000077500000000000000000000000001167051330000341705ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000350755ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/test/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000372675ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/test/java/org/sonatype/guice/bean/convertersFileTypeConverterTest.java000066400000000000000000000026571167051330000444150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/test/java/org/sonatype/guice/bean/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.converters; import java.io.File; import junit.framework.TestCase; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Key; import com.google.inject.name.Names; public class FileTypeConverterTest extends TestCase { public void testFileConversion() { final File file = Guice.createInjector( new FileTypeConverter(), new AbstractModule() { @Override protected void configure() { bindConstant().annotatedWith( Names.named( "file" ) ).to( "work/temp" ); } } ).getInstance( Key.get( File.class, Names.named( "file" ) ) ); assertEquals( "work" + File.separator + "temp", file.getPath() ); } } URLTypeConverterTest.java000066400000000000000000000040211167051330000441630ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-converters/src/test/java/org/sonatype/guice/bean/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.converters; import java.net.URL; import junit.framework.TestCase; import com.google.inject.AbstractModule; import com.google.inject.ConfigurationException; import com.google.inject.Guice; import com.google.inject.Key; import com.google.inject.name.Names; public class URLTypeConverterTest extends TestCase { public void testURLConversion() { final URL url = Guice.createInjector( new URLTypeConverter(), new AbstractModule() { @Override protected void configure() { bindConstant().annotatedWith( Names.named( "url" ) ).to( "http://127.0.0.1/" ); } } ).getInstance( Key.get( URL.class, Names.named( "url" ) ) ); assertEquals( "http://127.0.0.1/", url.toString() ); } public void testBrokenURLConversion() { try { Guice.createInjector( new URLTypeConverter(), new AbstractModule() { @Override protected void configure() { bindConstant().annotatedWith( Names.named( "url" ) ).to( "foo^bar" ); } } ).getInstance( Key.get( URL.class, Names.named( "url" ) ) ); fail( "Expected ConfigurationException" ); } catch ( final ConfigurationException e ) { } } } sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/000077500000000000000000000000001167051330000251155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/pom.xml000066400000000000000000000025041167051330000264330ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-bean 2.3.0 guice-bean-inject Sisu-Inject-Bean : Property injection org.sonatype.sisu sisu-guice org.sonatype.sisu.inject guice-bean-reflect sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/000077500000000000000000000000001167051330000257045ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/000077500000000000000000000000001167051330000266305ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/000077500000000000000000000000001167051330000275515ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/000077500000000000000000000000001167051330000303405ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/sonatype/000077500000000000000000000000001167051330000322025ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/sonatype/guice/000077500000000000000000000000001167051330000332765ustar00rootroot00000000000000000077500000000000000000000000001167051330000341245ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000354005ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/sonatype/guice/bean/injectBeanBinder.java000066400000000000000000000024101167051330000402310ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/sonatype/guice/bean/inject/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.inject; import com.google.inject.TypeLiteral; import com.google.inject.spi.TypeEncounter; /** * Provides custom {@link PropertyBinder}s for beans that contain one or more properties. */ public interface BeanBinder { /** * Returns the appropriate {@link PropertyBinder} for the given bean type. * * @param type The bean type * @param encounter The Guice type encounter * @return Property binder for the given type; {@code null} if no binder is applicable */ PropertyBinder bindBean( TypeLiteral type, TypeEncounter encounter ); } BeanInjector.java000066400000000000000000000040001167051330000406000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/sonatype/guice/bean/inject/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.inject; import java.util.List; import com.google.inject.MembersInjector; /** * {@link MembersInjector} that takes {@link PropertyBinding}s and applies them to bean instances. */ final class BeanInjector implements MembersInjector { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final PropertyBinding[] bindings; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BeanInjector( final List bindings ) { final int size = bindings.size(); this.bindings = new PropertyBinding[size]; for ( int i = 0, n = size; i < size; ) { // reverse: inject superclass before sub this.bindings[i++] = bindings.get( --n ); } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void injectMembers( final B bean ) { for ( final PropertyBinding b : bindings ) { b.injectProperty( bean ); } } } BeanListener.java000066400000000000000000000066441167051330000406300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/sonatype/guice/bean/inject/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.inject; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sonatype.guice.bean.reflect.BeanProperties; import org.sonatype.guice.bean.reflect.BeanProperty; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; /** * {@link TypeListener} that listens for bean types and arranges for their properties to be injected. */ public final class BeanListener implements TypeListener { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final BeanBinder beanBinder; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public BeanListener( final BeanBinder beanBinder ) { this.beanBinder = beanBinder; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void hear( final TypeLiteral type, final TypeEncounter encounter ) { final PropertyBinder propertyBinder = beanBinder.bindBean( type, encounter ); if ( null == propertyBinder ) { return; // no properties to bind } final List bindings = new ArrayList(); final Set visited = new HashSet(); for ( final BeanProperty property : new BeanProperties( type.getRawType() ) ) { final String name = property.getName(); if ( visited.add( name ) ) { try { final PropertyBinding binding = propertyBinder.bindProperty( property ); if ( binding == PropertyBinder.LAST_BINDING ) { break; // no more bindings } if ( binding != null ) { bindings.add( binding ); } else { visited.remove( name ); } } catch ( final RuntimeException e ) { encounter.addError( new ProvisionException( "Error binding: " + property, e ) ); } } } if ( bindings.size() > 0 ) { encounter.register( new BeanInjector( bindings ) ); } } } PropertyBinder.java000066400000000000000000000030001167051330000412040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/sonatype/guice/bean/inject/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.inject; import org.sonatype.guice.bean.reflect.BeanProperty; /** * Provides custom {@link PropertyBinding}s for bean properties such as fields or setter methods. */ public interface PropertyBinder { /** * Returns the appropriate {@link PropertyBinding} for the given bean property. * * @param property The bean property * @return Binding for the given property; {@code null} if no binding is applicable */ PropertyBinding bindProperty( BeanProperty property ); /** * Binders may return {@code LAST_BINDING} to indicate they are done binding a bean. */ PropertyBinding LAST_BINDING = new PropertyBinding() { public void injectProperty( final B bean ) { throw new UnsupportedOperationException( "LAST_BINDING" ); } }; } PropertyBinding.java000066400000000000000000000017701167051330000413670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/sonatype/guice/bean/inject/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.inject; /** * Represents a bean property that has been bound by a {@link PropertyBinder}. */ public interface PropertyBinding { /** * Injects the current bound value into the property of the given bean. * * @param bean The bean to inject */ void injectProperty( B bean ); } package-info.java000066400000000000000000000026171167051330000405750ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/main/java/org/sonatype/guice/bean/inject/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * Custom bean injection. * *

The principal members of this package are: *

*
{@link org.sonatype.guice.bean.inject.BeanListener} *
{@link com.google.inject.spi.TypeListener} that listens for bean types and wires up their properties. *
{@link org.sonatype.guice.bean.inject.BeanBinder} *
Provides custom {@link org.sonatype.guice.bean.inject.PropertyBinder}s for bean types. *
{@link org.sonatype.guice.bean.inject.PropertyBinder} *
Provides custom {@link org.sonatype.guice.bean.inject.PropertyBinding}s for bean properties. *
{@link org.sonatype.guice.bean.inject.PropertyBinding} *
Injects a customized bean property into bean instances. *
*/ package org.sonatype.guice.bean.inject; sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/test/000077500000000000000000000000001167051330000266635ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/test/java/000077500000000000000000000000001167051330000276045ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/test/java/org/000077500000000000000000000000001167051330000303735ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/test/java/org/sonatype/000077500000000000000000000000001167051330000322355ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/test/java/org/sonatype/guice/000077500000000000000000000000001167051330000333315ustar00rootroot00000000000000000077500000000000000000000000001167051330000341575ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/test/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000354335ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/test/java/org/sonatype/guice/bean/injectPropertyListenerTest.java000066400000000000000000000127511167051330000424760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-inject/src/test/java/org/sonatype/guice/bean/inject/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.inject; import junit.framework.TestCase; import org.sonatype.guice.bean.reflect.BeanProperty; import com.google.inject.AbstractModule; import com.google.inject.ConfigurationException; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.matcher.AbstractMatcher; import com.google.inject.spi.TypeEncounter; public class PropertyListenerTest extends TestCase { static class Base { String a; } static class Bean0 extends Base { String last; } static class Bean1 extends Base { String b; Bean2 bean; } static class Bean2 extends Base { String b; String last; String c; String ignore; String d; } static class Bean3 extends Base { String b; String error; String c; } static class Bean4 extends Bean1 { void setA( @SuppressWarnings( "unused" ) final String unused ) { assertNull( a ); // hidden by our setter method assertNotNull( b ); // should be injected first a = "correct order"; } } class NamedPropertyBinder implements PropertyBinder { public PropertyBinding bindProperty( final BeanProperty property ) { if ( "last".equals( property.getName() ) ) { return PropertyBinder.LAST_BINDING; } if ( "ignore".equals( property.getName() ) ) { return null; } if ( "error".equals( property.getName() ) ) { throw new RuntimeException( "Broken binding" ); } if ( "bean".equals( property.getName() ) ) { return new PropertyBinding() { public void injectProperty( final Object bean ) { property.set( bean, injector.getInstance( Key.get( property.getType() ) ) ); } }; } return new PropertyBinding() { @SuppressWarnings( "unchecked" ) public void injectProperty( final Object bean ) { property.set( bean, (T) ( property.getName() + "Value" ) ); } }; } } final PropertyBinder namedPropertyBinder = new NamedPropertyBinder(); Injector injector; @Override public void setUp() { injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindListener( new AbstractMatcher>() { public boolean matches( final TypeLiteral type ) { return Base.class.isAssignableFrom( type.getRawType() ); } }, new BeanListener( new BeanBinder() { public PropertyBinder bindBean( final TypeLiteral type, final TypeEncounter encounter ) { return type.getRawType().getName().contains( "Bean" ) ? namedPropertyBinder : null; } } ) ); } } ); } public void testNoBean() { final Base base = injector.getInstance( Base.class ); assertNull( base.a ); } public void testNoBindings() { final Bean0 bean0 = injector.getInstance( Bean0.class ); assertNull( bean0.a ); } public void testPropertyBindings() { final Bean1 bean1 = injector.getInstance( Bean1.class ); assertEquals( "bValue", bean1.b ); assertEquals( "aValue", bean1.a ); } public void testSpecialProperties() { final Bean2 bean2 = injector.getInstance( Bean2.class ); assertEquals( "dValue", bean2.d ); assertEquals( "cValue", bean2.c ); assertNull( bean2.b ); assertNull( bean2.a ); try { PropertyBinder.LAST_BINDING.injectProperty( bean2 ); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } } public void testBrokenBinding() { try { injector.getInstance( Bean3.class ); fail( "Expected ConfigurationException" ); } catch ( final ConfigurationException e ) { e.printStackTrace(); } } public void testInjectionOrder() { assertEquals( "correct order", injector.getInstance( Bean4.class ).a ); } } sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/000077500000000000000000000000001167051330000254675ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/pom.xml000066400000000000000000000031101167051330000267770ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-bean 2.3.0 guice-bean-locators Sisu-Inject-Bean : Dynamic bindings javax.inject javax.inject org.sonatype.sisu sisu-guice org.sonatype.sisu.inject guice-bean-reflect org.slf4j slf4j-api true sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/000077500000000000000000000000001167051330000262565ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/000077500000000000000000000000001167051330000272025ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/000077500000000000000000000000001167051330000301235ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/000077500000000000000000000000001167051330000307125ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/000077500000000000000000000000001167051330000325545ustar00rootroot00000000000000000077500000000000000000000000001167051330000335715ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000344765ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000363245ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locatorsBeanCache.java000066400000000000000000000151571167051330000407710ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.sonatype.inject.BeanEntry; import com.google.inject.Binding; /** * Atomic cache mapping {@link Binding}s to {@link BeanEntry}s; optimized for common case of single entries. *

* Uses {@code ==} instead of {@code equals} to compare {@link Binding}s because we want referential equality. */ @SuppressWarnings( { "rawtypes", "unchecked" } ) final class BeanCache extends AtomicReference { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final long serialVersionUID = 1L; private static final long REFRESH_MILLIS = 888L; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private Map, BeanEntry> readCache; private long lastTimeMillis; private volatile boolean mutated; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- /** * Atomically creates a new {@link BeanEntry} for the given {@link Binding} reference. * * @param qualifier The qualifier * @param binding The binding * @param rank The assigned rank * @return Associated bean entry */ public BeanEntry create( final Q qualifier, final Binding binding, final int rank ) { LazyBeanEntry newBean; Object o, n; /* * Compare-and-swap approach; avoids locking without missing any updates */ do { o = get(); if ( null == o ) { // most common case: adding the one (and-only) entry n = newBean = new LazyBeanEntry( qualifier, binding, rank ); } else if ( o instanceof LazyBeanEntry ) { final LazyBeanEntry oldBean = (LazyBeanEntry) o; if ( binding == oldBean.binding ) { return oldBean; } n = createMap( oldBean, newBean = new LazyBeanEntry( qualifier, binding, rank ) ); } else { synchronized ( this ) { final Map map = (Map) o; if ( null == ( newBean = map.get( binding ) ) ) { map.put( binding, newBean = new LazyBeanEntry( qualifier, binding, rank ) ); mutated = true; } return newBean; } } } while ( !compareAndSet( o, n ) ); return newBean; } public Map, BeanEntry> flush() { long now = 0; if ( mutated && ( null == readCache || ( now = System.currentTimeMillis() ) - lastTimeMillis > REFRESH_MILLIS ) ) { synchronized ( this ) { if ( mutated ) { readCache = (Map) ( (IdentityHashMap) get() ).clone(); lastTimeMillis = now == 0 ? System.currentTimeMillis() : now; mutated = false; } } } return readCache; } /** * Retrieves the {@link Binding} references currently associated with {@link BeanEntry}s. * * @return Associated bindings */ public Iterable> bindings() { final Object o = get(); if ( null == o ) { return Collections.EMPTY_SET; } else if ( o instanceof LazyBeanEntry ) { return Collections.singleton( ( (LazyBeanEntry) o ).binding ); } synchronized ( this ) { return new ArrayList( ( (Map) o ).keySet() ); } } /** * Removes the {@link BeanEntry} associated with the given {@link Binding} reference. * * @param binding The binding * @return Associated bean entry */ public BeanEntry remove( final Binding binding ) { LazyBeanEntry oldBean; Object o, n; /* * Compare-and-swap approach; avoids locking without missing any updates */ do { o = get(); if ( null == o ) { return null; } else if ( o instanceof LazyBeanEntry ) { oldBean = (LazyBeanEntry) o; if ( binding != oldBean.binding ) { return null; } n = null; // clear single entry } else { synchronized ( this ) { oldBean = ( (Map) o ).remove( binding ); if ( null != oldBean ) { readCache = null; mutated = true; } return oldBean; } } } while ( !compareAndSet( o, n ) ); return oldBean; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static Map createMap( final LazyBeanEntry one, final LazyBeanEntry two ) { final Map map = new IdentityHashMap(); map.put( one.binding, one ); map.put( two.binding, two ); return map; } } BeanDescription.java000066400000000000000000000020101167051330000422310ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import com.google.inject.Binder; /** * Binding source locations should implement this interface to supply descriptions to the {@link BeanLocator}. * * @see Binder#withSource(Object) */ public interface BeanDescription { /** * @return Human-readable description */ String getDescription(); } BeanLocator.java000066400000000000000000000034371167051330000413670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Annotation; import javax.inject.Qualifier; import org.sonatype.inject.BeanEntry; import org.sonatype.inject.Mediator; import com.google.inject.ImplementedBy; import com.google.inject.Key; /** * Finds and tracks bean implementations annotated with {@link Qualifier} annotations. */ @ImplementedBy( MutableBeanLocator.class ) public interface BeanLocator { /** * Finds bean implementations that match the given qualified binding {@link Key}. * * @param key The qualified key * @return Sequence of bean entries that match the given key */ Iterable> locate( Key key ); /** * Tracks bean implementations that match the given qualified binding {@link Key}. *

* Uses the {@link Mediator} pattern to send events to an arbitrary watcher object. * * @param key The qualified key * @param mediator The event mediator * @param watcher The bean watcher */ void watch( Key key, Mediator mediator, W watcher ); } DefaultBeanLocator.java000066400000000000000000000150541167051330000426720ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; import javax.inject.Inject; import javax.inject.Singleton; import org.sonatype.guice.bean.locators.spi.BindingPublisher; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.reflect.Soft; import org.sonatype.guice.bean.reflect.TypeParameters; import org.sonatype.guice.bean.reflect.Weak; import org.sonatype.inject.BeanEntry; import org.sonatype.inject.Mediator; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; /** * Default {@link MutableBeanLocator} that locates qualified beans across a dynamic group of {@link BindingPublisher}s. */ @Singleton @SuppressWarnings( { "rawtypes", "unchecked" } ) public final class DefaultBeanLocator extends ReentrantLock implements MutableBeanLocator { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final long serialVersionUID = 1L; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final RankedSequence publishers = new RankedSequence(); private final ConcurrentMap cachedBindings = Soft.concurrentValues( 256, 8 ); // reverse mapping; can't use watcher as key since it may not be unique private final Map cachedWatchers = Weak.values(); private final ImplicitBindings implicitBindings = new ImplicitBindings( publishers ); // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterable locate( final Key key ) { final TypeLiteral type = key.getTypeLiteral(); RankedBindings bindings = cachedBindings.get( type ); if ( null == bindings ) { lock(); try { bindings = new RankedBindings( type, publishers ); final RankedBindings oldBindings = cachedBindings.putIfAbsent( type, bindings ); if ( null != oldBindings ) { bindings = oldBindings; } } finally { unlock(); } } final boolean isImplicit = key.getAnnotationType() == null && TypeParameters.isImplicit( type ); return new LocatedBeans( key, bindings, isImplicit ? implicitBindings : null ); } public void watch( final Key key, final Mediator mediator, final Object watcher ) { lock(); try { final WatchedBeans beans = new WatchedBeans( key, mediator, watcher ); for ( final BindingPublisher p : publishers.snapshot() ) { p.subscribe( beans ); } cachedWatchers.put( beans, watcher ); } finally { unlock(); } } public void add( final BindingPublisher publisher, final int rank ) { lock(); try { if ( !publishers.contains( publisher ) ) { Logs.debug( "Add publisher: {}", publisher, null ); publishers.insert( publisher, rank ); for ( final RankedBindings bindings : cachedBindings.values() ) { bindings.add( publisher, rank ); } for ( final WatchedBeans beans : cachedWatchers.keySet() ) { publisher.subscribe( beans ); } } } finally { unlock(); } } public void remove( final BindingPublisher publisher ) { lock(); try { if ( publishers.remove( publisher ) ) { Logs.debug( "Remove publisher: {}", publisher, null ); for ( final RankedBindings bindings : cachedBindings.values() ) { bindings.remove( publisher ); } for ( final WatchedBeans beans : cachedWatchers.keySet() ) { publisher.unsubscribe( beans ); } } } finally { unlock(); } } public void clear() { lock(); try { for ( final BindingPublisher p : publishers.snapshot() ) { remove( p ); } } finally { unlock(); } } public void add( final Injector injector, final int rank ) { add( new InjectorPublisher( injector, new DefaultRankingFunction( rank ) ), rank ); } public void remove( final Injector injector ) { remove( new InjectorPublisher( injector, null ) ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Automatically publishes any {@link Injector} that contains a binding to this {@link BeanLocator}. * * @param injector The injector */ @Inject void autoPublish( final Injector injector ) { staticAutoPublish( this, injector ); } @Inject static void staticAutoPublish( final MutableBeanLocator locator, final Injector injector ) { final RankingFunction function = injector.getInstance( RankingFunction.class ); locator.add( new InjectorPublisher( injector, function ), function.maxRank() ); } } DefaultRankingFunction.java000066400000000000000000000046001167051330000435730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import javax.inject.Inject; import com.google.inject.Binding; /** * Simple {@link RankingFunction} that partitions qualified bindings into two main groups. *

* Default bindings are given zero or positive ranks; the rest are given negative ranks. */ public final class DefaultRankingFunction implements RankingFunction { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final int primaryRank; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public DefaultRankingFunction( final int primaryRank ) { if ( primaryRank < 0 ) { throw new IllegalArgumentException( "Primary rank must be zero or more" ); } this.primaryRank = primaryRank; } @Inject public DefaultRankingFunction() { this( 0 ); // use this as the default primary rank unless otherwise configured } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public int maxRank() { return primaryRank; } public int rank( final Binding binding ) { if ( QualifyingStrategy.DEFAULT_QUALIFIER.equals( QualifyingStrategy.qualify( binding.getKey() ) ) ) { return primaryRank; } return primaryRank + Integer.MIN_VALUE; // shifts primary range of [0,MAX_VALUE] down to [MIN_VALUE,-1] } } EntryListAdapter.java000066400000000000000000000146311167051330000424320ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.AbstractSequentialList; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * {@link List} backed by an {@link Iterable} sequence of map entries. */ public final class EntryListAdapter extends AbstractSequentialList { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterable> iterable; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public EntryListAdapter( final Iterable> iterable ) { this.iterable = iterable; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public Iterator iterator() { return new ValueIterator( iterable ); } @Override public ListIterator listIterator( final int index ) { return new ValueListIterator( iterable, index ); } @Override public boolean isEmpty() { return false == iterator().hasNext(); } @Override public int size() { int size = 0; for ( final Iterator i = iterable.iterator(); i.hasNext(); i.next() ) { size++; } return size; } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Value {@link Iterator} backed by a Key:Value {@link Iterator}. */ private static final class ValueIterator implements Iterator { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterator> iterator; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ValueIterator( final Iterable> iterable ) { this.iterator = iterable.iterator(); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public V next() { return iterator.next().getValue(); } public void remove() { throw new UnsupportedOperationException(); } } /** * Value {@link ListIterator} backed by a cached Key:Value {@link Iterator}. */ private static final class ValueListIterator implements ListIterator { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterator> iterator; private final List> entryCache = new ArrayList>(); private int index; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ValueListIterator( final Iterable> iterable, final int index ) { if ( index < 0 ) { throw new IndexOutOfBoundsException(); } this.iterator = iterable.iterator(); try { while ( this.index < index ) { next(); // position iterator at the index position } } catch ( final NoSuchElementException e ) { throw new IndexOutOfBoundsException(); } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { return index < entryCache.size() || iterator.hasNext(); } public boolean hasPrevious() { return index > 0; } public V next() { if ( index >= entryCache.size() ) { entryCache.add( iterator.next() ); } return entryCache.get( index++ ).getValue(); } public V previous() { if ( index <= 0 ) { throw new NoSuchElementException(); } return entryCache.get( --index ).getValue(); } public int nextIndex() { return index; } public int previousIndex() { return index - 1; } public void add( final V o ) { throw new UnsupportedOperationException(); } public void set( final V o ) { throw new UnsupportedOperationException(); } public void remove() { throw new UnsupportedOperationException(); } } } EntryMapAdapter.java000066400000000000000000000070421167051330000422320ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * {@link Map} backed by an {@link Iterable} sequence of map entries. */ public final class EntryMapAdapter extends AbstractMap { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Set> entrySet; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public EntryMapAdapter( final Iterable> iterable ) { entrySet = new EntrySet( iterable ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public Set> entrySet() { return entrySet; } @Override public boolean isEmpty() { return entrySet.isEmpty(); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Entry {@link Set} backed by an {@link Iterable} sequence of map entries. */ private static final class EntrySet extends AbstractSet> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterable> iterable; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- @SuppressWarnings( "unchecked" ) EntrySet( final Iterable> iterable ) { this.iterable = (Iterable>) iterable; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public Iterator> iterator() { return iterable.iterator(); } @Override public boolean isEmpty() { return false == iterator().hasNext(); } @Override public int size() { int size = 0; for ( final Iterator i = iterable.iterator(); i.hasNext(); i.next() ) { size++; } return size; } } } EntrySetAdapter.java000066400000000000000000000067611167051330000422570ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.AbstractSet; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; /** * {@link Set} backed by an {@link Iterable} sequence of map entries. */ public final class EntrySetAdapter extends AbstractSet { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterable> iterable; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public EntrySetAdapter( final Iterable> iterable ) { this.iterable = iterable; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public Iterator iterator() { return new ValueIterator( iterable ); } @Override public boolean isEmpty() { return false == iterator().hasNext(); } @Override public int size() { int size = 0; for ( final Iterator i = iterable.iterator(); i.hasNext(); i.next() ) { size++; } return size; } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Value {@link Iterator} backed by a Key:Value {@link Iterator}. */ private static final class ValueIterator implements Iterator { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterator> iterator; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ValueIterator( final Iterable> iterable ) { this.iterator = iterable.iterator(); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public V next() { return iterator.next().getValue(); } public void remove() { throw new UnsupportedOperationException(); } } } HiddenBinding.java000066400000000000000000000016531167051330000416620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import com.google.inject.Binder; /** * Binding source locations should implement this interface to hide bindings from the {@link BeanLocator}. * * @see Binder#withSource(Object) */ public interface HiddenBinding { } ImplementationVisitor.java000066400000000000000000000064011167051330000435350ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import org.sonatype.guice.bean.reflect.DeferredProvider; import com.google.inject.Provider; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.ConstructorBinding; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.ExposedBinding; import com.google.inject.spi.InstanceBinding; import com.google.inject.spi.LinkedKeyBinding; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.UntargettedBinding; /** * {@link BindingTargetVisitor} that attempts to discover implementations behind bindings. */ final class ImplementationVisitor extends DefaultBindingTargetVisitor> { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- static final ImplementationVisitor THIS = new ImplementationVisitor(); // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public Class visit( final UntargettedBinding binding ) { return binding.getKey().getTypeLiteral().getRawType(); } @Override public Class visit( final LinkedKeyBinding binding ) { // this assumes only one level of indirection: api-->impl return binding.getLinkedKey().getTypeLiteral().getRawType(); } @Override public Class visit( final ConstructorBinding binding ) { return binding.getConstructor().getDeclaringType().getRawType(); } @Override public Class visit( final InstanceBinding binding ) { return binding.getInstance().getClass(); } @Override public Class visit( final ProviderInstanceBinding binding ) { final Provider provider = binding.getProviderInstance(); if ( provider instanceof DeferredProvider ) { try { // deferred providers let us peek at the underlying implementation type return ( (DeferredProvider) provider ).getImplementationClass().load(); } catch ( final TypeNotPresentException e ) // NOPMD { // fall-through } } return null; } @Override public Class visit( final ExposedBinding binding ) { return binding.getPrivateElements().getInjector().getBinding( binding.getKey() ).acceptTargetVisitor( this ); } } Implicit.java000066400000000000000000000020431167051330000407400ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier; /** * {@link Qualifier} used to record and tag implicit bindings (not for direct use). */ @Qualifier @Retention( RetentionPolicy.RUNTIME ) @Target( value = {} ) public @interface Implicit { } ImplicitBindings.java000066400000000000000000000072261167051330000424260ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import org.sonatype.guice.bean.locators.spi.BindingPublisher; import org.sonatype.guice.bean.reflect.Logs; import com.google.inject.Binding; import com.google.inject.ImplementedBy; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.ProvidedBy; import com.google.inject.TypeLiteral; /** * Source of "implicit" bindings; includes @{@link ImplementedBy}, @{@link ProvidedBy}, and concrete types. */ final class ImplicitBindings { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterable publishers; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ImplicitBindings( final Iterable publishers ) { this.publishers = publishers; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @SuppressWarnings( { "unchecked", "rawtypes" } ) public Binding get( final TypeLiteral type ) { final Key implicitKey = Key.get( type.getRawType(), Implicit.class ); for ( final BindingPublisher p : publishers ) { if ( p instanceof InjectorPublisher ) { // first round: check for any re-written implicit bindings final Injector i = ( (InjectorPublisher) p ).getInjector(); final Binding binding = i.getBindings().get( implicitKey ); if ( null != binding ) { Logs.debug( "Using implicit binding: {} from: <>", binding, i ); return binding; } } } final Key justInTimeKey = Key.get( type ); for ( final BindingPublisher p : publishers ) { if ( p instanceof InjectorPublisher ) { // second round: fall back to just-in-time binding lookup final Injector i = ( (InjectorPublisher) p ).getInjector(); try { final Binding binding = i.getBinding( justInTimeKey ); if ( InjectorPublisher.isVisible( binding ) ) { Logs.debug( "Using just-in-time binding: {} from: <>", binding, i ); return binding; } } catch ( final RuntimeException e ) // NOPMD { // no luck, move onto next injector } catch ( final LinkageError e ) // NOPMD { // no luck, move onto next injector } } } return null; } } InjectorPublisher.java000066400000000000000000000126231167051330000426260ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.List; import java.util.Map; import org.sonatype.guice.bean.locators.spi.BindingPublisher; import org.sonatype.guice.bean.locators.spi.BindingSubscriber; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.reflect.TypeParameters; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; /** * Publisher of {@link Binding}s from a single {@link Injector}; ranked according to a given {@link RankingFunction}. */ final class InjectorPublisher implements BindingPublisher { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final TypeLiteral OBJECT_TYPE_LITERAL = TypeLiteral.get( Object.class ); // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Injector injector; private final RankingFunction function; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- InjectorPublisher( final Injector injector, final RankingFunction function ) { this.injector = injector; this.function = function; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Injector getInjector() { return injector; } public void subscribe( final BindingSubscriber subscriber ) { final TypeLiteral type = subscriber.type(); publishBindings( type, subscriber, null ); final Class clazz = type.getRawType(); if ( clazz != type.getType() ) { publishBindings( TypeLiteral.get( clazz ), subscriber, type ); } if ( clazz != Object.class ) { publishBindings( OBJECT_TYPE_LITERAL, subscriber, type ); } } public void unsubscribe( final BindingSubscriber subscriber ) { final Map, ?> ourBindings = injector.getBindings(); for ( final Binding binding : subscriber.bindings() ) { if ( binding == ourBindings.get( binding.getKey() ) ) { subscriber.remove( binding ); } } } @Override public int hashCode() { return injector.hashCode(); } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof InjectorPublisher ) { return injector.equals( ( (InjectorPublisher) rhs ).injector ); } return false; } @Override public String toString() { return Logs.toString( injector ); } // ---------------------------------------------------------------------- // Local methods // ---------------------------------------------------------------------- static boolean isVisible( final Binding binding ) { return false == binding.getSource() instanceof HiddenBinding; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static boolean isAssignableFrom( final TypeLiteral superType, final Binding binding ) { // don't match the exact implementation as it's already covered by an explicit binding final Class implementation = binding.acceptTargetVisitor( ImplementationVisitor.THIS ); if ( null != implementation && superType.getRawType() != implementation ) { return TypeParameters.isAssignableFrom( superType, TypeLiteral.get( implementation ) ); } return false; } @SuppressWarnings( { "rawtypes", "unchecked" } ) private void publishBindings( final TypeLiteral searchType, final BindingSubscriber subscriber, final TypeLiteral superType ) { final List> bindings = injector.findBindingsByType( searchType ); for ( int i = 0, size = bindings.size(); i < size; i++ ) { final Binding binding = bindings.get( i ); if ( isVisible( binding ) && ( null == superType || isAssignableFrom( superType, binding ) ) ) { subscriber.add( binding, function.rank( binding ) ); } } } } LazyBeanEntry.java000066400000000000000000000143041167051330000417200ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Annotation; import javax.inject.Provider; import org.sonatype.inject.BeanEntry; import org.sonatype.inject.Description; import com.google.inject.Binding; import com.google.inject.Scopes; /** * Lazy {@link BeanEntry} backed by a qualified {@link Binding} and an assigned rank. */ final class LazyBeanEntry implements BeanEntry { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Q qualifier; final Binding binding; private final Provider provider; private final int rank; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- @SuppressWarnings( "unchecked" ) LazyBeanEntry( final Q qualifier, final Binding binding, final int rank ) { if ( null != qualifier && com.google.inject.name.Named.class == qualifier.annotationType() ) { this.qualifier = (Q) new JsrNamed( (com.google.inject.name.Named) qualifier ); } else { this.qualifier = qualifier; } this.binding = binding; this.rank = rank; if ( Scopes.isSingleton( binding ) ) { this.provider = binding.getProvider(); } else { // use Guice's singleton logic to get lazy-loading without introducing extra locks this.provider = Scopes.SINGLETON.scope( binding.getKey(), binding.getProvider() ); } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Q getKey() { return qualifier; } public T getValue() { return provider.get(); } public T setValue( final T value ) { throw new UnsupportedOperationException(); } public Provider getProvider() { return binding.getProvider(); } public String getDescription() { final Object source = binding.getSource(); if ( source instanceof BeanDescription ) { return ( (BeanDescription) source ).getDescription(); } final Class clazz = getImplementationClass(); if ( null != clazz ) { final Description description = clazz.getAnnotation( Description.class ); if ( null != description ) { return description.value(); } } return null; } @SuppressWarnings( "unchecked" ) public Class getImplementationClass() { return (Class) binding.acceptTargetVisitor( ImplementationVisitor.THIS ); } public Object getSource() { return binding.getSource(); } public int getRank() { return rank; } @Override public String toString() { final StringBuilder buf = new StringBuilder().append( getKey() ).append( '=' ); try { buf.append( getValue() ); } catch ( final RuntimeException e ) { buf.append( e ); } return buf.toString(); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Implementation of @{@link javax.inject.Named} that can also act like @{@link com.google.inject.name.Named}. */ private static final class JsrNamed implements com.google.inject.name.Named, javax.inject.Named { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final String value; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- JsrNamed( final com.google.inject.name.Named named ) { value = named.value(); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public String value() { return value; } public Class annotationType() { return javax.inject.Named.class; } @Override public int hashCode() { return 127 * "value".hashCode() ^ value.hashCode(); } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof com.google.inject.name.Named ) { return value.equals( ( (com.google.inject.name.Named) rhs ).value() ); } if ( rhs instanceof javax.inject.Named ) { return value.equals( ( (javax.inject.Named) rhs ).value() ); } return false; } @Override public String toString() { return "@" + javax.inject.Named.class.getName() + "(value=" + value + ")"; } } } LocatedBeans.java000066400000000000000000000120501167051330000415110ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Annotation; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import org.sonatype.inject.BeanEntry; import com.google.inject.Binding; import com.google.inject.Key; /** * Provides a sequence of {@link BeanEntry}s by iterating over qualified {@link Binding}s. * * @see BeanLocator#locate(Key) */ final class LocatedBeans implements Iterable> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- final Key key; final RankedBindings explicitBindings; final ImplicitBindings implicitBindings; final QualifyingStrategy strategy; final BeanCache beans; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- LocatedBeans( final Key key, final RankedBindings explicitBindings, final ImplicitBindings implicitBindings ) { this.key = key; this.explicitBindings = explicitBindings; this.implicitBindings = implicitBindings; strategy = QualifyingStrategy.selectFor( key ); beans = explicitBindings.newBeanCache(); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterator> iterator() { return new Itr(); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * {@link BeanEntry} iterator that creates new elements from {@link Binding}s as required. */ final class Itr implements Iterator> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final RankedBindings.Itr itr = explicitBindings.iterator(); private final Map, BeanEntry> readCache = beans.flush(); private boolean checkImplicitBindings = implicitBindings != null; private BeanEntry nextBean; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @SuppressWarnings( "unchecked" ) public boolean hasNext() { if ( null != nextBean ) { return true; } while ( itr.hasNext() ) { final Binding binding = itr.next(); if ( null != readCache && null != ( nextBean = readCache.get( binding ) ) ) { return true; } final Q qualifier = (Q) strategy.qualifies( key, binding ); if ( null != qualifier ) { nextBean = beans.create( qualifier, binding, itr.rank() ); return true; } } if ( checkImplicitBindings ) { // last-chance, see if we can locate a valid implicit binding somewhere final Binding binding = implicitBindings.get( key.getTypeLiteral() ); if ( null != binding ) { nextBean = beans.create( (Q) QualifyingStrategy.DEFAULT_QUALIFIER, binding, Integer.MIN_VALUE ); return true; } } return false; } public BeanEntry next() { if ( hasNext() ) { // no need to check this again checkImplicitBindings = false; // populated by hasNext() final BeanEntry bean = nextBean; nextBean = null; return bean; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } } } MutableBeanLocator.java000066400000000000000000000034701167051330000426760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import org.sonatype.guice.bean.locators.spi.BindingDistributor; import org.sonatype.guice.bean.locators.spi.BindingPublisher; import com.google.inject.Binding; import com.google.inject.ImplementedBy; import com.google.inject.Injector; /** * Mutable {@link BeanLocator} that finds and tracks bindings across zero or more {@link BindingPublisher}s. */ @ImplementedBy( DefaultBeanLocator.class ) public interface MutableBeanLocator extends BeanLocator, BindingDistributor { /** * Adds the given ranked {@link Injector} and distributes its {@link Binding}s. Marked as deprecated because most * clients should not call this method; any injector that contains a binding to the {@link BeanLocator} is * automatically added to that locator as part of the bootstrapping process. * * @param injector The new injector * @param rank The assigned rank */ @Deprecated void add( Injector injector, int rank ); /** * Removes the given {@link Injector} and its {@link Binding}s. * * @param injector The old injector */ void remove( Injector injector ); } NamedIterableAdapter.java000066400000000000000000000110471167051330000431670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.Iterator; import java.util.Map.Entry; import com.google.inject.name.Named; /** * String mapping {@link Iterable} backed by a {@link Named} mapping {@link Iterable}. */ public final class NamedIterableAdapter implements Iterable> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterable> delegate; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public NamedIterableAdapter( final Iterable> delegate ) { this.delegate = delegate; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterator> iterator() { return new NamedIterator( delegate ); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * String mapping {@link Iterator} backed by a {@link Named} mapping {@link Iterator}. */ private static final class NamedIterator implements Iterator> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterator> iterator; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- NamedIterator( final Iterable> iterable ) { iterator = iterable.iterator(); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public Entry next() { return new NamedEntry( iterator.next() ); } public void remove() { throw new UnsupportedOperationException(); } } /** * String mapping {@link Entry} backed by a {@link Named} mapping {@link Entry}. */ private static final class NamedEntry implements Entry { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Entry entry; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- NamedEntry( final Entry entry ) { this.entry = entry; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public String getKey() { return entry.getKey().value(); } public V getValue() { return entry.getValue(); } public V setValue( final V value ) { throw new UnsupportedOperationException(); } @Override public String toString() { return getKey() + "=" + getValue(); } } } ProviderIterableAdapter.java000066400000000000000000000113771167051330000437430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Annotation; import java.util.Iterator; import java.util.Map.Entry; import javax.inject.Provider; import org.sonatype.inject.BeanEntry; /** * {@link Iterable} sequence of {@link Provider} entries backed by a sequence of {@link BeanEntry}s. */ public final class ProviderIterableAdapter implements Iterable>> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterable> delegate; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public ProviderIterableAdapter( final Iterable> delegate ) { this.delegate = delegate; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterator>> iterator() { return new ProviderIterator( delegate ); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Iterator of {@link Provider} {@link Entry}s backed by an iterator of {@link BeanEntry}s. */ private static final class ProviderIterator implements Iterator>> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterator> iterator; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ProviderIterator( final Iterable> iterable ) { iterator = iterable.iterator(); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public Entry> next() { return new ProviderEntry( iterator.next() ); } public void remove() { throw new UnsupportedOperationException(); } } /** * {@link Provider} {@link Entry} backed by a {@link BeanEntry}. */ private static final class ProviderEntry implements Entry> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final BeanEntry entry; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ProviderEntry( final BeanEntry entry ) { this.entry = entry; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public K getKey() { return entry.getKey(); } public Provider getValue() { return entry.getProvider(); } public Provider setValue( final Provider value ) { throw new UnsupportedOperationException(); } @Override public String toString() { return getKey() + "=" + getValue(); } } } QualifyingStrategy.java000066400000000000000000000122361167051330000430260ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Annotation; import javax.inject.Qualifier; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.name.Named; import com.google.inject.name.Names; /** * Enumerates the different strategies for qualifying {@link Binding}s against requirement {@link Key}s. */ enum QualifyingStrategy { // ---------------------------------------------------------------------- // Enumerated values // ---------------------------------------------------------------------- UNRESTRICTED { @Override final Annotation qualifies( final Key requirement, final Binding binding ) { final Annotation qualifier = qualify( binding.getKey() ); return null != qualifier ? qualifier : BLANK_QUALIFIER; } }, NAMED { @Override final Annotation qualifies( final Key requirement, final Binding binding ) { final Annotation qualifier = qualify( binding.getKey() ); return qualifier instanceof Named ? qualifier : null; } }, NAMED_WITH_ATTRIBUTES { @Override final Annotation qualifies( final Key requirement, final Binding binding ) { final Annotation qualifier = qualify( binding.getKey() ); return requirement.getAnnotation().equals( qualifier ) ? qualifier : null; } }, MARKED { @Override final Annotation qualifies( final Key requirement, final Binding binding ) { final Class markerType = requirement.getAnnotationType(); final Annotation qualifier = qualify( binding.getKey() ); if ( markerType.isInstance( qualifier ) ) { return qualifier; } final Class implementation = binding.acceptTargetVisitor( ImplementationVisitor.THIS ); return null != implementation ? implementation.getAnnotation( markerType ) : null; } }, MARKED_WITH_ATTRIBUTES { @Override final Annotation qualifies( final Key requirement, final Binding binding ) { final Annotation qualifier = MARKED.qualifies( requirement, binding ); return requirement.getAnnotation().equals( qualifier ) ? qualifier : null; } }; // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- static final Annotation DEFAULT_QUALIFIER = Names.named( "default" ); static final Annotation BLANK_QUALIFIER = Names.named( "" ); // ---------------------------------------------------------------------- // Local methods // ---------------------------------------------------------------------- /** * Attempts to qualify the given {@link Binding} against the requirement {@link Key}. * * @param requirement The requirement key * @param binding The binding to qualify * @return Qualifier annotation when the binding qualifies; otherwise {@code null} */ abstract Annotation qualifies( final Key requirement, final Binding binding ); /** * Selects the appropriate qualifying strategy for the given requirement {@link Key}. * * @param key The requirement key * @return Qualifying strategy */ static final QualifyingStrategy selectFor( final Key key ) { final Class qualifierType = key.getAnnotationType(); if ( null == qualifierType ) { return QualifyingStrategy.UNRESTRICTED; } if ( Named.class == qualifierType ) { return key.hasAttributes() ? QualifyingStrategy.NAMED_WITH_ATTRIBUTES : QualifyingStrategy.NAMED; } return key.hasAttributes() ? QualifyingStrategy.MARKED_WITH_ATTRIBUTES : QualifyingStrategy.MARKED; } /** * Computes a canonical {@link Qualifier} annotation for the given binding {@link Key}. * * @param key The key to qualify * @return Qualifier for the key */ static final Annotation qualify( final Key key ) { if ( key instanceof WildcardKey ) { final Annotation qualifier = ( (WildcardKey) key ).getQualifier(); return null != qualifier ? qualifier : DEFAULT_QUALIFIER; } return null != key.getAnnotationType() ? key.getAnnotation() : DEFAULT_QUALIFIER; } } RankedBindings.java000066400000000000000000000132531167051330000420550ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Iterator; import org.sonatype.guice.bean.locators.spi.BindingPublisher; import org.sonatype.guice.bean.locators.spi.BindingSubscriber; import org.sonatype.guice.bean.reflect.Weak; import com.google.inject.Binding; import com.google.inject.TypeLiteral; /** * Ordered sequence of {@link Binding}s of a given type; subscribes to {@link BindingPublisher}s on demand. */ final class RankedBindings implements Iterable>, BindingSubscriber { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- final transient RankedSequence> bindings = new RankedSequence>(); final transient TypeLiteral type; final transient RankedSequence pendingPublishers; final Collection> cachedBeans = Weak.elements(); volatile int topRank = Integer.MAX_VALUE; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- RankedBindings( final TypeLiteral type, final RankedSequence publishers ) { this.type = type; this.pendingPublishers = new RankedSequence( publishers ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public TypeLiteral type() { return type; } public void add( final Binding binding, final int rank ) { bindings.insert( binding, rank ); } public void remove( final Binding binding ) { if ( bindings.removeThis( binding ) ) { synchronized ( cachedBeans ) { for ( final BeanCache beans : cachedBeans ) { beans.remove( binding ); } } } } public Iterable> bindings() { return bindings.snapshot(); } public Itr iterator() { return new Itr(); } // ---------------------------------------------------------------------- // Local methods // ---------------------------------------------------------------------- BeanCache newBeanCache() { final BeanCache beans = new BeanCache(); synchronized ( cachedBeans ) { cachedBeans.add( beans ); } return beans; } void add( final BindingPublisher publisher, final int rank ) { /* * No need to lock; ranked sequence is thread-safe. */ pendingPublishers.insert( publisher, rank ); if ( rank > topRank ) { topRank = rank; } } void remove( final BindingPublisher publisher ) { /* * Lock just to prevent subscription race condition. */ synchronized ( pendingPublishers ) { if ( !pendingPublishers.remove( publisher ) ) { publisher.unsubscribe( this ); } } } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * {@link Binding} iterator that only subscribes to {@link BindingPublisher}s as required. */ final class Itr implements Iterator> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final RankedSequence>.Itr itr = bindings.iterator(); // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { int rank = topRank; if ( rank > Integer.MIN_VALUE && rank > itr.peekNextRank() ) { synchronized ( pendingPublishers ) { while ( ( rank = pendingPublishers.topRank() ) > Integer.MIN_VALUE && rank > itr.peekNextRank() ) { pendingPublishers.poll().subscribe( RankedBindings.this ); } topRank = rank; } } return itr.hasNext(); } public Binding next() { return itr.next(); } public int rank() { return itr.rank(); } public void remove() { throw new UnsupportedOperationException(); } } } RankedSequence.java000066400000000000000000000305331167051330000420700ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicReference; /** * Ordered {@link List} that arranges elements by descending rank; supports concurrent iteration and modification. */ final class RankedSequence extends AtomicReference implements Iterable { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final long serialVersionUID = 1L; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- RankedSequence() { // nothing to do } RankedSequence( final RankedSequence sequence ) { if ( null != sequence ) { set( sequence.get() ); } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- /** * Inserts the given element into the ordered list, using the assigned rank as a guide. *

* The rank can be any value from {@link Integer#MIN_VALUE} to {@link Integer#MAX_VALUE}. * * @param element The element to insert * @param rank The assigned rank */ public void insert( final T element, final int rank ) { Content o, n; do { n = null != ( o = get() ) ? o.insert( element, rank ) : new Content( element, rank ); } while ( !compareAndSet( o, n ) ); } @SuppressWarnings( "unchecked" ) public T poll() { final Content content = get(); set( content.remove( 0 ) ); return (T) content.objs[0]; } public int topRank() { final Content content = get(); return null != content ? uid2rank( content.uids[0] ) : Integer.MIN_VALUE; } public boolean contains( final Object element ) { final Content content = get(); return null != content && content.indexOf( element ) >= 0; } public boolean containsThis( final Object element ) { final Content content = get(); return null != content && content.indexOfThis( element ) >= 0; } public boolean remove( final Object element ) { Content o, n; do { final int index; if ( null == ( o = get() ) || ( index = o.indexOf( element ) ) < 0 ) { return false; } n = o.remove( index ); } while ( !compareAndSet( o, n ) ); return true; } public boolean removeThis( final T element ) { Content o, n; do { final int index; if ( null == ( o = get() ) || ( index = o.indexOfThis( element ) ) < 0 ) { return false; } n = o.remove( index ); } while ( !compareAndSet( o, n ) ); return true; } @SuppressWarnings( { "rawtypes", "unchecked" } ) public Iterable snapshot() { final Content content = get(); return null != content ? (List) Arrays.asList( content.objs ) : Collections.EMPTY_SET; } public void clear() { set( null ); } public boolean isEmpty() { return null == get(); } public int size() { final Content content = get(); return null != content ? content.objs.length : 0; } public Itr iterator() { return new Itr(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Turns the given (potentially non-unique) rank into a unique id by appending a counter. * * @param rank The assigned rank * @param uniq The unique counter * @return The unique id */ static long rank2uid( final int rank, final int uniq ) { return (long) ~rank << 32 | 0x00000000FFFFFFFFL & uniq; } /** * Extracts the original (potentially non-unique) assigned rank from the given unique id. * * @param uid The unique id * @return Assigned rank */ static int uid2rank( final long uid ) { return (int) ( ~uid >>> 32 ); } /** * Finds the insertion point with the nearest UID, regardless of whether the UID is in the list or not. *

* Unlike {@link Arrays#binarySearch} this will always return a number from zero to {@link #size()} inclusive. * * @param uids The UIDs array * @param uid The UID to find * @return Index with nearest UID */ static int safeBinarySearch( final long[] uids, final long uid ) { if ( uid < uids[0] ) { return 0; } int min = 0; int max = uids.length - 1; while ( min < max ) { final int m = min + max >>> 1; if ( uid <= uids[m] ) { max = m; } else { min = m + 1; } } if ( min == uids.length - 1 && uids[min] < uid ) { min++; // append } return min; } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- static final class Content { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- final Object[] objs; final long[] uids; final int uniq; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- Content( final Object element, final int rank ) { objs = new Object[] { element }; uids = new long[] { rank2uid( rank, 0 ) }; uniq = 1; } Content( final Object[] objs, final long[] uids, final int uniq ) { this.objs = objs; this.uids = uids; this.uniq = uniq; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public int indexOf( final Object element ) { for ( int i = 0; i < objs.length; i++ ) { if ( element.equals( objs[i] ) ) { return i; } } return -1; } public int indexOfThis( final Object element ) { for ( int i = 0; i < objs.length; i++ ) { if ( element == objs[i] ) { return i; } } return -1; } public Content insert( final Object element, final int rank ) { final int size = objs.length + 1; final Object[] newObjs = new Object[size]; final long[] newUIDs = new long[size]; final long uid = rank2uid( rank, uniq ); final int index = safeBinarySearch( uids, uid ); if ( index > 0 ) { System.arraycopy( objs, 0, newObjs, 0, index ); System.arraycopy( uids, 0, newUIDs, 0, index ); } newObjs[index] = element; newUIDs[index] = uid; final int destPos = index + 1, len = size - destPos; if ( len > 0 ) { System.arraycopy( objs, index, newObjs, destPos, len ); System.arraycopy( uids, index, newUIDs, destPos, len ); } return new Content( newObjs, newUIDs, uniq + 1 ); } public Content remove( final int index ) { if ( objs.length == 1 ) { return null; } final int size = objs.length - 1; final Object[] newObjs = new Object[size]; final long[] newUIDs = new long[size]; if ( index > 0 ) { System.arraycopy( objs, 0, newObjs, 0, index ); System.arraycopy( uids, 0, newUIDs, 0, index ); } final int srcPos = index + 1, len = size - index; if ( len > 0 ) { System.arraycopy( objs, srcPos, newObjs, index, len ); System.arraycopy( uids, srcPos, newUIDs, index, len ); } return new Content( newObjs, newUIDs, uniq ); } } /** * Custom {@link Iterator} that copes with modification by repositioning itself in the updated list. */ final class Itr implements Iterator { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private Content content; private T nextObj; private long nextUID = Long.MIN_VALUE; private int index = -1; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @SuppressWarnings( "unchecked" ) public boolean hasNext() { if ( null != nextObj ) { return true; } final Content newContent = get(); if ( content != newContent ) { index = null != newContent ? safeBinarySearch( newContent.uids, nextUID ) : -1; content = newContent; } if ( index >= 0 && index < content.objs.length ) { nextObj = (T) content.objs[index]; nextUID = content.uids[index]; return true; } return false; } /** * @return Rank assigned to the next element; returns {@link Integer#MIN_VALUE} if there is no next element. */ public int peekNextRank() { if ( null != nextObj ) { return uid2rank( nextUID ); } final Content newContent = get(); if ( content != newContent ) { index = null != newContent ? safeBinarySearch( newContent.uids, nextUID ) : -1; content = newContent; } if ( index >= 0 && index < content.uids.length ) { return uid2rank( content.uids[index] ); } return Integer.MIN_VALUE; } public T next() { if ( hasNext() ) { nextUID++; // guarantees progress when re-positioning index++; // populated by hasNext() final T element = nextObj; nextObj = null; return element; } throw new NoSuchElementException(); } public int rank() { return uid2rank( nextUID ); } public void remove() { throw new UnsupportedOperationException(); } } } RankingFunction.java000066400000000000000000000025321167051330000422700ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import com.google.inject.Binding; import com.google.inject.ImplementedBy; /** * Assigns each {@link Binding} a rank according to some function; higher ranks take precedence over lower ranks. */ @ImplementedBy( DefaultRankingFunction.class ) public interface RankingFunction { /** * Estimates the maximum possible rank for this function; used to arrange injectors in order of ranking probability. * * @return Maximum rank */ int maxRank(); /** * Assigns a numeric rank to the given binding. * * @param binding The binding * @return Assigned rank */ int rank( Binding binding ); } WatchedBeans.java000066400000000000000000000103111167051330000415130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Annotation; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import org.sonatype.guice.bean.locators.spi.BindingSubscriber; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.inject.BeanEntry; import org.sonatype.inject.Mediator; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.TypeLiteral; /** * Provides dynamic {@link BeanEntry} notifications by tracking qualified {@link Binding}s. * * @see BeanLocator#watch(Key, Mediator, Object) */ final class WatchedBeans implements BindingSubscriber { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final BeanCache beans = new BeanCache(); private final Key key; private final Mediator mediator; private final QualifyingStrategy strategy; private final Reference watcherRef; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- WatchedBeans( final Key key, final Mediator mediator, final W watcher ) { this.key = key; this.mediator = mediator; strategy = QualifyingStrategy.selectFor( key ); watcherRef = new WeakReference( watcher ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public TypeLiteral type() { return key.getTypeLiteral(); } public void add( final Binding binding, final int rank ) { @SuppressWarnings( "unchecked" ) final Q qualifier = (Q) strategy.qualifies( key, binding ); if ( null != qualifier ) { final W watcher = watcherRef.get(); if ( null != watcher ) { final BeanEntry bean = beans.create( qualifier, binding, rank ); try { mediator.add( bean, watcher ); } catch ( final Throwable e ) { Logs.catchThrowable( e ); Logs.warn( "Problem adding: <> to: " + detail( watcher ), bean, e ); } } } } public void remove( final Binding binding ) { final BeanEntry bean = beans.remove( binding ); if ( null != bean ) { final W watcher = watcherRef.get(); if ( null != watcher ) { try { mediator.remove( bean, watcher ); } catch ( final Throwable e ) { Logs.catchThrowable( e ); Logs.warn( "Problem removing: <> from: " + detail( watcher ), bean, e ); } } } } public Iterable> bindings() { return beans.bindings(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private String detail( final Object watcher ) { return Logs.identityToString( watcher ) + " via: " + Logs.identityToString( mediator ); } } WildcardKey.java000066400000000000000000000104111167051330000413660ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.inject.Qualifier; import com.google.inject.Key; /** * Binding {@link Key} for implementations that act as "wild-cards", meaning they match against any assignable type. *

* Since the wild-card type is {@link Object} and the associated qualifier may not be unique between implementations, * the qualifier is saved and replaced with a unique (per-implementation) pseudo-qualifier. The original qualifier is * available from {@link #getQualifier()}. */ public final class WildcardKey extends Key // all wild-card keys have Object as their type { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Annotation qualifier; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public WildcardKey( final Class type, final Annotation qualifier ) { super( new Wrapped( type ) ); this.qualifier = qualifier; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- /** * @return Original qualifier associated with the implementation */ public Annotation getQualifier() { return qualifier; } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- @Qualifier @Retention( RetentionPolicy.RUNTIME ) private static @interface Wrapper { Class value(); } /** * Pseudo-{@link Annotation} that can wrap any implementation type as a {@link Qualifier}. */ private static final class Wrapped implements Wrapper { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Class value; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- Wrapped( final Class value ) { this.value = value; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Class value() { return value; } public Class annotationType() { return Wrapper.class; } @Override public int hashCode() { return value.hashCode(); // no need to follow strict annotation spec } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof Wrapped ) { return value == ( (Wrapped) rhs ).value; } return false; } @Override public String toString() { return "*"; // let people know this is a "wild-card" qualifier } } } package-info.java000066400000000000000000000031331167051330000415130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * Locate qualified bean implementations across multiple injectors. * *

The principal members of this package are: *

*
{@link org.sonatype.guice.bean.locators.BeanLocator} *
Finds and tracks bean implementations annotated with {@link javax.inject.Qualifier} annotations. *
{@link org.sonatype.guice.bean.locators.MutableBeanLocator} *
Mutable {@link org.sonatype.guice.bean.locators.BeanLocator} that distributes bindings from zero or more {@link org.sonatype.guice.bean.locators.spi.BindingPublisher}s. *
{@link org.sonatype.guice.bean.locators.BeanDescription} *
Source location mixin used to supply descriptions to the {@link org.sonatype.guice.bean.locators.BeanLocator}. *
{@link org.sonatype.guice.bean.locators.HiddenBinding} *
Source location mixin used to hide bindings from the {@link org.sonatype.guice.bean.locators.BeanLocator}. *
*/ package org.sonatype.guice.bean.locators; 000077500000000000000000000000001167051330000371175ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/spiBindingDistributor.java000066400000000000000000000026461167051330000435770ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/spi/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators.spi; import com.google.inject.Binding; /** * Distributor of {@link Binding}s retrieved from a series of {@link BindingPublisher}s. */ public interface BindingDistributor { /** * Adds the given ranked {@link BindingPublisher} and distributes its {@link Binding}s. * * @param publisher The new publisher * @param rank The assigned rank */ void add( BindingPublisher publisher, int rank ); /** * Removes the given {@link BindingPublisher} and its {@link Binding}s. * * @param publisher The old publisher */ void remove( BindingPublisher publisher ); /** * Removes all known {@link BindingPublisher}s and their {@link Binding}s. */ void clear(); } BindingPublisher.java000066400000000000000000000024131167051330000432120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/spi/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators.spi; import com.google.inject.Binding; /** * Publisher of {@link Binding}s to interested {@link BindingSubscriber}s. */ public interface BindingPublisher { /** * Subscribes the given {@link BindingSubscriber} to receive {@link Binding}s. * * @param subscriber The subscriber */ void subscribe( BindingSubscriber subscriber ); /** * Stops the given {@link BindingSubscriber} from receiving {@link Binding}s. * * @param subscriber The subscriber */ void unsubscribe( BindingSubscriber subscriber ); } BindingSubscriber.java000066400000000000000000000031151167051330000433600ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/spi/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators.spi; import com.google.inject.Binding; import com.google.inject.TypeLiteral; /** * Subscriber of {@link Binding}s from one or more {@link BindingPublisher}s. */ public interface BindingSubscriber { /** * Returns the type of {@link Binding}s that are of interest. * * @return The literal type */ TypeLiteral type(); /** * Adds the given ranked {@link Binding} to this subscriber. * * @param binding The new binding * @param rank The assigned rank */ void add( Binding binding, int rank ); /** * Removes the given {@link Binding} from this subscriber. * * @param binding The old binding */ void remove( Binding binding ); /** * Reports any {@link Binding}s that are currently in use. * * @return The used {@link Binding}s */ Iterable> bindings(); } package-info.java000066400000000000000000000030221167051330000423030ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/guice/bean/locators/spi/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * SPI for contributing {@link com.google.inject.Binding}s to the {@link org.sonatype.guice.bean.locators.MutableBeanLocator}. * *

The principal members of this package are: *

*
{@link org.sonatype.guice.bean.locators.spi.BindingDistributor} *
Distributor of {@link com.google.inject.Binding}s retrieved from a series of {@link org.sonatype.guice.bean.locators.spi.BindingPublisher}s. *
{@link org.sonatype.guice.bean.locators.spi.BindingPublisher} *
Publisher of {@link com.google.inject.Binding}s to interested {@link org.sonatype.guice.bean.locators.spi.BindingSubscriber}s. *
{@link org.sonatype.guice.bean.locators.spi.BindingSubscriber} *
Subscriber of {@link com.google.inject.Binding}s from one or more {@link org.sonatype.guice.bean.locators.spi.BindingPublisher}s. *
*/ package org.sonatype.guice.bean.locators.spi; 000077500000000000000000000000001167051330000337515ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/injectBeanEntry.java000066400000000000000000000043641167051330000365120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/inject/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.inject; import java.lang.annotation.Annotation; import java.util.Map.Entry; import javax.inject.Provider; import javax.inject.Qualifier; /** * Map {@link Entry} that maps a JSR330 @{@link Qualifier} annotation to a bean implementation. */ public interface BeanEntry extends Entry { /** * Returns the @{@link Qualifier} annotation associated with this particular bean. * * @return Qualifier annotation */ Q getKey(); /** * Returns the associated instance of the bean; returns same instance for each call. * * @return Bean instance (lazily-created) */ T getValue(); /** * Returns the underlying {@link Provider}; may support creation of multiple instances. * * @return Bean provider */ Provider getProvider(); /** * Returns a human-readable description of the bean; see @{@link Description}. * * @return Human-readable description */ String getDescription(); /** * Attempts to find the implementation type without creating the bean instance. * * @return Implementation type; {@code null} if the type cannot be determined */ Class getImplementationClass(); /** * Returns an arbitrary object that describes where this bean was configured. * * @return Source location * @see Object#toString() */ Object getSource(); /** * Returns the bean's rank; higher ranked beans override lower ranked beans. * * @return Assigned rank */ int getRank(); } Description.java000066400000000000000000000020671167051330000371040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/inject/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.inject; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Describes a bean. */ @Target( value = { ElementType.TYPE } ) @Retention( RetentionPolicy.RUNTIME ) @Documented public @interface Description { String value(); } Mediator.java000066400000000000000000000026641167051330000363700ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/inject/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.inject; import java.lang.annotation.Annotation; /** * Mediates bean entries sent from the {@code BeanLocator} to associated watching objects. */ public interface Mediator { /** * Processes the added {@link BeanEntry} and sends the necessary updates to the watcher. * * @param entry The added bean entry * @param watcher The watching object */ void add( BeanEntry entry, W watcher ) throws Exception; /** * Processes the removed {@link BeanEntry} and sends the necessary updates to the watcher. * * @param entry The removed bean entry * @param watcher The watching object */ void remove( BeanEntry entry, W watcher ) throws Exception; } package-info.java000066400000000000000000000014451167051330000371440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/main/java/org/sonatype/inject/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * Optional Sonatype extensions to JSR330. */ package org.sonatype.inject; sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/000077500000000000000000000000001167051330000272355ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/000077500000000000000000000000001167051330000301565ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/000077500000000000000000000000001167051330000307455ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/000077500000000000000000000000001167051330000326075ustar00rootroot00000000000000000077500000000000000000000000001167051330000336245ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000345315ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000363575ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locatorsDefaultBeanLocatorTest.java000066400000000000000000000324571167051330000435730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.Iterator; import java.util.Map.Entry; import java.util.NoSuchElementException; import junit.framework.TestCase; import org.sonatype.guice.bean.locators.RankedBindingsTest.Bean; import org.sonatype.guice.bean.locators.RankedBindingsTest.BeanImpl; import org.sonatype.guice.bean.locators.RankedBindingsTest.BeanImpl2; import org.sonatype.guice.bean.locators.spi.BindingPublisher; import org.sonatype.guice.bean.locators.spi.BindingSubscriber; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.name.Named; import com.google.inject.name.Names; public class DefaultBeanLocatorTest extends TestCase { Injector parent; Injector child1; Injector child2; Injector child3; Injector child4; @Override public void setUp() throws Exception { parent = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "A" ) ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Names.named( "-" ) ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Names.named( "Z" ) ).to( BeanImpl.class ); } } ); child1 = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "M1" ) ).to( BeanImpl.class ); bind( Bean.class ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Names.named( "N1" ) ).to( BeanImpl.class ); } } ); child2 = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { binder().withSource( new HiddenBinding() { } ).bind( Bean.class ).annotatedWith( Names.named( "HIDDEN" ) ).to( BeanImpl.class ); } } ); child3 = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "M3" ) ).to( BeanImpl.class ); bind( Bean.class ).to( BeanImpl2.class ); bind( Bean.class ).annotatedWith( Names.named( "N3" ) ).to( BeanImpl.class ); } } ); child4 = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { // no bindings } } ); } public void testDefaultLocator() { final BeanLocator locator = parent.getInstance( BeanLocator.class ); assertSame( locator, parent.getInstance( MutableBeanLocator.class ) ); Iterator> i; i = locator. locate( Key.get( Bean.class, Named.class ) ).iterator(); assertTrue( i.hasNext() ); assertEquals( Names.named( "A" ), i.next().getKey() ); assertEquals( Names.named( "-" ), i.next().getKey() ); assertEquals( Names.named( "Z" ), i.next().getKey() ); assertFalse( i.hasNext() ); i = locator. locate( Key.get( Bean.class, Named.class ) ).iterator(); assertTrue( i.hasNext() ); assertEquals( Names.named( "A" ), i.next().getKey() ); assertEquals( Names.named( "-" ), i.next().getKey() ); assertEquals( Names.named( "Z" ), i.next().getKey() ); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { // expected } try { i.remove(); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { // expected } } public void testInjectorPublisherEquality() { final RankingFunction function1 = new DefaultRankingFunction( 1 ); final RankingFunction function2 = new DefaultRankingFunction( 2 ); assertTrue( new InjectorPublisher( parent, function1 ).equals( new InjectorPublisher( parent, function2 ) ) ); assertTrue( new InjectorPublisher( parent, function2 ).equals( new InjectorPublisher( parent, function1 ) ) ); assertFalse( new InjectorPublisher( child1, function1 ).equals( new InjectorPublisher( child2, function1 ) ) ); assertFalse( new InjectorPublisher( child2, function2 ).equals( new InjectorPublisher( child1, function2 ) ) ); assertFalse( new BindingPublisher() { public void subscribe( final BindingSubscriber subscriber ) { } public void unsubscribe( final BindingSubscriber subscriber ) { } }.equals( new InjectorPublisher( child1, function1 ) ) ); assertFalse( new InjectorPublisher( child2, function2 ).equals( new BindingPublisher() { public void subscribe( final BindingSubscriber subscriber ) { } public void unsubscribe( final BindingSubscriber subscriber ) { } } ) ); assertTrue( new InjectorPublisher( parent, function1 ).hashCode() == new InjectorPublisher( parent, function2 ).hashCode() ); assertTrue( new InjectorPublisher( parent, function2 ).hashCode() == new InjectorPublisher( parent, function1 ).hashCode() ); assertFalse( new InjectorPublisher( child1, function1 ).hashCode() == new InjectorPublisher( child2, function1 ).hashCode() ); assertFalse( new InjectorPublisher( child2, function2 ).hashCode() == new InjectorPublisher( child1, function2 ).hashCode() ); } @SuppressWarnings( "deprecation" ) public void testInjectorOrdering() { final MutableBeanLocator locator = new DefaultBeanLocator(); final Iterable> roles = locator. locate( Key.get( Bean.class, Named.class ) ); locator.add( parent, 0 ); locator.add( child1, 1 ); locator.add( child2, 2 ); locator.add( child3, 3 ); locator.add( child4, 4 ); Iterator> i; i = roles.iterator(); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "M3" ), i.next().getKey() ); assertEquals( Names.named( "N3" ), i.next().getKey() ); assertEquals( Names.named( "M1" ), i.next().getKey() ); assertEquals( Names.named( "N1" ), i.next().getKey() ); assertEquals( Names.named( "A" ), i.next().getKey() ); assertEquals( Names.named( "-" ), i.next().getKey() ); assertEquals( Names.named( "Z" ), i.next().getKey() ); assertFalse( i.hasNext() ); locator.remove( child1 ); i = roles.iterator(); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "M3" ), i.next().getKey() ); assertEquals( Names.named( "N3" ), i.next().getKey() ); assertEquals( Names.named( "A" ), i.next().getKey() ); assertEquals( Names.named( "-" ), i.next().getKey() ); assertEquals( Names.named( "Z" ), i.next().getKey() ); assertFalse( i.hasNext() ); locator.add( child1, 4 ); i = roles.iterator(); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "M1" ), i.next().getKey() ); assertEquals( Names.named( "N1" ), i.next().getKey() ); assertEquals( Names.named( "M3" ), i.next().getKey() ); assertEquals( Names.named( "N3" ), i.next().getKey() ); assertEquals( Names.named( "A" ), i.next().getKey() ); assertEquals( Names.named( "-" ), i.next().getKey() ); assertEquals( Names.named( "Z" ), i.next().getKey() ); assertFalse( i.hasNext() ); locator.remove( child2 ); locator.remove( child2 ); i = roles.iterator(); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "M1" ), i.next().getKey() ); assertEquals( Names.named( "N1" ), i.next().getKey() ); assertEquals( Names.named( "M3" ), i.next().getKey() ); assertEquals( Names.named( "N3" ), i.next().getKey() ); assertEquals( Names.named( "A" ), i.next().getKey() ); assertEquals( Names.named( "-" ), i.next().getKey() ); assertEquals( Names.named( "Z" ), i.next().getKey() ); assertFalse( i.hasNext() ); locator.remove( child3 ); locator.add( child3, 5 ); locator.add( child3, 5 ); i = roles.iterator(); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "M3" ), i.next().getKey() ); assertEquals( Names.named( "N3" ), i.next().getKey() ); assertEquals( Names.named( "M1" ), i.next().getKey() ); assertEquals( Names.named( "N1" ), i.next().getKey() ); assertEquals( Names.named( "A" ), i.next().getKey() ); assertEquals( Names.named( "-" ), i.next().getKey() ); assertEquals( Names.named( "Z" ), i.next().getKey() ); assertFalse( i.hasNext() ); locator.remove( parent ); i = roles.iterator(); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "M3" ), i.next().getKey() ); assertEquals( Names.named( "N3" ), i.next().getKey() ); assertEquals( Names.named( "M1" ), i.next().getKey() ); assertEquals( Names.named( "N1" ), i.next().getKey() ); assertFalse( i.hasNext() ); locator.remove( child1 ); i = roles.iterator(); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "M3" ), i.next().getKey() ); assertEquals( Names.named( "N3" ), i.next().getKey() ); assertFalse( i.hasNext() ); locator.remove( child3 ); i = roles.iterator(); assertFalse( i.hasNext() ); locator.add( parent, 3 ); locator.add( child1, 2 ); locator.add( child2, 1 ); locator.add( child3, 0 ); i = roles.iterator(); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "A" ), i.next().getKey() ); assertEquals( Names.named( "-" ), i.next().getKey() ); assertEquals( Names.named( "Z" ), i.next().getKey() ); assertEquals( Names.named( "M1" ), i.next().getKey() ); assertEquals( Names.named( "N1" ), i.next().getKey() ); assertEquals( Names.named( "M3" ), i.next().getKey() ); assertEquals( Names.named( "N3" ), i.next().getKey() ); assertFalse( i.hasNext() ); locator.clear(); i = roles.iterator(); assertFalse( i.hasNext() ); } @SuppressWarnings( "deprecation" ) public void testExistingInjectors() { final MutableBeanLocator locator = new DefaultBeanLocator(); locator.add( parent, 0 ); locator.add( child1, 1 ); Iterable> roles = locator. locate( Key.get( Bean.class, Named.class ) ); locator.add( child2, 2 ); locator.add( child3, 3 ); Iterator> i; i = roles.iterator(); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "default" ), i.next().getKey() ); assertEquals( Names.named( "M3" ), i.next().getKey() ); assertEquals( Names.named( "N3" ), i.next().getKey() ); assertEquals( Names.named( "M1" ), i.next().getKey() ); assertEquals( Names.named( "N1" ), i.next().getKey() ); assertEquals( Names.named( "A" ), i.next().getKey() ); assertEquals( Names.named( "-" ), i.next().getKey() ); assertEquals( Names.named( "Z" ), i.next().getKey() ); assertFalse( i.hasNext() ); i = null; roles = null; System.gc(); locator.clear(); } } EntryListAdapterTest.java000066400000000000000000000236421167051330000433270ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import junit.framework.TestCase; public class EntryListAdapterTest extends TestCase { @SuppressWarnings( "boxing" ) public void testListSize() { final Map map = new HashMap(); final List list = new EntryListAdapter( map.entrySet() ); assertTrue( list.isEmpty() ); map.put( "A", 1 ); assertFalse( list.isEmpty() ); assertEquals( 1, list.size() ); map.put( "C", 3 ); assertEquals( 2, list.size() ); map.put( "B", 2 ); assertEquals( 3, list.size() ); map.remove( "C" ); assertEquals( 2, list.size() ); } public void testEmptyList() { final ListIterator i = new EntryListAdapter( Collections.> emptyList() ).listIterator( 0 ); assertFalse( i.hasNext() ); assertEquals( 0, i.nextIndex() ); assertFalse( i.hasPrevious() ); assertEquals( -1, i.previousIndex() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } try { i.previous(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } assertFalse( i.hasNext() ); assertEquals( 0, i.nextIndex() ); assertFalse( i.hasPrevious() ); assertEquals( -1, i.previousIndex() ); } @SuppressWarnings( "boxing" ) public void testInvalidListIterator() { final Map map = new HashMap(); map.put( 3, "C" ); map.put( 1, "A" ); map.put( 2, "B" ); try { new EntryListAdapter( map.entrySet() ).listIterator( -1 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( final IndexOutOfBoundsException e ) { } try { new EntryListAdapter( map.entrySet() ).listIterator( 4 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( final IndexOutOfBoundsException e ) { } } @SuppressWarnings( "boxing" ) public void testIterator() { final Map map = new LinkedHashMap(); map.put( 3, "C" ); map.put( 1, "A" ); map.put( 2, "B" ); final Iterator i = new EntryListAdapter( map.entrySet() ).iterator(); assertTrue( i.hasNext() ); try { i.remove(); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } assertEquals( "C", i.next() ); assertTrue( i.hasNext() ); assertEquals( "A", i.next() ); assertTrue( i.hasNext() ); assertEquals( "B", i.next() ); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } } @SuppressWarnings( "boxing" ) public void testListIterator() { final Map map = new LinkedHashMap(); map.put( 3, "C" ); map.put( 1, "A" ); map.put( 2, "B" ); final ListIterator i = new EntryListAdapter( map.entrySet() ).listIterator( 1 ); assertTrue( i.hasNext() ); assertEquals( 1, i.nextIndex() ); assertTrue( i.hasPrevious() ); assertEquals( 0, i.previousIndex() ); try { i.add( "X" ); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } try { i.remove(); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } try { i.set( "X" ); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } assertEquals( "A", i.next() ); assertTrue( i.hasNext() ); assertEquals( 2, i.nextIndex() ); assertTrue( i.hasPrevious() ); assertEquals( 1, i.previousIndex() ); assertEquals( "B", i.next() ); assertFalse( i.hasNext() ); assertEquals( 3, i.nextIndex() ); assertTrue( i.hasPrevious() ); assertEquals( 2, i.previousIndex() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } assertEquals( "B", i.previous() ); assertTrue( i.hasNext() ); assertEquals( 2, i.nextIndex() ); assertTrue( i.hasPrevious() ); assertEquals( 1, i.previousIndex() ); assertEquals( "A", i.previous() ); assertTrue( i.hasNext() ); assertEquals( 1, i.nextIndex() ); assertTrue( i.hasPrevious() ); assertEquals( 0, i.previousIndex() ); assertEquals( "C", i.previous() ); assertTrue( i.hasNext() ); assertEquals( 0, i.nextIndex() ); assertFalse( i.hasPrevious() ); assertEquals( -1, i.previousIndex() ); try { i.previous(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } assertEquals( "C", i.next() ); assertTrue( i.hasNext() ); assertEquals( 1, i.nextIndex() ); assertTrue( i.hasPrevious() ); assertEquals( 0, i.previousIndex() ); } @SuppressWarnings( "boxing" ) public void testVanishingList() { final Map map = new LinkedHashMap(); map.put( 3, "C" ); map.put( 1, "A" ); map.put( 2, "B" ); final IndexList> entries = new IndexList>(); entries.addAll( map.entrySet() ); final ListIterator i = new EntryListAdapter( entries ).listIterator( 1 ); entries.clear(); assertFalse( i.hasNext() ); assertEquals( 1, i.nextIndex() ); assertTrue( i.hasPrevious() ); assertEquals( 0, i.previousIndex() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } assertEquals( "C", i.previous() ); assertTrue( i.hasNext() ); assertEquals( 0, i.nextIndex() ); assertFalse( i.hasPrevious() ); assertEquals( -1, i.previousIndex() ); try { i.previous(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } assertEquals( "C", i.next() ); assertFalse( i.hasNext() ); assertEquals( 1, i.nextIndex() ); assertTrue( i.hasPrevious() ); assertEquals( 0, i.previousIndex() ); } @SuppressWarnings( "boxing" ) public void testCachedList() { final Map map = new LinkedHashMap(); map.put( 3, "C" ); map.put( 1, "A" ); map.put( 2, "B" ); final IndexList> entries = new IndexList>(); entries.addAll( map.entrySet() ); final ListIterator i = new EntryListAdapter( entries ).listIterator( 3 ); entries.clear(); assertFalse( i.hasNext() ); assertEquals( "B", i.previous() ); assertEquals( "A", i.previous() ); assertEquals( "C", i.previous() ); assertFalse( i.hasPrevious() ); assertEquals( "C", i.next() ); assertEquals( "A", i.next() ); assertEquals( "B", i.next() ); assertFalse( i.hasNext() ); } static final class IndexList extends ArrayList { private static final long serialVersionUID = 1L; @Override public Iterator iterator() { return new Iterator() { int index; public boolean hasNext() { return index < size(); } public T next() { if ( hasNext() ) { return get( index++ ); } throw new NoSuchElementException(); } public void remove() { IndexList.this.remove( index ); } }; } } } EntryMapAdapterTest.java000066400000000000000000000040721167051330000431250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; public class EntryMapAdapterTest extends TestCase { @SuppressWarnings( "boxing" ) public void testMapSize() { final Map original = new HashMap(); final Map adapter = new EntryMapAdapter( original.entrySet() ); assertTrue( adapter.isEmpty() ); original.put( "A", 1 ); assertFalse( adapter.isEmpty() ); assertEquals( 1, adapter.size() ); original.put( "C", 3 ); assertEquals( 2, adapter.size() ); original.put( "B", 2 ); assertEquals( 3, adapter.size() ); original.remove( "C" ); assertEquals( 2, adapter.size() ); } @SuppressWarnings( "boxing" ) public void testMapEquality() { final Map original = new HashMap(); final Map adapter = new EntryMapAdapter( original.entrySet() ); assertEquals( original, adapter ); original.put( 3, "C" ); assertEquals( original, adapter ); original.put( 1, "A" ); assertEquals( original, adapter ); original.put( 2, "B" ); assertEquals( original, adapter ); original.clear(); assertEquals( original, adapter ); } } ImplementationVisitorTest.java000066400000000000000000000132141167051330000444300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.Iterator; import junit.framework.TestCase; import org.sonatype.guice.bean.locators.RankedBindingsTest.Bean; import org.sonatype.guice.bean.locators.RankedBindingsTest.BeanImpl; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.DeferredProvider; import org.sonatype.guice.bean.reflect.LoadedClass; import com.google.inject.AbstractModule; import com.google.inject.Binder; import com.google.inject.Binding; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.PrivateModule; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; import com.google.inject.spi.BindingScopingVisitor; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.ElementVisitor; import com.google.inject.spi.UntargettedBinding; import com.google.inject.util.Providers; public class ImplementationVisitorTest extends TestCase { Injector injector; @Override public void setUp() throws Exception { injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "linked" ) ).to( BeanImpl.class ); try { bind( Bean.class ).annotatedWith( Names.named( "ctor" ) ).toConstructor( BeanImpl.class.getDeclaredConstructor() ); } catch ( final NoSuchMethodException e ) { } bind( Bean.class ).annotatedWith( Names.named( "instance" ) ).toInstance( new BeanImpl() ); bind( Bean.class ).annotatedWith( Names.named( "deferred" ) ).toProvider( new LoadedClass( BeanImpl.class ) ); install( new PrivateModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "exposed" ) ).to( BeanImpl.class ); expose( Bean.class ).annotatedWith( Names.named( "exposed" ) ); } } ); bind( Bean.class ).annotatedWith( Names.named( "provider" ) ).toProvider( Providers.of( new BeanImpl() ) ); bind( Bean.class ).annotatedWith( Names.named( "broken" ) ).toProvider( new DeferredProvider() { public Bean get() { throw new TypeNotPresentException( "", null ); } public DeferredClass getImplementationClass() { throw new TypeNotPresentException( "", null ); } } ); } } ); } public void testImplementationVisitor() { assertEquals( BeanImpl.class, new UntargettedBinding() { public Key getKey() { return Key.get( BeanImpl.class ); } public Provider getProvider() { return null; } public V acceptTargetVisitor( final BindingTargetVisitor visitor ) { return visitor.visit( this ); } public V acceptScopingVisitor( final BindingScopingVisitor visitor ) { return null; } public Object getSource() { return null; } public T acceptVisitor( final ElementVisitor visitor ) { return null; } public void applyTo( final Binder binder ) { } }.acceptTargetVisitor( ImplementationVisitor.THIS ) ); final Iterator> itr = injector.findBindingsByType( TypeLiteral.get( Bean.class ) ).iterator(); assertEquals( BeanImpl.class, itr.next().acceptTargetVisitor( ImplementationVisitor.THIS ) ); // linked assertEquals( BeanImpl.class, itr.next().acceptTargetVisitor( ImplementationVisitor.THIS ) ); // ctor assertEquals( BeanImpl.class, itr.next().acceptTargetVisitor( ImplementationVisitor.THIS ) ); // instance assertEquals( BeanImpl.class, itr.next().acceptTargetVisitor( ImplementationVisitor.THIS ) ); // deferred assertEquals( BeanImpl.class, itr.next().acceptTargetVisitor( ImplementationVisitor.THIS ) ); // exposed assertNull( itr.next().acceptTargetVisitor( ImplementationVisitor.THIS ) ); // provider instance assertNull( itr.next().acceptTargetVisitor( ImplementationVisitor.THIS ) ); // broken provider assertFalse( itr.hasNext() ); } } LazyBeanEntryTest.java000066400000000000000000000206301167051330000426120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.lang.annotation.Annotation; import java.util.Map.Entry; import junit.framework.TestCase; import org.sonatype.guice.bean.locators.RankedBindingsTest.Bean; import org.sonatype.guice.bean.locators.RankedBindingsTest.BeanImpl; import org.sonatype.inject.Description; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.Scopes; import com.google.inject.name.Named; import com.google.inject.name.Names; import com.google.inject.util.Providers; public class LazyBeanEntryTest extends TestCase { @Description( "This is a test" ) static class DescribedBean implements Bean { } public void testDetails() { final Key key1 = Key.get( Bean.class, Names.named( "1" ) ); final Key key2 = Key.get( Bean.class, Names.named( "2" ) ); final Key key3 = Key.get( Bean.class, Names.named( "3" ) ); final Key key4 = Key.get( Bean.class, Names.named( "4" ) ); final Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( key1 ).to( DescribedBean.class ).in( Scopes.SINGLETON ); binder().withSource( new BeanDescription() { public String getDescription() { return "Another test"; } } ).bind( key2 ).toInstance( new BeanImpl() ); binder().withSource( "where?" ).bind( key3 ).to( BeanImpl.class ); bind( key4 ).toProvider( Providers.of( new BeanImpl() ) ); } } ); final LazyBeanEntry bean1 = new LazyBeanEntry( key1.getAnnotation(), injector.getBinding( key1 ), 42 ); final LazyBeanEntry bean2 = new LazyBeanEntry( key2.getAnnotation(), injector.getBinding( key2 ), -24 ); final LazyBeanEntry bean3 = new LazyBeanEntry( key3.getAnnotation(), injector.getBinding( key3 ), 0 ); final LazyBeanEntry bean4 = new LazyBeanEntry( key4.getAnnotation(), injector.getBinding( key4 ), -1 ); assertEquals( "This is a test", bean1.getDescription() ); assertTrue( bean1.getSource() instanceof StackTraceElement ); assertEquals( DescribedBean.class, bean1.getImplementationClass() ); assertEquals( 42, bean1.getRank() ); assertEquals( "Another test", bean2.getDescription() ); assertTrue( bean2.getSource() instanceof BeanDescription ); assertEquals( BeanImpl.class, bean2.getImplementationClass() ); assertEquals( -24, bean2.getRank() ); assertNull( bean3.getDescription() ); assertTrue( bean3.getSource() instanceof String ); assertEquals( BeanImpl.class, bean3.getImplementationClass() ); assertEquals( 0, bean3.getRank() ); assertNull( bean4.getDescription() ); assertTrue( bean4.getSource() instanceof StackTraceElement ); assertEquals( null, bean4.getImplementationClass() ); assertEquals( -1, bean4.getRank() ); } static class CountingProvider implements Provider { static int count; public Object get() { count++; return ""; } } public void testGetContention() { final Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Object.class ).toProvider( CountingProvider.class ); } } ); final Entry countingEntry = new LazyBeanEntry( null, injector.getBinding( Object.class ), 0 ); final Thread[] pool = new Thread[8]; for ( int i = 0; i < pool.length; i++ ) { pool[i] = new Thread() { @Override public void run() { countingEntry.getValue(); } }; } for ( final Thread thread : pool ) { thread.start(); } for ( final Thread thread : pool ) { try { thread.join(); } catch ( final InterruptedException e ) { } } assertEquals( 1, CountingProvider.count ); try { countingEntry.setValue( null ); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } } @javax.inject.Named( "TEST" ) interface T { } public void testJsrNamed() { final Named guiceNamed = Names.named( "TEST" ); final Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindConstant().annotatedWith( guiceNamed ).to( "CONSTANT" ); } } ); @SuppressWarnings( { "unchecked", "rawtypes" } ) final LazyBeanEntry entry = new LazyBeanEntry( guiceNamed, injector.getBinding( Key.get( String.class, guiceNamed ) ), 0 ); final javax.inject.Named jsrNamed = entry.getKey(); assertTrue( jsrNamed.equals( jsrNamed ) ); assertTrue( jsrNamed.equals( entry.getKey() ) ); assertTrue( jsrNamed.equals( T.class.getAnnotation( javax.inject.Named.class ) ) ); assertTrue( jsrNamed.equals( guiceNamed ) ); assertFalse( jsrNamed.equals( Names.named( "" ) ) ); assertFalse( jsrNamed.equals( "TEST" ) ); assertEquals( javax.inject.Named.class, jsrNamed.annotationType() ); assertEquals( T.class.getAnnotation( javax.inject.Named.class ).hashCode(), jsrNamed.hashCode() ); } static class ToStringProvider implements Provider { public String get() { return "VALUE"; } } static class BadToStringProvider implements Provider { public String get() { throw new ProvisionException( "OOPS" ); } } public void testToString() { final Key key1 = Key.get( String.class, Names.named( "KEY" ) ); final Key key2 = Key.get( String.class, Names.named( "BAD" ) ); final Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( key1 ).toProvider( new ToStringProvider() ); bind( key2 ).toProvider( new BadToStringProvider() ); } } ); final Entry entry1 = new LazyBeanEntry( (Named) key1.getAnnotation(), injector.getBinding( key1 ), 0 ); final Entry entry2 = new LazyBeanEntry( (Named) key2.getAnnotation(), injector.getBinding( key2 ), 0 ); Exception error = null; try { injector.getInstance( key2 ); } catch ( final Exception e ) { error = e; } assertEquals( '@' + javax.inject.Named.class.getName() + "(value=KEY)=VALUE", entry1.toString() ); assertEquals( '@' + javax.inject.Named.class.getName() + "(value=BAD)=" + error, entry2.toString() ); } } LocatedBeansTest.java000066400000000000000000000163761167051330000424230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.util.Iterator; import javax.inject.Named; import javax.inject.Qualifier; import junit.framework.TestCase; import org.sonatype.guice.bean.locators.RankedBindingsTest.Bean; import org.sonatype.guice.bean.locators.RankedBindingsTest.BeanImpl; import org.sonatype.inject.BeanEntry; import com.google.inject.AbstractModule; import com.google.inject.Binding; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.name.Names; import com.google.inject.util.Providers; public class LocatedBeansTest extends TestCase { @Qualifier @Retention( RUNTIME ) public @interface Marked { String value() default ""; } @Marked( "MarkedBean1" ) static class MarkedBeanImpl1 implements Bean { } @Marked( "MarkedBean2" ) static class MarkedBeanImpl2 implements Bean { } Injector injector; @Override public void setUp() throws Exception { injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).to( BeanImpl.class ); // also seen as @Named("default") bind( Bean.class ).annotatedWith( Named.class ).to( BeanImpl.class ); // only in unrestricted search bind( Bean.class ).annotatedWith( Names.named( "Named1" ) ).toProvider( Providers.of( new BeanImpl() ) ); bind( Bean.class ).annotatedWith( Names.named( "Named2" ) ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Marked.class ).to( BeanImpl.class ); // only in unrestricted search bind( Bean.class ).annotatedWith( MarkedBeanImpl1.class.getAnnotation( Marked.class ) ).to( MarkedBeanImpl1.class ); bind( Bean.class ).annotatedWith( Names.named( "Marked2" ) ).to( MarkedBeanImpl2.class ); } } ); } public void testCacheConcurrency() { final LocatedBeans beans = locate( Key.get( Bean.class ) ); final Iterator> itr1 = beans.iterator(); final Iterator> itr2 = beans.iterator(); Bean a, b; a = itr1.next().getValue(); assertSame( a, itr2.next().getValue() ); a = itr1.next().getValue(); assertSame( a, itr2.next().getValue() ); a = itr1.next().getValue(); assertSame( a, itr2.next().getValue() ); a = itr1.next().getValue(); for ( final Binding binding : beans.beans.bindings() ) { beans.beans.remove( binding ); } b = itr2.next().getValue(); assertFalse( a == b ); a = itr1.next().getValue(); assertSame( a, itr2.next().getValue() ); a = itr1.next().getValue(); assertSame( a, itr2.next().getValue() ); a = itr1.next().getValue(); assertSame( a, itr2.next().getValue() ); } public void testUnrestrictedSearch() { final LocatedBeans beans = locate( Key.get( Bean.class ) ); final Iterator> itr = beans.iterator(); assertTrue( itr.hasNext() ); assertEquals( QualifyingStrategy.DEFAULT_QUALIFIER, itr.next().getKey() ); assertTrue( itr.hasNext() ); assertEquals( QualifyingStrategy.BLANK_QUALIFIER, itr.next().getKey() ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "Named1" ), itr.next().getKey() ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "Named2" ), itr.next().getKey() ); assertTrue( itr.hasNext() ); assertEquals( QualifyingStrategy.BLANK_QUALIFIER, itr.next().getKey() ); assertTrue( itr.hasNext() ); assertEquals( MarkedBeanImpl1.class.getAnnotation( Marked.class ), itr.next().getKey() ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "Marked2" ), itr.next().getKey() ); assertFalse( itr.hasNext() ); } public void testNamedSearch() { final LocatedBeans beans = locate( Key.get( Bean.class, Named.class ) ); final Iterator> itr = beans.iterator(); assertTrue( itr.hasNext() ); assertEquals( QualifyingStrategy.DEFAULT_QUALIFIER, itr.next().getKey() ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "Named1" ), itr.next().getKey() ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "Named2" ), itr.next().getKey() ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "Marked2" ), itr.next().getKey() ); assertFalse( itr.hasNext() ); } public void testNamedWithAttributesSearch() { final LocatedBeans beans = locate( Key.get( Bean.class, Names.named( "Named2" ) ) ); final Iterator> itr = beans.iterator(); assertTrue( itr.hasNext() ); assertEquals( Names.named( "Named2" ), itr.next().getKey() ); assertFalse( itr.hasNext() ); } public void testMarkedSearch() { final LocatedBeans beans = locate( Key.get( Bean.class, Marked.class ) ); final Iterator> itr = beans.iterator(); assertTrue( itr.hasNext() ); assertEquals( MarkedBeanImpl1.class.getAnnotation( Marked.class ), itr.next().getKey() ); assertTrue( itr.hasNext() ); assertEquals( MarkedBeanImpl2.class.getAnnotation( Marked.class ), itr.next().getKey() ); assertFalse( itr.hasNext() ); } public void testMarkedWithAttributesSearch() { final LocatedBeans beans = locate( Key.get( Bean.class, MarkedBeanImpl2.class.getAnnotation( Marked.class ) ) ); final Iterator> itr = beans.iterator(); assertTrue( itr.hasNext() ); assertEquals( MarkedBeanImpl2.class.getAnnotation( Marked.class ), itr.next().getKey() ); assertFalse( itr.hasNext() ); } private LocatedBeans locate( final Key key ) { final RankedBindings bindings = new RankedBindings( key.getTypeLiteral(), null ); for ( final Binding b : injector.findBindingsByType( key.getTypeLiteral() ) ) { bindings.add( b, 0 ); } return new LocatedBeans( key, bindings, null ); } } NamedIterableAdapterTest.java000066400000000000000000000065201167051330000440620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import junit.framework.TestCase; import com.google.inject.name.Named; import com.google.inject.name.Names; public class NamedIterableAdapterTest extends TestCase { public void testNamedAdapter() { final Map original = new LinkedHashMap(); final Map adapter = new EntryMapAdapter( new NamedIterableAdapter( original.entrySet() ) ); assertEquals( original, adapter ); original.put( Names.named( "3" ), "C" ); assertEquals( original, adapter ); original.put( Names.named( "1" ), "A" ); assertEquals( original, adapter ); original.put( Names.named( "2" ), "B" ); assertEquals( original, adapter ); assertEquals( "{3=C, 1=A, 2=B}", adapter.toString() ); final Iterator> i = adapter.entrySet().iterator(); assertEquals( "3=C", i.next().toString() ); assertEquals( "1=A", i.next().toString() ); assertEquals( "2=B", i.next().toString() ); original.clear(); assertEquals( original, adapter ); } private static void assertEquals( final Map named, final Map hinted ) { final Iterator> i = named.entrySet().iterator(); final Iterator> j = hinted.entrySet().iterator(); while ( i.hasNext() ) { assertTrue( j.hasNext() ); final Entry lhs = i.next(); final Entry rhs = j.next(); assertEquals( lhs.getKey().value(), rhs.getKey() ); assertEquals( lhs.getValue(), rhs.getValue() ); } assertFalse( j.hasNext() ); } public void testUnsupportedOperations() { final Map original = new LinkedHashMap(); final Map adapter = new EntryMapAdapter( new NamedIterableAdapter( original.entrySet() ) ); original.put( Names.named( "1" ), "A" ); try { adapter.entrySet().iterator().remove(); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } try { adapter.entrySet().iterator().next().setValue( "B" ); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } } } RankedBindingsTest.java000066400000000000000000000230041167051330000427430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.Iterator; import java.util.NoSuchElementException; import junit.framework.TestCase; import org.sonatype.guice.bean.locators.spi.BindingPublisher; import com.google.inject.AbstractModule; import com.google.inject.Binding; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Injector; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; public class RankedBindingsTest extends TestCase { @ImplementedBy( BeanImpl2.class ) static interface Bean { } static abstract class AbstractBean implements Bean { } static class BeanImpl extends AbstractBean { } static class BeanImpl2 extends AbstractBean { } static Injector injector0 = Guice.createInjector(); static Injector injector1 = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "1" ) ).to( BeanImpl.class ); } } ); static Injector injector2 = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "2" ) ).to( BeanImpl.class ); bind( Bean.class ).to( BeanImpl.class ); } } ); static Injector injector3 = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "3" ) ).to( BeanImpl.class ); } } ); public void testExistingExporters() { final RankedSequence exporters = new RankedSequence(); RankingFunction function; try { new DefaultRankingFunction( -1 ); fail( "Expected IllegalArgumentException" ); } catch ( final IllegalArgumentException e ) { // expected } function = new DefaultRankingFunction( 0 ); exporters.insert( new InjectorPublisher( injector0, function ), function.maxRank() ); function = new DefaultRankingFunction( 1 ); exporters.insert( new InjectorPublisher( injector1, function ), function.maxRank() ); function = new DefaultRankingFunction( 3 ); exporters.insert( new InjectorPublisher( injector3, function ), function.maxRank() ); function = new DefaultRankingFunction( 2 ); exporters.insert( new InjectorPublisher( injector2, function ), function.maxRank() ); final RankedBindings bindings = new RankedBindings( TypeLiteral.get( Bean.class ), exporters ); final Iterator> itr = bindings.iterator(); assertEquals( 0, bindings.bindings.size() ); assertTrue( itr.hasNext() ); assertEquals( 3, bindings.bindings.size() ); final Binding explicitBinding = itr.next(); assertNull( explicitBinding.getKey().getAnnotation() ); assertEquals( BeanImpl.class, explicitBinding.acceptTargetVisitor( ImplementationVisitor.THIS ) ); assertEquals( 3, bindings.bindings.size() ); assertTrue( itr.hasNext() ); assertEquals( 4, bindings.bindings.size() ); assertEquals( Names.named( "3" ), itr.next().getKey().getAnnotation() ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "2" ), itr.next().getKey().getAnnotation() ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "1" ), itr.next().getKey().getAnnotation() ); assertFalse( itr.hasNext() ); } public void testPendingExporters() { final RankedBindings bindings = new RankedBindings( TypeLiteral.get( Bean.class ), null ); Iterator> itr = bindings.iterator(); assertFalse( itr.hasNext() ); try { itr.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { // expected } try { itr.remove(); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { // expected } RankingFunction function; assertEquals( 0, bindings.bindings.size() ); function = new DefaultRankingFunction( 2 ); bindings.add( new InjectorPublisher( injector2, function ), function.maxRank() ); assertEquals( 0, bindings.bindings.size() ); assertTrue( itr.hasNext() ); assertEquals( 2, bindings.bindings.size() ); Binding explicitBinding = itr.next(); assertNull( explicitBinding.getKey().getAnnotation() ); assertEquals( BeanImpl.class, explicitBinding.acceptTargetVisitor( ImplementationVisitor.THIS ) ); assertEquals( 2, bindings.bindings.size() ); assertTrue( itr.hasNext() ); assertEquals( 2, bindings.bindings.size() ); function = new DefaultRankingFunction( 0 ); bindings.add( new InjectorPublisher( injector0, function ), function.maxRank() ); assertEquals( 2, bindings.bindings.size() ); function = new DefaultRankingFunction( 3 ); bindings.add( new InjectorPublisher( injector3, function ), function.maxRank() ); assertEquals( 2, bindings.bindings.size() ); assertTrue( itr.hasNext() ); assertEquals( 3, bindings.bindings.size() ); assertEquals( 3, bindings.bindings.size() ); function = new DefaultRankingFunction( 1 ); bindings.add( new InjectorPublisher( injector1, function ), function.maxRank() ); assertEquals( 3, bindings.bindings.size() ); assertTrue( itr.hasNext() ); assertEquals( 4, bindings.bindings.size() ); assertEquals( Names.named( "2" ), itr.next().getKey().getAnnotation() ); assertEquals( 4, bindings.bindings.size() ); assertTrue( itr.hasNext() ); assertEquals( 4, bindings.bindings.size() ); itr = bindings.iterator(); explicitBinding = itr.next(); assertNull( explicitBinding.getKey().getAnnotation() ); assertEquals( BeanImpl.class, explicitBinding.acceptTargetVisitor( ImplementationVisitor.THIS ) ); assertEquals( Names.named( "3" ), itr.next().getKey().getAnnotation() ); assertEquals( Names.named( "2" ), itr.next().getKey().getAnnotation() ); assertEquals( Names.named( "1" ), itr.next().getKey().getAnnotation() ); assertFalse( itr.hasNext() ); } public void testExporterRemoval() { final BindingPublisher exporter0 = new InjectorPublisher( injector0, new DefaultRankingFunction( 0 ) ); final BindingPublisher exporter1 = new InjectorPublisher( injector1, new DefaultRankingFunction( 1 ) ); final BindingPublisher exporter2 = new InjectorPublisher( injector2, new DefaultRankingFunction( 2 ) ); final BindingPublisher exporter3 = new InjectorPublisher( injector3, new DefaultRankingFunction( 3 ) ); final RankedBindings bindings = new RankedBindings( TypeLiteral.get( Bean.class ), null ); bindings.add( exporter0, 0 ); bindings.add( exporter1, 1 ); bindings.add( exporter2, 2 ); bindings.add( exporter3, 3 ); Iterator> itr = bindings.iterator(); bindings.remove( exporter1 ); assertTrue( itr.hasNext() ); Binding explicitBinding = itr.next(); assertNull( explicitBinding.getKey().getAnnotation() ); assertEquals( BeanImpl.class, explicitBinding.acceptTargetVisitor( ImplementationVisitor.THIS ) ); bindings.remove( injector3.findBindingsByType( TypeLiteral.get( Bean.class ) ).get( 0 ) ); bindings.remove( exporter2 ); bindings.remove( injector1.findBindingsByType( TypeLiteral.get( Bean.class ) ).get( 0 ) ); assertFalse( itr.hasNext() ); itr = bindings.iterator(); bindings.bindings.clear(); bindings.add( exporter3, 0 ); bindings.add( exporter1, 0 ); bindings.add( exporter0, 0 ); bindings.add( exporter2, 0 ); assertTrue( itr.hasNext() ); explicitBinding = itr.next(); assertNull( explicitBinding.getKey().getAnnotation() ); assertEquals( BeanImpl.class, explicitBinding.acceptTargetVisitor( ImplementationVisitor.THIS ) ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "3" ), itr.next().getKey().getAnnotation() ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "2" ), itr.next().getKey().getAnnotation() ); assertTrue( itr.hasNext() ); assertEquals( Names.named( "1" ), itr.next().getKey().getAnnotation() ); assertFalse( itr.hasNext() ); assertFalse( itr.hasNext() ); } } RankedSequenceTest.java000066400000000000000000000174361167051330000427720ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import junit.framework.TestCase; public class RankedSequenceTest extends TestCase { static final AtomicBoolean active = new AtomicBoolean( true ); static final List errors = Collections.synchronizedList( new ArrayList() ); static final Random random = new Random( System.currentTimeMillis() ); static final int CONCURRENCY = 8; static final RankedSequence rankedList = new RankedSequence(); public void testOrdering() { final RankedSequence list = new RankedSequence(); list.insert( "A1", Integer.MAX_VALUE ); list.insert( "F", Integer.MIN_VALUE + 1 ); list.insert( "E", -1 ); list.insert( "G1", Integer.MIN_VALUE ); list.insert( "D", 0 ); list.insert( "B", Integer.MAX_VALUE - 1 ); list.insert( "C", 1 ); list.insert( "G2", Integer.MIN_VALUE ); list.insert( "D", 0 ); list.insert( "A2", Integer.MAX_VALUE ); assertEquals( 10, list.size() ); Iterator itr = list.iterator(); assertTrue( itr.hasNext() ); assertTrue( itr.hasNext() ); assertTrue( itr.hasNext() ); assertEquals( "A1", itr.next() ); assertTrue( itr.hasNext() ); assertEquals( "A2", itr.next() ); assertTrue( itr.hasNext() ); assertEquals( "B", itr.next() ); assertTrue( itr.hasNext() ); assertEquals( "C", itr.next() ); assertTrue( itr.hasNext() ); assertEquals( "D", itr.next() ); assertTrue( itr.hasNext() ); assertEquals( "D", itr.next() ); assertTrue( itr.hasNext() ); assertEquals( "E", itr.next() ); assertTrue( itr.hasNext() ); assertEquals( "F", itr.next() ); assertTrue( itr.hasNext() ); assertEquals( "G1", itr.next() ); assertTrue( itr.hasNext() ); assertEquals( "G2", itr.next() ); assertFalse( itr.hasNext() ); assertFalse( itr.hasNext() ); assertFalse( itr.hasNext() ); itr = list.iterator(); assertEquals( "A1", itr.next() ); assertEquals( "A2", itr.next() ); assertEquals( "B", itr.next() ); assertEquals( "C", itr.next() ); assertEquals( "D", itr.next() ); assertEquals( "D", itr.next() ); assertEquals( "E", itr.next() ); assertEquals( "F", itr.next() ); assertEquals( "G1", itr.next() ); assertEquals( "G2", itr.next() ); itr = list.iterator(); list.remove( "D" ); list.insert( "D-", 0 ); list.remove( "D" ); assertEquals( "A1", itr.next() ); assertEquals( "A2", itr.next() ); assertTrue( itr.hasNext() ); list.remove( "B" ); list.insert( "512", 512 ); assertEquals( "B", itr.next() ); assertTrue( itr.hasNext() ); list.insert( "1024", 1024 ); assertEquals( "512", itr.next() ); assertEquals( "C", itr.next() ); assertEquals( "D-", itr.next() ); assertEquals( "E", itr.next() ); assertEquals( "F", itr.next() ); assertEquals( "G1", itr.next() ); assertEquals( "G2", itr.next() ); } public void testEmptyList() { final Iterator itr = new RankedSequence().iterator(); assertFalse( itr.hasNext() ); try { itr.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { // expected } try { itr.remove(); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { // expected } } public void testConcurrentIteration() { final Thread[] threads = new Thread[3 * CONCURRENCY]; int i = 0; while ( i < threads.length ) { threads[i++] = new Thread( new Push() ); threads[i++] = new Thread( new Pull() ); threads[i++] = new Thread( new Read() ); } for ( final Thread t : threads ) { t.start(); } try { Thread.sleep( 10 * 1000 ); } catch ( final InterruptedException e ) { // ignore } active.set( false ); for ( final Thread t : threads ) { try { t.join(); } catch ( final InterruptedException e ) { // ignore } } for ( final Throwable e : errors ) { e.printStackTrace(); } if ( errors.size() > 0 ) { fail( "Unexpected errors!" ); } } static class Push implements Runnable { public void run() { while ( active.get() ) { Thread.yield(); if ( rankedList.size() < 64 * 1024 ) { final int rank = random.nextInt(); rankedList.insert( Integer.valueOf( rank ), rank ); } Thread.yield(); } } } static class Pull implements Runnable { public void run() { try { while ( active.get() || !rankedList.isEmpty() ) { Thread.yield(); Integer element = Integer.valueOf( 0 ); final Iterator itr = rankedList.iterator(); for ( int i = 0; i < random.nextInt( rankedList.size() + 1 ) && itr.hasNext(); i++ ) { element = itr.next(); } rankedList.remove( element ); Thread.yield(); } } catch ( final Throwable e ) { errors.add( e ); } } } static class Read implements Runnable { public void run() { try { while ( active.get() ) { Thread.yield(); int lastRank = Integer.MAX_VALUE; final Iterator itr = rankedList.iterator(); while ( itr.hasNext() ) { Thread.yield(); final int rank = itr.next().intValue(); Thread.yield(); assertTrue( "Rank should descend during iteration", lastRank >= rank ); lastRank = rank; } Thread.yield(); } } catch ( final Throwable e ) { errors.add( e ); } } } } WatchedBeansTest.java000066400000000000000000000172431167051330000424210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-locators/src/test/java/org/sonatype/guice/bean/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.locators; import java.util.Iterator; import javax.inject.Named; import junit.framework.TestCase; import org.sonatype.guice.bean.locators.LocatedBeansTest.Marked; import org.sonatype.guice.bean.locators.RankedBindingsTest.Bean; import org.sonatype.guice.bean.locators.RankedBindingsTest.BeanImpl; import org.sonatype.guice.bean.locators.spi.BindingPublisher; import org.sonatype.guice.bean.locators.spi.BindingSubscriber; import org.sonatype.inject.BeanEntry; import org.sonatype.inject.Mediator; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.name.Names; public class WatchedBeansTest extends TestCase { Injector parent; Injector child1; Injector child2; Injector child3; @Override public void setUp() throws Exception { parent = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "A" ) ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Names.named( "B" ) ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Names.named( "C" ) ).to( BeanImpl.class ); } } ); child1 = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "X" ) ).to( BeanImpl.class ); } } ); child2 = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "Y" ) ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Marked.class ).to( BeanImpl.class ); } } ); child3 = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "Z" ) ).to( BeanImpl.class ); } } ); } static class RankingMediator implements Mediator> { public void add( final BeanEntry entry, final RankedSequence names ) { names.insert( entry.getKey().value(), entry.getRank() ); } public void remove( final BeanEntry entry, final RankedSequence names ) { assertTrue( names.remove( entry.getKey().value() ) ); } } @SuppressWarnings( { "deprecation", "rawtypes", "unchecked" } ) public void testWatchedBeans() { final MutableBeanLocator locator = new DefaultBeanLocator(); RankedSequence names = new RankedSequence(); locator.watch( Key.get( Bean.class, Named.class ), new RankingMediator(), names ); assertTrue( names.isEmpty() ); locator.add( parent, 0 ); checkNames( names, "A", "B", "C" ); locator.add( child1, 1 ); checkNames( names, "X", "A", "B", "C" ); final BindingSubscriber[] subscriberHolder = new BindingSubscriber[1]; final BindingPublisher subscriberHook = new BindingPublisher() { public void subscribe( final BindingSubscriber subscriber ) { subscriberHolder[0] = subscriber; } public void unsubscribe( final BindingSubscriber subscriber ) { subscriberHolder[0] = null; } }; locator.add( subscriberHook, Integer.MIN_VALUE ); assertNotNull( subscriberHolder[0] ); subscriberHolder[0].add( child2.getBinding( Key.get( Bean.class, Names.named( "Y" ) ) ), Integer.MIN_VALUE ); subscriberHolder[0].add( child2.getBinding( Key.get( Bean.class, Marked.class ) ), Integer.MIN_VALUE ); checkNames( names, "X", "A", "B", "C", "Y" ); locator.remove( parent ); checkNames( names, "X", "Y" ); subscriberHolder[0].remove( child2.getBinding( Key.get( Bean.class, Names.named( "Y" ) ) ) ); subscriberHolder[0].remove( child2.getBinding( Key.get( Bean.class, Marked.class ) ) ); locator.remove( subscriberHook ); assertNull( subscriberHolder[0] ); checkNames( names, "X" ); locator.add( child1, 42 ); checkNames( names, "X" ); locator.remove( subscriberHook ); checkNames( names, "X" ); locator.add( child3, 3 ); checkNames( names, "Z", "X" ); locator.add( parent, 2 ); checkNames( names, "Z", "A", "B", "C", "X" ); locator.clear(); checkNames( names ); names = null; System.gc(); locator.add( parent, Integer.MAX_VALUE ); locator.remove( parent ); } static class BrokenMediator implements Mediator { public void add( final BeanEntry entry, final Object watcher ) { throw new LinkageError(); } public void remove( final BeanEntry entry, final Object watcher ) { throw new LinkageError(); } } @SuppressWarnings( { "deprecation", "rawtypes", "unchecked" } ) public void testBrokenWatcher() { final MutableBeanLocator locator = new DefaultBeanLocator(); Object keepAlive = new Object(); locator.add( parent, 0 ); locator.watch( Key.get( Bean.class, Named.class ), new BrokenMediator(), keepAlive ); locator.remove( parent ); final BindingSubscriber[] subscriberHolder = new BindingSubscriber[1]; final BindingPublisher subscriberHook = new BindingPublisher() { public void subscribe( final BindingSubscriber subscriber ) { subscriberHolder[0] = subscriber; } public void unsubscribe( final BindingSubscriber subscriber ) { subscriberHolder[0] = null; } }; locator.add( subscriberHook, 0 ); subscriberHolder[0].add( child2.getBinding( Key.get( Bean.class, Names.named( "Y" ) ) ), Integer.MIN_VALUE ); subscriberHolder[0].add( child2.getBinding( Key.get( Bean.class, Marked.class ) ), Integer.MIN_VALUE ); keepAlive = null; System.gc(); subscriberHolder[0].remove( child2.getBinding( Key.get( Bean.class, Names.named( "Y" ) ) ) ); subscriberHolder[0].remove( child2.getBinding( Key.get( Bean.class, Marked.class ) ) ); } private static void checkNames( final Iterable actual, final String... expected ) { final Iterator itr = actual.iterator(); for ( final String n : expected ) { assertEquals( n, itr.next() ); } assertFalse( itr.hasNext() ); } } sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/000077500000000000000000000000001167051330000252655ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/pom.xml000066400000000000000000000033651167051330000266110ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-bean 2.3.0 guice-bean-reflect Sisu-Inject-Bean : Generic reflection javax.inject javax.inject org.sonatype.sisu sisu-guice org.slf4j slf4j-api true org.osgi org.osgi.core true org.apache.felix org.apache.felix.framework test sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/000077500000000000000000000000001167051330000260545ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/000077500000000000000000000000001167051330000270005ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/000077500000000000000000000000001167051330000277215ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/000077500000000000000000000000001167051330000305105ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/000077500000000000000000000000001167051330000323525ustar00rootroot00000000000000000077500000000000000000000000001167051330000333675ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000342745ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000357205ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflectAbstractDeferredClass.java000066400000000000000000000040001167051330000427470ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import javax.inject.Inject; import com.google.inject.Injector; /** * Abstract combination of {@link DeferredClass} and {@link DeferredProvider}. */ abstract class AbstractDeferredClass implements DeferredClass, DeferredProvider { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- @Inject private Injector injector; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public final DeferredProvider asProvider() { return this; } public final T get() { try { // load class and bootstrap injection return injector.getInstance( load() ); } catch ( final Throwable e ) { Logs.catchThrowable( e ); try { Logs.warn( "Error injecting: {}", getName(), e ); } finally { Logs.throwUnchecked( e ); } } return null; // not used } public final DeferredClass getImplementationClass() { return this; } } BeanProperties.java000066400000000000000000000041501167051330000415050ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.reflect.Member; import java.util.Iterator; import org.sonatype.guice.bean.reflect.DeclaredMembers.View; /** * {@link Iterable} that iterates over potential bean properties in a class hierarchy. */ public final class BeanProperties implements Iterable> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterable members; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public BeanProperties( final Class clazz ) { if ( clazz.isAnnotationPresent( IgnoreSetters.class ) ) { members = new DeclaredMembers( clazz, View.FIELDS ); } else { members = new DeclaredMembers( clazz, View.METHODS, View.FIELDS ); } } BeanProperties( final Iterable members ) { this.members = members; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterator> iterator() { return new BeanPropertyIterator( members ); } } BeanProperty.java000066400000000000000000000036711167051330000412040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.annotation.Annotation; import com.google.inject.TypeLiteral; /** * Represents a bean property such as a field or setter method. * *
 * // like...
 * @SomeAnnotation
 * SomeType someProperty;
 * 
 * // ...or...
 * @SomeAnnotation
 * void setSomeProperty( SomeType _someProperty )
 * {
 *     // ...etc...
 * }
 * 
*/ public interface BeanProperty { /** * Returns the property annotation with the specified type. * * @param annotationType The annotation type * @return Property annotation if it exists; otherwise {@code null} */ A getAnnotation( Class annotationType ); /** * Returns the reified generic type of the property; for example {@code TypeLiteral>}. * * @return Reified generic type */ TypeLiteral getType(); /** * Returns the normalized property name excluding the namespace; for example {@code "address"}. * * @return Normalized property name */ String getName(); /** * Sets the property in the given bean to the given value. * * @param bean The bean to update * @param value The value to set */ void set( B bean, T value ); } BeanPropertyField.java000066400000000000000000000066671167051330000421600ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; /** * {@link BeanProperty} backed by a {@link Field}. */ final class BeanPropertyField implements BeanProperty, PrivilegedAction { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Field field; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BeanPropertyField( final Field field ) { this.field = field; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public A getAnnotation( final Class annotationType ) { return field.getAnnotation( annotationType ); } @SuppressWarnings( "unchecked" ) public TypeLiteral getType() { return (TypeLiteral) TypeLiteral.get( field.getGenericType() ); } public String getName() { return field.getName(); } public void set( final B bean, final T value ) { if ( !field.isAccessible() ) { // make sure we can apply the binding AccessController.doPrivileged( this ); } try { field.set( bean, value ); } catch ( final Exception e ) { throw new ProvisionException( "Error injecting: " + field, e ); } catch ( final LinkageError e ) { throw new ProvisionException( "Error injecting: " + field, e ); } } @Override public int hashCode() { return field.hashCode(); } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof BeanPropertyField ) { return field.equals( ( (BeanPropertyField) rhs ).field ); } return false; } @Override public String toString() { return field.toString(); } // ---------------------------------------------------------------------- // PrivilegedAction methods // ---------------------------------------------------------------------- public Void run() { // enable private injection field.setAccessible( true ); return null; } } BeanPropertyIterator.java000066400000000000000000000104151167051330000427100ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.NoSuchElementException; /** * Read-only {@link Iterator} that picks out potential bean properties from declared members. */ final class BeanPropertyIterator implements Iterator> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterator memberIterator; // look-ahead, maintained by hasNext() private BeanProperty nextProperty; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BeanPropertyIterator( final Iterable members ) { memberIterator = members.iterator(); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { while ( null == nextProperty ) { if ( !memberIterator.hasNext() ) { return false; // no more properties } final Member member = memberIterator.next(); final int modifiers = member.getModifiers(); // static members can't be properties, abstracts and synthetics are just noise so we ignore them if ( Modifier.isStatic( modifiers ) || Modifier.isAbstract( modifiers ) || member.isSynthetic() ) { continue; } if ( member instanceof Method ) { final Method method = (Method) member; if ( isSetter( method ) ) { nextProperty = new BeanPropertySetter( method ); } } else if ( member instanceof Field ) { nextProperty = new BeanPropertyField( (Field) member ); } // ignore properties annotated with JSR330/Guice if ( null != nextProperty && atInject( member ) ) { nextProperty = null; } } return true; } public BeanProperty next() { if ( hasNext() ) { // initialized by hasNext() final BeanProperty property = nextProperty; nextProperty = null; return property; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static boolean isSetter( final Method method ) { final String name = method.getName(); if ( name.startsWith( "set" ) && name.length() > 3 && Character.isUpperCase( name.charAt( 3 ) ) ) { return method.getParameterTypes().length == 1; } return false; } private static boolean atInject( final Member member ) { final AnnotatedElement e = (AnnotatedElement) member; return e.isAnnotationPresent( javax.inject.Inject.class ) || e.isAnnotationPresent( com.google.inject.Inject.class ); } } BeanPropertySetter.java000066400000000000000000000074721167051330000423760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; /** * {@link BeanProperty} backed by a single-parameter setter {@link Method}. */ final class BeanPropertySetter implements BeanProperty, PrivilegedAction { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Method method; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- BeanPropertySetter( final Method method ) { this.method = method; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public A getAnnotation( final Class annotationType ) { return method.getAnnotation( annotationType ); } @SuppressWarnings( "unchecked" ) public TypeLiteral getType() { return (TypeLiteral) TypeLiteral.get( method.getGenericParameterTypes()[0] ); } public String getName() { final String name = method.getName(); // this is guaranteed OK by the checks made in the BeanProperties code return Character.toLowerCase( name.charAt( 3 ) ) + name.substring( 4 ); } public void set( final B bean, final T value ) { if ( !method.isAccessible() ) { // ensure we can update the property AccessController.doPrivileged( this ); } try { method.invoke( bean, value ); } catch ( final Exception e ) { final Throwable cause = e instanceof InvocationTargetException ? e.getCause() : e; throw new ProvisionException( "Error injecting: " + method, cause ); } catch ( final LinkageError e ) { throw new ProvisionException( "Error injecting: " + method, e ); } } @Override public int hashCode() { return method.hashCode(); } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof BeanPropertySetter ) { return method.equals( ( (BeanPropertySetter) rhs ).method ); } return false; } @Override public String toString() { return method.toString(); } // ---------------------------------------------------------------------- // PrivilegedAction methods // ---------------------------------------------------------------------- public Void run() { // enable private injection method.setAccessible( true ); return null; } } BundleClassSpace.java000066400000000000000000000167301167051330000417450ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; /** * {@link ClassSpace} backed by a strongly-referenced {@link Bundle}. */ public final class BundleClassSpace implements ClassSpace { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final URL[] NO_URLS = {}; private static final Enumeration NO_ENTRIES = Collections.enumeration( Collections. emptySet() ); // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Bundle bundle; private URL[] classPath; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public BundleClassSpace( final Bundle bundle ) { this.bundle = bundle; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Class loadClass( final String name ) { try { return bundle.loadClass( name ); } catch ( final Exception e ) { throw new TypeNotPresentException( name, e ); } catch ( final LinkageError e ) { throw new TypeNotPresentException( name, e ); } } public DeferredClass deferLoadClass( final String name ) { return new NamedClass( this, name ); } public URL getResource( final String name ) { return bundle.getResource( name ); } @SuppressWarnings( "unchecked" ) public Enumeration getResources( final String name ) { try { final Enumeration resources = bundle.getResources( name ); return null != resources ? resources : NO_ENTRIES; } catch ( final IOException e ) { return NO_ENTRIES; } } @SuppressWarnings( "unchecked" ) public synchronized Enumeration findEntries( final String path, final String glob, final boolean recurse ) { if ( null == classPath ) { classPath = getBundleClassPath( bundle ); } final Enumeration entries = bundle.findEntries( null != path ? path : "/", glob, recurse ); if ( classPath.length > 0 ) { return new ChainedEnumeration( entries, new ResourceEnumeration( path, glob, recurse, classPath ) ); } return null != entries ? entries : NO_ENTRIES; } @Override public int hashCode() { return bundle.hashCode(); } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof BundleClassSpace ) { return bundle.equals( ( (BundleClassSpace) rhs ).bundle ); } return false; } @Override public String toString() { return bundle.toString(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Returns the expanded Bundle-ClassPath; we need this to iterate over embedded JARs. * * @param bundle The bundle * @return URL class path */ private static URL[] getBundleClassPath( final Bundle bundle ) { final String path = (String) bundle.getHeaders().get( Constants.BUNDLE_CLASSPATH ); if ( null == path ) { return NO_URLS; } final List classPath = new ArrayList(); final Set visited = new HashSet(); visited.add( "." ); for ( final String entry : path.trim().split( "\\s*,\\s*" ) ) { if ( visited.add( entry ) ) { final URL url = bundle.getEntry( entry ); if ( null != url ) { classPath.add( url ); } } } return classPath.isEmpty() ? NO_URLS : classPath.toArray( new URL[classPath.size()] ); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Chains a series of {@link Enumeration}s together to look like a single {@link Enumeration}. */ private static final class ChainedEnumeration implements Enumeration { // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private final Enumeration[] enumerations; private Enumeration currentEnumeration; private T nextElement; private int index; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ChainedEnumeration( final Enumeration... enumerations ) { this.enumerations = enumerations; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasMoreElements() { while ( null == nextElement ) { if ( null != currentEnumeration && currentEnumeration.hasMoreElements() ) { nextElement = currentEnumeration.nextElement(); } else if ( index < enumerations.length ) { currentEnumeration = enumerations[index++]; } else { return false; // no more elements } } return true; } public T nextElement() { if ( hasMoreElements() ) { final T element = nextElement; nextElement = null; return element; } throw new NoSuchElementException(); } } } ClassSpace.java000066400000000000000000000050621167051330000406070ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.net.URL; import java.util.Enumeration; import org.osgi.framework.Bundle; /** * Represents an abstract collection of related classes and resources. */ public interface ClassSpace { /** * Loads the named class from the surrounding class space. * * @param name The class name * @return Class instance * @see ClassLoader#loadClass(String) */ Class loadClass( String name ) throws TypeNotPresentException; /** * Defers loading of the named class from the surrounding class space. * * @param name The class name * @return Deferred class * @see ClassLoader#loadClass(String) */ DeferredClass deferLoadClass( String name ); /** * Queries the surrounding class space for the resource with the given name. * * @param name The resource name * @return URL pointing to the resource; {@code null} if it wasn't found * @see ClassLoader#getResource(String) */ URL getResource( String name ); /** * Queries the surrounding class space for all resources with the given name. * * @param name The resource name * @return Sequence of URLs, one for each matching resource * @see ClassLoader#getResources(String) */ Enumeration getResources( String name ); /** * Queries local class space content for entries matching the given pattern. * * @param path The initial search directory; for example {@code "META-INF"} * @param glob The filename glob pattern; for example {@code "*.xml"} * @param recurse If {@code true} recurse into sub-directories; otherwise only search initial directory * @return Sequence of URLs, one for each matching entry * @see Bundle#findEntries(String, String, boolean) */ Enumeration findEntries( String path, String glob, boolean recurse ); } DeclaredMembers.java000066400000000000000000000131141167051330000416010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.reflect.Member; import java.util.Iterator; import java.util.NoSuchElementException; /** * {@link Iterable} that iterates over declared members of a class hierarchy. */ public final class DeclaredMembers implements Iterable { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Class clazz; private final View[] views; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public DeclaredMembers( final Class clazz, final View... views ) { this.clazz = clazz; this.views = views.length == 0 ? View.values() : views; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterator iterator() { return new MemberIterator( clazz, views ); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Read-only {@link Iterator} that uses rolling {@link View}s to traverse the different members. */ private static final class MemberIterator implements Iterator { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final Member[] NO_MEMBERS = {}; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private Class clazz; private final View[] views; private int viewIndex; private Member[] members = NO_MEMBERS; private int memberIndex; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- MemberIterator( final Class clazz, final View[] views ) { this.clazz = filterClass( clazz ); this.views = views; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { while ( memberIndex <= 0 ) { if ( viewIndex >= views.length ) { // no more views, time to move up hierarchy clazz = filterClass( clazz.getSuperclass() ); viewIndex = 0; } if ( null == clazz ) { return false; } final int index = viewIndex++; members = views[index].members( clazz ); memberIndex = members.length; } return true; } public Member next() { if ( hasNext() ) { // initialized by hasNext() return members[--memberIndex]; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static Class filterClass( final Class clazz ) { // deliberately ignore all java.* classes because we won't be injecting them return null == clazz || clazz.getName().startsWith( "java." ) ? null : clazz; } } /** * {@link Enum} implementation that provides different views of a class's members. */ public static enum View { CONSTRUCTORS { @Override final Member[] members( final Class clazz ) { return clazz.getDeclaredConstructors(); } }, METHODS { @Override final Member[] members( final Class clazz ) { return clazz.getDeclaredMethods(); } }, FIELDS { @Override final Member[] members( final Class clazz ) { return clazz.getDeclaredFields(); } }; abstract Member[] members( final Class clazz ); } } DeferredClass.java000066400000000000000000000024241167051330000412730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; /** * Placeholder {@link Class}; postpones classloading until absolutely necessary. */ public interface DeferredClass { /** * Retrieves the class, for example from a cache or a class loader. * * @return Class instance */ Class load() throws TypeNotPresentException; /** * Returns the name of the deferred class. * * @return Class name */ String getName(); /** * Returns a provider based on the deferred class. * * @return Deferred provider */ DeferredProvider asProvider(); } DeferredProvider.java000066400000000000000000000017341167051330000420230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import com.google.inject.Provider; /** * {@link Provider} backed by a {@link DeferredClass}. */ public interface DeferredProvider extends Provider { /** * @return Deferred implementation class */ DeferredClass getImplementationClass(); } FileEntryIterator.java000066400000000000000000000114561167051330000422050ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.File; import java.net.URL; import java.util.Iterator; import java.util.LinkedList; /** * {@link Iterator} that iterates over named entries beneath a file-system directory. */ final class FileEntryIterator implements Iterator { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final String rootPath; private final LinkedList entryNames = new LinkedList(); private final boolean recurse; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- /** * Creates an iterator that iterates over entries beneath the given file URL and sub-path. * * @param url The root file URL * @param subPath The path below the root URL * @param recurse When {@code true} include sub-directories; otherwise don't */ FileEntryIterator( final URL url, final String subPath, final boolean recurse ) { rootPath = normalizePath( toFile( url ).getAbsoluteFile() ); this.recurse = recurse; appendEntries( subPath ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { return entryNames.size() > 0; } public String next() { final String name = entryNames.removeFirst(); if ( recurse && name.endsWith( "/" ) ) { appendEntries( name ); } return name; } public void remove() { throw new UnsupportedOperationException(); } // ---------------------------------------------------------------------- // Local methods // ---------------------------------------------------------------------- /** * Converts a {@link URL} into a {@link File} converting slashes and encoded characters where appropriate. * * @param url The file URL * @return File instance for the given URL */ static File toFile( final URL url ) { final StringBuilder buf = new StringBuilder(); final String path = url.getPath(); for ( int i = 0, length = path.length(); i < length; i++ ) { final char c = path.charAt( i ); if ( '/' == c ) { buf.append( File.separatorChar ); } else if ( '%' == c && i < length - 2 ) { final int hi = Character.digit( path.charAt( i + 1 ), 16 ); final int lo = Character.digit( path.charAt( i + 2 ), 16 ); if ( hi >= 0 && lo >= 0 ) { buf.append( (char) ( hi << 4 | lo ) ); i += 2; } else { buf.append( '%' ); } } else { buf.append( c ); } } return new File( buf.toString() ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Appends entries from the given sub-path to the cached list of named entries. * * @param subPath The sub path */ private void appendEntries( final String subPath ) { final File[] listing = new File( rootPath + subPath ).listFiles(); if ( null != listing ) { for ( final File f : listing ) { entryNames.add( normalizePath( f ).substring( rootPath.length() ) ); } } } /** * Returns the normalized URI path of the given file. * * @param file The file to normalize * @return Normalized URI path */ private static String normalizePath( final File file ) { return file.toURI().getPath(); } } GlobberStrategy.java000066400000000000000000000116011167051330000416610ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.util.regex.Pattern; /** * Enumerates various optimized filename globbing strategies. */ enum GlobberStrategy { // ---------------------------------------------------------------------- // Enumerated values // ---------------------------------------------------------------------- ANYTHING { @Override final Object compile( final String glob ) { return null; } @Override final boolean matches( final Object globPattern, final String filename ) { return true; } }, SUFFIX { @Override final Object compile( final String glob ) { return glob.substring( 1 ); // remove leading asterisk } @Override final boolean matches( final Object globPattern, final String filename ) { return filename.endsWith( (String) globPattern ); // no need for basename(...) } }, PREFIX { @Override final Object compile( final String glob ) { return glob.substring( 0, glob.length() - 1 ); // remove trailing asterisk } @Override final boolean matches( final Object globPattern, final String filename ) { return basename( filename ).startsWith( (String) globPattern ); } }, EXACT { @Override final Object compile( final String glob ) { return glob; } @Override final boolean matches( final Object globPattern, final String filename ) { return globPattern.equals( basename( filename ) ); } }, PATTERN { @Override final Object compile( final String glob ) { return Pattern.compile( "\\Q" + glob.replaceAll( "\\*+", "\\\\E.*\\\\Q" ) + "\\E" ); } @Override final boolean matches( final Object globPattern, final String filename ) { return ( (Pattern) globPattern ).matcher( basename( filename ) ).matches(); } }; // ---------------------------------------------------------------------- // Local methods // ---------------------------------------------------------------------- /** * Selects the optimal globber strategy for the given plain-text glob. * * @param glob The plain-text glob * @return Optimal globber strategy */ static final GlobberStrategy selectFor( final String glob ) { if ( null == glob || "*".equals( glob ) ) { return GlobberStrategy.ANYTHING; } final int firstWildcard = glob.indexOf( '*' ); if ( firstWildcard < 0 ) { return GlobberStrategy.EXACT; } final int lastWildcard = glob.lastIndexOf( '*' ); if ( firstWildcard == lastWildcard ) { if ( firstWildcard == 0 ) { return GlobberStrategy.SUFFIX; } if ( lastWildcard == glob.length() - 1 ) { return GlobberStrategy.PREFIX; } } return GlobberStrategy.PATTERN; } /** * Compiles the given plain-text glob into an optimized pattern. * * @param glob The plain-text glob * @return Compiled glob pattern */ abstract Object compile( final String glob ); /** * Attempts to match the given compiled glob pattern against a filename. * * @param globPattern The compiled glob pattern * @param filename The candidate filename * @return {@code true} if the pattern matches; otherwise {@code false} */ abstract boolean matches( final Object globPattern, final String filename ); // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Extracts the basename segment from the given filename. * * @param filename The filename * @return Basename segment */ static final String basename( final String filename ) { return filename.substring( 1 + filename.lastIndexOf( '/' ) ); } } IgnoreSetters.java000066400000000000000000000021271167051330000413620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotates class hierarchies that don't want setter injection. */ @Target( value = ElementType.TYPE ) @Retention( RetentionPolicy.RUNTIME ) @Inherited public @interface IgnoreSetters { } LoadedClass.java000066400000000000000000000044271167051330000407500ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; /** * Pseudo {@link DeferredClass} backed by an already loaded {@link Class}. */ public final class LoadedClass extends AbstractDeferredClass { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Class clazz; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- @SuppressWarnings( "unchecked" ) public LoadedClass( final Class clazz ) { this.clazz = (Class) clazz; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Class load() { return clazz; } public String getName() { return clazz.getName(); } @Override public int hashCode() { return clazz.hashCode(); } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof LoadedClass ) { return clazz == ( (LoadedClass) rhs ).clazz; } return false; } @Override public String toString() { final String id = "Loaded " + clazz; final ClassLoader space = clazz.getClassLoader(); return null != space ? id + " from " + space : id; } } Logs.java000066400000000000000000000321511167051330000374710ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.util.Map; import java.util.logging.Level; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.ProvisionException; import com.google.inject.spi.Element; import com.google.inject.spi.Elements; /** * Utility methods for dealing with internal debug and warning messages. *

* Set -Dorg.sonatype.inject.debug=true to send debug to the console. */ public final class Logs { // ---------------------------------------------------------------------- // Static initialization // ---------------------------------------------------------------------- static { String newLine; boolean isDebug; try { newLine = System.getProperty( "line.separator", "\n" ); final String debug = System.getProperty( "org.sonatype.inject.debug", "false" ); isDebug = "".equals( debug ) || "true".equalsIgnoreCase( debug ); } catch ( final RuntimeException e ) { newLine = "\n"; isDebug = false; } NEW_LINE = newLine; Sink sink; try { sink = isDebug ? new ConsoleSink() : new SLF4JSink(); } catch ( final RuntimeException e ) { sink = new JULSink(); } catch ( final LinkageError e ) { sink = new JULSink(); } SINK = sink; } // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- public static final String NEW_LINE; private static final String SISU = "Sisu"; private static final Sink SINK; public static final boolean DEBUG_ENABLED = SINK.isDebugEnabled(); // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private Logs() { // static utility class, not allowed to create instances } // ---------------------------------------------------------------------- // Utility methods // ---------------------------------------------------------------------- /** * Logs a debug message; uses "{}" format anchors. Pass {@link Throwable}s in last parameter for special handling. * * @param format The debug message format * @param arg1 First object to format * @param arg2 Second object to format */ public static void debug( final String format, final Object arg1, final Object arg2 ) { if ( DEBUG_ENABLED ) { SINK.debug( format( format( format, arg1 ), arg2 ), arg2 instanceof Throwable ? (Throwable) arg2 : null ); } } /** * Logs a warning message; uses "{}" format anchors. Pass {@link Throwable}s in last parameter for special handling. * * @param format The warning message format * @param arg1 First object to format * @param arg2 Second object to format */ public static void warn( final String format, final Object arg1, final Object arg2 ) { SINK.warn( format( format( format, arg1 ), arg2 ), arg2 instanceof Throwable ? (Throwable) arg2 : null ); } /** * Helper method for catching {@link Throwable}s; severe errors such as {@link ThreadDeath} are always re-thrown. * * @param problem The problem */ public static void catchThrowable( final Throwable problem ) { for ( Throwable cause = problem; cause != null; cause = cause.getCause() ) { if ( cause instanceof ThreadDeath || cause instanceof VirtualMachineError ) { throw (Error) cause; // must immediately re-throw severe errors } } } /** * Helper method for throwing {@link Throwable}s; checked exceptions are wrapped as {@link ProvisionException}s. * * @param problem The problem */ public static void throwUnchecked( final Throwable problem ) { if ( problem instanceof RuntimeException ) { throw (RuntimeException) problem; } if ( problem instanceof Error ) { throw (Error) problem; } throw new ProvisionException( problem.toString(), problem ); } /** * Returns an identity string for the given object. * * @see System#identityHashCode(Object) * @param object The object * @return Identity string of the object. */ public static String identityToString( final Object object ) { return null == object ? null : object.getClass().getName() + '@' + Integer.toHexString( System.identityHashCode( object ) ); } /** * Returns a string representation of the given {@link Module}. * * @param module The module * @return String representation of the module. */ public static String toString( final Module module ) { final StringBuilder buf = new StringBuilder( identityToString( module ) ); buf.append( NEW_LINE ).append( NEW_LINE ); buf.append( "-----[elements]----------------------------------------------------------------" ).append( NEW_LINE ); int i = 0; for ( final Element e : Elements.getElements( module ) ) { buf.append( i++ ).append( ". " ).append( e ).append( NEW_LINE ); } return buf.append( "-------------------------------------------------------------------------------" ).append( NEW_LINE ).toString(); } /** * Returns a string representation of the given {@link Injector}. * * @param injector The injector * @return String representation of the injector. */ public static String toString( final Injector injector ) { final StringBuilder buf = new StringBuilder( identityToString( injector ) ); if ( null != injector.getParent() ) { buf.append( " parent: " ).append( identityToString( injector.getParent() ) ); } buf.append( NEW_LINE ).append( NEW_LINE ); buf.append( "-----[explicit bindings]-------------------------------------------------------" ).append( NEW_LINE ); int i = 0; final Map, Binding> explicitBindings = injector.getBindings(); for ( final Binding b : explicitBindings.values() ) { buf.append( i++ ).append( ". " ).append( b ).append( NEW_LINE ); } buf.append( "-----[implicit bindings]-------------------------------------------------------" ).append( NEW_LINE ); for ( final Binding b : injector.getAllBindings().values() ) { if ( !explicitBindings.containsKey( b.getKey() ) ) { buf.append( i++ ).append( ". " ).append( b ).append( NEW_LINE ); } } return buf.append( "-------------------------------------------------------------------------------" ).append( NEW_LINE ).toString(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Replaces the first available formatting anchor with the given object. * * @param format The format string * @param arg The object to format */ private static String format( final String format, final Object arg ) { boolean detailed = true; int cursor = format.indexOf( "{}" ); // replaced with String.valueOf if ( cursor < 0 ) { cursor = format.indexOf( "<>" ); // use identityToString instead detailed = false; } if ( cursor < 0 ) { return format; } final StringBuilder buf = new StringBuilder(); if ( cursor > 0 ) { buf.append( format.substring( 0, cursor ) ); } try { buf.append( detailed ? arg : identityToString( arg ) ); } catch ( final RuntimeException e ) { buf.append( e ); } cursor += 2; if ( cursor < format.length() ) { buf.append( format.substring( cursor, format.length() ) ); } return buf.toString(); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Something that accepts formatted messages. */ private interface Sink { /** * @return {@code true} if debug is enabled; otherwise {@code false} */ boolean isDebugEnabled(); /** * Accepts a debug message and optional exception cause. * * @param message The debug message * @param cause The exception cause */ void debug( String message, Throwable cause ); /** * Accepts a warning message and optional exception cause. * * @param message The warning message * @param cause The exception cause */ void warn( String message, Throwable cause ); } /** * {@link Sink}s messages to the system console. */ static final class ConsoleSink implements Sink { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String DEBUG = "DEBUG: " + SISU + " - "; private static final String WARN = "WARN: " + SISU + " - "; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean isDebugEnabled() { return true; } public void debug( final String message, final Throwable cause ) { System.out.println( DEBUG + message ); if ( null != cause ) { cause.printStackTrace( System.out ); } } public void warn( final String message, final Throwable cause ) { System.err.println( WARN + message ); if ( null != cause ) { cause.printStackTrace( System.err ); } } } /** * {@link Sink}s messages to the JDK. */ static final class JULSink implements Sink { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger( SISU ); // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean isDebugEnabled() { return logger.isLoggable( Level.FINE ); } public void debug( final String message, final Throwable cause ) { logger.log( Level.FINE, message, cause ); } public void warn( final String message, final Throwable cause ) { logger.log( Level.WARNING, message, cause ); } } /** * {@link Sink}s messages via SLF4J. */ static final class SLF4JSink implements Sink { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger( SISU ); // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean isDebugEnabled() { return logger.isDebugEnabled(); } public void debug( final String message, final Throwable cause ) { logger.debug( message, cause ); } public void warn( final String message, final Throwable cause ) { logger.warn( message, cause ); } } } MildElements.java000066400000000000000000000166011167051330000411510ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * NON-thread-safe {@link Collection} of elements kept alive by soft/weak {@link Reference}s. */ final class MildElements extends AbstractCollection { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final ReferenceQueue queue = new ReferenceQueue(); final List> list; private final boolean soft; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- MildElements( final List> list, final boolean soft ) { this.list = list; this.soft = soft; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public boolean add( final T element ) { compact(); return list.add( soft ? new Soft( element, queue, list.size() ) : new Weak( element, queue, list.size() ) ); } @Override public int size() { compact(); return list.size(); } @Override public Iterator iterator() { compact(); return new Itr(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Compacts the list by replacing unreachable {@link Reference}s with ones from the end. */ private void compact() { Reference ref; while ( ( ref = queue.poll() ) != null ) { evict( ref ); } } /** * Evicts a single {@link Reference} from the list; replacing it with one from the end. * * @param ref The reference to evict */ void evict( final Reference ref ) { final int index = ( (Indexable) ref ).index( -1 ); if ( index >= 0 ) { final Reference last = list.remove( list.size() - 1 ); if ( ref != last ) { ( (Indexable) last ).index( index ); list.set( index, last ); } } } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Represents an element that can be indexed. */ private interface Indexable { int index( int index ); } /** * {@link Iterator} that iterates over reachable {@link Reference}s in the list. */ final class Itr implements Iterator { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private int index; private T nextElement; private boolean haveElement; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { // find next element that is still reachable while ( null == nextElement && index < list.size() ) { nextElement = list.get( index++ ).get(); } return null != nextElement; } public T next() { haveElement = hasNext(); if ( haveElement ) { // populated by hasNext() final T element = nextElement; nextElement = null; return element; } throw new NoSuchElementException(); } public void remove() { if ( haveElement ) { evict( list.get( --index ) ); haveElement = false; } else { throw new IllegalStateException(); } } } /** * Soft {@link Indexable} element. */ private static final class Soft extends SoftReference implements Indexable { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private int index; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- Soft( final T value, final ReferenceQueue queue, final int index ) { super( value, queue ); this.index = index; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public int index( final int newIndex ) { final int oldIndex = index; index = newIndex; return oldIndex; } } /** * Weak {@link Indexable} element. */ private static final class Weak extends WeakReference implements Indexable { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private int index; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- Weak( final T value, final ReferenceQueue queue, final int index ) { super( value, queue ); this.index = index; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public int index( final int newIndex ) { final int oldIndex = index; index = newIndex; return oldIndex; } } } MildKeys.java000066400000000000000000000235051167051330000403110ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; /** * NON-thread-safe {@link Map} whose keys are kept alive by soft/weak {@link Reference}s. */ class MildKeys implements Map { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final ReferenceQueue queue = new ReferenceQueue(); private final Map, V> map; private final boolean soft; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- MildKeys( final Map, V> map, final boolean soft ) { this.map = map; this.soft = soft; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public final boolean containsKey( final Object key ) { // skip compact for performance reasons return map.containsKey( tempKey( key ) ); } public final boolean containsValue( final Object value ) { // skip compact for performance reasons return map.containsValue( value ); } public final V get( final Object key ) { // skip compact for performance reasons return map.get( tempKey( key ) ); } public final V put( final K key, final V value ) { compact(); return map.put( mildKey( key ), value ); } public final void putAll( final Map m ) { compact(); for ( final Entry e : m.entrySet() ) { map.put( mildKey( e.getKey() ), e.getValue() ); } } public final V remove( final Object key ) { compact(); return map.remove( tempKey( key ) ); } public final void clear() { map.clear(); compact(); } public final boolean isEmpty() { compact(); return map.isEmpty(); } public final int size() { compact(); return map.size(); } /** * WARNING: this view is a snapshot; updates to it are not reflected in the original map, or vice-versa. *


* {@inheritDoc} */ public final Set keySet() { compact(); final Set keys = new HashSet(); for ( final Reference r : map.keySet() ) { final K key = r.get(); if ( null != key ) { keys.add( key ); } } return keys; } public final Collection values() { compact(); return map.values(); } /** * WARNING: this view is a snapshot; updates to it are not reflected in the original map, or vice-versa. *
* {@inheritDoc} */ public final Set> entrySet() { compact(); final Map entries = new HashMap(); for ( final Entry, V> e : map.entrySet() ) { final K key = e.getKey().get(); if ( null != key ) { entries.put( key, e.getValue() ); } } return entries.entrySet(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * @return Soft or weak {@link Reference} for the given key. */ final Reference mildKey( final K key ) { return soft ? new Soft( key, queue ) : new Weak( key, queue ); } /** * @return Temporary {@link Reference} for the given key; used in queries. */ static final Reference tempKey( final Object key ) { return new Weak( key, null ); } /** * Compacts the map by removing cleared keys. */ final void compact() { Reference ref; while ( ( ref = queue.poll() ) != null ) { map.remove( ref ); } } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Soft key that maintains a constant hash and uses referential equality. */ static class Soft extends SoftReference { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final int hash; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- Soft( final T o, final ReferenceQueue queue ) { super( o, queue ); hash = o.hashCode(); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public final int hashCode() { return hash; } @Override public final boolean equals( final Object rhs ) { if ( this == rhs ) { return true; // exact same reference } final T o = get(); if ( null != o && rhs instanceof Reference ) { // different reference, but same referent return o == ( (Reference) rhs ).get(); } return false; } } /** * Weak key that maintains a constant hash and uses referential equality. */ static class Weak extends WeakReference { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final int hash; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- Weak( final T o, final ReferenceQueue queue ) { super( o, queue ); hash = o.hashCode(); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public final int hashCode() { return hash; } @Override public final boolean equals( final Object rhs ) { if ( this == rhs ) { return true; // exact same reference } final T o = get(); if ( null != o && rhs instanceof Reference ) { // different reference, but same referent return o == ( (Reference) rhs ).get(); } return false; } } } /** * Thread-safe {@link Map} whose keys are kept alive by soft/weak {@link Reference}s. */ final class MildConcurrentKeys extends MildKeys implements ConcurrentMap { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final ConcurrentMap, V> concurrentMap; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- MildConcurrentKeys( final ConcurrentMap, V> map, final boolean soft ) { super( map, soft ); this.concurrentMap = map; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public V putIfAbsent( final K key, final V value ) { compact(); return concurrentMap.putIfAbsent( mildKey( key ), value ); } public V replace( final K key, final V value ) { compact(); return concurrentMap.replace( mildKey( key ), value ); } public boolean replace( final K key, final V oldValue, final V newValue ) { compact(); return concurrentMap.replace( mildKey( key ), oldValue, newValue ); } public boolean remove( final Object key, final Object value ) { compact(); return concurrentMap.remove( tempKey( key ), value ); } } MildValues.java000066400000000000000000000250771167051330000406430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; /** * NON-thread-safe {@link Map} whose values are kept alive by soft/weak {@link Reference}s. */ class MildValues implements Map { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- final ReferenceQueue queue = new ReferenceQueue(); private final Map> map; private final boolean soft; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- MildValues( final Map> map, final boolean soft ) { this.map = map; this.soft = soft; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public final boolean containsKey( final Object key ) { // skip compact for performance reasons return map.containsKey( key ); } public final boolean containsValue( final Object value ) { // skip compact for performance reasons return map.containsValue( tempValue( value ) ); } public final V get( final Object key ) { // skip compact for performance reasons final Reference ref = map.get( key ); return null != ref ? ref.get() : null; } public final V put( final K key, final V value ) { compact(); final Reference ref = map.put( key, mildValue( key, value ) ); return null != ref ? ref.get() : null; } public final void putAll( final Map m ) { compact(); for ( final Entry e : m.entrySet() ) { map.put( e.getKey(), mildValue( e.getKey(), e.getValue() ) ); } } public final V remove( final Object key ) { compact(); final Reference ref = map.remove( key ); return null != ref ? ref.get() : null; } public final void clear() { map.clear(); compact(); } public final boolean isEmpty() { compact(); return map.isEmpty(); } public final int size() { compact(); return map.size(); } public final Set keySet() { compact(); return map.keySet(); } /** * WARNING: this view is a snapshot; updates to it are not reflected in the original map, or vice-versa. *
* {@inheritDoc} */ public final Collection values() { compact(); final List values = new ArrayList(); for ( final Reference r : map.values() ) { final V value = r.get(); if ( null != value ) { values.add( value ); } } return values; } /** * WARNING: this view is a snapshot; updates to it are not reflected in the original map, or vice-versa. *
* {@inheritDoc} */ public final Set> entrySet() { compact(); final Map entries = new HashMap(); for ( final Entry> e : map.entrySet() ) { final V value = e.getValue().get(); if ( null != value ) { entries.put( e.getKey(), value ); } } return entries.entrySet(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * @return Soft or weak {@link Reference} for the given key-value mapping. */ final Reference mildValue( final K key, final V value ) { return soft ? new Soft( key, value, queue ) : new Weak( key, value, queue ); } /** * @return Temporary {@link Reference} for the given value; used in queries. */ static final Reference tempValue( final Object value ) { return new Weak( null, value, null ); } /** * Compacts the map by removing cleared values. */ void compact() { Reference ref; while ( ( ref = queue.poll() ) != null ) { // only remove this specific key-value mapping final Object key = ( (InverseMapping) ref ).key(); if ( map.get( key ) == ref ) { map.remove( key ); } } } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Represents an inverse mapping from a value to its key. */ interface InverseMapping { Object key(); } /** * Soft value with an {@link InverseMapping} back to its key. */ private final static class Soft extends MildKeys.Soft implements InverseMapping { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final K key; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- Soft( final K key, final V value, final ReferenceQueue queue ) { super( value, queue ); this.key = key; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Object key() { return key; } } /** * Weak value with an {@link InverseMapping} back to its key. */ private final static class Weak extends MildKeys.Weak implements InverseMapping { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final K key; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- Weak( final K key, final V value, final ReferenceQueue queue ) { super( value, queue ); this.key = key; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Object key() { return key; } } } /** * Thread-safe {@link Map} whose values are kept alive by soft/weak {@link Reference}s. */ final class MildConcurrentValues extends MildValues implements ConcurrentMap { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final ConcurrentMap> concurrentMap; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- MildConcurrentValues( final ConcurrentMap> map, final boolean soft ) { super( map, soft ); this.concurrentMap = map; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public V putIfAbsent( final K key, final V value ) { compact(); final Reference ref = mildValue( key, value ); /* * We must either add our value to the map, or return a non-null existing value. */ Reference oldRef; while ( ( oldRef = concurrentMap.putIfAbsent( key, ref ) ) != null ) { final V oldValue = oldRef.get(); if ( null != oldValue ) { return oldValue; } concurrentMap.remove( key, oldRef ); // gone AWOL; remove entry and try again } return null; } public V replace( final K key, final V value ) { compact(); final Reference ref = concurrentMap.replace( key, mildValue( key, value ) ); return null != ref ? ref.get() : null; } public boolean replace( final K key, final V oldValue, final V newValue ) { compact(); return concurrentMap.replace( key, mildValue( null, oldValue ), mildValue( key, newValue ) ); } public boolean remove( final Object key, final Object value ) { compact(); return concurrentMap.remove( key, tempValue( value ) ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- @Override void compact() { Reference ref; while ( ( ref = queue.poll() ) != null ) { // only remove this specific key-value mapping; thread-safe concurrentMap.remove( ( (InverseMapping) ref ).key(), ref ); } } } NamedClass.java000066400000000000000000000045461167051330000406060ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; /** * {@link DeferredClass} representing a named class from a {@link ClassSpace}. */ final class NamedClass extends AbstractDeferredClass { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final ClassSpace space; private final String name; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public NamedClass( final ClassSpace space, final String name ) { this.space = space; this.name = name; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @SuppressWarnings( "unchecked" ) public Class load() { return (Class) space.loadClass( name ); } public String getName() { return name; } @Override public int hashCode() { return ( 17 * 31 + name.hashCode() ) * 31 + space.hashCode(); } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof NamedClass ) { final NamedClass clazz = (NamedClass) rhs; return name.equals( clazz.name ) && space.equals( clazz.space ); } return false; } @Override public String toString() { return "Deferred " + name + " from " + space; } } ResourceEnumeration.java000066400000000000000000000224021167051330000425610ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipInputStream; /** * {@link Enumeration} of resources found by scanning JARs and directories. */ final class ResourceEnumeration implements Enumeration { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final Iterator NO_ENTRIES = Collections. emptySet().iterator(); // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final URL[] urls; private final String subPath; private final GlobberStrategy globber; private final Object globPattern; private final boolean recurse; private int index; private URL currentURL; private boolean isFolder; private Iterator entryNames = NO_ENTRIES; private String nextEntryName; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- /** * Creates an {@link Enumeration} that scans the given URLs for resources matching the globbed pattern. * * @param subPath An optional path to begin the search from * @param glob The globbed basename pattern * @param recurse When {@code true} search paths below the initial search point; otherwise don't * @param urls The URLs containing resources */ ResourceEnumeration( final String subPath, final String glob, final boolean recurse, final URL[] urls ) { this.subPath = normalizeSearchPath( subPath ); globber = GlobberStrategy.selectFor( glob ); globPattern = globber.compile( glob ); this.recurse = recurse; this.urls = urls; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasMoreElements() { while ( null == nextEntryName ) { if ( entryNames.hasNext() ) { final String name = entryNames.next(); if ( matchesRequest( name ) ) { nextEntryName = name; } } else if ( index < urls.length ) { currentURL = urls[index++]; entryNames = scan( currentURL ); } else { return false; // no more URLs } } return true; } public URL nextElement() { if ( hasMoreElements() ) { // initialized by hasMoreElements() final String name = nextEntryName; nextEntryName = null; try { return findResource( name ); } catch ( final MalformedURLException e ) { // this shouldn't happen, hence illegal state throw new IllegalStateException( e.toString() ); } } throw new NoSuchElementException(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Normalizes the initial search path by removing any duplicate or initial slashes. * * @param path The path to normalize * @return Normalized search path */ private static String normalizeSearchPath( final String path ) { if ( null == path || "/".equals( path ) ) { return ""; } boolean echoSlash = false; final StringBuilder buf = new StringBuilder(); for ( int i = 0, length = path.length(); i < length; i++ ) { // ignore any duplicate slashes final char c = path.charAt( i ); final boolean isNotSlash = '/' != c; if ( echoSlash || isNotSlash ) { echoSlash = isNotSlash; buf.append( c ); } } if ( echoSlash ) { // add final slash buf.append( '/' ); } return buf.toString(); } /** * Returns the appropriate {@link Iterator} to iterate over the contents of the given URL. * * @param url The containing URL * @return Iterator that iterates over resources contained inside the given URL */ private Iterator scan( final URL url ) { isFolder = url.getPath().endsWith( "/" ); if ( globber == GlobberStrategy.EXACT && !recurse ) { try { // short-cut the nextElement() process nextEntryName = subPath + globPattern; // but still need to check resource actually exists! Streams.open( findResource( nextEntryName ) ).close(); } catch ( final Exception e ) // IOException + SecurityException + etc... { nextEntryName = null; } return NO_ENTRIES; } return isFolder ? new FileEntryIterator( url, subPath, recurse ) : new ZipEntryIterator( url ); } /** * Returns a {@link URL} pointing to the named resource underneath the current search URL. * * @param name The resource name * @return URL for the resource */ private URL findResource( final String name ) throws MalformedURLException { if ( isFolder ) { return new URL( currentURL, name ); } if ( "jar".equals( currentURL.getProtocol() ) ) { // workaround JDK limitation that doesn't allow nested "jar:" URLs return new URL( currentURL, "#" + name, new NestedJarURLHandler() ); } return new URL( "jar:" + currentURL + "!/" + name ); } /** * Compares the given entry name against the normalized search path and compiled glob pattern. * * @param entryName The entry name * @return {@code true} if the given name matches the search criteria; otherwise {@code false} */ private boolean matchesRequest( final String entryName ) { if ( entryName.endsWith( "/" ) || !entryName.startsWith( subPath ) ) { return false; // not inside the search scope } if ( !recurse && entryName.indexOf( '/', subPath.length() ) > 0 ) { return false; // inside a sub-directory } return globber.matches( globPattern, entryName ); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- /** * Custom {@link URLStreamHandler} that can stream JARs nested inside an arbitrary resource. */ static final class NestedJarURLHandler extends URLStreamHandler { @Override protected URLConnection openConnection( final URL url ) { return new URLConnection( url ) { @Override public void connect() { // postpone until someone actually requests an input stream } @Override public InputStream getInputStream() throws IOException { final URL containingURL = new URL( "jar", null, -1, url.getFile() ); final ZipInputStream is = new ZipInputStream( Streams.open( containingURL ) ); final String entryName = url.getRef(); for ( ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry() ) { if ( entryName.equals( entry.getName() ) ) { return is; } } throw new ZipException( "No such entry: " + entryName + " in: " + containingURL ); } }; } } } Soft.java000066400000000000000000000102571167051330000375030ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Utility methods for dealing with {@link SoftReference} collections. */ @SuppressWarnings( { "rawtypes", "unchecked" } ) public final class Soft { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private Soft() { // static utility class, not allowed to create instances } // ---------------------------------------------------------------------- // Utility methods // ---------------------------------------------------------------------- /** * @return {@link Collection} whose elements are kept alive with {@link SoftReference}s */ public static Collection elements() { return elements( 10 ); } /** * @param capacity The initial capacity * @return {@link Collection} whose elements are kept alive with {@link SoftReference}s */ public static Collection elements( final int capacity ) { return new MildElements( new ArrayList( capacity ), true ); } /** * @return {@link Map} whose keys are kept alive with {@link SoftReference}s */ public static Map keys() { return keys( 16 ); } /** * @param capacity The initial capacity * @return {@link Map} whose keys are kept alive with {@link SoftReference}s */ public static Map keys( final int capacity ) { return new MildKeys( new HashMap( capacity ), true ); } /** * @return {@link ConcurrentMap} whose keys are kept alive with {@link SoftReference}s */ public static ConcurrentMap concurrentKeys() { return concurrentKeys( 16, 4 ); } /** * @param capacity The initial capacity * @param concurrency The concurrency level * @return {@link ConcurrentMap} whose keys are kept alive with {@link SoftReference}s */ public static ConcurrentMap concurrentKeys( final int capacity, final int concurrency ) { return new MildConcurrentKeys( new ConcurrentHashMap( capacity, 0.75f, concurrency ), true ); } /** * @return {@link Map} whose values are kept alive with {@link SoftReference}s */ public static Map values() { return values( 16 ); } /** * @param capacity The initial capacity * @return {@link Map} whose values are kept alive with {@link SoftReference}s */ public static Map values( final int capacity ) { return new MildValues( new HashMap( capacity ), true ); } /** * @return {@link ConcurrentMap} whose values are kept alive with {@link SoftReference}s */ public static ConcurrentMap concurrentValues() { return concurrentValues( 16, 4 ); } /** * @param capacity The initial capacity * @param concurrency The concurrency level * @return {@link ConcurrentMap} whose values are kept alive with {@link SoftReference}s */ public static ConcurrentMap concurrentValues( final int capacity, final int concurrency ) { return new MildConcurrentValues( new ConcurrentHashMap( capacity, 0.75f, concurrency ), true ); } } Streams.java000066400000000000000000000047271167051330000402130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Locale; /** * Utility methods for dealing with streams. */ public final class Streams { // ---------------------------------------------------------------------- // Static initialization // ---------------------------------------------------------------------- static { boolean onWindows; try { onWindows = System.getProperty( "os.name" ).toLowerCase( Locale.US ).contains( "windows" ); } catch ( final RuntimeException e ) { onWindows = false; } ON_WINDOWS = onWindows; } // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final boolean ON_WINDOWS; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private Streams() { // static utility class, not allowed to create instances } // ---------------------------------------------------------------------- // Utility methods // ---------------------------------------------------------------------- /** * Opens an input stream to the given URL; disables JAR caching on Windows. */ public static InputStream open( final URL url ) throws IOException { if ( ON_WINDOWS ) { final URLConnection conn = url.openConnection(); conn.setUseCaches( false ); return conn.getInputStream(); } return url.openStream(); } } TypeParameters.java000066400000000000000000000236221167051330000415350ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import com.google.inject.ImplementedBy; import com.google.inject.ProvidedBy; import com.google.inject.TypeLiteral; /** * Utility methods for dealing with generic type parameters and arguments. */ public final class TypeParameters { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final TypeLiteral[] NO_TYPE_LITERALS = {}; private static final TypeLiteral OBJECT_TYPE_LITERAL = TypeLiteral.get( Object.class ); // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private TypeParameters() { // static utility class, not allowed to create instances } // ---------------------------------------------------------------------- // Utility methods // ---------------------------------------------------------------------- /** * Get all type arguments from a generic type, for example {@code [Foo,Bar]} from {@code Map}. * * @param typeLiteral The generic type * @return Array of type arguments */ public static TypeLiteral[] get( final TypeLiteral typeLiteral ) { final Type type = typeLiteral.getType(); if ( type instanceof ParameterizedType ) { final Type[] argumentTypes = ( (ParameterizedType) type ).getActualTypeArguments(); final TypeLiteral[] argumentLiterals = new TypeLiteral[argumentTypes.length]; for ( int i = 0; i < argumentTypes.length; i++ ) { argumentLiterals[i] = expand( argumentTypes[i] ); } return argumentLiterals; } if ( type instanceof GenericArrayType ) { return new TypeLiteral[] { expand( ( (GenericArrayType) type ).getGenericComponentType() ) }; } return NO_TYPE_LITERALS; } /** * Get an indexed type argument from a generic type, for example {@code Bar} from {@code Map}. * * @param typeLiteral The generic type * @param index The argument index * @return Indexed type argument; {@code TypeLiteral} if the given type is a raw class */ public static TypeLiteral get( final TypeLiteral typeLiteral, final int index ) { final Type type = typeLiteral.getType(); if ( type instanceof ParameterizedType ) { return expand( ( (ParameterizedType) type ).getActualTypeArguments()[index] ); } if ( type instanceof GenericArrayType ) { if ( 0 == index ) { return expand( ( (GenericArrayType) type ).getGenericComponentType() ); } throw new ArrayIndexOutOfBoundsException( index ); } return OBJECT_TYPE_LITERAL; } /** * Determines if the sub-type can be converted to the generic super-type via an identity or widening conversion. * * @param superLiteral The generic super-type * @param subLiteral The generic sub-type * @return {@code true} if the sub-type can be converted to the generic super-type; otherwise {@code false} * @see Class#isAssignableFrom(Class) */ public static boolean isAssignableFrom( final TypeLiteral superLiteral, final TypeLiteral subLiteral ) { final Class superClazz = superLiteral.getRawType(); if ( !superClazz.isAssignableFrom( subLiteral.getRawType() ) ) { return false; } final Type superType = superLiteral.getType(); if ( superClazz == superType ) { return true; } if ( superType instanceof ParameterizedType ) { final Type resolvedType = subLiteral.getSupertype( superClazz ).getType(); if ( resolvedType instanceof ParameterizedType ) { final Type[] superArgs = ( (ParameterizedType) superType ).getActualTypeArguments(); final Type[] subArgs = ( (ParameterizedType) resolvedType ).getActualTypeArguments(); return isAssignableFrom( superArgs, subArgs ); } } else if ( superType instanceof GenericArrayType ) { final Type resolvedType = subLiteral.getSupertype( superClazz ).getType(); if ( resolvedType instanceof GenericArrayType ) { final Type superComponent = ( (GenericArrayType) superType ).getGenericComponentType(); final Type subComponent = ( (GenericArrayType) resolvedType ).getGenericComponentType(); return isAssignableFrom( new Type[] { superComponent }, new Type[] { subComponent } ); } } return false; } /** * Determines if the given generic type represents a concrete type. * * @param literal The generic type * @return {@code true} if the generic type is concrete; otherwise {@code false} */ public static boolean isConcrete( final TypeLiteral literal ) { return isConcrete( literal.getRawType() ); } /** * Determines if the given raw type represents a concrete type. * * @param clazz The raw type * @return {@code true} if the raw type is concrete; otherwise {@code false} */ public static boolean isConcrete( final Class clazz ) { return !clazz.isInterface() && !Modifier.isAbstract( clazz.getModifiers() ); } /** * Determines if the given generic type represents an implicit binding. * * @param literal The generic type * @return {@code true} if the generic type is implicit; otherwise {@code false} */ public static boolean isImplicit( final TypeLiteral literal ) { return isImplicit( literal.getRawType() ); } /** * Determines if the given raw type represents an implicit binding. * * @param clazz The raw type * @return {@code true} if the raw type is implicit; otherwise {@code false} */ public static boolean isImplicit( final Class clazz ) { return isConcrete( clazz ) || clazz.isAnnotationPresent( ImplementedBy.class ) || clazz.isAnnotationPresent( ProvidedBy.class ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Expands wild-card types where possible, for example {@code Bar} from {@code ? extends Bar}. * * @param type The generic type * @return Widened type that is still assignment-compatible with the original. */ private static TypeLiteral expand( final Type type ) { if ( type instanceof WildcardType ) { return TypeLiteral.get( ( (WildcardType) type ).getUpperBounds()[0] ); } if ( type instanceof TypeVariable ) { return TypeLiteral.get( ( (TypeVariable) type ).getBounds()[0] ); } return TypeLiteral.get( type ); } /** * Determines whether the resolved sub-type arguments can be assigned to their generic super-type arguments. * * @param superArgs The generic super-arguments * @param subArgs The resolved sub-arguments * @return {@code true} if all the super-arguments have assignable resolved arguments; otherwise {@code false} */ private static boolean isAssignableFrom( final Type[] superArgs, final Type[] subArgs ) { for ( int i = 0, len = Math.min( superArgs.length, subArgs.length ); i < len; i++ ) { final Type superType = superArgs[i]; final Type subType = subArgs[i]; /* * Implementations could have unbound type variables, such as ArrayList. We want to support injecting * MyList into List. This is why the isAssignableFrom parameters are reversed. */ if ( subType instanceof TypeVariable && isAssignableFrom( expand( subType ), expand( superType ) ) ) { continue; } /* * Interfaces can have wild-card types, such as List. Note: we only check the initial * upper-bound of the super-type against the resolved type (trading absolute accuracy for performance). */ if ( superType instanceof WildcardType || superType instanceof TypeVariable ) { if ( !isAssignableFrom( expand( superType ), expand( subType ) ) ) { return false; } } /* * Non-wild-card arguments must be tested with equals: List is not assignable from List. */ else if ( !superType.equals( subType ) ) { return false; } } return true; } } URLClassSpace.java000066400000000000000000000235671167051330000412040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.Manifest; /** * {@link ClassSpace} backed by a strongly-referenced {@link ClassLoader} and a {@link URL} class path. */ public final class URLClassSpace implements ClassSpace { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String MANIFEST_ENTRY = "META-INF/MANIFEST.MF"; private static final URL[] NO_URLS = {}; private static final Enumeration NO_ENTRIES = Collections.enumeration( Collections. emptySet() ); private static final String[] EMPTY_CLASSPATH = {}; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final ClassLoader loader; private URL[] classPath; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- /** * Creates a {@link ClassSpace} backed by a {@link ClassLoader} and its default class path. *

* For {@link URLClassLoader}s this is their expanded Class-Path; otherwise it is empty. * * @param loader The class loader to use when getting/finding resources */ public URLClassSpace( final ClassLoader loader ) { this.loader = loader; // compute class path on demand } /** * Creates a {@link ClassSpace} backed by a {@link ClassLoader} with a restricted class path. * * @param loader The class loader to use when getting resources * @param path The class path to use when finding resources * @see #getResources(String) * @see #findEntries(String, String, boolean) */ public URLClassSpace( final ClassLoader loader, final URL[] path ) { this.loader = loader; if ( null != path && path.length > 0 ) { classPath = expandClassPath( path ); } else { classPath = NO_URLS; } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Class loadClass( final String name ) { try { return loader.loadClass( name ); } catch ( final Exception e ) { throw new TypeNotPresentException( name, e ); } catch ( final LinkageError e ) { throw new TypeNotPresentException( name, e ); } } public DeferredClass deferLoadClass( final String name ) { return new NamedClass( this, name ); } public URL getResource( final String name ) { return loader.getResource( name ); } public Enumeration getResources( final String name ) { try { final Enumeration resources = loader.getResources( name ); return null != resources ? resources : NO_ENTRIES; } catch ( final IOException e ) { return NO_ENTRIES; } } public Enumeration findEntries( final String path, final String glob, final boolean recurse ) { return new ResourceEnumeration( path, glob, recurse, getClassPath() ); } public URL[] getURLs() { return getClassPath().clone(); } @Override public int hashCode() { return loader.hashCode(); // the loader is the primary key } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof URLClassSpace ) { return loader.equals( ( (URLClassSpace) rhs ).loader ); } return false; } @Override public String toString() { return loader.toString(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Returns the associated {@link URL} class path; this can either be explicit or implicit. */ private synchronized URL[] getClassPath() { if ( null == classPath ) { for ( ClassLoader l = loader; l != null; l = l.getParent() ) { if ( l instanceof URLClassLoader ) { // pick first class loader with non-empty class path final URL[] path = ( (URLClassLoader) l ).getURLs(); if ( null != path && path.length > 0 ) { classPath = expandClassPath( path ); break; } } } if ( null == classPath ) { classPath = NO_URLS; // no detectable Class-Path } } return classPath; } /** * Expands the given {@link URL} class path to include Class-Path entries from local manifests. * * @param classPath The URL class path * @return Expanded URL class path */ private static URL[] expandClassPath( final URL[] classPath ) { final List searchPath = new ArrayList(); Collections.addAll( searchPath, classPath ); final List expandedPath = new ArrayList(); final Set visited = new HashSet(); // search path may grow, so use index not iterator for ( int i = 0; i < searchPath.size(); i++ ) { final URL url = normalizeEntry( searchPath.get( i ) ); if ( null == url || !visited.add( url.toString() ) ) { continue; // already processed } expandedPath.add( url ); final String[] classPathEntries; try { classPathEntries = getClassPathEntries( url ); } catch ( final IOException e ) { continue; // missing manifest } for ( final String entry : classPathEntries ) { try { searchPath.add( new URL( url, entry ) ); } catch ( final MalformedURLException e ) // NOPMD { // invalid Class-Path entry } } } return expandedPath.toArray( new URL[expandedPath.size()] ); } /** * Normalizes the given class path entry by removing any extraneous "jar:"..."!/" padding. * * @param path The URL to normalize * @return Normalized class path entry */ private static URL normalizeEntry( final URL url ) { if ( null != url && "jar".equals( url.getProtocol() ) ) { final String path = url.getPath(); if ( path.endsWith( "!/" ) ) { try { return new URL( path.substring( 0, path.length() - 2 ) ); } catch ( final MalformedURLException e ) { // this shouldn't happen, hence illegal state throw new IllegalStateException( e.toString() ); } } } return url; } /** * Looks for Class-Path entries in the given jar or directory; returns empty array if none are found. * * @param url The jar or directory to inspect * @return Array of Class-Path entries */ private static String[] getClassPathEntries( final URL url ) throws IOException { final Manifest manifest; if ( url.getPath().endsWith( "/" ) ) { final InputStream in = Streams.open( new URL( url, MANIFEST_ENTRY ) ); try { manifest = new Manifest( in ); } finally { in.close(); } } else if ( "file".equals( url.getProtocol() ) ) { manifest = new JarFile( FileEntryIterator.toFile( url ) ).getManifest(); } else { final JarInputStream jin = new JarInputStream( Streams.open( url ) ); try { manifest = jin.getManifest(); } finally { jin.close(); } } if ( null != manifest ) { final String classPath = manifest.getMainAttributes().getValue( "Class-Path" ); if ( null != classPath ) { return classPath.split( " " ); } } return EMPTY_CLASSPATH; } } Weak.java000066400000000000000000000102641167051330000374550ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Utility methods for dealing with {@link WeakReference} collections. */ @SuppressWarnings( { "rawtypes", "unchecked" } ) public final class Weak { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private Weak() { // static utility class, not allowed to create instances } // ---------------------------------------------------------------------- // Utility methods // ---------------------------------------------------------------------- /** * @return {@link Collection} whose elements are kept alive with {@link WeakReference}s */ public static Collection elements() { return elements( 10 ); } /** * @param capacity The initial capacity * @return {@link Collection} whose elements are kept alive with {@link WeakReference}s */ public static Collection elements( final int capacity ) { return new MildElements( new ArrayList( capacity ), false ); } /** * @return {@link Map} whose keys are kept alive with {@link WeakReference}s */ public static Map keys() { return keys( 16 ); } /** * @param capacity The initial capacity * @return {@link Map} whose keys are kept alive with {@link WeakReference}s */ public static Map keys( final int capacity ) { return new MildKeys( new HashMap( capacity ), false ); } /** * @return {@link ConcurrentMap} whose keys are kept alive with {@link WeakReference}s */ public static ConcurrentMap concurrentKeys() { return concurrentKeys( 16, 4 ); } /** * @param capacity The initial capacity * @param concurrency The concurrency level * @return {@link ConcurrentMap} whose keys are kept alive with {@link WeakReference}s */ public static ConcurrentMap concurrentKeys( final int capacity, final int concurrency ) { return new MildConcurrentKeys( new ConcurrentHashMap( capacity, 0.75f, concurrency ), false ); } /** * @return {@link Map} whose values are kept alive with {@link WeakReference}s */ public static Map values() { return values( 16 ); } /** * @param capacity The initial capacity * @return {@link Map} whose values are kept alive with {@link WeakReference}s */ public static Map values( final int capacity ) { return new MildValues( new HashMap( capacity ), false ); } /** * @return {@link ConcurrentMap} whose values are kept alive with {@link WeakReference}s */ public static ConcurrentMap concurrentValues() { return concurrentValues( 16, 4 ); } /** * @param capacity The initial capacity * @param concurrency The concurrency level * @return {@link ConcurrentMap} whose values are kept alive with {@link WeakReference}s */ public static ConcurrentMap concurrentValues( final int capacity, final int concurrency ) { return new MildConcurrentValues( new ConcurrentHashMap( capacity, 0.75f, concurrency ), false ); } } ZipEntryIterator.java000066400000000000000000000076501167051330000420710ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; /** * {@link Iterator} that iterates over named entries inside JAR or ZIP resources. */ final class ZipEntryIterator implements Iterator { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private String[] entryNames; private int index; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ZipEntryIterator( final URL url ) { try { if ( "file".equals( url.getProtocol() ) ) { entryNames = getEntryNames( new ZipFile( FileEntryIterator.toFile( url ) ) ); } else { entryNames = getEntryNames( new ZipInputStream( Streams.open( url ) ) ); } } catch ( final IOException e ) { entryNames = new String[0]; } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean hasNext() { return index < entryNames.length; } public String next() { return entryNames[index++]; } public void remove() { throw new UnsupportedOperationException(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Returns a string array listing the entries in the given zip file. * * @param zipFile The zip file * @return Array of entry names */ private static String[] getEntryNames( final ZipFile zipFile ) throws IOException { try { final String names[] = new String[zipFile.size()]; final Enumeration e = zipFile.entries(); for ( int i = 0; i < names.length; i++ ) { names[i] = e.nextElement().getName(); } return names; } finally { zipFile.close(); } } /** * Returns a string array listing the entries in the given zip stream. * * @param zipStream The zip stream * @return Array of entry names */ private static String[] getEntryNames( final ZipInputStream zipStream ) throws IOException { try { final List names = new ArrayList( 64 ); for ( ZipEntry e = zipStream.getNextEntry(); e != null; e = zipStream.getNextEntry() ) { names.add( e.getName() ); } return names.toArray( new String[names.size()] ); } finally { zipStream.close(); } } } package-info.java000066400000000000000000000025031167051330000411070ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * Bean reflection and introspection. * *

The principal members of this package are: *

*
{@link org.sonatype.guice.bean.reflect.ClassSpace} *
Represents a source of classes and resources that can be scanned. *
{@link org.sonatype.guice.bean.reflect.BeanProperties} *
Picks out potential bean properties from declared class members. *
{@link org.sonatype.guice.bean.reflect.Logs} *
Utility methods for logging internal debug and warning messages. *
{@link org.sonatype.guice.bean.reflect.TypeParameters} *
Utility methods for dealing with generic type parameters. *
*/ package org.sonatype.guice.bean.reflect; sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/000077500000000000000000000000001167051330000270335ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/000077500000000000000000000000001167051330000277545ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/000077500000000000000000000000001167051330000305435ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/000077500000000000000000000000001167051330000324055ustar00rootroot00000000000000000077500000000000000000000000001167051330000334225ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000343275ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000357535ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflectBeanPropertiesTest.java000066400000000000000000000302761167051330000424100ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.math.BigDecimal; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import javax.inject.Named; import javax.inject.Singleton; import junit.framework.TestCase; import com.google.inject.TypeLiteral; import com.google.inject.util.Types; @SuppressWarnings( "unused" ) public class BeanPropertiesTest extends TestCase { @Retention( RetentionPolicy.RUNTIME ) @interface Metadata { String value(); } @Target( ElementType.METHOD ) @Retention( RetentionPolicy.RUNTIME ) @interface MethodMetadata { String value(); } @Target( ElementType.FIELD ) @Retention( RetentionPolicy.RUNTIME ) @interface FieldMetadata { String value(); } @Target( { ElementType.FIELD, ElementType.METHOD } ) @Retention( RetentionPolicy.RUNTIME ) @interface MultiMetadata { String value(); } static interface A { String name = ""; void setName( String name ); } static class B { static void setName( final String name ) { } } static class C { final String name = ""; } static class D { public D() { } private void setName( final String name ) { } } static class E { void setName() { } void setName( final String firstName, final String lastName ) { } void name( final String _name ) { } @javax.inject.Inject void setName( final String _name ) { } @com.google.inject.Inject void setLastName( final String _name ) { } } static class F { void setName( final String name ) { } void setName() { } String name; void setName( final String firstName, final String lastName ) { } void name( final String _name ) { } } static class G { List names; void setMap( final Map map ) { } } static abstract class IBase { public abstract void setId( T id ); } static class H extends IBase { private volatile String vid = "test"; private static Internal internal = new Internal(); static class Internal { String m_id; } @Override public void setId( final String _id ) { internal.m_id = _id; } @Override public String toString() { return vid + "@" + internal.m_id; } } static class I { @Singleton @Named( "bar" ) String bar; @Singleton @Named( "foo" ) void setFoo( final String foo ) { } } static class J { String a; String b; String c; } static class K { void setName( final String name ) { throw new RuntimeException(); } } static class L { void setter( final String value ) { } } static class M { void set( final String value ) { } } static class N { @Metadata( "Field1" ) @MultiMetadata( "A" ) @FieldMetadata( "1" ) int value; @MethodMetadata( "1" ) void init() { } @MethodMetadata( "2" ) void setValue( final int value ) { this.value = value; } } static class O1 { private String a1; void setA( final String a ) { } } @IgnoreSetters static class O2 extends O1 { private String b2; void setB( final String b ) { } } static class O3 extends O2 { void setC( final String c ) { } } public void testInterface() { for ( final BeanProperty bp : new BeanProperties( A.class ) ) { fail( "Expected no bean properties" ); } } public void testEmptyClass() { for ( final BeanProperty bp : new BeanProperties( B.class ) ) { fail( "Expected no bean properties" ); } } public void testPropertyField() { final Iterator> i = new BeanProperties( C.class ).iterator(); assertEquals( "name", i.next().getName() ); assertFalse( i.hasNext() ); } public void testPropertySetter() { final Iterator> i = new BeanProperties( D.class ).iterator(); assertEquals( "name", i.next().getName() ); assertFalse( i.hasNext() ); } public void testHashCodeAndEquals() throws Exception { final BeanProperty propertyField = new BeanProperties( C.class ).iterator().next(); final BeanProperty propertySetter = new BeanProperties( D.class ).iterator().next(); assertEquals( propertyField, propertyField ); assertEquals( propertySetter, propertySetter ); assertFalse( propertyField.equals( propertySetter ) ); assertFalse( propertySetter.equals( propertyField ) ); final Field field = C.class.getDeclaredField( "name" ); final Method setter = D.class.getDeclaredMethod( "setName", String.class ); assertEquals( propertyField, new BeanPropertyField( field ) ); assertEquals( propertySetter, new BeanPropertySetter( setter ) ); assertFalse( propertyField.equals( new BeanPropertyField( F.class.getDeclaredField( "name" ) ) ) ); assertFalse( propertySetter.equals( new BeanPropertySetter( F.class.getDeclaredMethod( "setName", String.class ) ) ) ); assertEquals( field.hashCode(), propertyField.hashCode() ); assertEquals( setter.hashCode(), propertySetter.hashCode() ); assertEquals( field.toString(), propertyField.toString() ); assertEquals( setter.toString(), propertySetter.toString() ); } public void testSkipInvalidSetters() { for ( final BeanProperty bp : new BeanProperties( E.class ) ) { fail( "Expected no bean properties" ); } } public void testPropertyCombination() { final Iterator> i = new BeanProperties( F.class ).iterator(); BeanProperty bp; bp = i.next(); assertEquals( "name", bp.getName() ); assertTrue( bp instanceof BeanPropertySetter ); bp = i.next(); assertEquals( "name", bp.getName() ); assertTrue( bp instanceof BeanPropertyField ); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } try { i.remove(); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } } public void testConstructor() throws NoSuchMethodException { final Iterable members = Collections.singleton( (Member) String.class.getConstructor() ); final Iterator> i = new BeanProperties( members ).iterator(); assertFalse( i.hasNext() ); } public void testPropertyType() { final Iterator> i = new BeanProperties( G.class ).iterator(); assertEquals( TypeLiteral.get( Types.mapOf( BigDecimal.class, Float.class ) ), i.next().getType() ); assertEquals( TypeLiteral.get( Types.listOf( String.class ) ), i.next().getType() ); } public void testPropertyUpdate() { final Iterator> i = new BeanProperties( H.class ).iterator(); final BeanProperty a = i.next(); final BeanProperty b = i.next(); assertFalse( i.hasNext() ); final H component = new H(); a.set( component, "bar" ); b.set( component, "foo" ); assertEquals( "foo@bar", component.toString() ); b.set( component, "abc" ); a.set( component, "xyz" ); assertEquals( "abc@xyz", component.toString() ); } public void testIllegalAccess() { try { final BeanProperty p = new BeanPropertyField( A.class.getDeclaredField( "name" ) ); p.set( new Object(), "test" ); fail( "Expected RuntimeException" ); } catch ( final NoSuchFieldException e ) { fail( e.toString() ); } catch ( final RuntimeException e ) { e.printStackTrace(); } try { final BeanProperty p = new BeanPropertySetter( A.class.getDeclaredMethod( "setName", String.class ) ); p.set( new Object(), "test" ); fail( "Expected RuntimeException" ); } catch ( final NoSuchMethodException e ) { fail( e.toString() ); } catch ( final RuntimeException e ) { e.printStackTrace(); } } public void testPropertyAnnotations() { final Iterator> i = new BeanProperties( I.class ).iterator(); assertEquals( "foo", i.next().getAnnotation( Named.class ).value() ); assertEquals( "bar", i.next().getAnnotation( Named.class ).value() ); assertFalse( i.hasNext() ); } public void testPropertyIteration() { final Iterator> i = new BeanProperties( J.class ).iterator(); assertTrue( i.hasNext() ); assertTrue( i.hasNext() ); assertEquals( "c", i.next().getName() ); assertTrue( i.hasNext() ); assertTrue( i.hasNext() ); assertEquals( "b", i.next().getName() ); assertTrue( i.hasNext() ); assertTrue( i.hasNext() ); assertEquals( "a", i.next().getName() ); assertFalse( i.hasNext() ); assertFalse( i.hasNext() ); } public void testBadPropertySetter() { try { final Iterator> i = new BeanProperties( K.class ).iterator(); i.next().set( new K(), "TEST" ); fail( "Expected RuntimeException" ); } catch ( final RuntimeException e ) { e.printStackTrace(); } } public void testSetterNames() { assertFalse( new BeanProperties( L.class ).iterator().hasNext() ); assertFalse( new BeanProperties( M.class ).iterator().hasNext() ); } public void testIgnoreSetters() { final Iterator> i = new BeanProperties( O3.class ).iterator(); assertTrue( i.hasNext() ); assertEquals( "b2", i.next().getName() ); assertTrue( i.hasNext() ); assertEquals( "a1", i.next().getName() ); assertFalse( i.hasNext() ); } } BundleClassSpaceTest.java000066400000000000000000000252631167051330000426410ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.jar.Manifest; import junit.framework.TestCase; import org.apache.felix.framework.FrameworkFactory; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.osgi.framework.Version; import org.osgi.framework.launch.Framework; public class BundleClassSpaceTest extends TestCase { private static final URL EMPTY_BUNDLE = ZipEntryIteratorTest.class.getClassLoader().getResource( "empty.jar" ); private static final URL SIMPLE_BUNDLE = ZipEntryIteratorTest.class.getClassLoader().getResource( "simple_bundle.jar" ); private static final URL LOGGING_BUNDLE = ZipEntryIteratorTest.class.getClassLoader().getResource( "logging_bundle.jar" ); private Framework framework; @Override protected void setUp() throws Exception { super.setUp(); final Map configuration = new HashMap(); configuration.put( Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT ); configuration.put( Constants.FRAMEWORK_STORAGE, "target/bundlecache" ); final FrameworkFactory frameworkFactory = new FrameworkFactory(); framework = frameworkFactory.newFramework( configuration ); framework.start(); } @Override protected void tearDown() throws Exception { framework.stop(); framework.waitForStop( 0 ); super.tearDown(); } public void testHashCodeAndEquals() throws Exception { final Bundle testBundle = framework.getBundleContext().installBundle( LOGGING_BUNDLE.toString() ); final ClassSpace space = new BundleClassSpace( testBundle ); assertEquals( space, space ); assertEquals( space, new BundleClassSpace( testBundle ) ); assertFalse( space.equals( new ClassSpace() { public Class loadClass( final String name ) { return space.loadClass( name ); } public DeferredClass deferLoadClass( final String name ) { return space.deferLoadClass( name ); } public Enumeration getResources( final String name ) { return space.getResources( name ); } public URL getResource( final String name ) { return space.getResource( name ); } public Enumeration findEntries( final String path, final String glob, final boolean recurse ) { return space.findEntries( path, glob, recurse ); } } ) ); assertEquals( testBundle.hashCode(), space.hashCode() ); assertEquals( testBundle.toString(), space.toString() ); } public void testClassSpaceResources() throws Exception { final Bundle testBundle1 = framework.getBundleContext().installBundle( LOGGING_BUNDLE.toString() ); final ClassSpace space1 = new BundleClassSpace( testBundle1 ); final Bundle testBundle2 = framework.getBundleContext().installBundle( SIMPLE_BUNDLE.toString() ); final ClassSpace space2 = new BundleClassSpace( testBundle2 ); final Bundle testBundle3 = framework.getBundleContext().installBundle( EMPTY_BUNDLE.toString() ); final ClassSpace space3 = new BundleClassSpace( testBundle3 ); Enumeration e; // logging bundle class-path has repeated entries... e = space1.getResources( "META-INF/MANIFEST.MF" ); assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().toString().matches( "bundle://.*/META-INF/MANIFEST.MF" ) ); assertTrue( e.nextElement().toString().matches( "bundle://.*/META-INF/MANIFEST.MF" ) ); assertTrue( e.nextElement().toString().matches( "bundle://.*/META-INF/MANIFEST.MF" ) ); assertTrue( e.nextElement().toString().matches( "bundle://.*/META-INF/MANIFEST.MF" ) ); assertFalse( e.hasMoreElements() ); // ...which we try to collapse when using find e = space1.findEntries( "META-INF", "*.MF", false ); assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().toString().matches( "bundle://.*/META-INF/MANIFEST.MF" ) ); assertTrue( e.nextElement().toString().matches( "jar:bundle://.*!/META-INF/MANIFEST.MF" ) ); assertFalse( e.hasMoreElements() ); try { e.nextElement(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException t ) { } e = space2.findEntries( "a/b", "*", true ); assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().toString().matches( "bundle://.*/a/b/2" ) ); assertTrue( e.nextElement().toString().matches( "bundle://.*/a/b/c/" ) ); assertTrue( e.nextElement().toString().matches( "bundle://.*/a/b/c/3" ) ); assertFalse( e.hasMoreElements() ); e = space3.findEntries( "", "*", true ); assertTrue( e.nextElement().toString().matches( "bundle://.*/META-INF/" ) ); assertTrue( e.nextElement().toString().matches( "bundle://.*/META-INF/MANIFEST.MF" ) ); assertFalse( e.hasMoreElements() ); e = space1.findEntries( null, "missing", true ); assertFalse( e.hasMoreElements() ); e = space2.findEntries( null, "missing", true ); assertFalse( e.hasMoreElements() ); e = space3.findEntries( null, "missing", true ); assertFalse( e.hasMoreElements() ); final URL manifestURL = space1.getResource( "META-INF/MANIFEST.MF" ); assertNotNull( manifestURL ); new Manifest( manifestURL.openStream() ); } public void testDeferredClass() throws Exception { final Bundle testBundle = framework.getBundleContext().installBundle( LOGGING_BUNDLE.toString() ); final ClassSpace space = new BundleClassSpace( testBundle ); final String clazzName = "org.apache.commons.logging.Log"; final DeferredClass clazz = space.deferLoadClass( clazzName ); assertEquals( clazzName, clazz.getName() ); assertSame( space.loadClass( clazzName ), clazz.load() ); final DeferredClass missingClazz = space.deferLoadClass( "missing.class" ); try { missingClazz.load(); fail( "Expected TypeNotPresentException" ); } catch ( final TypeNotPresentException e ) { } } public void testBrokenResources() { final ClassSpace space = new BundleClassSpace( new Bundle() { public Enumeration getResources( final String name ) throws IOException { throw new IOException(); // the rest of the methods aren't used... } public void update( final InputStream input ) throws BundleException { } public void update() throws BundleException { } public void uninstall() throws BundleException { } public void stop( final int options ) throws BundleException { } public void stop() throws BundleException { } public void start( final int options ) throws BundleException { } public void start() throws BundleException { } public Class loadClass( final String name ) throws ClassNotFoundException { return null; } public boolean hasPermission( final Object permission ) { return false; } public Version getVersion() { return null; } public String getSymbolicName() { return null; } public int getState() { return 0; } public Map getSignerCertificates( final int signersType ) { return null; } public ServiceReference[] getServicesInUse() { return null; } public URL getResource( final String name ) { return null; } public ServiceReference[] getRegisteredServices() { return null; } public String getLocation() { return null; } public long getLastModified() { return 0; } public Dictionary getHeaders( final String locale ) { return null; } public Dictionary getHeaders() { return null; } public Enumeration getEntryPaths( final String path ) { return null; } public URL getEntry( final String path ) { return null; } public long getBundleId() { return 0; } public BundleContext getBundleContext() { return null; } public Enumeration findEntries( final String path, final String filePattern, final boolean recurse ) { return null; } } ); assertFalse( space.getResources( "error" ).hasMoreElements() ); } } DeclaredMembersTest.java000066400000000000000000000106671167051330000425060ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.reflect.Member; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import junit.framework.TestCase; public class DeclaredMembersTest extends TestCase { interface A { char a = 'a'; void a(); } static class B implements A { public B() { } char b = 'b'; public void a() { } } interface C extends A { char c = 'c'; void c(); } static class D extends B implements C { public D() { } char d = 'd'; public void c() { } } public void testNullClass() { final Iterator i = new DeclaredMembers( null ).iterator(); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } } public void testJavaClass() { final Iterator i = new DeclaredMembers( List.class ).iterator(); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } } public void testReadOnlyIterator() { final Iterator i = new DeclaredMembers( D.class ).iterator(); try { i.remove(); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } } public void testInterfaceHierarchy() throws NoSuchMethodException, NoSuchFieldException { final Member[] elements = { C.class.getDeclaredMethod( "c" ), C.class.getDeclaredField( "c" ) }; int i = 0; for ( final Member e : new DeclaredMembers( C.class ) ) { assertEquals( elements[i++], e ); } assertEquals( 2, i ); } public void testClassHierarchy() throws NoSuchMethodException, NoSuchFieldException { final Member[] elements = { D.class.getDeclaredConstructor(), D.class.getDeclaredMethod( "c" ), D.class.getDeclaredField( "d" ), B.class.getDeclaredConstructor(), B.class.getDeclaredMethod( "a" ), B.class.getDeclaredField( "b" ) }; int i = 0; for ( final Member e : new DeclaredMembers( D.class ) ) { assertEquals( elements[i++], e ); } assertEquals( 6, i ); } public void testResumableIteration() throws ClassNotFoundException { final Iterator itr = new DeclaredMembers( Class.forName( "Incomplete" ) ).iterator(); assertTrue( itr.hasNext() ); assertEquals( "public Incomplete(java.lang.String)", itr.next().toString() ); try { itr.hasNext(); fail( "Expected NoClassDefFoundError" ); } catch ( final NoClassDefFoundError e ) { assertEquals( "java.lang.NoClassDefFoundError: Param", e.toString() ); } assertTrue( itr.hasNext() ); assertEquals( "public java.lang.String Incomplete.address", itr.next().toString() ); try { itr.hasNext(); fail( "Expected NoClassDefFoundError" ); } catch ( final NoClassDefFoundError e ) { assertEquals( "java.lang.NoClassDefFoundError: Param", e.toString() ); } assertTrue( itr.hasNext() ); assertEquals( "public void IncompleteBase.setName(java.lang.String)", itr.next().toString() ); assertFalse( itr.hasNext() ); } } DeferredClassTest.java000066400000000000000000000101741167051330000421670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import junit.framework.TestCase; public class DeferredClassTest extends TestCase { URLClassLoader testLoader; @Override protected void setUp() throws MalformedURLException { testLoader = URLClassLoader.newInstance( new URL[] { new File( "target/test-classes" ).toURI().toURL() }, null ); } private static class Dummy { } public void testStrongDeferredClass() { final String clazzName = Dummy.class.getName(); final ClassSpace space = new URLClassSpace( testLoader ); final DeferredClass clazz = space.deferLoadClass( clazzName ); assertEquals( clazzName, clazz.getName() ); assertEquals( clazzName, clazz.load().getName() ); assertFalse( Dummy.class.equals( clazz.load() ) ); assertEquals( ( 17 * 31 + clazzName.hashCode() ) * 31 + space.hashCode(), clazz.hashCode() ); assertEquals( clazz, clazz ); assertEquals( new NamedClass( space, clazzName ), clazz ); assertFalse( clazz.equals( new DeferredClass() { @SuppressWarnings( "unchecked" ) public Class load() throws TypeNotPresentException { return (Class) clazz.load(); } public String getName() { return clazz.getName(); } public DeferredProvider asProvider() { throw new UnsupportedOperationException(); } } ) ); final String clazzName2 = clazzName + "$1"; final ClassSpace space2 = new URLClassSpace( ClassLoader.getSystemClassLoader(), null ); assertFalse( clazz.equals( new NamedClass( space, clazzName2 ) ) ); assertFalse( clazz.equals( new NamedClass( space2, clazzName ) ) ); assertTrue( clazz.toString().contains( clazzName ) ); assertTrue( clazz.toString().contains( space.toString() ) ); } public void testLoadedClass() { final DeferredClass dummyClazz = new LoadedClass( Dummy.class ); final DeferredClass stringClazz = new LoadedClass( String.class ); assertEquals( String.class.getName(), stringClazz.getName() ); assertEquals( String.class.getName(), stringClazz.load().getName() ); assertSame( String.class, stringClazz.load() ); assertEquals( stringClazz, stringClazz ); assertFalse( stringClazz.equals( dummyClazz ) ); assertFalse( stringClazz.equals( String.class ) ); assertEquals( String.class.hashCode(), stringClazz.hashCode() ); assertEquals( "Loaded " + String.class, stringClazz.toString() ); assertEquals( "Loaded " + Dummy.class + " from " + Dummy.class.getClassLoader(), dummyClazz.toString() ); } public void testMissingStrongDeferredClass() { try { final ClassSpace space = new URLClassSpace( testLoader ); System.out.println( new NamedClass( space, "unknown-class" ) ); System.out.println( new LoadedClass( getClass() ) ); new NamedClass( space, "unknown-class" ).load(); fail( "Expected TypeNotPresentException" ); } catch ( final TypeNotPresentException e ) { } } } DeferredProviderTest.java000066400000000000000000000144151167051330000427160ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import javax.inject.Inject; import junit.framework.TestCase; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Provider; import com.google.inject.ProvisionException; public class DeferredProviderTest extends TestCase { interface A { } interface B { } interface C { } static class AImpl implements A { } static class BImpl implements B { @Inject A a; } static class CImpl implements C { @Inject B b; } public void testRootDeferredProvider() { Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( C.class ).toProvider( new LoadedClass( CImpl.class ).asProvider() ); bind( B.class ).to( BImpl.class ); bind( A.class ).to( AImpl.class ); } } ).getInstance( C.class ); } public void testChildDeferredProvider() { Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( A.class ).to( AImpl.class ); } } ).createChildInjector( new AbstractModule() { @Override protected void configure() { bind( B.class ).to( BImpl.class ); } } ).createChildInjector( new AbstractModule() { @Override protected void configure() { bind( C.class ).toProvider( new LoadedClass( CImpl.class ).asProvider() ); } } ).getInstance( C.class ); } public void testBrokenDeferredProvider() { try { Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( C.class ).toProvider( new LoadedClass( CImpl.class ).asProvider() ); bind( CImpl.class ).toProvider( new Provider() { public CImpl get() { throw new ProvisionException( "Broken Provider" ); } } ); } } ).getInstance( C.class ); fail( "Expected ProvisionException" ); } catch ( final ProvisionException e ) { } try { Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( C.class ).toProvider( new LoadedClass( CImpl.class ).asProvider() ); bind( CImpl.class ).toProvider( new Provider() { public CImpl get() { throw new LinkageError( "Broken Provider" ); } } ); } } ).getInstance( C.class ); fail( "Expected LinkageError" ); } catch ( final LinkageError e ) { } try { Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( C.class ).toProvider( new LoadedClass( CImpl.class ).asProvider() ); bind( CImpl.class ).toProvider( new Provider() { public CImpl get() { throw new IllegalArgumentException( new IllegalStateException( new ThreadDeath() ) ); } } ); } } ).getInstance( C.class ); fail( "Expected ThreadDeath" ); } catch ( final ThreadDeath e ) { } final ClassSpace space = new URLClassSpace( C.class.getClassLoader(), null ); try { Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( C.class ).toProvider( new NamedClass( space, CImpl.class.getName() ).asProvider() ); bind( CImpl.class ).toProvider( new Provider() { public CImpl get() { throw new ProvisionException( "Broken Provider" ); } } ); } } ).getInstance( C.class ); fail( "Expected ProvisionException" ); } catch ( final ProvisionException e ) { } } public void testDeferredImplementationClass() { final ClassSpace space = new URLClassSpace( C.class.getClassLoader(), null ); final DeferredClass clazz1 = new NamedClass( space, CImpl.class.getName() ); final DeferredClass clazz2 = new LoadedClass( CImpl.class ); final DeferredProvider provider1 = clazz1.asProvider(); final DeferredProvider provider2 = clazz2.asProvider(); assertSame( clazz1, provider1.getImplementationClass() ); assertSame( clazz2, provider2.getImplementationClass() ); assertTrue( provider1.toString().contains( clazz1.toString() ) ); assertTrue( provider2.toString().contains( clazz2.toString() ) ); } } FileEntryIteratorTest.java000066400000000000000000000156571167051330000431070ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import junit.framework.TestCase; public class FileEntryIteratorTest extends TestCase { public void testURLtoFile() throws MalformedURLException { assertEquals( "test", FileEntryIterator.toFile( new URL( "file:test" ) ).getPath() ); assertEquals( "A B C", FileEntryIterator.toFile( new URL( "file:A B C" ) ).getPath() ); assertEquals( "A B C%%", FileEntryIterator.toFile( new URL( "file:A B%20C%%" ) ).getPath() ); assertEquals( "A%B%C%", FileEntryIterator.toFile( new URL( "file:A%B%C%" ) ).getPath() ); assertEquals( "A+%+C", FileEntryIterator.toFile( new URL( "file:A+%+C" ) ).getPath() ); } public void testNoSuchFile() throws Exception { final Iterator i = new FileEntryIterator( new URL( "file:UNKNOWN" ), "", true ); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } } public void testEmptyFolder() throws Exception { final Iterator i = new FileEntryIterator( expand( resource( "empty.zip" ) ), "", true ); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } } public void testTrivialFolder() throws Exception { final Iterator i = new FileEntryIterator( expand( resource( "empty.jar" ) ), "", true ); assertTrue( i.hasNext() ); assertEquals( "META-INF/", i.next() ); assertTrue( i.hasNext() ); assertEquals( "META-INF/MANIFEST.MF", i.next() ); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } } public void testSimpleFolder() throws Exception { final Iterator i = new FileEntryIterator( expand( resource( "simple.jar" ) ), "", true ); final Set names = new HashSet(); while ( i.hasNext() ) { names.add( i.next() ); } assertTrue( names.remove( "META-INF/" ) ); assertTrue( names.remove( "META-INF/MANIFEST.MF" ) ); assertTrue( names.remove( "0" ) ); assertTrue( names.remove( "a/" ) ); assertTrue( names.remove( "a/1" ) ); assertTrue( names.remove( "a/b/" ) ); assertTrue( names.remove( "a/b/2" ) ); assertTrue( names.remove( "a/b/c/" ) ); assertTrue( names.remove( "a/b/c/3" ) ); assertTrue( names.remove( "4" ) ); assertTrue( names.remove( "x/" ) ); assertTrue( names.remove( "x/5" ) ); assertTrue( names.remove( "x/y/" ) ); assertTrue( names.remove( "x/y/6" ) ); assertTrue( names.remove( "7" ) ); assertTrue( names.isEmpty() ); } public void testNoRecursion() throws Exception { final Iterator i = new FileEntryIterator( expand( resource( "simple.jar" ) ), "", false ); final Set names = new HashSet(); while ( i.hasNext() ) { names.add( i.next() ); } assertTrue( names.remove( "META-INF/" ) ); assertTrue( names.remove( "0" ) ); assertTrue( names.remove( "a/" ) ); assertTrue( names.remove( "4" ) ); assertTrue( names.remove( "x/" ) ); assertTrue( names.remove( "7" ) ); assertTrue( names.isEmpty() ); } public void testSubPath() throws Exception { final Iterator i = new FileEntryIterator( expand( resource( "simple.jar" ) ), "a/b", true ); final Set names = new HashSet(); while ( i.hasNext() ) { names.add( i.next() ); } assertTrue( names.remove( "a/b/2" ) ); assertTrue( names.remove( "a/b/c/" ) ); assertTrue( names.remove( "a/b/c/3" ) ); assertTrue( names.isEmpty() ); } public void testRemoveNotSupported() throws IOException { final Iterator i = new FileEntryIterator( new URL( "file:" ), "", false ); try { i.remove(); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } } static URL expand( final URL url ) throws Exception { final File jar = new File( url.toURI() ); final File dir = new File( jar.getParentFile(), jar.getName() + "_expanded" ); try { final ZipFile zip = new ZipFile( jar ); for ( final Enumeration e = zip.entries(); e.hasMoreElements(); ) { final ZipEntry entry = e.nextElement(); final File path = new File( dir, entry.getName() ); if ( entry.isDirectory() ) { path.mkdirs(); } else { path.getParentFile().mkdirs(); final ReadableByteChannel in = Channels.newChannel( zip.getInputStream( entry ) ); final FileChannel out = new FileOutputStream( path ).getChannel(); out.transferFrom( in, 0, entry.getSize() ); out.close(); in.close(); } } } catch ( final IOException e ) { } return dir.toURI().toURL(); } private static URL resource( final String name ) { return FileEntryIteratorTest.class.getClassLoader().getResource( name ); } } LoggingExample.java000066400000000000000000000057211167051330000415250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.rmi.UnexpectedException; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Module; public class LoggingExample { static class BadValue { @Override public String toString() { throw new RuntimeException( "sigh" ); } } public LoggingExample() { Logs.debug( "", null, null ); Logs.debug( "", "a", "b" ); Logs.debug( "{", null, null ); Logs.debug( "}", "a", "b" ); Logs.debug( "}{", null, null ); Logs.debug( "{}", "a", "b" ); Logs.debug( "}{}", null, null ); Logs.debug( "{{}", "a", "b" ); Logs.debug( "{}{", null, null ); Logs.debug( "{}}", "a", "b" ); Logs.debug( "{{}}", null, null ); Logs.debug( "}{}{", "a", "b" ); Logs.debug( "{}{}", null, null ); Logs.debug( "{}{}", "a", "b" ); Logs.debug( "{{}}{{}}", null, null ); Logs.debug( "{}-{}", "a", "b" ); Logs.debug( "{} {}", new BadValue(), new BadValue() ); Logs.debug( "Error: {} cause: {}", "oops", new UnexpectedException( "doh!" ) ); Logs.warn( "", null, null ); Logs.warn( "", "a", "b" ); Logs.warn( "{", null, null ); Logs.warn( "}", "a", "b" ); Logs.warn( "}{", null, null ); Logs.warn( "{}", "a", "b" ); Logs.warn( "}{}", null, null ); Logs.warn( "{{}", "a", "b" ); Logs.warn( "{}{", null, null ); Logs.warn( "{}}", "a", "b" ); Logs.warn( "{{}}", null, null ); Logs.warn( "}{}{", "a", "b" ); Logs.warn( "{}{}", null, null ); Logs.warn( "{}{}", "a", "b" ); Logs.warn( "{{}}{{}}", null, null ); Logs.warn( "{}-{}", "a", "b" ); Logs.warn( "{} {}", new BadValue(), new BadValue() ); Logs.warn( "Error: {} cause: {}", "oops", new UnexpectedException( "doh!" ) ); final Module module = new AbstractModule() { @Override protected void configure() { bind( Object.class ).to( BadValue.class ); } }; Logs.debug( Logs.toString( module ), null, null ); Logs.debug( Logs.toString( Guice.createInjector( module ) ), null, null ); } } LogsTest.java000066400000000000000000000110151167051330000403600ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.net.URLClassLoader; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import junit.framework.TestCase; import org.slf4j.LoggerFactory; public class LogsTest extends TestCase { public void testLogging() { new LoggingExample(); } public void testProductionLogging() throws Exception { try { ( (ch.qos.logback.classic.Logger) LoggerFactory.getLogger( Logs.class ) ).setLevel( ch.qos.logback.classic.Level.WARN ); final ClassLoader productionLoader = new URLClassLoader( ( (URLClassLoader) getClass().getClassLoader() ).getURLs(), null ) { @Override protected synchronized Class loadClass( final String name, final boolean resolve ) throws ClassNotFoundException { if ( name.startsWith( "ch" ) || name.contains( "cobertura" ) ) { return LogsTest.class.getClassLoader().loadClass( name ); } return super.loadClass( name, resolve ); } }; productionLoader.loadClass( LoggingExample.class.getName() ).newInstance(); } finally { } } public void testFallBackToJDKLogging() throws Exception { final Logger rootLogger = Logger.getLogger( "" ); final Handler[] handlers = rootLogger.getHandlers(); if ( handlers.length > 0 ) { handlers[0].setLevel( Level.FINE ); } final Level level = rootLogger.getLevel(); try { rootLogger.setLevel( Level.FINE ); final ClassLoader noSLF4JLoader = new URLClassLoader( ( (URLClassLoader) getClass().getClassLoader() ).getURLs(), null ) { @Override protected synchronized Class loadClass( final String name, final boolean resolve ) throws ClassNotFoundException { if ( name.contains( "slf4j" ) ) { throw new ClassNotFoundException( name ); } if ( name.contains( "cobertura" ) ) { return LogsTest.class.getClassLoader().loadClass( name ); } return super.loadClass( name, resolve ); } }; noSLF4JLoader.loadClass( LoggingExample.class.getName() ).newInstance(); } finally { rootLogger.setLevel( level ); } } public void testConsoleLogging() throws Exception { System.setProperty( "org.sonatype.inject.debug", "true" ); try { final ClassLoader consoleLoader = new URLClassLoader( ( (URLClassLoader) getClass().getClassLoader() ).getURLs(), null ) { @Override protected synchronized Class loadClass( final String name, final boolean resolve ) throws ClassNotFoundException { if ( name.contains( "cobertura" ) ) { return LogsTest.class.getClassLoader().loadClass( name ); } return super.loadClass( name, resolve ); } }; consoleLoader.loadClass( LoggingExample.class.getName() ).newInstance(); } finally { System.clearProperty( "org.sonatype.inject.debug" ); } } } MildElementsTest.java000066400000000000000000000103461167051330000420440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.ref.Reference; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import junit.framework.TestCase; public class MildElementsTest extends TestCase { public void testSoftElements() { testElements( true ); } public void testWeakElements() { testElements( false ); } private static void testElements( final boolean soft ) { final Collection names = new MildElements( new ArrayList>(), soft ); String a = new String( "A" ), b = new String( "B" ), c = new String( "C" ); assertTrue( names.isEmpty() ); assertEquals( 0, names.size() ); names.add( a ); assertFalse( names.isEmpty() ); assertEquals( 1, names.size() ); names.add( b ); assertFalse( names.isEmpty() ); assertEquals( 2, names.size() ); names.add( c ); assertFalse( names.isEmpty() ); assertEquals( 3, names.size() ); Iterator itr = names.iterator(); assertTrue( itr.hasNext() ); assertEquals( "A", itr.next() ); assertEquals( "B", itr.next() ); itr.remove(); assertTrue( itr.hasNext() ); assertEquals( "C", itr.next() ); assertFalse( itr.hasNext() ); names.add( b = new String( "b2b" ) ); itr = names.iterator(); assertEquals( "A", itr.next() ); assertEquals( "C", itr.next() ); assertEquals( "b2b", itr.next() ); try { itr.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } try { itr.remove(); fail( "Expected IllegalStateException" ); } catch ( final IllegalStateException e ) { } itr = null; int size; size = names.size(); c = null; // clear so element can be evicted gc( names, size ); itr = names.iterator(); assertEquals( "A", itr.next() ); assertEquals( "b2b", itr.next() ); assertFalse( itr.hasNext() ); itr = null; size = names.size(); a = null; // clear so element can be evicted gc( names, size ); itr = names.iterator(); assertEquals( "b2b", itr.next() ); assertFalse( itr.hasNext() ); itr = null; size = names.size(); b = null; // clear so element can be evicted gc( names, size ); itr = names.iterator(); assertFalse( itr.hasNext() ); } private static int gc( final Collection elements, final int size ) { /* * Keep forcing GC until the collection compacts itself */ int gcCount = 0, hash = 0; do { try { final List buf = new LinkedList(); for ( int i = 0; i < 1024 * 1024; i++ ) { // try to trigger aggressive GC buf.add( new byte[1024 * 1024] ); } hash += buf.hashCode(); // so JIT doesn't optimize this away } catch ( final OutOfMemoryError e ) { // ignore... } System.gc(); gcCount++; } while ( elements.size() == size && gcCount < 1024 ); return hash; } } MildKeysTest.java000066400000000000000000000101461167051330000412010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.ref.Reference; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import junit.framework.TestCase; public class MildKeysTest extends TestCase { public void testSoftKeys() { testKeys( true ); } public void testWeakKeys() { testKeys( false ); } private static void testKeys( final boolean soft ) { final Map names = new MildKeys( new LinkedHashMap, String>(), soft ); String a = new String( "A" ), b = new String( "B" ), c = new String( "C" ); assertTrue( names.isEmpty() ); assertEquals( 0, names.size() ); names.put( a, "1" ); assertFalse( names.isEmpty() ); assertEquals( 1, names.size() ); names.put( b, "2" ); assertFalse( names.isEmpty() ); assertEquals( 2, names.size() ); names.put( c, "3" ); assertFalse( names.isEmpty() ); assertEquals( 3, names.size() ); Iterator itr = names.values().iterator(); assertTrue( itr.hasNext() ); assertEquals( "1", itr.next() ); assertEquals( "2", itr.next() ); itr.remove(); assertTrue( itr.hasNext() ); assertEquals( "3", itr.next() ); assertFalse( itr.hasNext() ); names.put( b = new String( "b2b" ), "2" ); itr = names.keySet().iterator(); assertEquals( "A", itr.next() ); assertEquals( "C", itr.next() ); assertEquals( "b2b", itr.next() ); try { itr.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } itr = null; int size; size = names.size(); c = null; // clear so element can be evicted gc( names, size ); itr = names.keySet().iterator(); assertEquals( "A", itr.next() ); assertEquals( "b2b", itr.next() ); assertFalse( itr.hasNext() ); itr = null; size = names.size(); a = null; // clear so element can be evicted gc( names, size ); itr = names.keySet().iterator(); assertEquals( "b2b", itr.next() ); assertFalse( itr.hasNext() ); itr = null; size = names.size(); b = null; // clear so element can be evicted gc( names, size ); itr = names.keySet().iterator(); assertFalse( itr.hasNext() ); } private static int gc( final Map map, final int size ) { /* * Keep forcing GC until the collection compacts itself */ int gcCount = 0, hash = 0; do { try { final List buf = new LinkedList(); for ( int i = 0; i < 1024 * 1024; i++ ) { // try to trigger aggressive GC buf.add( new byte[1024 * 1024] ); } hash += buf.hashCode(); // so JIT doesn't optimize this away } catch ( final OutOfMemoryError e ) { // ignore... } System.gc(); gcCount++; } while ( map.size() == size && gcCount < 1024 ); return hash; } } MildValuesTest.java000066400000000000000000000101641167051330000415250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.ref.Reference; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import junit.framework.TestCase; public class MildValuesTest extends TestCase { public void testSoftValues() { testValues( true ); } public void testWeakValues() { testValues( false ); } private static void testValues( final boolean soft ) { final Map names = new MildValues( new LinkedHashMap>(), soft ); String a = new String( "A" ), b = new String( "B" ), c = new String( "C" ); assertTrue( names.isEmpty() ); assertEquals( 0, names.size() ); names.put( "1", a ); assertFalse( names.isEmpty() ); assertEquals( 1, names.size() ); names.put( "2", b ); assertFalse( names.isEmpty() ); assertEquals( 2, names.size() ); names.put( "3", c ); assertFalse( names.isEmpty() ); assertEquals( 3, names.size() ); Iterator itr = names.keySet().iterator(); assertTrue( itr.hasNext() ); assertEquals( "1", itr.next() ); assertEquals( "2", itr.next() ); itr.remove(); assertTrue( itr.hasNext() ); assertEquals( "3", itr.next() ); assertFalse( itr.hasNext() ); names.put( "2", b = new String( "b2b" ) ); itr = names.values().iterator(); assertEquals( "A", itr.next() ); assertEquals( "C", itr.next() ); assertEquals( "b2b", itr.next() ); try { itr.next(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException e ) { } itr = null; int size; size = names.size(); c = null; // clear so element can be evicted gc( names, size ); itr = names.values().iterator(); assertEquals( "A", itr.next() ); assertEquals( "b2b", itr.next() ); assertFalse( itr.hasNext() ); itr = null; size = names.size(); a = null; // clear so element can be evicted gc( names, size ); itr = names.values().iterator(); assertEquals( "b2b", itr.next() ); assertFalse( itr.hasNext() ); itr = null; size = names.size(); b = null; // clear so element can be evicted gc( names, size ); itr = names.values().iterator(); assertFalse( itr.hasNext() ); } private static int gc( final Map map, final int size ) { /* * Keep forcing GC until the collection compacts itself */ int gcCount = 0, hash = 0; do { try { final List buf = new LinkedList(); for ( int i = 0; i < 1024 * 1024; i++ ) { // try to trigger aggressive GC buf.add( new byte[1024 * 1024] ); } hash += buf.hashCode(); // so JIT doesn't optimize this away } catch ( final OutOfMemoryError e ) { // ignore... } System.gc(); gcCount++; } while ( map.size() == size && gcCount < 1024 ); return hash; } } ResourceEnumerationTest.java000066400000000000000000000222601167051330000434560ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import static org.sonatype.guice.bean.reflect.FileEntryIteratorTest.expand; import java.lang.reflect.Field; import java.net.URL; import java.util.Enumeration; import java.util.NoSuchElementException; import junit.framework.TestCase; public class ResourceEnumerationTest extends TestCase { private static final URL COMMONS_LOGGING_JAR = ZipEntryIteratorTest.class.getClassLoader().getResource( "commons-logging-1.1.1.jar" ); public void testResourceEnumeration() throws Exception { final Enumeration e = new ResourceEnumeration( null, null, true, new URL[] { COMMONS_LOGGING_JAR, expand( COMMONS_LOGGING_JAR ) } ); int n = 0; while ( e.hasMoreElements() ) { e.nextElement(); n++; } assertEquals( 66, n ); try { e.nextElement(); fail( "Expected NoSuchElementException" ); } catch ( final NoSuchElementException nse ) { } } public void testFixedEnumeration() { final Enumeration e1 = new ResourceEnumeration( "org/apache/commons/logging", "LogFactory.clazz", false, new URL[] { COMMONS_LOGGING_JAR } ); assertFalse( e1.hasMoreElements() ); final Enumeration e2 = new ResourceEnumeration( "org/apache/commons/logging", "LogFactory.class", false, new URL[] { COMMONS_LOGGING_JAR } ); final String prefix = COMMONS_LOGGING_JAR + "!/"; assertEquals( prefix + "org/apache/commons/logging/LogFactory.class", e2.nextElement().getPath() ); assertFalse( e2.hasMoreElements() ); } public void testRecursiveEnumeration() { final Enumeration e = new ResourceEnumeration( "/", "LogFactory.class", true, new URL[] { COMMONS_LOGGING_JAR } ); final String prefix = COMMONS_LOGGING_JAR + "!/"; assertEquals( prefix + "org/apache/commons/logging/LogFactory.class", e.nextElement().getPath() ); assertFalse( e.hasMoreElements() ); } public void testGlobbedEnumeration() { int n = 0; final Enumeration e = new ResourceEnumeration( "/", "*", true, new URL[] { COMMONS_LOGGING_JAR } ); while ( e.hasMoreElements() ) { e.nextElement(); n++; } assertEquals( 33, n ); } public void testGlobbedEnumerationStart() { final Enumeration e = new ResourceEnumeration( null, "*$2.class", true, new URL[] { COMMONS_LOGGING_JAR } ); final String prefix = COMMONS_LOGGING_JAR + "!/"; assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl$2.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$2.class", e.nextElement().getPath() ); assertFalse( e.hasMoreElements() ); } public void testGlobbedEnumerationEnd() { final Enumeration e = new ResourceEnumeration( null, "SimpleLog.*", true, new URL[] { COMMONS_LOGGING_JAR } ); final String prefix = COMMONS_LOGGING_JAR + "!/"; assertEquals( prefix + "org/apache/commons/logging/impl/SimpleLog.class", e.nextElement().getPath() ); assertFalse( e.hasMoreElements() ); } public void testGlobbedEnumerationMiddle() { final Enumeration e = new ResourceEnumeration( null, "LogFactory*.class", true, new URL[] { COMMONS_LOGGING_JAR } ); final String prefix = COMMONS_LOGGING_JAR + "!/"; assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl$1.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl$2.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl$3.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$1.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$2.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$3.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$4.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$5.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$6.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory.class", e.nextElement().getPath() ); assertFalse( e.hasMoreElements() ); } public void testMultiGlobbedEnumeration() { final Enumeration e = new ResourceEnumeration( null, "*Fact*$*", true, new URL[] { COMMONS_LOGGING_JAR } ); final String prefix = COMMONS_LOGGING_JAR + "!/"; assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl$1.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl$2.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl$3.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$1.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$2.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$3.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$4.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$5.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$6.class", e.nextElement().getPath() ); assertFalse( e.hasMoreElements() ); } public void testSubPathEnumeration() { final Enumeration e = new ResourceEnumeration( "/org/apache/commons/logging/impl", "*Fact*$*", true, new URL[] { COMMONS_LOGGING_JAR } ); final String prefix = COMMONS_LOGGING_JAR + "!/"; assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl$1.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl$2.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/impl/LogFactoryImpl$3.class", e.nextElement().getPath() ); assertFalse( e.hasMoreElements() ); } public void testNonRecursiveSubPathEnumeration() { final Enumeration e = new ResourceEnumeration( "/org/apache/commons/logging/", "*Fact*$*", false, new URL[] { COMMONS_LOGGING_JAR } ); final String prefix = COMMONS_LOGGING_JAR + "!/"; assertEquals( prefix + "org/apache/commons/logging/LogFactory$1.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$2.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$3.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$4.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$5.class", e.nextElement().getPath() ); assertEquals( prefix + "org/apache/commons/logging/LogFactory$6.class", e.nextElement().getPath() ); assertFalse( e.hasMoreElements() ); } public void testBrokenUrlEnumeration() throws Exception { final Enumeration e = new ResourceEnumeration( null, null, true, new URL[] { expand( COMMONS_LOGGING_JAR ) } ); assertTrue( e.hasMoreElements() ); // intentionally break the internal next entry name to trigger a malformed URL problem final Field nextEntryName = ResourceEnumeration.class.getDeclaredField( "nextEntryName" ); nextEntryName.setAccessible( true ); nextEntryName.set( e, "foo:" ); try { e.nextElement(); fail( "Expected IllegalStateException" ); } catch ( final IllegalStateException ise ) { } } } TypeParametersTest.java000066400000000000000000000430311167051330000424240ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.AbstractMap; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import junit.framework.TestCase; import com.google.inject.ImplementedBy; import com.google.inject.ProvidedBy; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.util.Types; public class TypeParametersTest extends TestCase { static TypeLiteral OBJECT_TYPE = TypeLiteral.get( Object.class ); static TypeLiteral STRING_TYPE = TypeLiteral.get( String.class ); static TypeLiteral FLOAT_TYPE = TypeLiteral.get( Float.class ); static TypeLiteral SHORT_TYPE = TypeLiteral.get( Short.class ); static TypeLiteral NUMBER_TYPE = TypeLiteral.get( Number.class ); @SuppressWarnings( "rawtypes" ) List rawList; List shortList; List wildcardList; List wildcardStringList; @SuppressWarnings( "rawtypes" ) Map rawMap; Map stringFloatMap; Map wildcardMap; Map wildcardFloatShortMap; interface CallableNumber extends Callable { } public void testTypeArguments() { TypeLiteral[] types; assertEquals( OBJECT_TYPE, TypeParameters.get( getFieldType( "rawList" ), 0 ) ); types = TypeParameters.get( getFieldType( "rawList" ) ); assertEquals( 0, types.length ); assertEquals( OBJECT_TYPE, TypeParameters.get( getFieldType( "rawMap" ), 0 ) ); assertEquals( OBJECT_TYPE, TypeParameters.get( getFieldType( "rawMap" ), 1 ) ); types = TypeParameters.get( getFieldType( "rawMap" ) ); assertEquals( 0, types.length ); assertEquals( SHORT_TYPE, TypeParameters.get( getFieldType( "shortList" ), 0 ) ); types = TypeParameters.get( getFieldType( "shortList" ) ); assertEquals( 1, types.length ); assertEquals( SHORT_TYPE, types[0] ); assertEquals( STRING_TYPE, TypeParameters.get( getFieldType( "stringFloatMap" ), 0 ) ); assertEquals( FLOAT_TYPE, TypeParameters.get( getFieldType( "stringFloatMap" ), 1 ) ); types = TypeParameters.get( getFieldType( "stringFloatMap" ) ); assertEquals( 2, types.length ); assertEquals( STRING_TYPE, types[0] ); assertEquals( FLOAT_TYPE, types[1] ); assertEquals( OBJECT_TYPE, TypeParameters.get( getFieldType( "wildcardList" ), 0 ) ); types = TypeParameters.get( getFieldType( "wildcardList" ) ); assertEquals( 1, types.length ); assertEquals( OBJECT_TYPE, types[0] ); assertEquals( OBJECT_TYPE, TypeParameters.get( getFieldType( "wildcardMap" ), 0 ) ); assertEquals( OBJECT_TYPE, TypeParameters.get( getFieldType( "wildcardMap" ), 1 ) ); types = TypeParameters.get( getFieldType( "wildcardMap" ) ); assertEquals( 2, types.length ); assertEquals( OBJECT_TYPE, types[0] ); assertEquals( OBJECT_TYPE, types[1] ); assertEquals( STRING_TYPE, TypeParameters.get( getFieldType( "wildcardStringList" ), 0 ) ); types = TypeParameters.get( getFieldType( "wildcardStringList" ) ); assertEquals( 1, types.length ); assertEquals( STRING_TYPE, types[0] ); assertEquals( FLOAT_TYPE, TypeParameters.get( getFieldType( "wildcardFloatShortMap" ), 0 ) ); assertEquals( SHORT_TYPE, TypeParameters.get( getFieldType( "wildcardFloatShortMap" ), 1 ) ); types = TypeParameters.get( getFieldType( "wildcardFloatShortMap" ) ); assertEquals( 2, types.length ); assertEquals( FLOAT_TYPE, types[0] ); assertEquals( SHORT_TYPE, types[1] ); final TypeLiteral genericSuperType = TypeLiteral.get( CallableNumber.class ).getSupertype( Callable.class ); assertEquals( NUMBER_TYPE, TypeParameters.get( genericSuperType, 0 ) ); types = TypeParameters.get( genericSuperType ); assertEquals( 1, types.length ); assertEquals( NUMBER_TYPE, types[0] ); } @SuppressWarnings( "rawtypes" ) List[] rawListArray; List[] shortListArray; List[] wildcardListArray; List[] wildcardStringListArray; @SuppressWarnings( "rawtypes" ) Map[] rawMapArray; Map[] stringFloatMapArray; Map[] wildcardMapArray; Map[] wildcardFloatShortMapArray; List stringArrayList; public void testComponentType() { TypeLiteral[] types; types = TypeParameters.get( getFieldType( "rawListArray" ) ); assertEquals( getFieldType( "rawList" ), types[0] ); assertEquals( types[0], TypeParameters.get( getFieldType( "rawListArray" ), 0 ) ); assertEquals( List.class, types[0].getType() ); types = TypeParameters.get( getFieldType( "rawMapArray" ) ); assertEquals( getFieldType( "rawMap" ), types[0] ); assertEquals( types[0], TypeParameters.get( getFieldType( "rawMapArray" ), 0 ) ); assertEquals( Map.class, types[0].getType() ); types = TypeParameters.get( getFieldType( "shortListArray" ) ); assertEquals( getFieldType( "shortList" ), types[0] ); assertEquals( types[0], TypeParameters.get( getFieldType( "shortListArray" ), 0 ) ); assertEquals( Types.listOf( Short.class ), types[0].getType() ); types = TypeParameters.get( getFieldType( "stringFloatMapArray" ) ); assertEquals( getFieldType( "stringFloatMap" ), types[0] ); assertEquals( types[0], TypeParameters.get( getFieldType( "stringFloatMapArray" ), 0 ) ); assertEquals( Types.mapOf( String.class, Float.class ), types[0].getType() ); types = TypeParameters.get( getFieldType( "wildcardListArray" ) ); assertEquals( getFieldType( "wildcardList" ), types[0] ); assertEquals( types[0], TypeParameters.get( getFieldType( "wildcardListArray" ), 0 ) ); assertEquals( Types.listOf( Types.subtypeOf( Object.class ) ), types[0].getType() ); types = TypeParameters.get( getFieldType( "wildcardMapArray" ) ); assertEquals( getFieldType( "wildcardMap" ), types[0] ); assertEquals( types[0], TypeParameters.get( getFieldType( "wildcardMapArray" ), 0 ) ); assertEquals( Types.mapOf( Types.subtypeOf( Object.class ), Types.subtypeOf( Object.class ) ), types[0].getType() ); types = TypeParameters.get( getFieldType( "wildcardStringListArray" ) ); assertEquals( getFieldType( "wildcardStringList" ), types[0] ); assertEquals( types[0], TypeParameters.get( getFieldType( "wildcardStringListArray" ), 0 ) ); assertEquals( Types.listOf( Types.subtypeOf( String.class ) ), types[0].getType() ); types = TypeParameters.get( getFieldType( "wildcardFloatShortMapArray" ) ); assertEquals( getFieldType( "wildcardFloatShortMap" ), types[0] ); assertEquals( types[0], TypeParameters.get( getFieldType( "wildcardFloatShortMapArray" ), 0 ) ); assertEquals( Types.mapOf( Types.subtypeOf( Float.class ), Types.subtypeOf( Short.class ) ), types[0].getType() ); types = TypeParameters.get( TypeParameters.get( getFieldType( "stringArrayList" ) )[0] ); assertEquals( STRING_TYPE, types[0] ); assertEquals( types[0], TypeParameters.get( TypeParameters.get( getFieldType( "stringArrayList" ), 0 ), 0 ) ); } public void testTypeParameterRangeChecks() { try { TypeParameters.get( getFieldType( "stringFloatMap" ), -1 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( final IndexOutOfBoundsException e ) { } try { TypeParameters.get( getFieldType( "stringFloatMap" ), 2 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( final IndexOutOfBoundsException e ) { } try { TypeParameters.get( getFieldType( "wildcardStringListArray" ), -1 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( final IndexOutOfBoundsException e ) { } try { TypeParameters.get( getFieldType( "wildcardStringListArray" ), 1 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( final IndexOutOfBoundsException e ) { } } static class CallableImpl implements Callable { public T call() throws Exception { return null; } } static class CallableNumberImpl implements CallableNumber { public T call() throws Exception { return null; } } @SuppressWarnings( "rawtypes" ) static class CallableListImpl implements Callable { public List call() throws Exception { return null; } } @SuppressWarnings( "rawtypes" ) public void testIsAssignableFrom() { // === simple types === assertTrue( TypeParameters.isAssignableFrom( TypeLiteral.get( Object.class ), TypeLiteral.get( String.class ) ) ); assertTrue( TypeParameters.isAssignableFrom( TypeLiteral.get( Number.class ), TypeLiteral.get( Short.class ) ) ); assertTrue( TypeParameters.isAssignableFrom( TypeLiteral.get( Collection.class ), TypeLiteral.get( Set.class ) ) ); // === generic types === assertFalse( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableListImpl.class ) ) ); // not assignable since no wild-card assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableListImpl.class ) ) ); assertFalse( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableListImpl.class ) ) ); // === unbound type-variables === assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral() { }, TypeLiteral.get( Callable.class ) ) ); assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral() { }, TypeLiteral.get( CallableImpl.class ) ) ); assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableImpl.class ) ) ); assertFalse( TypeParameters.isAssignableFrom( new TypeLiteral() { }, TypeLiteral.get( Callable.class ) ) ); // === bound type-variables === assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral() { }, TypeLiteral.get( CallableNumberImpl.class ) ) ); assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableNumberImpl.class ) ) ); assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableNumberImpl.class ) ) ); assertFalse( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableNumberImpl.class ) ) ); // mismatched type-bounds // === unbound wild-cards === assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableImpl.class ) ) ); assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableNumberImpl.class ) ) ); assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableNumberImpl.class ) ) ); // === bound wild-cards === assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableListImpl.class ) ) ); assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableNumberImpl.class ) ) ); assertTrue( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableNumberImpl.class ) ) ); assertFalse( TypeParameters.isAssignableFrom( new TypeLiteral>() { }, TypeLiteral.get( CallableNumberImpl.class ) ) ); // === array types === assertTrue( TypeParameters.isAssignableFrom( TypeLiteral.get( Types.arrayOf( Object.class ) ), TypeLiteral.get( Types.arrayOf( String.class ) ) ) ); assertTrue( TypeParameters.isAssignableFrom( TypeLiteral.get( Types.arrayOf( Number.class ) ), TypeLiteral.get( Types.arrayOf( Float.class ) ) ) ); // === mismatched types === assertFalse( TypeParameters.isAssignableFrom( TypeLiteral.get( Types.arrayOf( Object.class ) ), TypeLiteral.get( Types.listOf( Object.class ) ) ) ); assertFalse( TypeParameters.isAssignableFrom( TypeLiteral.get( Types.listOf( Object.class ) ), TypeLiteral.get( Types.arrayOf( Object.class ) ) ) ); // === corner case === final Type T = new TypeVariable() { public Type[] getBounds() { return new Type[] { String.class }; } public GenericDeclaration getGenericDeclaration() { return null; } public String getName() { return "T"; } }; final Type callableT = new ParameterizedType() { public Type getRawType() { return Callable.class; } public Type getOwnerType() { return null; } public Type[] getActualTypeArguments() { return new Type[] { T }; } }; assertFalse( TypeParameters.isAssignableFrom( TypeLiteral.get( callableT ), TypeLiteral.get( Callable.class ) ) ); assertFalse( TypeParameters.isAssignableFrom( TypeLiteral.get( callableT ), TypeLiteral.get( CallableNumberImpl.class ) ) ); } public void testIsConcrete() { assertFalse( TypeParameters.isConcrete( Map.class ) ); assertFalse( TypeParameters.isConcrete( AbstractMap.class ) ); assertTrue( TypeParameters.isConcrete( HashMap.class ) ); assertFalse( TypeParameters.isConcrete( new TypeLiteral>() { } ) ); assertFalse( TypeParameters.isConcrete( new TypeLiteral>() { } ) ); assertTrue( TypeParameters.isConcrete( new TypeLiteral>() { } ) ); } @ImplementedBy( Object.class ) static interface Implicit1 { } static class SomeProvider implements Provider { public Object get() { return null; } } @ProvidedBy( SomeProvider.class ) static interface Implicit2 { } public void testIsImplicit() { assertFalse( TypeParameters.isImplicit( Map.class ) ); assertFalse( TypeParameters.isImplicit( AbstractMap.class ) ); assertTrue( TypeParameters.isImplicit( HashMap.class ) ); assertFalse( TypeParameters.isImplicit( new TypeLiteral>() { } ) ); assertFalse( TypeParameters.isImplicit( new TypeLiteral>() { } ) ); assertTrue( TypeParameters.isImplicit( new TypeLiteral>() { } ) ); assertTrue( TypeParameters.isImplicit( Implicit1.class ) ); assertTrue( TypeParameters.isImplicit( Implicit2.class ) ); assertTrue( TypeParameters.isImplicit( new TypeLiteral>() { } ) ); assertTrue( TypeParameters.isImplicit( new TypeLiteral>() { } ) ); } private static TypeLiteral getFieldType( final String name ) { try { return TypeLiteral.get( TypeParametersTest.class.getDeclaredField( name ).getGenericType() ); } catch ( final NoSuchFieldException e ) { throw new IllegalArgumentException( "Unknown test field " + name ); } } } URLClassSpaceTest.java000066400000000000000000000246571167051330000421000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.Arrays; import java.util.Enumeration; import java.util.jar.Manifest; import junit.framework.TestCase; import org.sonatype.guice.bean.reflect.barf.Handler; public class URLClassSpaceTest extends TestCase { private static final ClassLoader TEST_LOADER = URLClassSpaceTest.class.getClassLoader(); private static final URL SIMPLE_JAR = TEST_LOADER.getResource( "simple.jar" ); private static final URL CLASS_PATH_JAR = TEST_LOADER.getResource( "class path.jar" ); private static final URL COMMONS_LOGGING_JAR = TEST_LOADER.getResource( "commons-logging-1.1.1.jar" ); private static final URL CORRUPT_MANIFEST = TEST_LOADER.getResource( "corrupt.manifest/" ); private static final URL BROKEN_JAR = TEST_LOADER.getResource( "broken.jar" ); private static final URL NESTED_WAR = TEST_LOADER.getResource( "nested.war" ); public void testHashCodeAndEquals() { final ClassLoader systemLoader = ClassLoader.getSystemClassLoader(); final ClassSpace space = new URLClassSpace( systemLoader, null ); assertEquals( space, space ); assertEquals( space, new URLClassSpace( systemLoader, new URL[] { SIMPLE_JAR } ) ); assertFalse( space.equals( new ClassSpace() { public Class loadClass( final String name ) { return space.loadClass( name ); } public DeferredClass deferLoadClass( final String name ) { return space.deferLoadClass( name ); } public Enumeration getResources( final String name ) { return space.getResources( name ); } public URL getResource( final String name ) { return space.getResource( name ); } public Enumeration findEntries( final String path, final String glob, final boolean recurse ) { return space.findEntries( path, glob, recurse ); } } ) ); assertEquals( systemLoader.hashCode(), space.hashCode() ); assertEquals( systemLoader.toString(), space.toString() ); } public void testClassSpaceResources() throws IOException { final ClassSpace space = new URLClassSpace( URLClassLoader.newInstance( new URL[] { COMMONS_LOGGING_JAR } ) ); Enumeration e; int n = 0; e = space.getResources( "META-INF/MANIFEST.MF" ); while ( true ) { n++; // should have several matches from parent loader, local match should be last if ( e.nextElement().getPath().startsWith( COMMONS_LOGGING_JAR.toString() ) ) { assertFalse( e.hasMoreElements() ); break; } } assertTrue( n > 1 ); e = space.findEntries( "META-INF", "*.MF", false ); // only expect to see single result assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().getPath().startsWith( COMMONS_LOGGING_JAR.toString() ) ); assertFalse( e.hasMoreElements() ); final URL manifestURL = space.getResource( "META-INF/MANIFEST.MF" ); assertNotNull( manifestURL ); new Manifest( manifestURL.openStream() ); } public void testClassPathExpansion() throws IOException { // System.setProperty( "java.protocol.handler.pkgs", getClass().getPackage().getName() ); URL.setURLStreamHandlerFactory( new URLStreamHandlerFactory() { public URLStreamHandler createURLStreamHandler( final String protocol ) { if ( "barf".equals( protocol ) ) { return new Handler(); } return null; } } ); final URLClassSpace space = new URLClassSpace( URLClassLoader.newInstance( new URL[] { SIMPLE_JAR, CLASS_PATH_JAR, null, new URL( "barf:up/" ), CLASS_PATH_JAR, CORRUPT_MANIFEST } ) ); final Enumeration e = space.findEntries( "META-INF", "*.MF", false ); // expect to see three results assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().getPath().startsWith( SIMPLE_JAR.toString() ) ); assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().getPath().startsWith( CLASS_PATH_JAR.toString() ) ); assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().getPath().startsWith( COMMONS_LOGGING_JAR.toString() ) ); assertFalse( e.hasMoreElements() ); assertTrue( Arrays.equals( new URL[] { SIMPLE_JAR, CLASS_PATH_JAR, new URL( "barf:up/" ), CORRUPT_MANIFEST, BROKEN_JAR, COMMONS_LOGGING_JAR }, space.getURLs() ) ); } public void testNullSearchPath() { final ClassSpace space = new URLClassSpace( getClass().getClassLoader(), null ); final Enumeration e = space.findEntries( null, null, true ); // local search should see nothing assertFalse( e.hasMoreElements() ); } public void testEmptySearchPath() { final ClassSpace space = new URLClassSpace( getClass().getClassLoader(), new URL[0] ); final Enumeration e = space.findEntries( null, null, true ); // local search should see nothing assertFalse( e.hasMoreElements() ); } public void testBrokenResources() { final ClassSpace space = new URLClassSpace( new ClassLoader() { @Override public Enumeration getResources( final String name ) throws IOException { throw new IOException(); } } ); // should see nothing, and not throw any exceptions assertFalse( space.getResources( "error" ).hasMoreElements() ); } public void testClassPathDetection() { final ClassLoader parent = URLClassLoader.newInstance( new URL[] { CLASS_PATH_JAR } ); final ClassLoader child = URLClassLoader.newInstance( new URL[0], parent ); final ClassLoader grandchild = new URLClassLoader( new URL[0], child ) { @Override public URL[] getURLs() { return null; } }; final Enumeration e = new URLClassSpace( new ClassLoader( grandchild ) { } ).findEntries( "META-INF", "*.MF", false ); // expect to see three results assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().getPath().startsWith( CLASS_PATH_JAR.toString() ) ); assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().getPath().startsWith( COMMONS_LOGGING_JAR.toString() ) ); assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().getPath().startsWith( SIMPLE_JAR.toString() ) ); assertFalse( e.hasMoreElements() ); final ClassLoader orphan = URLClassLoader.newInstance( new URL[0], null ); // expect to see no results assertFalse( new URLClassSpace( orphan ).findEntries( "META-INF", "*.MF", false ).hasMoreElements() ); } public void testJarProtocol() throws MalformedURLException { final URLClassSpace space = new URLClassSpace( URLClassLoader.newInstance( new URL[] { new URL( "jar:" + CLASS_PATH_JAR + "!/" ) } ) ); final Enumeration e = space.findEntries( "META-INF", "*.MF", false ); // expect to see three results assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().getPath().startsWith( CLASS_PATH_JAR.toString() ) ); assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().getPath().startsWith( COMMONS_LOGGING_JAR.toString() ) ); assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().getPath().startsWith( SIMPLE_JAR.toString() ) ); assertFalse( e.hasMoreElements() ); } public void testNestedWar() throws MalformedURLException { final URLClassSpace space = new URLClassSpace( URLClassLoader.newInstance( new URL[] { new URL( "jar:" + NESTED_WAR + "!/WEB-INF/classes/" ), new URL( "jar:" + NESTED_WAR + "!/WEB-INF/lib/commons-logging-1.1.1.jar" ) } ) ); Enumeration e = space.findEntries( "META-INF", "*.MF", false ); // expect to see one result assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().toString().endsWith( "/nested.war!/WEB-INF/lib/commons-logging-1.1.1.jar#META-INF/MANIFEST.MF" ) ); assertFalse( e.hasMoreElements() ); e = space.findEntries( null, "Log.class", true ); // only one result, as can't "glob" embedded directory assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().toString().endsWith( "/nested.war!/WEB-INF/lib/commons-logging-1.1.1.jar#org/apache/commons/logging/Log.class" ) ); assertFalse( e.hasMoreElements() ); e = space.findEntries( "org/apache/commons/logging", "Log.class", false ); // can see both results, as using non-"globbed" search assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().toString().endsWith( "/nested.war!/WEB-INF/classes/org/apache/commons/logging/Log.class" ) ); assertTrue( e.hasMoreElements() ); assertTrue( e.nextElement().toString().endsWith( "/nested.war!/WEB-INF/lib/commons-logging-1.1.1.jar#org/apache/commons/logging/Log.class" ) ); assertFalse( e.hasMoreElements() ); e = space.findEntries( null, "missing", true ); assertFalse( e.hasMoreElements() ); } } ZipEntryIteratorTest.java000066400000000000000000000123141167051330000427550ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import junit.framework.TestCase; public class ZipEntryIteratorTest extends TestCase { public void testNonJar() throws IOException { final Iterator i = new ZipEntryIterator( new URL( "file:" ) ); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected Exception" ); } catch ( final Exception e ) { } } public void testBlankZip() { final Iterator i = new ZipEntryIterator( resource( "blank.zip" ) ); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected Exception" ); } catch ( final Exception e ) { } } public void testEmptyZip() { final Iterator i = new ZipEntryIterator( resource( "empty.zip" ) ); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected Exception" ); } catch ( final Exception e ) { } } public void testEmptyJar() { final Iterator i = new ZipEntryIterator( resource( "empty.jar" ) ); assertTrue( i.hasNext() ); assertEquals( "META-INF/MANIFEST.MF", i.next() ); assertFalse( i.hasNext() ); try { i.next(); fail( "Expected Exception" ); } catch ( final Exception e ) { } } public void testSimpleZip() { final Iterator i = new ZipEntryIterator( resource( "simple.zip" ) ); assertEquals( "0", i.next() ); assertEquals( "a/1", i.next() ); assertEquals( "a/b/2", i.next() ); assertEquals( "a/b/c/3", i.next() ); assertEquals( "4", i.next() ); assertEquals( "x/5", i.next() ); assertEquals( "x/y/6", i.next() ); assertEquals( "7", i.next() ); try { i.next(); fail( "Expected Exception" ); } catch ( final Exception e ) { } } public void testSimpleJar() { final Iterator i = new ZipEntryIterator( resource( "simple.jar" ) ); assertEquals( "META-INF/", i.next() ); assertEquals( "META-INF/MANIFEST.MF", i.next() ); assertEquals( "0", i.next() ); assertEquals( "a/", i.next() ); assertEquals( "a/1", i.next() ); assertEquals( "a/b/", i.next() ); assertEquals( "a/b/2", i.next() ); assertEquals( "a/b/c/", i.next() ); assertEquals( "a/b/c/3", i.next() ); assertEquals( "4", i.next() ); assertEquals( "x/", i.next() ); assertEquals( "x/5", i.next() ); assertEquals( "x/y/", i.next() ); assertEquals( "x/y/6", i.next() ); assertEquals( "7", i.next() ); try { i.next(); fail( "Expected Exception" ); } catch ( final Exception e ) { } } public void testEmbeddedZip() throws MalformedURLException { final Iterator i = new ZipEntryIterator( new URL( "jar:" + resource( "embedded.zip" ) + "!/simple.zip" ) ); assertEquals( "0", i.next() ); assertEquals( "a/1", i.next() ); assertEquals( "a/b/2", i.next() ); assertEquals( "a/b/c/3", i.next() ); assertEquals( "4", i.next() ); assertEquals( "x/5", i.next() ); assertEquals( "x/y/6", i.next() ); assertEquals( "7", i.next() ); try { i.next(); fail( "Expected Exception" ); } catch ( final Exception e ) { } } public void testBrokenJar() { final Iterator i = new ZipEntryIterator( resource( "broken.jar" ) ); try { i.next(); fail( "Expected Exception" ); } catch ( final Exception e ) { } } public void testRemoveNotSupported() throws IOException { final Iterator i = new ZipEntryIterator( new URL( "file:" ) ); try { i.remove(); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } } private static URL resource( final String name ) { return ZipEntryIteratorTest.class.getClassLoader().getResource( name ); } } 000077500000000000000000000000001167051330000366655ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/barfHandler.java000066400000000000000000000037021167051330000411070ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/java/org/sonatype/guice/bean/reflect/barf/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.reflect.barf; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; public class Handler extends URLStreamHandler { @Override protected URLConnection openConnection( final URL url ) throws IOException { return new DodgyConnection( url ); } static class DodgyConnection extends URLConnection { DodgyConnection( final URL url ) { super( url ); } @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { final InputStream in = new ByteArrayInputStream( new byte[0] ); return new InputStream() { @Override public int read() throws IOException { return in.read(); } @Override public void close() throws IOException { throw new IOException(); } }; } } } sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/resources/000077500000000000000000000000001167051330000310455ustar00rootroot00000000000000000077500000000000000000000000001167051330000342715ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/resources/corrupt.manifest000077500000000000000000000000001167051330000354315ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/resources/corrupt.manifest/META-INF000077500000000000000000000000001167051330000371405ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/resources/corrupt.manifest/META-INF/MANIFEST.MFplaceholder.txt000066400000000000000000000000001167051330000421510ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-reflect/src/test/resources/corrupt.manifest/META-INF/MANIFEST.MFsisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/000077500000000000000000000000001167051330000254555ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/pom.xml000066400000000000000000000025001167051330000267670ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-bean 2.3.0 guice-bean-scanners Sisu-Inject-Bean : @Named scanning javax.inject javax.inject org.sonatype.sisu.inject guice-bean-reflect sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/000077500000000000000000000000001167051330000262445ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/000077500000000000000000000000001167051330000271705ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/000077500000000000000000000000001167051330000301115ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/000077500000000000000000000000001167051330000307005ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/000077500000000000000000000000001167051330000325425ustar00rootroot00000000000000000077500000000000000000000000001167051330000335575ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000344645ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000363005ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scannersClassFinder.java000066400000000000000000000022231167051330000413370ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners; import java.net.URL; import java.util.Enumeration; import org.sonatype.guice.bean.reflect.ClassSpace; /** * Finds (and optionally filters) {@link Class} resources from {@link ClassSpace}s. */ public interface ClassFinder { /** * Searches the given {@link ClassSpace} for {@link Class} resources. * * @param space The space to search * @return Sequence of Class URLs */ Enumeration findClasses( ClassSpace space ); } ClassSpaceScanner.java000066400000000000000000000113701167051330000425000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.scanners.asm.ClassReader; import org.sonatype.guice.bean.scanners.asm.ClassVisitor; /** * ASM-style scanner that makes a {@link ClassSpaceVisitor} visit an existing {@link ClassSpace}. */ public final class ClassSpaceScanner { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final int ASM_FLAGS = ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final ClassFinder finder; private final ClassSpace space; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public ClassSpaceScanner( final ClassSpace space ) { this( null, space ); } public ClassSpaceScanner( final ClassFinder finder, final ClassSpace space ) { this.finder = finder; this.space = space; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- /** * Makes the given {@link ClassSpaceVisitor} visit the {@link ClassSpace} of this scanner. * * @param visitor The class space visitor */ public void accept( final ClassSpaceVisitor visitor ) { visitor.visit( space ); final Enumeration result = null != finder ? finder.findClasses( space ) : space.findEntries( null, "*.class", true ); while ( result.hasMoreElements() ) { final URL url = result.nextElement(); final ClassVisitor cv = visitor.visitClass( url ); if ( null != cv ) { accept( cv, url ); } } visitor.visitEnd(); } /** * Makes the given {@link ClassVisitor} visit the class contained in the resource {@link URL}. * * @param visitor The class space visitor * @param url The class resource URL */ public static void accept( final ClassVisitor visitor, final URL url ) { if ( null == url ) { return; // nothing to visit } try { final InputStream in = url.openStream(); try { new ClassReader( in ).accept( visitor, ASM_FLAGS ); } finally { in.close(); } } catch ( final ArrayIndexOutOfBoundsException e ) // NOPMD { // ignore broken class constant pool in icu4j } catch ( final Exception e ) { Logs.debug( "Problem scanning: {}", url, e ); } } public static boolean verify( final ClassSpace space, final Class... specification ) { for ( final Class expectedClazz : specification ) { try { final Class spaceClazz = space.loadClass( expectedClazz.getName() ); if ( spaceClazz != expectedClazz ) { Logs.warn( "Inconsistent ClassLoader for: {} in: {}", expectedClazz, space ); Logs.warn( "Expected: {} saw: {}", expectedClazz.getClassLoader(), spaceClazz.getClassLoader() ); } } catch ( final TypeNotPresentException e ) { if ( expectedClazz.isAnnotation() ) { Logs.debug( "Potential problem: {} is not visible from: {}", expectedClazz, space ); } } } return true; } } ClassSpaceVisitor.java000066400000000000000000000030171167051330000425450ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners; import java.net.URL; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.scanners.asm.ClassVisitor; /** * ASM-style visitor that visits a {@link ClassSpace}. The methods of this interface must be called in the following * order: {@code visit ( visitClass )* visitEnd}. */ public interface ClassSpaceVisitor { /** * Visits the start of the class space. * * @param space The class space */ void visit( final ClassSpace space ); /** * Visits a class resource in the class space. * * @param url The class resource URL * @return Class visitor; {@code null} if this visitor is not interested in visiting the class */ ClassVisitor visitClass( final URL url ); /** * Visits the end of the class space. */ void visitEnd(); } EmptyAnnotationVisitor.java000066400000000000000000000030531167051330000436550ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners; import org.sonatype.guice.bean.scanners.asm.AnnotationVisitor; /** * Skeletal {@link AnnotationVisitor} that helps minimize the effort required to implement bytecode scanners. */ public class EmptyAnnotationVisitor implements AnnotationVisitor { // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void visit( final String name, final Object value ) { } public void visitEnum( final String name, final String desc, final String value ) { } public AnnotationVisitor visitAnnotation( final String name, final String desc ) { return null; } public AnnotationVisitor visitArray( final String name ) { return null; } public void visitEnd() { } } EmptyClassVisitor.java000066400000000000000000000047451167051330000426210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners; import org.sonatype.guice.bean.scanners.asm.AnnotationVisitor; import org.sonatype.guice.bean.scanners.asm.Attribute; import org.sonatype.guice.bean.scanners.asm.ClassVisitor; import org.sonatype.guice.bean.scanners.asm.FieldVisitor; import org.sonatype.guice.bean.scanners.asm.MethodVisitor; /** * Skeletal {@link ClassVisitor} that helps minimize the effort required to implement bytecode scanners. */ public class EmptyClassVisitor implements ClassVisitor { // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void visit( final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces ) { } public void visitSource( final String source, final String debug ) { } public void visitOuterClass( final String owner, final String name, final String desc ) { } public AnnotationVisitor visitAnnotation( final String desc, final boolean visible ) { return null; } public void visitAttribute( final Attribute attr ) { } public void visitInnerClass( final String name, final String outerName, final String innerName, final int access ) { } public FieldVisitor visitField( final int access, final String name, final String desc, final String signature, final Object value ) { return null; } public MethodVisitor visitMethod( final int access, final String name, final String desc, final String signature, final String[] exceptions ) { return null; } public void visitEnd() { } } QualifiedTypeListener.java000066400000000000000000000024361167051330000434230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners; import java.lang.annotation.Annotation; import javax.inject.Qualifier; import com.google.inject.Binder; /** * Listens for types annotated with {@link Qualifier} annotations. */ public interface QualifiedTypeListener { /** * Invoked when the {@link QualifiedTypeVisitor} finds a qualified type. * * @param qualifier The qualifier (unused) * @param qualifiedType The qualified type * @param source The source of this type * @see Binder#withSource(Object) */ void hear( @Deprecated Annotation qualifier, Class qualifiedType, Object source ); } QualifiedTypeVisitor.java000066400000000000000000000074401167051330000432750ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners; import java.net.URL; import javax.inject.Qualifier; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.scanners.asm.AnnotationVisitor; import org.sonatype.guice.bean.scanners.asm.ClassVisitor; import org.sonatype.guice.bean.scanners.asm.Opcodes; import com.google.inject.Module; /** * {@link ClassSpaceVisitor} that reports types annotated with {@link Qualifier} annotations. */ public final class QualifiedTypeVisitor extends EmptyClassVisitor implements ClassSpaceVisitor { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final QualifierCache qualifierCache = new QualifierCache(); private final QualifiedTypeListener listener; private ClassSpace space; private URL location; private String source; private String clazzName; private boolean qualified; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public QualifiedTypeVisitor( final QualifiedTypeListener listener ) { this.listener = listener; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void visit( final ClassSpace _space ) { space = _space; source = null; if ( Logs.DEBUG_ENABLED ) { ClassSpaceScanner.verify( _space, Qualifier.class, Module.class ); } } public ClassVisitor visitClass( final URL url ) { location = url; clazzName = null; qualified = false; return this; } @Override public void visit( final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces ) { if ( ( access & ( Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_SYNTHETIC ) ) == 0 ) { clazzName = name; // concrete type } } @Override public AnnotationVisitor visitAnnotation( final String desc, final boolean visible ) { if ( null != clazzName ) { qualified = qualified || qualifierCache.qualify( space, desc ); } return null; } @Override public void visitEnd() { if ( qualified ) { qualified = false; // we might be called twice (once per-class, once per-space) // compressed record of class location final String path = location.getPath(); if ( null == source || !path.startsWith( source ) ) { final int i = path.indexOf( clazzName ); source = i <= 0 ? path : path.substring( 0, i ); } listener.hear( null, space.loadClass( clazzName.replace( '/', '.' ) ), source ); } } } QualifierCache.java000066400000000000000000000061171167051330000420150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Qualifier; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.scanners.asm.AnnotationVisitor; import org.sonatype.guice.bean.scanners.asm.ClassVisitor; import org.sonatype.guice.bean.scanners.asm.Type; /** * Caching {@link ClassVisitor} that maintains a map of known {@link Qualifier} annotations. */ final class QualifierCache extends EmptyClassVisitor { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String QUALIFIER_DESC = Type.getDescriptor( Qualifier.class ); // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private static final Map cachedResults = new ConcurrentHashMap( 32, 0.75f, 1 ); private boolean isQualified; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public AnnotationVisitor visitAnnotation( final String desc, final boolean visible ) { isQualified |= QUALIFIER_DESC.equals( desc ); return null; } // ---------------------------------------------------------------------- // Local methods // ---------------------------------------------------------------------- /** * Attempts to load the potential {@link Qualifier} annotation and return its class. * * @param space The class space * @param desc The annotation descriptor * @return {@code true} if the annotation is a qualifier; otherwise {@code false} */ boolean qualify( final ClassSpace space, final String desc ) { final Boolean result = cachedResults.get( desc ); if ( null == result ) { isQualified = false; final String name = desc.substring( 1, desc.length() - 1 ); ClassSpaceScanner.accept( this, space.getResource( name + ".class" ) ); cachedResults.put( desc, Boolean.valueOf( isQualified ) ); return isQualified; } return result.booleanValue(); } } 000077500000000000000000000000001167051330000370605ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asmAnnotationVisitor.java000066400000000000000000000104631167051330000434210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * A visitor to visit a Java annotation. The methods of this interface must be * called in the following order: (visit | visitEnum | * visitAnnotation | visitArray)* visitEnd. * * @author Eric Bruneton * @author Eugene Kuleshov */ public interface AnnotationVisitor { /** * Visits a primitive value of the annotation. * * @param name the value name. * @param value the actual value, whose type must be {@link Byte}, * {@link Boolean}, {@link Character}, {@link Short}, * {@link Integer}, {@link Long}, {@link Float}, {@link Double}, * {@link String} or {@link Type}. This value can also be an array * of byte, boolean, short, char, int, long, float or double values * (this is equivalent to using {@link #visitArray visitArray} and * visiting each array element in turn, but is more convenient). */ void visit(String name, Object value); /** * Visits an enumeration value of the annotation. * * @param name the value name. * @param desc the class descriptor of the enumeration class. * @param value the actual enumeration value. */ void visitEnum(String name, String desc, String value); /** * Visits a nested annotation value of the annotation. * * @param name the value name. * @param desc the class descriptor of the nested annotation class. * @return a visitor to visit the actual nested annotation value, or * null if this visitor is not interested in visiting * this nested annotation. The nested annotation value must be * fully visited before calling other methods on this annotation * visitor. */ AnnotationVisitor visitAnnotation(String name, String desc); /** * Visits an array value of the annotation. Note that arrays of primitive * types (such as byte, boolean, short, char, int, long, float or double) * can be passed as value to {@link #visit visit}. This is what * {@link ClassReader} does. * * @param name the value name. * @return a visitor to visit the actual array value elements, or * null if this visitor is not interested in visiting * these values. The 'name' parameters passed to the methods of this * visitor are ignored. All the array values must be visited * before calling other methods on this annotation visitor. */ AnnotationVisitor visitArray(String name); /** * Visits the end of the annotation. */ void visitEnd(); } AnnotationWriter.java000066400000000000000000000253631167051330000432430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * An {@link AnnotationVisitor} that generates annotations in bytecode form. * * @author Eric Bruneton * @author Eugene Kuleshov */ final class AnnotationWriter implements AnnotationVisitor { /** * The class writer to which this annotation must be added. */ private final ClassWriter cw; /** * The number of values in this annotation. */ private int size; /** * true if values are named, false otherwise. Annotation * writers used for annotation default and annotation arrays use unnamed * values. */ private final boolean named; /** * The annotation values in bytecode form. This byte vector only contains * the values themselves, i.e. the number of values must be stored as a * unsigned short just before these bytes. */ private final ByteVector bv; /** * The byte vector to be used to store the number of values of this * annotation. See {@link #bv}. */ private final ByteVector parent; /** * Where the number of values of this annotation must be stored in * {@link #parent}. */ private final int offset; /** * Next annotation writer. This field is used to store annotation lists. */ AnnotationWriter next; /** * Previous annotation writer. This field is used to store annotation lists. */ AnnotationWriter prev; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ /** * Constructs a new {@link AnnotationWriter}. * * @param cw the class writer to which this annotation must be added. * @param named true if values are named, false otherwise. * @param bv where the annotation values must be stored. * @param parent where the number of annotation values must be stored. * @param offset where in parent the number of annotation values must * be stored. */ AnnotationWriter( final ClassWriter cw, final boolean named, final ByteVector bv, final ByteVector parent, final int offset) { this.cw = cw; this.named = named; this.bv = bv; this.parent = parent; this.offset = offset; } // ------------------------------------------------------------------------ // Implementation of the AnnotationVisitor interface // ------------------------------------------------------------------------ public void visit(final String name, final Object value) { ++size; if (named) { bv.putShort(cw.newUTF8(name)); } if (value instanceof String) { bv.put12('s', cw.newUTF8((String) value)); } else if (value instanceof Byte) { bv.put12('B', cw.newInteger(((Byte) value).byteValue()).index); } else if (value instanceof Boolean) { int v = ((Boolean) value).booleanValue() ? 1 : 0; bv.put12('Z', cw.newInteger(v).index); } else if (value instanceof Character) { bv.put12('C', cw.newInteger(((Character) value).charValue()).index); } else if (value instanceof Short) { bv.put12('S', cw.newInteger(((Short) value).shortValue()).index); } else if (value instanceof Type) { bv.put12('c', cw.newUTF8(((Type) value).getDescriptor())); } else if (value instanceof byte[]) { byte[] v = (byte[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('B', cw.newInteger(v[i]).index); } } else if (value instanceof boolean[]) { boolean[] v = (boolean[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('Z', cw.newInteger(v[i] ? 1 : 0).index); } } else if (value instanceof short[]) { short[] v = (short[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('S', cw.newInteger(v[i]).index); } } else if (value instanceof char[]) { char[] v = (char[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('C', cw.newInteger(v[i]).index); } } else if (value instanceof int[]) { int[] v = (int[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('I', cw.newInteger(v[i]).index); } } else if (value instanceof long[]) { long[] v = (long[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('J', cw.newLong(v[i]).index); } } else if (value instanceof float[]) { float[] v = (float[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('F', cw.newFloat(v[i]).index); } } else if (value instanceof double[]) { double[] v = (double[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('D', cw.newDouble(v[i]).index); } } else { Item i = cw.newConstItem(value); bv.put12(".s.IFJDCS".charAt(i.type), i.index); } } public void visitEnum( final String name, final String desc, final String value) { ++size; if (named) { bv.putShort(cw.newUTF8(name)); } bv.put12('e', cw.newUTF8(desc)).putShort(cw.newUTF8(value)); } public AnnotationVisitor visitAnnotation( final String name, final String desc) { ++size; if (named) { bv.putShort(cw.newUTF8(name)); } // write tag and type, and reserve space for values count bv.put12('@', cw.newUTF8(desc)).putShort(0); return new AnnotationWriter(cw, true, bv, bv, bv.length - 2); } public AnnotationVisitor visitArray(final String name) { ++size; if (named) { bv.putShort(cw.newUTF8(name)); } // write tag, and reserve space for array size bv.put12('[', 0); return new AnnotationWriter(cw, false, bv, bv, bv.length - 2); } public void visitEnd() { if (parent != null) { byte[] data = parent.data; data[offset] = (byte) (size >>> 8); data[offset + 1] = (byte) size; } } // ------------------------------------------------------------------------ // Utility methods // ------------------------------------------------------------------------ /** * Returns the size of this annotation writer list. * * @return the size of this annotation writer list. */ int getSize() { int size = 0; AnnotationWriter aw = this; while (aw != null) { size += aw.bv.length; aw = aw.next; } return size; } /** * Puts the annotations of this annotation writer list into the given byte * vector. * * @param out where the annotations must be put. */ void put(final ByteVector out) { int n = 0; int size = 2; AnnotationWriter aw = this; AnnotationWriter last = null; while (aw != null) { ++n; size += aw.bv.length; aw.visitEnd(); // in case user forgot to call visitEnd aw.prev = last; last = aw; aw = aw.next; } out.putInt(size); out.putShort(n); aw = last; while (aw != null) { out.putByteArray(aw.bv.data, 0, aw.bv.length); aw = aw.prev; } } /** * Puts the given annotation lists into the given byte vector. * * @param panns an array of annotation writer lists. * @param off index of the first annotation to be written. * @param out where the annotations must be put. */ static void put( final AnnotationWriter[] panns, final int off, final ByteVector out) { int size = 1 + 2 * (panns.length - off); for (int i = off; i < panns.length; ++i) { size += panns[i] == null ? 0 : panns[i].getSize(); } out.putInt(size).putByte(panns.length - off); for (int i = off; i < panns.length; ++i) { AnnotationWriter aw = panns[i]; AnnotationWriter last = null; int n = 0; while (aw != null) { ++n; aw.visitEnd(); // in case user forgot to call visitEnd aw.prev = last; last = aw; aw = aw.next; } out.putShort(n); aw = last; while (aw != null) { out.putByteArray(aw.bv.data, 0, aw.bv.length); aw = aw.prev; } } } } Attribute.java000066400000000000000000000231721167051330000416730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * A non standard class, field, method or code attribute. * * @author Eric Bruneton * @author Eugene Kuleshov */ public class Attribute { /** * The type of this attribute. */ public final String type; /** * The raw value of this attribute, used only for unknown attributes. */ byte[] value; /** * The next attribute in this attribute list. May be null. */ Attribute next; /** * Constructs a new empty attribute. * * @param type the type of the attribute. */ protected Attribute(final String type) { this.type = type; } /** * Returns true if this type of attribute is unknown. The default * implementation of this method always returns true. * * @return true if this type of attribute is unknown. */ public boolean isUnknown() { return true; } /** * Returns true if this type of attribute is a code attribute. * * @return true if this type of attribute is a code attribute. */ public boolean isCodeAttribute() { return false; } /** * Returns the labels corresponding to this attribute. * * @return the labels corresponding to this attribute, or null if * this attribute is not a code attribute that contains labels. */ protected Label[] getLabels() { return null; } /** * Reads a {@link #type type} attribute. This method must return a new * {@link Attribute} object, of type {@link #type type}, corresponding to * the len bytes starting at the given offset, in the given class * reader. * * @param cr the class that contains the attribute to be read. * @param off index of the first byte of the attribute's content in {@link * ClassReader#b cr.b}. The 6 attribute header bytes, containing the * type and the length of the attribute, are not taken into account * here. * @param len the length of the attribute's content. * @param buf buffer to be used to call * {@link ClassReader#readUTF8 readUTF8}, * {@link ClassReader#readClass(int,char[]) readClass} or * {@link ClassReader#readConst readConst}. * @param codeOff index of the first byte of code's attribute content in * {@link ClassReader#b cr.b}, or -1 if the attribute to be read is * not a code attribute. The 6 attribute header bytes, containing the * type and the length of the attribute, are not taken into account * here. * @param labels the labels of the method's code, or null if the * attribute to be read is not a code attribute. * @return a new {@link Attribute} object corresponding to the given * bytes. */ protected Attribute read( final ClassReader cr, final int off, final int len, final char[] buf, final int codeOff, final Label[] labels) { Attribute attr = new Attribute(type); attr.value = new byte[len]; System.arraycopy(cr.b, off, attr.value, 0, len); return attr; } /** * Returns the byte array form of this attribute. * * @param cw the class to which this attribute must be added. This parameter * can be used to add to the constant pool of this class the items * that corresponds to this attribute. * @param code the bytecode of the method corresponding to this code * attribute, or null if this attribute is not a code * attributes. * @param len the length of the bytecode of the method corresponding to this * code attribute, or null if this attribute is not a code * attribute. * @param maxStack the maximum stack size of the method corresponding to * this code attribute, or -1 if this attribute is not a code * attribute. * @param maxLocals the maximum number of local variables of the method * corresponding to this code attribute, or -1 if this attribute is * not a code attribute. * @return the byte array form of this attribute. */ protected ByteVector write( final ClassWriter cw, final byte[] code, final int len, final int maxStack, final int maxLocals) { ByteVector v = new ByteVector(); v.data = value; v.length = value.length; return v; } /** * Returns the length of the attribute list that begins with this attribute. * * @return the length of the attribute list that begins with this attribute. */ final int getCount() { int count = 0; Attribute attr = this; while (attr != null) { count += 1; attr = attr.next; } return count; } /** * Returns the size of all the attributes in this attribute list. * * @param cw the class writer to be used to convert the attributes into byte * arrays, with the {@link #write write} method. * @param code the bytecode of the method corresponding to these code * attributes, or null if these attributes are not code * attributes. * @param len the length of the bytecode of the method corresponding to * these code attributes, or null if these attributes are * not code attributes. * @param maxStack the maximum stack size of the method corresponding to * these code attributes, or -1 if these attributes are not code * attributes. * @param maxLocals the maximum number of local variables of the method * corresponding to these code attributes, or -1 if these attributes * are not code attributes. * @return the size of all the attributes in this attribute list. This size * includes the size of the attribute headers. */ final int getSize( final ClassWriter cw, final byte[] code, final int len, final int maxStack, final int maxLocals) { Attribute attr = this; int size = 0; while (attr != null) { cw.newUTF8(attr.type); size += attr.write(cw, code, len, maxStack, maxLocals).length + 6; attr = attr.next; } return size; } /** * Writes all the attributes of this attribute list in the given byte * vector. * * @param cw the class writer to be used to convert the attributes into byte * arrays, with the {@link #write write} method. * @param code the bytecode of the method corresponding to these code * attributes, or null if these attributes are not code * attributes. * @param len the length of the bytecode of the method corresponding to * these code attributes, or null if these attributes are * not code attributes. * @param maxStack the maximum stack size of the method corresponding to * these code attributes, or -1 if these attributes are not code * attributes. * @param maxLocals the maximum number of local variables of the method * corresponding to these code attributes, or -1 if these attributes * are not code attributes. * @param out where the attributes must be written. */ final void put( final ClassWriter cw, final byte[] code, final int len, final int maxStack, final int maxLocals, final ByteVector out) { Attribute attr = this; while (attr != null) { ByteVector b = attr.write(cw, code, len, maxStack, maxLocals); out.putShort(cw.newUTF8(attr.type)).putInt(b.length); out.putByteArray(b.data, 0, b.length); attr = attr.next; } } } ByteVector.java000066400000000000000000000231561167051330000420200ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * A dynamically extensible vector of bytes. This class is roughly equivalent to * a DataOutputStream on top of a ByteArrayOutputStream, but is more efficient. * * @author Eric Bruneton */ public class ByteVector { /** * The content of this vector. */ byte[] data; /** * Actual number of bytes in this vector. */ int length; /** * Constructs a new {@link ByteVector ByteVector} with a default initial * size. */ public ByteVector() { data = new byte[64]; } /** * Constructs a new {@link ByteVector ByteVector} with the given initial * size. * * @param initialSize the initial size of the byte vector to be constructed. */ public ByteVector(final int initialSize) { data = new byte[initialSize]; } /** * Puts a byte into this byte vector. The byte vector is automatically * enlarged if necessary. * * @param b a byte. * @return this byte vector. */ public ByteVector putByte(final int b) { int length = this.length; if (length + 1 > data.length) { enlarge(1); } data[length++] = (byte) b; this.length = length; return this; } /** * Puts two bytes into this byte vector. The byte vector is automatically * enlarged if necessary. * * @param b1 a byte. * @param b2 another byte. * @return this byte vector. */ ByteVector put11(final int b1, final int b2) { int length = this.length; if (length + 2 > data.length) { enlarge(2); } byte[] data = this.data; data[length++] = (byte) b1; data[length++] = (byte) b2; this.length = length; return this; } /** * Puts a short into this byte vector. The byte vector is automatically * enlarged if necessary. * * @param s a short. * @return this byte vector. */ public ByteVector putShort(final int s) { int length = this.length; if (length + 2 > data.length) { enlarge(2); } byte[] data = this.data; data[length++] = (byte) (s >>> 8); data[length++] = (byte) s; this.length = length; return this; } /** * Puts a byte and a short into this byte vector. The byte vector is * automatically enlarged if necessary. * * @param b a byte. * @param s a short. * @return this byte vector. */ ByteVector put12(final int b, final int s) { int length = this.length; if (length + 3 > data.length) { enlarge(3); } byte[] data = this.data; data[length++] = (byte) b; data[length++] = (byte) (s >>> 8); data[length++] = (byte) s; this.length = length; return this; } /** * Puts an int into this byte vector. The byte vector is automatically * enlarged if necessary. * * @param i an int. * @return this byte vector. */ public ByteVector putInt(final int i) { int length = this.length; if (length + 4 > data.length) { enlarge(4); } byte[] data = this.data; data[length++] = (byte) (i >>> 24); data[length++] = (byte) (i >>> 16); data[length++] = (byte) (i >>> 8); data[length++] = (byte) i; this.length = length; return this; } /** * Puts a long into this byte vector. The byte vector is automatically * enlarged if necessary. * * @param l a long. * @return this byte vector. */ public ByteVector putLong(final long l) { int length = this.length; if (length + 8 > data.length) { enlarge(8); } byte[] data = this.data; int i = (int) (l >>> 32); data[length++] = (byte) (i >>> 24); data[length++] = (byte) (i >>> 16); data[length++] = (byte) (i >>> 8); data[length++] = (byte) i; i = (int) l; data[length++] = (byte) (i >>> 24); data[length++] = (byte) (i >>> 16); data[length++] = (byte) (i >>> 8); data[length++] = (byte) i; this.length = length; return this; } /** * Puts an UTF8 string into this byte vector. The byte vector is * automatically enlarged if necessary. * * @param s a String. * @return this byte vector. */ public ByteVector putUTF8(final String s) { int charLength = s.length(); int len = length; if (len + 2 + charLength > data.length) { enlarge(2 + charLength); } byte[] data = this.data; // optimistic algorithm: instead of computing the byte length and then // serializing the string (which requires two loops), we assume the byte // length is equal to char length (which is the most frequent case), and // we start serializing the string right away. During the serialization, // if we find that this assumption is wrong, we continue with the // general method. data[len++] = (byte) (charLength >>> 8); data[len++] = (byte) charLength; for (int i = 0; i < charLength; ++i) { char c = s.charAt(i); if (c >= '\001' && c <= '\177') { data[len++] = (byte) c; } else { int byteLength = i; for (int j = i; j < charLength; ++j) { c = s.charAt(j); if (c >= '\001' && c <= '\177') { byteLength++; } else if (c > '\u07FF') { byteLength += 3; } else { byteLength += 2; } } data[length] = (byte) (byteLength >>> 8); data[length + 1] = (byte) byteLength; if (length + 2 + byteLength > data.length) { length = len; enlarge(2 + byteLength); data = this.data; } for (int j = i; j < charLength; ++j) { c = s.charAt(j); if (c >= '\001' && c <= '\177') { data[len++] = (byte) c; } else if (c > '\u07FF') { data[len++] = (byte) (0xE0 | c >> 12 & 0xF); data[len++] = (byte) (0x80 | c >> 6 & 0x3F); data[len++] = (byte) (0x80 | c & 0x3F); } else { data[len++] = (byte) (0xC0 | c >> 6 & 0x1F); data[len++] = (byte) (0x80 | c & 0x3F); } } break; } } length = len; return this; } /** * Puts an array of bytes into this byte vector. The byte vector is * automatically enlarged if necessary. * * @param b an array of bytes. May be null to put len * null bytes into this byte vector. * @param off index of the fist byte of b that must be copied. * @param len number of bytes of b that must be copied. * @return this byte vector. */ public ByteVector putByteArray(final byte[] b, final int off, final int len) { if (length + len > data.length) { enlarge(len); } if (b != null) { System.arraycopy(b, off, data, length, len); } length += len; return this; } /** * Enlarge this byte vector so that it can receive n more bytes. * * @param size number of additional bytes that this byte vector should be * able to receive. */ private void enlarge(final int size) { int length1 = 2 * data.length; int length2 = length + size; byte[] newData = new byte[length1 > length2 ? length1 : length2]; System.arraycopy(data, 0, newData, 0, length); data = newData; } } ClassReader.java000066400000000000000000002471571167051330000421330ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; import java.io.InputStream; import java.io.IOException; /** * A Java class parser to make a {@link ClassVisitor} visit an existing class. * This class parses a byte array conforming to the Java class file format and * calls the appropriate visit methods of a given class visitor for each field, * method and bytecode instruction encountered. * * @author Eric Bruneton * @author Eugene Kuleshov */ public class ClassReader { /** * True to enable signatures support. */ static final boolean SIGNATURES = true; /** * True to enable annotations support. */ static final boolean ANNOTATIONS = true; /** * True to enable stack map frames support. */ static final boolean FRAMES = true; /** * True to enable bytecode writing support. */ static final boolean WRITER = true; /** * True to enable JSR_W and GOTO_W support. */ static final boolean RESIZE = true; /** * Flag to skip method code. If this class is set CODE * attribute won't be visited. This can be used, for example, to retrieve * annotations for methods and method parameters. */ public static final int SKIP_CODE = 1; /** * Flag to skip the debug information in the class. If this flag is set the * debug information of the class is not visited, i.e. the * {@link MethodVisitor#visitLocalVariable visitLocalVariable} and * {@link MethodVisitor#visitLineNumber visitLineNumber} methods will not be * called. */ public static final int SKIP_DEBUG = 2; /** * Flag to skip the stack map frames in the class. If this flag is set the * stack map frames of the class is not visited, i.e. the * {@link MethodVisitor#visitFrame visitFrame} method will not be called. * This flag is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is * used: it avoids visiting frames that will be ignored and recomputed from * scratch in the class writer. */ public static final int SKIP_FRAMES = 4; /** * Flag to expand the stack map frames. By default stack map frames are * visited in their original format (i.e. "expanded" for classes whose * version is less than V1_6, and "compressed" for the other classes). If * this flag is set, stack map frames are always visited in expanded format * (this option adds a decompression/recompression step in ClassReader and * ClassWriter which degrades performances quite a lot). */ public static final int EXPAND_FRAMES = 8; /** * The class to be parsed. The content of this array must not be * modified. This field is intended for {@link Attribute} sub classes, and * is normally not needed by class generators or adapters. */ public final byte[] b; /** * The start index of each constant pool item in {@link #b b}, plus one. * The one byte offset skips the constant pool item tag that indicates its * type. */ private final int[] items; /** * The String objects corresponding to the CONSTANT_Utf8 items. This cache * avoids multiple parsing of a given CONSTANT_Utf8 constant pool item, * which GREATLY improves performances (by a factor 2 to 3). This caching * strategy could be extended to all constant pool items, but its benefit * would not be so great for these items (because they are much less * expensive to parse than CONSTANT_Utf8 items). */ private final String[] strings; /** * Maximum length of the strings contained in the constant pool of the * class. */ private final int maxStringLength; /** * Start index of the class header information (access, name...) in * {@link #b b}. */ public final int header; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Constructs a new {@link ClassReader} object. * * @param b the bytecode of the class to be read. */ public ClassReader(final byte[] b) { this(b, 0, b.length); } /** * Constructs a new {@link ClassReader} object. * * @param b the bytecode of the class to be read. * @param off the start offset of the class data. * @param len the length of the class data. */ public ClassReader(final byte[] b, final int off, final int len) { this.b = b; // parses the constant pool items = new int[readUnsignedShort(off + 8)]; int n = items.length; strings = new String[n]; int max = 0; int index = off + 10; for (int i = 1; i < n; ++i) { items[i] = index + 1; int size; switch (b[index]) { case ClassWriter.FIELD: case ClassWriter.METH: case ClassWriter.IMETH: case ClassWriter.INT: case ClassWriter.FLOAT: case ClassWriter.NAME_TYPE: size = 5; break; case ClassWriter.LONG: case ClassWriter.DOUBLE: size = 9; ++i; break; case ClassWriter.UTF8: size = 3 + readUnsignedShort(index + 1); if (size > max) { max = size; } break; // case ClassWriter.CLASS: // case ClassWriter.STR: default: size = 3; break; } index += size; } maxStringLength = max; // the class header information starts just after the constant pool header = index; } /** * Returns the class's access flags (see {@link Opcodes}). This value may * not reflect Deprecated and Synthetic flags when bytecode is before 1.5 * and those flags are represented by attributes. * * @return the class access flags * * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public int getAccess() { return readUnsignedShort(header); } /** * Returns the internal name of the class (see * {@link Type#getInternalName() getInternalName}). * * @return the internal class name * * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public String getClassName() { return readClass(header + 2, new char[maxStringLength]); } /** * Returns the internal of name of the super class (see * {@link Type#getInternalName() getInternalName}). For interfaces, the * super class is {@link Object}. * * @return the internal name of super class, or null for * {@link Object} class. * * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public String getSuperName() { int n = items[readUnsignedShort(header + 4)]; return n == 0 ? null : readUTF8(n, new char[maxStringLength]); } /** * Returns the internal names of the class's interfaces (see * {@link Type#getInternalName() getInternalName}). * * @return the array of internal names for all implemented interfaces or * null. * * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public String[] getInterfaces() { int index = header + 6; int n = readUnsignedShort(index); String[] interfaces = new String[n]; if (n > 0) { char[] buf = new char[maxStringLength]; for (int i = 0; i < n; ++i) { index += 2; interfaces[i] = readClass(index, buf); } } return interfaces; } /** * Copies the constant pool data into the given {@link ClassWriter}. Should * be called before the {@link #accept(ClassVisitor,int)} method. * * @param classWriter the {@link ClassWriter} to copy constant pool into. */ void copyPool(final ClassWriter classWriter) { char[] buf = new char[maxStringLength]; int ll = items.length; Item[] items2 = new Item[ll]; for (int i = 1; i < ll; i++) { int index = items[i]; int tag = b[index - 1]; Item item = new Item(i); int nameType; switch (tag) { case ClassWriter.FIELD: case ClassWriter.METH: case ClassWriter.IMETH: nameType = items[readUnsignedShort(index + 2)]; item.set(tag, readClass(index, buf), readUTF8(nameType, buf), readUTF8(nameType + 2, buf)); break; case ClassWriter.INT: item.set(readInt(index)); break; case ClassWriter.FLOAT: item.set(Float.intBitsToFloat(readInt(index))); break; case ClassWriter.NAME_TYPE: item.set(tag, readUTF8(index, buf), readUTF8(index + 2, buf), null); break; case ClassWriter.LONG: item.set(readLong(index)); ++i; break; case ClassWriter.DOUBLE: item.set(Double.longBitsToDouble(readLong(index))); ++i; break; case ClassWriter.UTF8: { String s = strings[i]; if (s == null) { index = items[i]; s = strings[i] = readUTF(index + 2, readUnsignedShort(index), buf); } item.set(tag, s, null, null); } break; // case ClassWriter.STR: // case ClassWriter.CLASS: default: item.set(tag, readUTF8(index, buf), null, null); break; } int index2 = item.hashCode % items2.length; item.next = items2[index2]; items2[index2] = item; } int off = items[1] - 1; classWriter.pool.putByteArray(b, off, header - off); classWriter.items = items2; classWriter.threshold = (int) (0.75d * ll); classWriter.index = ll; } /** * Constructs a new {@link ClassReader} object. * * @param is an input stream from which to read the class. * @throws IOException if a problem occurs during reading. */ public ClassReader(final InputStream is) throws IOException { this(readClass(is)); } /** * Constructs a new {@link ClassReader} object. * * @param name the binary qualified name of the class to be read. * @throws IOException if an exception occurs during reading. */ public ClassReader(final String name) throws IOException { this(ClassLoader.getSystemResourceAsStream(name.replace('.', '/') + ".class")); } /** * Reads the bytecode of a class. * * @param is an input stream from which to read the class. * @return the bytecode read from the given input stream. * @throws IOException if a problem occurs during reading. */ private static byte[] readClass(final InputStream is) throws IOException { if (is == null) { throw new IOException("Class not found"); } byte[] b = new byte[is.available()]; int len = 0; while (true) { int n = is.read(b, len, b.length - len); if (n == -1) { if (len < b.length) { byte[] c = new byte[len]; System.arraycopy(b, 0, c, 0, len); b = c; } return b; } len += n; if (len == b.length) { int last = is.read(); if (last < 0) { return b; } byte[] c = new byte[b.length + 1000]; System.arraycopy(b, 0, c, 0, len); c[len++] = (byte) last; b = c; } } } // ------------------------------------------------------------------------ // Public methods // ------------------------------------------------------------------------ /** * Makes the given visitor visit the Java class of this {@link ClassReader}. * This class is the one specified in the constructor (see * {@link #ClassReader(byte[]) ClassReader}). * * @param classVisitor the visitor that must visit this class. * @param flags option flags that can be used to modify the default behavior * of this class. See {@link #SKIP_DEBUG}, {@link #EXPAND_FRAMES}, * {@link #SKIP_FRAMES}, {@link #SKIP_CODE}. */ public void accept(final ClassVisitor classVisitor, final int flags) { accept(classVisitor, new Attribute[0], flags); } /** * Makes the given visitor visit the Java class of this {@link ClassReader}. * This class is the one specified in the constructor (see * {@link #ClassReader(byte[]) ClassReader}). * * @param classVisitor the visitor that must visit this class. * @param attrs prototypes of the attributes that must be parsed during the * visit of the class. Any attribute whose type is not equal to the * type of one the prototypes will not be parsed: its byte array * value will be passed unchanged to the ClassWriter. This may * corrupt it if this value contains references to the constant pool, * or has syntactic or semantic links with a class element that has * been transformed by a class adapter between the reader and the * writer. * @param flags option flags that can be used to modify the default behavior * of this class. See {@link #SKIP_DEBUG}, {@link #EXPAND_FRAMES}, * {@link #SKIP_FRAMES}, {@link #SKIP_CODE}. */ public void accept( final ClassVisitor classVisitor, final Attribute[] attrs, final int flags) { byte[] b = this.b; // the bytecode array char[] c = new char[maxStringLength]; // buffer used to read strings int i, j, k; // loop variables int u, v, w; // indexes in b Attribute attr; int access; String name; String desc; String attrName; String signature; int anns = 0; int ianns = 0; Attribute cattrs = null; // visits the header u = header; access = readUnsignedShort(u); name = readClass(u + 2, c); v = items[readUnsignedShort(u + 4)]; String superClassName = v == 0 ? null : readUTF8(v, c); String[] implementedItfs = new String[readUnsignedShort(u + 6)]; w = 0; u += 8; for (i = 0; i < implementedItfs.length; ++i) { implementedItfs[i] = readClass(u, c); u += 2; } boolean skipCode = (flags & SKIP_CODE) != 0; boolean skipDebug = (flags & SKIP_DEBUG) != 0; boolean unzip = (flags & EXPAND_FRAMES) != 0; // skips fields and methods v = u; i = readUnsignedShort(v); v += 2; for (; i > 0; --i) { j = readUnsignedShort(v + 6); v += 8; for (; j > 0; --j) { v += 6 + readInt(v + 2); } } i = readUnsignedShort(v); v += 2; for (; i > 0; --i) { j = readUnsignedShort(v + 6); v += 8; for (; j > 0; --j) { v += 6 + readInt(v + 2); } } // reads the class's attributes signature = null; String sourceFile = null; String sourceDebug = null; String enclosingOwner = null; String enclosingName = null; String enclosingDesc = null; i = readUnsignedShort(v); v += 2; for (; i > 0; --i) { attrName = readUTF8(v, c); // tests are sorted in decreasing frequency order // (based on frequencies observed on typical classes) if ("SourceFile".equals(attrName)) { sourceFile = readUTF8(v + 6, c); } else if ("InnerClasses".equals(attrName)) { w = v + 6; } else if ("EnclosingMethod".equals(attrName)) { enclosingOwner = readClass(v + 6, c); int item = readUnsignedShort(v + 8); if (item != 0) { enclosingName = readUTF8(items[item], c); enclosingDesc = readUTF8(items[item] + 2, c); } } else if (SIGNATURES && "Signature".equals(attrName)) { signature = readUTF8(v + 6, c); } else if (ANNOTATIONS && "RuntimeVisibleAnnotations".equals(attrName)) { anns = v + 6; } else if ("Deprecated".equals(attrName)) { access |= Opcodes.ACC_DEPRECATED; } else if ("Synthetic".equals(attrName)) { access |= Opcodes.ACC_SYNTHETIC | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE; } else if ("SourceDebugExtension".equals(attrName)) { int len = readInt(v + 2); sourceDebug = readUTF(v + 6, len, new char[len]); } else if (ANNOTATIONS && "RuntimeInvisibleAnnotations".equals(attrName)) { ianns = v + 6; } else { attr = readAttribute(attrs, attrName, v + 6, readInt(v + 2), c, -1, null); if (attr != null) { attr.next = cattrs; cattrs = attr; } } v += 6 + readInt(v + 2); } // calls the visit method classVisitor.visit(readInt(4), access, name, signature, superClassName, implementedItfs); // calls the visitSource method if (!skipDebug && (sourceFile != null || sourceDebug != null)) { classVisitor.visitSource(sourceFile, sourceDebug); } // calls the visitOuterClass method if (enclosingOwner != null) { classVisitor.visitOuterClass(enclosingOwner, enclosingName, enclosingDesc); } // visits the class annotations if (ANNOTATIONS) { for (i = 1; i >= 0; --i) { v = i == 0 ? ianns : anns; if (v != 0) { j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { v = readAnnotationValues(v + 2, c, true, classVisitor.visitAnnotation(readUTF8(v, c), i != 0)); } } } } // visits the class attributes while (cattrs != null) { attr = cattrs.next; cattrs.next = null; classVisitor.visitAttribute(cattrs); cattrs = attr; } // calls the visitInnerClass method if (w != 0) { i = readUnsignedShort(w); w += 2; for (; i > 0; --i) { classVisitor.visitInnerClass(readUnsignedShort(w) == 0 ? null : readClass(w, c), readUnsignedShort(w + 2) == 0 ? null : readClass(w + 2, c), readUnsignedShort(w + 4) == 0 ? null : readUTF8(w + 4, c), readUnsignedShort(w + 6)); w += 8; } } // visits the fields i = readUnsignedShort(u); u += 2; for (; i > 0; --i) { access = readUnsignedShort(u); name = readUTF8(u + 2, c); desc = readUTF8(u + 4, c); // visits the field's attributes and looks for a ConstantValue // attribute int fieldValueItem = 0; signature = null; anns = 0; ianns = 0; cattrs = null; j = readUnsignedShort(u + 6); u += 8; for (; j > 0; --j) { attrName = readUTF8(u, c); // tests are sorted in decreasing frequency order // (based on frequencies observed on typical classes) if ("ConstantValue".equals(attrName)) { fieldValueItem = readUnsignedShort(u + 6); } else if (SIGNATURES && "Signature".equals(attrName)) { signature = readUTF8(u + 6, c); } else if ("Deprecated".equals(attrName)) { access |= Opcodes.ACC_DEPRECATED; } else if ("Synthetic".equals(attrName)) { access |= Opcodes.ACC_SYNTHETIC | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE; } else if (ANNOTATIONS && "RuntimeVisibleAnnotations".equals(attrName)) { anns = u + 6; } else if (ANNOTATIONS && "RuntimeInvisibleAnnotations".equals(attrName)) { ianns = u + 6; } else { attr = readAttribute(attrs, attrName, u + 6, readInt(u + 2), c, -1, null); if (attr != null) { attr.next = cattrs; cattrs = attr; } } u += 6 + readInt(u + 2); } // visits the field FieldVisitor fv = classVisitor.visitField(access, name, desc, signature, fieldValueItem == 0 ? null : readConst(fieldValueItem, c)); // visits the field annotations and attributes if (fv != null) { if (ANNOTATIONS) { for (j = 1; j >= 0; --j) { v = j == 0 ? ianns : anns; if (v != 0) { k = readUnsignedShort(v); v += 2; for (; k > 0; --k) { v = readAnnotationValues(v + 2, c, true, fv.visitAnnotation(readUTF8(v, c), j != 0)); } } } } while (cattrs != null) { attr = cattrs.next; cattrs.next = null; fv.visitAttribute(cattrs); cattrs = attr; } fv.visitEnd(); } } // visits the methods i = readUnsignedShort(u); u += 2; for (; i > 0; --i) { int u0 = u + 6; access = readUnsignedShort(u); name = readUTF8(u + 2, c); desc = readUTF8(u + 4, c); signature = null; anns = 0; ianns = 0; int dann = 0; int mpanns = 0; int impanns = 0; cattrs = null; v = 0; w = 0; // looks for Code and Exceptions attributes j = readUnsignedShort(u + 6); u += 8; for (; j > 0; --j) { attrName = readUTF8(u, c); int attrSize = readInt(u + 2); u += 6; // tests are sorted in decreasing frequency order // (based on frequencies observed on typical classes) if ("Code".equals(attrName)) { if (!skipCode) { v = u; } } else if ("Exceptions".equals(attrName)) { w = u; } else if (SIGNATURES && "Signature".equals(attrName)) { signature = readUTF8(u, c); } else if ("Deprecated".equals(attrName)) { access |= Opcodes.ACC_DEPRECATED; } else if (ANNOTATIONS && "RuntimeVisibleAnnotations".equals(attrName)) { anns = u; } else if (ANNOTATIONS && "AnnotationDefault".equals(attrName)) { dann = u; } else if ("Synthetic".equals(attrName)) { access |= Opcodes.ACC_SYNTHETIC | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE; } else if (ANNOTATIONS && "RuntimeInvisibleAnnotations".equals(attrName)) { ianns = u; } else if (ANNOTATIONS && "RuntimeVisibleParameterAnnotations".equals(attrName)) { mpanns = u; } else if (ANNOTATIONS && "RuntimeInvisibleParameterAnnotations".equals(attrName)) { impanns = u; } else { attr = readAttribute(attrs, attrName, u, attrSize, c, -1, null); if (attr != null) { attr.next = cattrs; cattrs = attr; } } u += attrSize; } // reads declared exceptions String[] exceptions; if (w == 0) { exceptions = null; } else { exceptions = new String[readUnsignedShort(w)]; w += 2; for (j = 0; j < exceptions.length; ++j) { exceptions[j] = readClass(w, c); w += 2; } } // visits the method's code, if any MethodVisitor mv = classVisitor.visitMethod(access, name, desc, signature, exceptions); if (mv != null) { /* * if the returned MethodVisitor is in fact a MethodWriter, it * means there is no method adapter between the reader and the * writer. If, in addition, the writer's constant pool was * copied from this reader (mw.cw.cr == this), and the signature * and exceptions of the method have not been changed, then it * is possible to skip all visit events and just copy the * original code of the method to the writer (the access, name * and descriptor can have been changed, this is not important * since they are not copied as is from the reader). */ if (WRITER && mv instanceof MethodWriter) { MethodWriter mw = (MethodWriter) mv; if (mw.cw.cr == this) { if (signature == mw.signature) { boolean sameExceptions = false; if (exceptions == null) { sameExceptions = mw.exceptionCount == 0; } else { if (exceptions.length == mw.exceptionCount) { sameExceptions = true; for (j = exceptions.length - 1; j >= 0; --j) { w -= 2; if (mw.exceptions[j] != readUnsignedShort(w)) { sameExceptions = false; break; } } } } if (sameExceptions) { /* * we do not copy directly the code into * MethodWriter to save a byte array copy * operation. The real copy will be done in * ClassWriter.toByteArray(). */ mw.classReaderOffset = u0; mw.classReaderLength = u - u0; continue; } } } } if (ANNOTATIONS && dann != 0) { AnnotationVisitor dv = mv.visitAnnotationDefault(); readAnnotationValue(dann, c, null, dv); if (dv != null) { dv.visitEnd(); } } if (ANNOTATIONS) { for (j = 1; j >= 0; --j) { w = j == 0 ? ianns : anns; if (w != 0) { k = readUnsignedShort(w); w += 2; for (; k > 0; --k) { w = readAnnotationValues(w + 2, c, true, mv.visitAnnotation(readUTF8(w, c), j != 0)); } } } } if (ANNOTATIONS && mpanns != 0) { readParameterAnnotations(mpanns, desc, c, true, mv); } if (ANNOTATIONS && impanns != 0) { readParameterAnnotations(impanns, desc, c, false, mv); } while (cattrs != null) { attr = cattrs.next; cattrs.next = null; mv.visitAttribute(cattrs); cattrs = attr; } } if (mv != null && v != 0) { int maxStack = readUnsignedShort(v); int maxLocals = readUnsignedShort(v + 2); int codeLength = readInt(v + 4); v += 8; int codeStart = v; int codeEnd = v + codeLength; mv.visitCode(); // 1st phase: finds the labels int label; Label[] labels = new Label[codeLength + 2]; readLabel(codeLength + 1, labels); while (v < codeEnd) { w = v - codeStart; int opcode = b[v] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: v += 1; break; case ClassWriter.LABEL_INSN: readLabel(w + readShort(v + 1), labels); v += 3; break; case ClassWriter.LABELW_INSN: readLabel(w + readInt(v + 1), labels); v += 5; break; case ClassWriter.WIDE_INSN: opcode = b[v + 1] & 0xFF; if (opcode == Opcodes.IINC) { v += 6; } else { v += 4; } break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes* v = v + 4 - (w & 3); // reads instruction readLabel(w + readInt(v), labels); j = readInt(v + 8) - readInt(v + 4) + 1; v += 12; for (; j > 0; --j) { readLabel(w + readInt(v), labels); v += 4; } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes* v = v + 4 - (w & 3); // reads instruction readLabel(w + readInt(v), labels); j = readInt(v + 4); v += 8; for (; j > 0; --j) { readLabel(w + readInt(v + 4), labels); v += 8; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: v += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: v += 3; break; case ClassWriter.ITFDYNMETH_INSN: v += 5; break; // case MANA_INSN: default: v += 4; break; } } // parses the try catch entries j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { Label start = readLabel(readUnsignedShort(v), labels); Label end = readLabel(readUnsignedShort(v + 2), labels); Label handler = readLabel(readUnsignedShort(v + 4), labels); int type = readUnsignedShort(v + 6); if (type == 0) { mv.visitTryCatchBlock(start, end, handler, null); } else { mv.visitTryCatchBlock(start, end, handler, readUTF8(items[type], c)); } v += 8; } // parses the local variable, line number tables, and code // attributes int varTable = 0; int varTypeTable = 0; int stackMap = 0; int stackMapSize = 0; int frameCount = 0; int frameMode = 0; int frameOffset = 0; int frameLocalCount = 0; int frameLocalDiff = 0; int frameStackCount = 0; Object[] frameLocal = null; Object[] frameStack = null; boolean zip = true; cattrs = null; j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { attrName = readUTF8(v, c); if ("LocalVariableTable".equals(attrName)) { if (!skipDebug) { varTable = v + 6; k = readUnsignedShort(v + 6); w = v + 8; for (; k > 0; --k) { label = readUnsignedShort(w); if (labels[label] == null) { readLabel(label, labels).status |= Label.DEBUG; } label += readUnsignedShort(w + 2); if (labels[label] == null) { readLabel(label, labels).status |= Label.DEBUG; } w += 10; } } } else if ("LocalVariableTypeTable".equals(attrName)) { varTypeTable = v + 6; } else if ("LineNumberTable".equals(attrName)) { if (!skipDebug) { k = readUnsignedShort(v + 6); w = v + 8; for (; k > 0; --k) { label = readUnsignedShort(w); if (labels[label] == null) { readLabel(label, labels).status |= Label.DEBUG; } labels[label].line = readUnsignedShort(w + 2); w += 4; } } } else if (FRAMES && "StackMapTable".equals(attrName)) { if ((flags & SKIP_FRAMES) == 0) { stackMap = v + 8; stackMapSize = readInt(v + 2); frameCount = readUnsignedShort(v + 6); } /* * here we do not extract the labels corresponding to * the attribute content. This would require a full * parsing of the attribute, which would need to be * repeated in the second phase (see below). Instead the * content of the attribute is read one frame at a time * (i.e. after a frame has been visited, the next frame * is read), and the labels it contains are also * extracted one frame at a time. Thanks to the ordering * of frames, having only a "one frame lookahead" is not * a problem, i.e. it is not possible to see an offset * smaller than the offset of the current insn and for * which no Label exist. */ /* * This is not true for UNINITIALIZED type offsets. We * solve this by parsing the stack map table without a * full decoding (see below). */ } else if (FRAMES && "StackMap".equals(attrName)) { if ((flags & SKIP_FRAMES) == 0) { stackMap = v + 8; stackMapSize = readInt(v + 2); frameCount = readUnsignedShort(v + 6); zip = false; } /* * IMPORTANT! here we assume that the frames are * ordered, as in the StackMapTable attribute, although * this is not guaranteed by the attribute format. */ } else { for (k = 0; k < attrs.length; ++k) { if (attrs[k].type.equals(attrName)) { attr = attrs[k].read(this, v + 6, readInt(v + 2), c, codeStart - 8, labels); if (attr != null) { attr.next = cattrs; cattrs = attr; } } } } v += 6 + readInt(v + 2); } // 2nd phase: visits each instruction if (FRAMES && stackMap != 0) { // creates the very first (implicit) frame from the method // descriptor frameLocal = new Object[maxLocals]; frameStack = new Object[maxStack]; if (unzip) { int local = 0; if ((access & Opcodes.ACC_STATIC) == 0) { if ("".equals(name)) { frameLocal[local++] = Opcodes.UNINITIALIZED_THIS; } else { frameLocal[local++] = readClass(header + 2, c); } } j = 1; loop: while (true) { k = j; switch (desc.charAt(j++)) { case 'Z': case 'C': case 'B': case 'S': case 'I': frameLocal[local++] = Opcodes.INTEGER; break; case 'F': frameLocal[local++] = Opcodes.FLOAT; break; case 'J': frameLocal[local++] = Opcodes.LONG; break; case 'D': frameLocal[local++] = Opcodes.DOUBLE; break; case '[': while (desc.charAt(j) == '[') { ++j; } if (desc.charAt(j) == 'L') { ++j; while (desc.charAt(j) != ';') { ++j; } } frameLocal[local++] = desc.substring(k, ++j); break; case 'L': while (desc.charAt(j) != ';') { ++j; } frameLocal[local++] = desc.substring(k + 1, j++); break; default: break loop; } } frameLocalCount = local; } /* * for the first explicit frame the offset is not * offset_delta + 1 but only offset_delta; setting the * implicit frame offset to -1 allow the use of the * "offset_delta + 1" rule in all cases */ frameOffset = -1; /* * Finds labels for UNINITIALIZED frame types. Instead of * decoding each element of the stack map table, we look * for 3 consecutive bytes that "look like" an UNINITIALIZED * type (tag 8, offset within code bounds, NEW instruction * at this offset). We may find false positives (i.e. not * real UNINITIALIZED types), but this should be rare, and * the only consequence will be the creation of an unneeded * label. This is better than creating a label for each NEW * instruction, and faster than fully decoding the whole * stack map table. */ for (j = stackMap; j < stackMap + stackMapSize - 2; ++j) { if (b[j] == 8) { // UNINITIALIZED FRAME TYPE k = readUnsignedShort(j + 1); if (k >= 0 && k < codeLength) { // potential offset if ((b[codeStart + k] & 0xFF) == Opcodes.NEW) { // NEW at this offset readLabel(k, labels); } } } } } v = codeStart; Label l; while (v < codeEnd) { w = v - codeStart; l = labels[w]; if (l != null) { mv.visitLabel(l); if (!skipDebug && l.line > 0) { mv.visitLineNumber(l.line, l); } } while (FRAMES && frameLocal != null && (frameOffset == w || frameOffset == -1)) { // if there is a frame for this offset, // makes the visitor visit it, // and reads the next frame if there is one. if (!zip || unzip) { mv.visitFrame(Opcodes.F_NEW, frameLocalCount, frameLocal, frameStackCount, frameStack); } else if (frameOffset != -1) { mv.visitFrame(frameMode, frameLocalDiff, frameLocal, frameStackCount, frameStack); } if (frameCount > 0) { int tag, delta, n; if (zip) { tag = b[stackMap++] & 0xFF; } else { tag = MethodWriter.FULL_FRAME; frameOffset = -1; } frameLocalDiff = 0; if (tag < MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME) { delta = tag; frameMode = Opcodes.F_SAME; frameStackCount = 0; } else if (tag < MethodWriter.RESERVED) { delta = tag - MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME; stackMap = readFrameType(frameStack, 0, stackMap, c, labels); frameMode = Opcodes.F_SAME1; frameStackCount = 1; } else { delta = readUnsignedShort(stackMap); stackMap += 2; if (tag == MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { stackMap = readFrameType(frameStack, 0, stackMap, c, labels); frameMode = Opcodes.F_SAME1; frameStackCount = 1; } else if (tag >= MethodWriter.CHOP_FRAME && tag < MethodWriter.SAME_FRAME_EXTENDED) { frameMode = Opcodes.F_CHOP; frameLocalDiff = MethodWriter.SAME_FRAME_EXTENDED - tag; frameLocalCount -= frameLocalDiff; frameStackCount = 0; } else if (tag == MethodWriter.SAME_FRAME_EXTENDED) { frameMode = Opcodes.F_SAME; frameStackCount = 0; } else if (tag < MethodWriter.FULL_FRAME) { j = unzip ? frameLocalCount : 0; for (k = tag - MethodWriter.SAME_FRAME_EXTENDED; k > 0; k--) { stackMap = readFrameType(frameLocal, j++, stackMap, c, labels); } frameMode = Opcodes.F_APPEND; frameLocalDiff = tag - MethodWriter.SAME_FRAME_EXTENDED; frameLocalCount += frameLocalDiff; frameStackCount = 0; } else { // if (tag == FULL_FRAME) { frameMode = Opcodes.F_FULL; n = frameLocalDiff = frameLocalCount = readUnsignedShort(stackMap); stackMap += 2; for (j = 0; n > 0; n--) { stackMap = readFrameType(frameLocal, j++, stackMap, c, labels); } n = frameStackCount = readUnsignedShort(stackMap); stackMap += 2; for (j = 0; n > 0; n--) { stackMap = readFrameType(frameStack, j++, stackMap, c, labels); } } } frameOffset += delta + 1; readLabel(frameOffset, labels); --frameCount; } else { frameLocal = null; } } int opcode = b[v] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: mv.visitInsn(opcode); v += 1; break; case ClassWriter.IMPLVAR_INSN: if (opcode > Opcodes.ISTORE) { opcode -= 59; // ISTORE_0 mv.visitVarInsn(Opcodes.ISTORE + (opcode >> 2), opcode & 0x3); } else { opcode -= 26; // ILOAD_0 mv.visitVarInsn(Opcodes.ILOAD + (opcode >> 2), opcode & 0x3); } v += 1; break; case ClassWriter.LABEL_INSN: mv.visitJumpInsn(opcode, labels[w + readShort(v + 1)]); v += 3; break; case ClassWriter.LABELW_INSN: mv.visitJumpInsn(opcode - 33, labels[w + readInt(v + 1)]); v += 5; break; case ClassWriter.WIDE_INSN: opcode = b[v + 1] & 0xFF; if (opcode == Opcodes.IINC) { mv.visitIincInsn(readUnsignedShort(v + 2), readShort(v + 4)); v += 6; } else { mv.visitVarInsn(opcode, readUnsignedShort(v + 2)); v += 4; } break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = v + 4 - (w & 3); // reads instruction label = w + readInt(v); int min = readInt(v + 4); int max = readInt(v + 8); v += 12; Label[] table = new Label[max - min + 1]; for (j = 0; j < table.length; ++j) { table[j] = labels[w + readInt(v)]; v += 4; } mv.visitTableSwitchInsn(min, max, labels[label], table); break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = v + 4 - (w & 3); // reads instruction label = w + readInt(v); j = readInt(v + 4); v += 8; int[] keys = new int[j]; Label[] values = new Label[j]; for (j = 0; j < keys.length; ++j) { keys[j] = readInt(v); values[j] = labels[w + readInt(v + 4)]; v += 8; } mv.visitLookupSwitchInsn(labels[label], keys, values); break; case ClassWriter.VAR_INSN: mv.visitVarInsn(opcode, b[v + 1] & 0xFF); v += 2; break; case ClassWriter.SBYTE_INSN: mv.visitIntInsn(opcode, b[v + 1]); v += 2; break; case ClassWriter.SHORT_INSN: mv.visitIntInsn(opcode, readShort(v + 1)); v += 3; break; case ClassWriter.LDC_INSN: mv.visitLdcInsn(readConst(b[v + 1] & 0xFF, c)); v += 2; break; case ClassWriter.LDCW_INSN: mv.visitLdcInsn(readConst(readUnsignedShort(v + 1), c)); v += 3; break; case ClassWriter.FIELDORMETH_INSN: case ClassWriter.ITFDYNMETH_INSN: int cpIndex = items[readUnsignedShort(v + 1)]; String iowner; // INVOKEDYNAMIC is receiverless if (opcode == Opcodes.INVOKEDYNAMIC) { iowner = Opcodes.INVOKEDYNAMIC_OWNER; } else { iowner = readClass(cpIndex, c); cpIndex = items[readUnsignedShort(cpIndex + 2)]; } String iname = readUTF8(cpIndex, c); String idesc = readUTF8(cpIndex + 2, c); if (opcode < Opcodes.INVOKEVIRTUAL) { mv.visitFieldInsn(opcode, iowner, iname, idesc); } else { mv.visitMethodInsn(opcode, iowner, iname, idesc); } if (opcode == Opcodes.INVOKEINTERFACE || opcode == Opcodes.INVOKEDYNAMIC) { v += 5; } else { v += 3; } break; case ClassWriter.TYPE_INSN: mv.visitTypeInsn(opcode, readClass(v + 1, c)); v += 3; break; case ClassWriter.IINC_INSN: mv.visitIincInsn(b[v + 1] & 0xFF, b[v + 2]); v += 3; break; // case MANA_INSN: default: mv.visitMultiANewArrayInsn(readClass(v + 1, c), b[v + 3] & 0xFF); v += 4; break; } } l = labels[codeEnd - codeStart]; if (l != null) { mv.visitLabel(l); } // visits the local variable tables if (!skipDebug && varTable != 0) { int[] typeTable = null; if (varTypeTable != 0) { k = readUnsignedShort(varTypeTable) * 3; w = varTypeTable + 2; typeTable = new int[k]; while (k > 0) { typeTable[--k] = w + 6; // signature typeTable[--k] = readUnsignedShort(w + 8); // index typeTable[--k] = readUnsignedShort(w); // start w += 10; } } k = readUnsignedShort(varTable); w = varTable + 2; for (; k > 0; --k) { int start = readUnsignedShort(w); int length = readUnsignedShort(w + 2); int index = readUnsignedShort(w + 8); String vsignature = null; if (typeTable != null) { for (int a = 0; a < typeTable.length; a += 3) { if (typeTable[a] == start && typeTable[a + 1] == index) { vsignature = readUTF8(typeTable[a + 2], c); break; } } } mv.visitLocalVariable(readUTF8(w + 4, c), readUTF8(w + 6, c), vsignature, labels[start], labels[start + length], index); w += 10; } } // visits the other attributes while (cattrs != null) { attr = cattrs.next; cattrs.next = null; mv.visitAttribute(cattrs); cattrs = attr; } // visits the max stack and max locals values mv.visitMaxs(maxStack, maxLocals); } if (mv != null) { mv.visitEnd(); } } // visits the end of the class classVisitor.visitEnd(); } /** * Reads parameter annotations and makes the given visitor visit them. * * @param v start offset in {@link #b b} of the annotations to be read. * @param desc the method descriptor. * @param buf buffer to be used to call {@link #readUTF8 readUTF8}, * {@link #readClass(int,char[]) readClass} or * {@link #readConst readConst}. * @param visible true if the annotations to be read are visible * at runtime. * @param mv the visitor that must visit the annotations. */ private void readParameterAnnotations( int v, final String desc, final char[] buf, final boolean visible, final MethodVisitor mv) { int i; int n = b[v++] & 0xFF; // workaround for a bug in javac (javac compiler generates a parameter // annotation array whose size is equal to the number of parameters in // the Java source file, while it should generate an array whose size is // equal to the number of parameters in the method descriptor - which // includes the synthetic parameters added by the compiler). This work- // around supposes that the synthetic parameters are the first ones. int synthetics = Type.getArgumentTypes(desc).length - n; AnnotationVisitor av; for (i = 0; i < synthetics; ++i) { // virtual annotation to detect synthetic parameters in MethodWriter av = mv.visitParameterAnnotation(i, "Ljava/lang/Synthetic;", false); if (av != null) { av.visitEnd(); } } for (; i < n + synthetics; ++i) { int j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { av = mv.visitParameterAnnotation(i, readUTF8(v, buf), visible); v = readAnnotationValues(v + 2, buf, true, av); } } } /** * Reads the values of an annotation and makes the given visitor visit them. * * @param v the start offset in {@link #b b} of the values to be read * (including the unsigned short that gives the number of values). * @param buf buffer to be used to call {@link #readUTF8 readUTF8}, * {@link #readClass(int,char[]) readClass} or * {@link #readConst readConst}. * @param named if the annotation values are named or not. * @param av the visitor that must visit the values. * @return the end offset of the annotation values. */ private int readAnnotationValues( int v, final char[] buf, final boolean named, final AnnotationVisitor av) { int i = readUnsignedShort(v); v += 2; if (named) { for (; i > 0; --i) { v = readAnnotationValue(v + 2, buf, readUTF8(v, buf), av); } } else { for (; i > 0; --i) { v = readAnnotationValue(v, buf, null, av); } } if (av != null) { av.visitEnd(); } return v; } /** * Reads a value of an annotation and makes the given visitor visit it. * * @param v the start offset in {@link #b b} of the value to be read (not * including the value name constant pool index). * @param buf buffer to be used to call {@link #readUTF8 readUTF8}, * {@link #readClass(int,char[]) readClass} or * {@link #readConst readConst}. * @param name the name of the value to be read. * @param av the visitor that must visit the value. * @return the end offset of the annotation value. */ private int readAnnotationValue( int v, final char[] buf, final String name, final AnnotationVisitor av) { int i; if (av == null) { switch (b[v] & 0xFF) { case 'e': // enum_const_value return v + 5; case '@': // annotation_value return readAnnotationValues(v + 3, buf, true, null); case '[': // array_value return readAnnotationValues(v + 1, buf, false, null); default: return v + 3; } } switch (b[v++] & 0xFF) { case 'I': // pointer to CONSTANT_Integer case 'J': // pointer to CONSTANT_Long case 'F': // pointer to CONSTANT_Float case 'D': // pointer to CONSTANT_Double av.visit(name, readConst(readUnsignedShort(v), buf)); v += 2; break; case 'B': // pointer to CONSTANT_Byte av.visit(name, Byte.valueOf((byte) readInt(items[readUnsignedShort(v)]))); v += 2; break; case 'Z': // pointer to CONSTANT_Boolean av.visit(name, readInt(items[readUnsignedShort(v)]) == 0 ? Boolean.FALSE : Boolean.TRUE); v += 2; break; case 'S': // pointer to CONSTANT_Short av.visit(name, Short.valueOf((short) readInt(items[readUnsignedShort(v)]))); v += 2; break; case 'C': // pointer to CONSTANT_Char av.visit(name, Character.valueOf((char) readInt(items[readUnsignedShort(v)]))); v += 2; break; case 's': // pointer to CONSTANT_Utf8 av.visit(name, readUTF8(v, buf)); v += 2; break; case 'e': // enum_const_value av.visitEnum(name, readUTF8(v, buf), readUTF8(v + 2, buf)); v += 4; break; case 'c': // class_info av.visit(name, Type.getType(readUTF8(v, buf))); v += 2; break; case '@': // annotation_value v = readAnnotationValues(v + 2, buf, true, av.visitAnnotation(name, readUTF8(v, buf))); break; case '[': // array_value int size = readUnsignedShort(v); v += 2; if (size == 0) { return readAnnotationValues(v - 2, buf, false, av.visitArray(name)); } switch (this.b[v++] & 0xFF) { case 'B': byte[] bv = new byte[size]; for (i = 0; i < size; i++) { bv[i] = (byte) readInt(items[readUnsignedShort(v)]); v += 3; } av.visit(name, bv); --v; break; case 'Z': boolean[] zv = new boolean[size]; for (i = 0; i < size; i++) { zv[i] = readInt(items[readUnsignedShort(v)]) != 0; v += 3; } av.visit(name, zv); --v; break; case 'S': short[] sv = new short[size]; for (i = 0; i < size; i++) { sv[i] = (short) readInt(items[readUnsignedShort(v)]); v += 3; } av.visit(name, sv); --v; break; case 'C': char[] cv = new char[size]; for (i = 0; i < size; i++) { cv[i] = (char) readInt(items[readUnsignedShort(v)]); v += 3; } av.visit(name, cv); --v; break; case 'I': int[] iv = new int[size]; for (i = 0; i < size; i++) { iv[i] = readInt(items[readUnsignedShort(v)]); v += 3; } av.visit(name, iv); --v; break; case 'J': long[] lv = new long[size]; for (i = 0; i < size; i++) { lv[i] = readLong(items[readUnsignedShort(v)]); v += 3; } av.visit(name, lv); --v; break; case 'F': float[] fv = new float[size]; for (i = 0; i < size; i++) { fv[i] = Float.intBitsToFloat(readInt(items[readUnsignedShort(v)])); v += 3; } av.visit(name, fv); --v; break; case 'D': double[] dv = new double[size]; for (i = 0; i < size; i++) { dv[i] = Double.longBitsToDouble(readLong(items[readUnsignedShort(v)])); v += 3; } av.visit(name, dv); --v; break; default: v = readAnnotationValues(v - 3, buf, false, av.visitArray(name)); } } return v; } private int readFrameType( final Object[] frame, final int index, int v, final char[] buf, final Label[] labels) { int type = b[v++] & 0xFF; switch (type) { case 0: frame[index] = Opcodes.TOP; break; case 1: frame[index] = Opcodes.INTEGER; break; case 2: frame[index] = Opcodes.FLOAT; break; case 3: frame[index] = Opcodes.DOUBLE; break; case 4: frame[index] = Opcodes.LONG; break; case 5: frame[index] = Opcodes.NULL; break; case 6: frame[index] = Opcodes.UNINITIALIZED_THIS; break; case 7: // Object frame[index] = readClass(v, buf); v += 2; break; default: // Uninitialized frame[index] = readLabel(readUnsignedShort(v), labels); v += 2; } return v; } /** * Returns the label corresponding to the given offset. The default * implementation of this method creates a label for the given offset if it * has not been already created. * * @param offset a bytecode offset in a method. * @param labels the already created labels, indexed by their offset. If a * label already exists for offset this method must not create a new * one. Otherwise it must store the new label in this array. * @return a non null Label, which must be equal to labels[offset]. */ protected Label readLabel(int offset, Label[] labels) { if (labels[offset] == null) { labels[offset] = new Label(); } return labels[offset]; } /** * Reads an attribute in {@link #b b}. * * @param attrs prototypes of the attributes that must be parsed during the * visit of the class. Any attribute whose type is not equal to the * type of one the prototypes is ignored (i.e. an empty * {@link Attribute} instance is returned). * @param type the type of the attribute. * @param off index of the first byte of the attribute's content in * {@link #b b}. The 6 attribute header bytes, containing the type * and the length of the attribute, are not taken into account here * (they have already been read). * @param len the length of the attribute's content. * @param buf buffer to be used to call {@link #readUTF8 readUTF8}, * {@link #readClass(int,char[]) readClass} or * {@link #readConst readConst}. * @param codeOff index of the first byte of code's attribute content in * {@link #b b}, or -1 if the attribute to be read is not a code * attribute. The 6 attribute header bytes, containing the type and * the length of the attribute, are not taken into account here. * @param labels the labels of the method's code, or null if the * attribute to be read is not a code attribute. * @return the attribute that has been read, or null to skip this * attribute. */ private Attribute readAttribute( final Attribute[] attrs, final String type, final int off, final int len, final char[] buf, final int codeOff, final Label[] labels) { for (int i = 0; i < attrs.length; ++i) { if (attrs[i].type.equals(type)) { return attrs[i].read(this, off, len, buf, codeOff, labels); } } return new Attribute(type).read(this, off, len, null, -1, null); } // ------------------------------------------------------------------------ // Utility methods: low level parsing // ------------------------------------------------------------------------ /** * Returns the start index of the constant pool item in {@link #b b}, plus * one. This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters. * * @param item the index a constant pool item. * @return the start index of the constant pool item in {@link #b b}, plus * one. */ public int getItem(final int item) { return items[item]; } /** * Reads a byte value in {@link #b b}. This method is intended for * {@link Attribute} sub classes, and is normally not needed by class * generators or adapters. * * @param index the start index of the value to be read in {@link #b b}. * @return the read value. */ public int readByte(final int index) { return b[index] & 0xFF; } /** * Reads an unsigned short value in {@link #b b}. This method is * intended for {@link Attribute} sub classes, and is normally not needed by * class generators or adapters. * * @param index the start index of the value to be read in {@link #b b}. * @return the read value. */ public int readUnsignedShort(final int index) { byte[] b = this.b; return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF); } /** * Reads a signed short value in {@link #b b}. This method is intended * for {@link Attribute} sub classes, and is normally not needed by class * generators or adapters. * * @param index the start index of the value to be read in {@link #b b}. * @return the read value. */ public short readShort(final int index) { byte[] b = this.b; return (short) (((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF)); } /** * Reads a signed int value in {@link #b b}. This method is intended for * {@link Attribute} sub classes, and is normally not needed by class * generators or adapters. * * @param index the start index of the value to be read in {@link #b b}. * @return the read value. */ public int readInt(final int index) { byte[] b = this.b; return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16) | ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF); } /** * Reads a signed long value in {@link #b b}. This method is intended * for {@link Attribute} sub classes, and is normally not needed by class * generators or adapters. * * @param index the start index of the value to be read in {@link #b b}. * @return the read value. */ public long readLong(final int index) { long l1 = readInt(index); long l0 = readInt(index + 4) & 0xFFFFFFFFL; return (l1 << 32) | l0; } /** * Reads an UTF8 string constant pool item in {@link #b b}. This method * is intended for {@link Attribute} sub classes, and is normally not needed * by class generators or adapters. * * @param index the start index of an unsigned short value in {@link #b b}, * whose value is the index of an UTF8 constant pool item. * @param buf buffer to be used to read the item. This buffer must be * sufficiently large. It is not automatically resized. * @return the String corresponding to the specified UTF8 item. */ public String readUTF8(int index, final char[] buf) { int item = readUnsignedShort(index); String s = strings[item]; if (s != null) { return s; } index = items[item]; return strings[item] = readUTF(index + 2, readUnsignedShort(index), buf); } /** * Reads UTF8 string in {@link #b b}. * * @param index start offset of the UTF8 string to be read. * @param utfLen length of the UTF8 string to be read. * @param buf buffer to be used to read the string. This buffer must be * sufficiently large. It is not automatically resized. * @return the String corresponding to the specified UTF8 string. */ private String readUTF(int index, final int utfLen, final char[] buf) { int endIndex = index + utfLen; byte[] b = this.b; int strLen = 0; int c; int st = 0; char cc = 0; while (index < endIndex) { c = b[index++]; switch (st) { case 0: c = c & 0xFF; if (c < 0x80) { // 0xxxxxxx buf[strLen++] = (char) c; } else if (c < 0xE0 && c > 0xBF) { // 110x xxxx 10xx xxxx cc = (char) (c & 0x1F); st = 1; } else { // 1110 xxxx 10xx xxxx 10xx xxxx cc = (char) (c & 0x0F); st = 2; } break; case 1: // byte 2 of 2-byte char or byte 3 of 3-byte char buf[strLen++] = (char) ((cc << 6) | (c & 0x3F)); st = 0; break; case 2: // byte 2 of 3-byte char cc = (char) ((cc << 6) | (c & 0x3F)); st = 1; break; } } return new String(buf, 0, strLen); } /** * Reads a class constant pool item in {@link #b b}. This method is * intended for {@link Attribute} sub classes, and is normally not needed by * class generators or adapters. * * @param index the start index of an unsigned short value in {@link #b b}, * whose value is the index of a class constant pool item. * @param buf buffer to be used to read the item. This buffer must be * sufficiently large. It is not automatically resized. * @return the String corresponding to the specified class item. */ public String readClass(final int index, final char[] buf) { // computes the start index of the CONSTANT_Class item in b // and reads the CONSTANT_Utf8 item designated by // the first two bytes of this CONSTANT_Class item return readUTF8(items[readUnsignedShort(index)], buf); } /** * Reads a numeric or string constant pool item in {@link #b b}. This * method is intended for {@link Attribute} sub classes, and is normally not * needed by class generators or adapters. * * @param item the index of a constant pool item. * @param buf buffer to be used to read the item. This buffer must be * sufficiently large. It is not automatically resized. * @return the {@link Integer}, {@link Float}, {@link Long}, * {@link Double}, {@link String} or {@link Type} corresponding to * the given constant pool item. */ public Object readConst(final int item, final char[] buf) { int index = items[item]; switch (b[index - 1]) { case ClassWriter.INT: return Integer.valueOf(readInt(index)); case ClassWriter.FLOAT: return new Float(Float.intBitsToFloat(readInt(index))); case ClassWriter.LONG: return Long.valueOf(readLong(index)); case ClassWriter.DOUBLE: return new Double(Double.longBitsToDouble(readLong(index))); case ClassWriter.CLASS: return Type.getObjectType(readUTF8(index, buf)); // case ClassWriter.STR: default: return readUTF8(index, buf); } } } ClassVisitor.java000066400000000000000000000207721167051330000423600ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * A visitor to visit a Java class. The methods of this interface must be called * in the following order: visit [ visitSource ] [ * visitOuterClass ] ( visitAnnotation | * visitAttribute )* (visitInnerClass | * visitField | visitMethod )* visitEnd. * * @author Eric Bruneton */ public interface ClassVisitor { /** * Visits the header of the class. * * @param version the class version. * @param access the class's access flags (see {@link Opcodes}). This * parameter also indicates if the class is deprecated. * @param name the internal name of the class (see * {@link Type#getInternalName() getInternalName}). * @param signature the signature of this class. May be null if * the class is not a generic one, and does not extend or implement * generic classes or interfaces. * @param superName the internal of name of the super class (see * {@link Type#getInternalName() getInternalName}). For interfaces, * the super class is {@link Object}. May be null, but * only for the {@link Object} class. * @param interfaces the internal names of the class's interfaces (see * {@link Type#getInternalName() getInternalName}). May be * null. */ void visit( int version, int access, String name, String signature, String superName, String[] interfaces); /** * Visits the source of the class. * * @param source the name of the source file from which the class was * compiled. May be null. * @param debug additional debug information to compute the correspondance * between source and compiled elements of the class. May be * null. */ void visitSource(String source, String debug); /** * Visits the enclosing class of the class. This method must be called only * if the class has an enclosing class. * * @param owner internal name of the enclosing class of the class. * @param name the name of the method that contains the class, or * null if the class is not enclosed in a method of its * enclosing class. * @param desc the descriptor of the method that contains the class, or * null if the class is not enclosed in a method of its * enclosing class. */ void visitOuterClass(String owner, String name, String desc); /** * Visits an annotation of the class. * * @param desc the class descriptor of the annotation class. * @param visible true if the annotation is visible at runtime. * @return a visitor to visit the annotation values, or null if * this visitor is not interested in visiting this annotation. */ AnnotationVisitor visitAnnotation(String desc, boolean visible); /** * Visits a non standard attribute of the class. * * @param attr an attribute. */ void visitAttribute(Attribute attr); /** * Visits information about an inner class. This inner class is not * necessarily a member of the class being visited. * * @param name the internal name of an inner class (see * {@link Type#getInternalName() getInternalName}). * @param outerName the internal name of the class to which the inner class * belongs (see {@link Type#getInternalName() getInternalName}). May * be null for not member classes. * @param innerName the (simple) name of the inner class inside its * enclosing class. May be null for anonymous inner * classes. * @param access the access flags of the inner class as originally declared * in the enclosing class. */ void visitInnerClass( String name, String outerName, String innerName, int access); /** * Visits a field of the class. * * @param access the field's access flags (see {@link Opcodes}). This * parameter also indicates if the field is synthetic and/or * deprecated. * @param name the field's name. * @param desc the field's descriptor (see {@link Type Type}). * @param signature the field's signature. May be null if the * field's type does not use generic types. * @param value the field's initial value. This parameter, which may be * null if the field does not have an initial value, must * be an {@link Integer}, a {@link Float}, a {@link Long}, a * {@link Double} or a {@link String} (for int, * float, long or String fields * respectively). This parameter is only used for static fields. * Its value is ignored for non static fields, which must be * initialized through bytecode instructions in constructors or * methods. * @return a visitor to visit field annotations and attributes, or * null if this class visitor is not interested in * visiting these annotations and attributes. */ FieldVisitor visitField( int access, String name, String desc, String signature, Object value); /** * Visits a method of the class. This method must return a new * {@link MethodVisitor} instance (or null) each time it is * called, i.e., it should not return a previously returned visitor. * * @param access the method's access flags (see {@link Opcodes}). This * parameter also indicates if the method is synthetic and/or * deprecated. * @param name the method's name. * @param desc the method's descriptor (see {@link Type Type}). * @param signature the method's signature. May be null if the * method parameters, return type and exceptions do not use generic * types. * @param exceptions the internal names of the method's exception classes * (see {@link Type#getInternalName() getInternalName}). May be * null. * @return an object to visit the byte code of the method, or null * if this class visitor is not interested in visiting the code of * this method. */ MethodVisitor visitMethod( int access, String name, String desc, String signature, String[] exceptions); /** * Visits the end of the class. This method, which is the last one to be * called, is used to inform the visitor that all the fields and methods of * the class have been visited. */ void visitEnd(); } ClassWriter.java000066400000000000000000001334111167051330000421700ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * A {@link ClassVisitor} that generates classes in bytecode form. More * precisely this visitor generates a byte array conforming to the Java class * file format. It can be used alone, to generate a Java class "from scratch", * or with one or more {@link ClassReader ClassReader} and adapter class visitor * to generate a modified class from one or more existing Java classes. * * @author Eric Bruneton */ public class ClassWriter implements ClassVisitor { /** * Flag to automatically compute the maximum stack size and the maximum * number of local variables of methods. If this flag is set, then the * arguments of the {@link MethodVisitor#visitMaxs visitMaxs} method of the * {@link MethodVisitor} returned by the {@link #visitMethod visitMethod} * method will be ignored, and computed automatically from the signature and * the bytecode of each method. * * @see #ClassWriter(int) */ public static final int COMPUTE_MAXS = 1; /** * Flag to automatically compute the stack map frames of methods from * scratch. If this flag is set, then the calls to the * {@link MethodVisitor#visitFrame} method are ignored, and the stack map * frames are recomputed from the methods bytecode. The arguments of the * {@link MethodVisitor#visitMaxs visitMaxs} method are also ignored and * recomputed from the bytecode. In other words, computeFrames implies * computeMaxs. * * @see #ClassWriter(int) */ public static final int COMPUTE_FRAMES = 2; /** * Pseudo access flag to distinguish between the synthetic attribute and * the synthetic access flag. */ static final int ACC_SYNTHETIC_ATTRIBUTE = 0x40000; /** * The type of instructions without any argument. */ static final int NOARG_INSN = 0; /** * The type of instructions with an signed byte argument. */ static final int SBYTE_INSN = 1; /** * The type of instructions with an signed short argument. */ static final int SHORT_INSN = 2; /** * The type of instructions with a local variable index argument. */ static final int VAR_INSN = 3; /** * The type of instructions with an implicit local variable index argument. */ static final int IMPLVAR_INSN = 4; /** * The type of instructions with a type descriptor argument. */ static final int TYPE_INSN = 5; /** * The type of field and method invocations instructions. */ static final int FIELDORMETH_INSN = 6; /** * The type of the INVOKEINTERFACE/INVOKEDYNAMIC instruction. */ static final int ITFDYNMETH_INSN = 7; /** * The type of instructions with a 2 bytes bytecode offset label. */ static final int LABEL_INSN = 8; /** * The type of instructions with a 4 bytes bytecode offset label. */ static final int LABELW_INSN = 9; /** * The type of the LDC instruction. */ static final int LDC_INSN = 10; /** * The type of the LDC_W and LDC2_W instructions. */ static final int LDCW_INSN = 11; /** * The type of the IINC instruction. */ static final int IINC_INSN = 12; /** * The type of the TABLESWITCH instruction. */ static final int TABL_INSN = 13; /** * The type of the LOOKUPSWITCH instruction. */ static final int LOOK_INSN = 14; /** * The type of the MULTIANEWARRAY instruction. */ static final int MANA_INSN = 15; /** * The type of the WIDE instruction. */ static final int WIDE_INSN = 16; /** * The instruction types of all JVM opcodes. */ static final byte[] TYPE; /** * The type of CONSTANT_Class constant pool items. */ static final int CLASS = 7; /** * The type of CONSTANT_Fieldref constant pool items. */ static final int FIELD = 9; /** * The type of CONSTANT_Methodref constant pool items. */ static final int METH = 10; /** * The type of CONSTANT_InterfaceMethodref constant pool items. */ static final int IMETH = 11; /** * The type of CONSTANT_String constant pool items. */ static final int STR = 8; /** * The type of CONSTANT_Integer constant pool items. */ static final int INT = 3; /** * The type of CONSTANT_Float constant pool items. */ static final int FLOAT = 4; /** * The type of CONSTANT_Long constant pool items. */ static final int LONG = 5; /** * The type of CONSTANT_Double constant pool items. */ static final int DOUBLE = 6; /** * The type of CONSTANT_NameAndType constant pool items. */ static final int NAME_TYPE = 12; /** * The type of CONSTANT_Utf8 constant pool items. */ static final int UTF8 = 1; /** * Normal type Item stored in the ClassWriter {@link ClassWriter#typeTable}, * instead of the constant pool, in order to avoid clashes with normal * constant pool items in the ClassWriter constant pool's hash table. */ static final int TYPE_NORMAL = 13; /** * Uninitialized type Item stored in the ClassWriter * {@link ClassWriter#typeTable}, instead of the constant pool, in order to * avoid clashes with normal constant pool items in the ClassWriter constant * pool's hash table. */ static final int TYPE_UNINIT = 14; /** * Merged type Item stored in the ClassWriter {@link ClassWriter#typeTable}, * instead of the constant pool, in order to avoid clashes with normal * constant pool items in the ClassWriter constant pool's hash table. */ static final int TYPE_MERGED = 15; /** * The class reader from which this class writer was constructed, if any. */ ClassReader cr; /** * Minor and major version numbers of the class to be generated. */ int version; /** * Index of the next item to be added in the constant pool. */ int index; /** * The constant pool of this class. */ final ByteVector pool; /** * The constant pool's hash table data. */ Item[] items; /** * The threshold of the constant pool's hash table. */ int threshold; /** * A reusable key used to look for items in the {@link #items} hash table. */ final Item key; /** * A reusable key used to look for items in the {@link #items} hash table. */ final Item key2; /** * A reusable key used to look for items in the {@link #items} hash table. */ final Item key3; /** * A type table used to temporarily store internal names that will not * necessarily be stored in the constant pool. This type table is used by * the control flow and data flow analysis algorithm used to compute stack * map frames from scratch. This array associates to each index i * the Item whose index is i. All Item objects stored in this * array are also stored in the {@link #items} hash table. These two arrays * allow to retrieve an Item from its index or, conversely, to get the index * of an Item from its value. Each Item stores an internal name in its * {@link Item#strVal1} field. */ Item[] typeTable; /** * Number of elements in the {@link #typeTable} array. */ private short typeCount; /** * The access flags of this class. */ private int access; /** * The constant pool item that contains the internal name of this class. */ private int name; /** * The internal name of this class. */ String thisName; /** * The constant pool item that contains the signature of this class. */ private int signature; /** * The constant pool item that contains the internal name of the super class * of this class. */ private int superName; /** * Number of interfaces implemented or extended by this class or interface. */ private int interfaceCount; /** * The interfaces implemented or extended by this class or interface. More * precisely, this array contains the indexes of the constant pool items * that contain the internal names of these interfaces. */ private int[] interfaces; /** * The index of the constant pool item that contains the name of the source * file from which this class was compiled. */ private int sourceFile; /** * The SourceDebug attribute of this class. */ private ByteVector sourceDebug; /** * The constant pool item that contains the name of the enclosing class of * this class. */ private int enclosingMethodOwner; /** * The constant pool item that contains the name and descriptor of the * enclosing method of this class. */ private int enclosingMethod; /** * The runtime visible annotations of this class. */ private AnnotationWriter anns; /** * The runtime invisible annotations of this class. */ private AnnotationWriter ianns; /** * The non standard attributes of this class. */ private Attribute attrs; /** * The number of entries in the InnerClasses attribute. */ private int innerClassesCount; /** * The InnerClasses attribute. */ private ByteVector innerClasses; /** * The fields of this class. These fields are stored in a linked list of * {@link FieldWriter} objects, linked to each other by their * {@link FieldWriter#next} field. This field stores the first element of * this list. */ FieldWriter firstField; /** * The fields of this class. These fields are stored in a linked list of * {@link FieldWriter} objects, linked to each other by their * {@link FieldWriter#next} field. This field stores the last element of * this list. */ FieldWriter lastField; /** * The methods of this class. These methods are stored in a linked list of * {@link MethodWriter} objects, linked to each other by their * {@link MethodWriter#next} field. This field stores the first element of * this list. */ MethodWriter firstMethod; /** * The methods of this class. These methods are stored in a linked list of * {@link MethodWriter} objects, linked to each other by their * {@link MethodWriter#next} field. This field stores the last element of * this list. */ MethodWriter lastMethod; /** * true if the maximum stack size and number of local variables * must be automatically computed. */ private final boolean computeMaxs; /** * true if the stack map frames must be recomputed from scratch. */ private final boolean computeFrames; /** * true if the stack map tables of this class are invalid. The * {@link MethodWriter#resizeInstructions} method cannot transform existing * stack map tables, and so produces potentially invalid classes when it is * executed. In this case the class is reread and rewritten with the * {@link #COMPUTE_FRAMES} option (the resizeInstructions method can resize * stack map tables when this option is used). */ boolean invalidFrames; // ------------------------------------------------------------------------ // Static initializer // ------------------------------------------------------------------------ /** * Computes the instruction types of JVM opcodes. */ static { int i; byte[] b = new byte[220]; String s = "AAAAAAAAAAAAAAAABCKLLDDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAADD" + "DDDEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAIIIIIIIIIIIIIIIIDNOAA" + "AAAAGGGGGGGHHFBFAAFFAAQPIIJJIIIIIIIIIIIIIIIIII"; for (i = 0; i < b.length; ++i) { b[i] = (byte) (s.charAt(i) - 'A'); } TYPE = b; // code to generate the above string // // // SBYTE_INSN instructions // b[Constants.NEWARRAY] = SBYTE_INSN; // b[Constants.BIPUSH] = SBYTE_INSN; // // // SHORT_INSN instructions // b[Constants.SIPUSH] = SHORT_INSN; // // // (IMPL)VAR_INSN instructions // b[Constants.RET] = VAR_INSN; // for (i = Constants.ILOAD; i <= Constants.ALOAD; ++i) { // b[i] = VAR_INSN; // } // for (i = Constants.ISTORE; i <= Constants.ASTORE; ++i) { // b[i] = VAR_INSN; // } // for (i = 26; i <= 45; ++i) { // ILOAD_0 to ALOAD_3 // b[i] = IMPLVAR_INSN; // } // for (i = 59; i <= 78; ++i) { // ISTORE_0 to ASTORE_3 // b[i] = IMPLVAR_INSN; // } // // // TYPE_INSN instructions // b[Constants.NEW] = TYPE_INSN; // b[Constants.ANEWARRAY] = TYPE_INSN; // b[Constants.CHECKCAST] = TYPE_INSN; // b[Constants.INSTANCEOF] = TYPE_INSN; // // // (Set)FIELDORMETH_INSN instructions // for (i = Constants.GETSTATIC; i <= Constants.INVOKESTATIC; ++i) { // b[i] = FIELDORMETH_INSN; // } // b[Constants.INVOKEINTERFACE] = ITFDYNMETH_INSN; // b[Constants.INVOKEDYNAMIC] = ITFDYNMETH_INSN; // // // LABEL(W)_INSN instructions // for (i = Constants.IFEQ; i <= Constants.JSR; ++i) { // b[i] = LABEL_INSN; // } // b[Constants.IFNULL] = LABEL_INSN; // b[Constants.IFNONNULL] = LABEL_INSN; // b[200] = LABELW_INSN; // GOTO_W // b[201] = LABELW_INSN; // JSR_W // // temporary opcodes used internally by ASM - see Label and // MethodWriter // for (i = 202; i < 220; ++i) { // b[i] = LABEL_INSN; // } // // // LDC(_W) instructions // b[Constants.LDC] = LDC_INSN; // b[19] = LDCW_INSN; // LDC_W // b[20] = LDCW_INSN; // LDC2_W // // // special instructions // b[Constants.IINC] = IINC_INSN; // b[Constants.TABLESWITCH] = TABL_INSN; // b[Constants.LOOKUPSWITCH] = LOOK_INSN; // b[Constants.MULTIANEWARRAY] = MANA_INSN; // b[196] = WIDE_INSN; // WIDE // // for (i = 0; i < b.length; ++i) { // System.err.print((char)('A' + b[i])); // } // System.err.println(); } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ /** * Constructs a new {@link ClassWriter} object. * * @param flags option flags that can be used to modify the default behavior * of this class. See {@link #COMPUTE_MAXS}, {@link #COMPUTE_FRAMES}. */ public ClassWriter(final int flags) { index = 1; pool = new ByteVector(); items = new Item[256]; threshold = (int) (0.75d * items.length); key = new Item(); key2 = new Item(); key3 = new Item(); this.computeMaxs = (flags & COMPUTE_MAXS) != 0; this.computeFrames = (flags & COMPUTE_FRAMES) != 0; } /** * Constructs a new {@link ClassWriter} object and enables optimizations for * "mostly add" bytecode transformations. These optimizations are the * following: * *
  • The constant pool from the original class is copied as is in * the new class, which saves time. New constant pool entries will be added * at the end if necessary, but unused constant pool entries won't be * removed.
  • Methods that are not transformed are copied as * is in the new class, directly from the original class bytecode (i.e. * without emitting visit events for all the method instructions), which * saves a lot of time. Untransformed methods are detected by the * fact that the {@link ClassReader} receives {@link MethodVisitor} objects * that come from a {@link ClassWriter} (and not from a custom * {@link ClassAdapter} or any other {@link ClassVisitor} instance).
  • *
* * @param classReader the {@link ClassReader} used to read the original * class. It will be used to copy the entire constant pool from the * original class and also to copy other fragments of original * bytecode where applicable. * @param flags option flags that can be used to modify the default behavior * of this class. These option flags do not affect methods that * are copied as is in the new class. This means that the maximum * stack size nor the stack frames will be computed for these * methods. See {@link #COMPUTE_MAXS}, {@link #COMPUTE_FRAMES}. */ public ClassWriter(final ClassReader classReader, final int flags) { this(flags); classReader.copyPool(this); this.cr = classReader; } // ------------------------------------------------------------------------ // Implementation of the ClassVisitor interface // ------------------------------------------------------------------------ public void visit( final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { this.version = version; this.access = access; this.name = newClass(name); thisName = name; if (ClassReader.SIGNATURES && signature != null) { this.signature = newUTF8(signature); } this.superName = superName == null ? 0 : newClass(superName); if (interfaces != null && interfaces.length > 0) { interfaceCount = interfaces.length; this.interfaces = new int[interfaceCount]; for (int i = 0; i < interfaceCount; ++i) { this.interfaces[i] = newClass(interfaces[i]); } } } public void visitSource(final String file, final String debug) { if (file != null) { sourceFile = newUTF8(file); } if (debug != null) { sourceDebug = new ByteVector().putUTF8(debug); } } public void visitOuterClass( final String owner, final String name, final String desc) { enclosingMethodOwner = newClass(owner); if (name != null && desc != null) { enclosingMethod = newNameType(name, desc); } } public AnnotationVisitor visitAnnotation( final String desc, final boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); // write type, and reserve space for values count bv.putShort(newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv, 2); if (visible) { aw.next = anns; anns = aw; } else { aw.next = ianns; ianns = aw; } return aw; } public void visitAttribute(final Attribute attr) { attr.next = attrs; attrs = attr; } public void visitInnerClass( final String name, final String outerName, final String innerName, final int access) { if (innerClasses == null) { innerClasses = new ByteVector(); } ++innerClassesCount; innerClasses.putShort(name == null ? 0 : newClass(name)); innerClasses.putShort(outerName == null ? 0 : newClass(outerName)); innerClasses.putShort(innerName == null ? 0 : newUTF8(innerName)); innerClasses.putShort(access); } public FieldVisitor visitField( final int access, final String name, final String desc, final String signature, final Object value) { return new FieldWriter(this, access, name, desc, signature, value); } public MethodVisitor visitMethod( final int access, final String name, final String desc, final String signature, final String[] exceptions) { return new MethodWriter(this, access, name, desc, signature, exceptions, computeMaxs, computeFrames); } public void visitEnd() { } // ------------------------------------------------------------------------ // Other public methods // ------------------------------------------------------------------------ /** * Returns the bytecode of the class that was build with this class writer. * * @return the bytecode of the class that was build with this class writer. */ public byte[] toByteArray() { if (index > Short.MAX_VALUE) { throw new RuntimeException("Class file too large!"); } // computes the real size of the bytecode of this class int size = 24 + 2 * interfaceCount; int nbFields = 0; FieldWriter fb = firstField; while (fb != null) { ++nbFields; size += fb.getSize(); fb = fb.next; } int nbMethods = 0; MethodWriter mb = firstMethod; while (mb != null) { ++nbMethods; size += mb.getSize(); mb = mb.next; } int attributeCount = 0; if (ClassReader.SIGNATURES && signature != 0) { ++attributeCount; size += 8; newUTF8("Signature"); } if (sourceFile != 0) { ++attributeCount; size += 8; newUTF8("SourceFile"); } if (sourceDebug != null) { ++attributeCount; size += sourceDebug.length + 4; newUTF8("SourceDebugExtension"); } if (enclosingMethodOwner != 0) { ++attributeCount; size += 10; newUTF8("EnclosingMethod"); } if ((access & Opcodes.ACC_DEPRECATED) != 0) { ++attributeCount; size += 6; newUTF8("Deprecated"); } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && ((version & 0xFFFF) < Opcodes.V1_5 || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0)) { ++attributeCount; size += 6; newUTF8("Synthetic"); } if (innerClasses != null) { ++attributeCount; size += 8 + innerClasses.length; newUTF8("InnerClasses"); } if (ClassReader.ANNOTATIONS && anns != null) { ++attributeCount; size += 8 + anns.getSize(); newUTF8("RuntimeVisibleAnnotations"); } if (ClassReader.ANNOTATIONS && ianns != null) { ++attributeCount; size += 8 + ianns.getSize(); newUTF8("RuntimeInvisibleAnnotations"); } if (attrs != null) { attributeCount += attrs.getCount(); size += attrs.getSize(this, null, 0, -1, -1); } size += pool.length; // allocates a byte vector of this size, in order to avoid unnecessary // arraycopy operations in the ByteVector.enlarge() method ByteVector out = new ByteVector(size); out.putInt(0xCAFEBABE).putInt(version); out.putShort(index).putByteArray(pool.data, 0, pool.length); int mask = Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC)); out.putShort(access & ~mask).putShort(name).putShort(superName); out.putShort(interfaceCount); for (int i = 0; i < interfaceCount; ++i) { out.putShort(interfaces[i]); } out.putShort(nbFields); fb = firstField; while (fb != null) { fb.put(out); fb = fb.next; } out.putShort(nbMethods); mb = firstMethod; while (mb != null) { mb.put(out); mb = mb.next; } out.putShort(attributeCount); if (ClassReader.SIGNATURES && signature != 0) { out.putShort(newUTF8("Signature")).putInt(2).putShort(signature); } if (sourceFile != 0) { out.putShort(newUTF8("SourceFile")).putInt(2).putShort(sourceFile); } if (sourceDebug != null) { int len = sourceDebug.length - 2; out.putShort(newUTF8("SourceDebugExtension")).putInt(len); out.putByteArray(sourceDebug.data, 2, len); } if (enclosingMethodOwner != 0) { out.putShort(newUTF8("EnclosingMethod")).putInt(4); out.putShort(enclosingMethodOwner).putShort(enclosingMethod); } if ((access & Opcodes.ACC_DEPRECATED) != 0) { out.putShort(newUTF8("Deprecated")).putInt(0); } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && ((version & 0xFFFF) < Opcodes.V1_5 || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0)) { out.putShort(newUTF8("Synthetic")).putInt(0); } if (innerClasses != null) { out.putShort(newUTF8("InnerClasses")); out.putInt(innerClasses.length + 2).putShort(innerClassesCount); out.putByteArray(innerClasses.data, 0, innerClasses.length); } if (ClassReader.ANNOTATIONS && anns != null) { out.putShort(newUTF8("RuntimeVisibleAnnotations")); anns.put(out); } if (ClassReader.ANNOTATIONS && ianns != null) { out.putShort(newUTF8("RuntimeInvisibleAnnotations")); ianns.put(out); } if (attrs != null) { attrs.put(this, null, 0, -1, -1, out); } if (invalidFrames) { ClassWriter cw = new ClassWriter(COMPUTE_FRAMES); new ClassReader(out.data).accept(cw, ClassReader.SKIP_FRAMES); return cw.toByteArray(); } return out.data; } // ------------------------------------------------------------------------ // Utility methods: constant pool management // ------------------------------------------------------------------------ /** * Adds a number or string constant to the constant pool of the class being * build. Does nothing if the constant pool already contains a similar item. * * @param cst the value of the constant to be added to the constant pool. * This parameter must be an {@link Integer}, a {@link Float}, a * {@link Long}, a {@link Double}, a {@link String} or a * {@link Type}. * @return a new or already existing constant item with the given value. */ Item newConstItem(final Object cst) { if (cst instanceof Integer) { int val = ((Integer) cst).intValue(); return newInteger(val); } else if (cst instanceof Byte) { int val = ((Byte) cst).intValue(); return newInteger(val); } else if (cst instanceof Character) { int val = ((Character) cst).charValue(); return newInteger(val); } else if (cst instanceof Short) { int val = ((Short) cst).intValue(); return newInteger(val); } else if (cst instanceof Boolean) { int val = ((Boolean) cst).booleanValue() ? 1 : 0; return newInteger(val); } else if (cst instanceof Float) { float val = ((Float) cst).floatValue(); return newFloat(val); } else if (cst instanceof Long) { long val = ((Long) cst).longValue(); return newLong(val); } else if (cst instanceof Double) { double val = ((Double) cst).doubleValue(); return newDouble(val); } else if (cst instanceof String) { return newString((String) cst); } else if (cst instanceof Type) { Type t = (Type) cst; return newClassItem(t.getSort() == Type.OBJECT ? t.getInternalName() : t.getDescriptor()); } else { throw new IllegalArgumentException("value " + cst); } } /** * Adds a number or string constant to the constant pool of the class being * build. Does nothing if the constant pool already contains a similar item. * This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters. * * @param cst the value of the constant to be added to the constant pool. * This parameter must be an {@link Integer}, a {@link Float}, a * {@link Long}, a {@link Double} or a {@link String}. * @return the index of a new or already existing constant item with the * given value. */ public int newConst(final Object cst) { return newConstItem(cst).index; } /** * Adds an UTF8 string to the constant pool of the class being build. Does * nothing if the constant pool already contains a similar item. This * method is intended for {@link Attribute} sub classes, and is normally not * needed by class generators or adapters. * * @param value the String value. * @return the index of a new or already existing UTF8 item. */ public int newUTF8(final String value) { key.set(UTF8, value, null, null); Item result = get(key); if (result == null) { pool.putByte(UTF8).putUTF8(value); result = new Item(index++, key); put(result); } return result.index; } /** * Adds a class reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters. * * @param value the internal name of the class. * @return a new or already existing class reference item. */ Item newClassItem(final String value) { key2.set(CLASS, value, null, null); Item result = get(key2); if (result == null) { pool.put12(CLASS, newUTF8(value)); result = new Item(index++, key2); put(result); } return result; } /** * Adds a class reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters. * * @param value the internal name of the class. * @return the index of a new or already existing class reference item. */ public int newClass(final String value) { return newClassItem(value).index; } /** * Adds a field reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * * @param owner the internal name of the field's owner class. * @param name the field's name. * @param desc the field's descriptor. * @return a new or already existing field reference item. */ Item newFieldItem(final String owner, final String name, final String desc) { key3.set(FIELD, owner, name, desc); Item result = get(key3); if (result == null) { put122(FIELD, newClass(owner), newNameType(name, desc)); result = new Item(index++, key3); put(result); } return result; } /** * Adds a field reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters. * * @param owner the internal name of the field's owner class. * @param name the field's name. * @param desc the field's descriptor. * @return the index of a new or already existing field reference item. */ public int newField(final String owner, final String name, final String desc) { return newFieldItem(owner, name, desc).index; } /** * Adds a method reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * * @param owner the internal name of the method's owner class. * @param name the method's name. * @param desc the method's descriptor. * @param itf true if owner is an interface. * @return a new or already existing method reference item. */ Item newMethodItem( final String owner, final String name, final String desc, final boolean itf) { int type = itf ? IMETH : METH; key3.set(type, owner, name, desc); Item result = get(key3); if (result == null) { put122(type, newClass(owner), newNameType(name, desc)); result = new Item(index++, key3); put(result); } return result; } /** * Adds a method reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters. * * @param owner the internal name of the method's owner class. * @param name the method's name. * @param desc the method's descriptor. * @param itf true if owner is an interface. * @return the index of a new or already existing method reference item. */ public int newMethod( final String owner, final String name, final String desc, final boolean itf) { return newMethodItem(owner, name, desc, itf).index; } /** * Adds an integer to the constant pool of the class being build. Does * nothing if the constant pool already contains a similar item. * * @param value the int value. * @return a new or already existing int item. */ Item newInteger(final int value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(INT).putInt(value); result = new Item(index++, key); put(result); } return result; } /** * Adds a float to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. * * @param value the float value. * @return a new or already existing float item. */ Item newFloat(final float value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(FLOAT).putInt(key.intVal); result = new Item(index++, key); put(result); } return result; } /** * Adds a long to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. * * @param value the long value. * @return a new or already existing long item. */ Item newLong(final long value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(LONG).putLong(value); result = new Item(index, key); index += 2; put(result); } return result; } /** * Adds a double to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. * * @param value the double value. * @return a new or already existing double item. */ Item newDouble(final double value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(DOUBLE).putLong(key.longVal); result = new Item(index, key); index += 2; put(result); } return result; } /** * Adds a string to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. * * @param value the String value. * @return a new or already existing string item. */ private Item newString(final String value) { key2.set(STR, value, null, null); Item result = get(key2); if (result == null) { pool.put12(STR, newUTF8(value)); result = new Item(index++, key2); put(result); } return result; } /** * Adds a name and type to the constant pool of the class being build. Does * nothing if the constant pool already contains a similar item. This * method is intended for {@link Attribute} sub classes, and is normally not * needed by class generators or adapters. * * @param name a name. * @param desc a type descriptor. * @return the index of a new or already existing name and type item. */ public int newNameType(final String name, final String desc) { return newNameTypeItem(name, desc).index; } /** * Adds a name and type to the constant pool of the class being build. Does * nothing if the constant pool already contains a similar item. * * @param name a name. * @param desc a type descriptor. * @return a new or already existing name and type item. */ Item newNameTypeItem(final String name, final String desc) { key2.set(NAME_TYPE, name, desc, null); Item result = get(key2); if (result == null) { put122(NAME_TYPE, newUTF8(name), newUTF8(desc)); result = new Item(index++, key2); put(result); } return result; } /** * Adds the given internal name to {@link #typeTable} and returns its index. * Does nothing if the type table already contains this internal name. * * @param type the internal name to be added to the type table. * @return the index of this internal name in the type table. */ int addType(final String type) { key.set(TYPE_NORMAL, type, null, null); Item result = get(key); if (result == null) { result = addType(key); } return result.index; } /** * Adds the given "uninitialized" type to {@link #typeTable} and returns its * index. This method is used for UNINITIALIZED types, made of an internal * name and a bytecode offset. * * @param type the internal name to be added to the type table. * @param offset the bytecode offset of the NEW instruction that created * this UNINITIALIZED type value. * @return the index of this internal name in the type table. */ int addUninitializedType(final String type, final int offset) { key.type = TYPE_UNINIT; key.intVal = offset; key.strVal1 = type; key.hashCode = 0x7FFFFFFF & (TYPE_UNINIT + type.hashCode() + offset); Item result = get(key); if (result == null) { result = addType(key); } return result.index; } /** * Adds the given Item to {@link #typeTable}. * * @param item the value to be added to the type table. * @return the added Item, which a new Item instance with the same value as * the given Item. */ private Item addType(final Item item) { ++typeCount; Item result = new Item(typeCount, key); put(result); if (typeTable == null) { typeTable = new Item[16]; } if (typeCount == typeTable.length) { Item[] newTable = new Item[2 * typeTable.length]; System.arraycopy(typeTable, 0, newTable, 0, typeTable.length); typeTable = newTable; } typeTable[typeCount] = result; return result; } /** * Returns the index of the common super type of the two given types. This * method calls {@link #getCommonSuperClass} and caches the result in the * {@link #items} hash table to speedup future calls with the same * parameters. * * @param type1 index of an internal name in {@link #typeTable}. * @param type2 index of an internal name in {@link #typeTable}. * @return the index of the common super type of the two given types. */ int getMergedType(final int type1, final int type2) { key2.type = TYPE_MERGED; key2.longVal = type1 | (((long) type2) << 32); key2.hashCode = 0x7FFFFFFF & (TYPE_MERGED + type1 + type2); Item result = get(key2); if (result == null) { String t = typeTable[type1].strVal1; String u = typeTable[type2].strVal1; key2.intVal = addType(getCommonSuperClass(t, u)); result = new Item((short) 0, key2); put(result); } return result.intVal; } /** * Returns the common super type of the two given types. The default * implementation of this method loads the two given classes and uses * the java.lang.Class methods to find the common super class. It can be * overridden to compute this common super type in other ways, in particular * without actually loading any class, or to take into account the class * that is currently being generated by this ClassWriter, which can of * course not be loaded since it is under construction. * * @param type1 the internal name of a class. * @param type2 the internal name of another class. * @return the internal name of the common super class of the two given * classes. */ protected String getCommonSuperClass(final String type1, final String type2) { Class c, d; try { c = Class.forName(type1.replace('/', '.')); d = Class.forName(type2.replace('/', '.')); } catch (Exception e) { throw new RuntimeException(e.toString()); } if (c.isAssignableFrom(d)) { return type1; } if (d.isAssignableFrom(c)) { return type2; } if (c.isInterface() || d.isInterface()) { return "java/lang/Object"; } else { do { c = c.getSuperclass(); } while (!c.isAssignableFrom(d)); return c.getName().replace('.', '/'); } } /** * Returns the constant pool's hash table item which is equal to the given * item. * * @param key a constant pool item. * @return the constant pool's hash table item which is equal to the given * item, or null if there is no such item. */ private Item get(final Item key) { Item i = items[key.hashCode % items.length]; while (i != null && (i.type != key.type || !key.isEqualTo(i))) { i = i.next; } return i; } /** * Puts the given item in the constant pool's hash table. The hash table * must not already contains this item. * * @param i the item to be added to the constant pool's hash table. */ private void put(final Item i) { if (index + typeCount > threshold) { int ll = items.length; int nl = ll * 2 + 1; Item[] newItems = new Item[nl]; for (int l = ll - 1; l >= 0; --l) { Item j = items[l]; while (j != null) { int index = j.hashCode % newItems.length; Item k = j.next; j.next = newItems[index]; newItems[index] = j; j = k; } } items = newItems; threshold = (int) (nl * 0.75); } int index = i.hashCode % items.length; i.next = items[index]; items[index] = i; } /** * Puts one byte and two shorts into the constant pool. * * @param b a byte. * @param s1 a short. * @param s2 another short. */ private void put122(final int b, final int s1, final int s2) { pool.put12(b, s1).putShort(s2); } } Edge.java000066400000000000000000000061651167051330000405770ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * An edge in the control flow graph of a method body. See {@link Label Label}. * * @author Eric Bruneton */ class Edge { /** * Denotes a normal control flow graph edge. */ static final int NORMAL = 0; /** * Denotes a control flow graph edge corresponding to an exception handler. * More precisely any {@link Edge} whose {@link #info} is strictly positive * corresponds to an exception handler. The actual value of {@link #info} is * the index, in the {@link ClassWriter} type table, of the exception that * is catched. */ static final int EXCEPTION = 0x7FFFFFFF; /** * Information about this control flow graph edge. If * {@link ClassWriter#COMPUTE_MAXS} is used this field is the (relative) * stack size in the basic block from which this edge originates. This size * is equal to the stack size at the "jump" instruction to which this edge * corresponds, relatively to the stack size at the beginning of the * originating basic block. If {@link ClassWriter#COMPUTE_FRAMES} is used, * this field is the kind of this control flow graph edge (i.e. NORMAL or * EXCEPTION). */ int info; /** * The successor block of the basic block from which this edge originates. */ Label successor; /** * The next edge in the list of successors of the originating basic block. * See {@link Label#successors successors}. */ Edge next; } FieldVisitor.java000066400000000000000000000053411167051330000423310ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * A visitor to visit a Java field. The methods of this interface must be called * in the following order: ( visitAnnotation | * visitAttribute )* visitEnd. * * @author Eric Bruneton */ public interface FieldVisitor { /** * Visits an annotation of the field. * * @param desc the class descriptor of the annotation class. * @param visible true if the annotation is visible at runtime. * @return a visitor to visit the annotation values, or null if * this visitor is not interested in visiting this annotation. */ AnnotationVisitor visitAnnotation(String desc, boolean visible); /** * Visits a non standard attribute of the field. * * @param attr an attribute. */ void visitAttribute(Attribute attr); /** * Visits the end of the field. This method, which is the last one to be * called, is used to inform the visitor that all the annotations and * attributes of the field have been visited. */ void visitEnd(); } FieldWriter.java000066400000000000000000000216601167051330000421500ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * An {@link FieldVisitor} that generates Java fields in bytecode form. * * @author Eric Bruneton */ final class FieldWriter implements FieldVisitor { /** * Next field writer (see {@link ClassWriter#firstField firstField}). */ FieldWriter next; /** * The class writer to which this field must be added. */ private final ClassWriter cw; /** * Access flags of this field. */ private final int access; /** * The index of the constant pool item that contains the name of this * method. */ private final int name; /** * The index of the constant pool item that contains the descriptor of this * field. */ private final int desc; /** * The index of the constant pool item that contains the signature of this * field. */ private int signature; /** * The index of the constant pool item that contains the constant value of * this field. */ private int value; /** * The runtime visible annotations of this field. May be null. */ private AnnotationWriter anns; /** * The runtime invisible annotations of this field. May be null. */ private AnnotationWriter ianns; /** * The non standard attributes of this field. May be null. */ private Attribute attrs; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ /** * Constructs a new {@link FieldWriter}. * * @param cw the class writer to which this field must be added. * @param access the field's access flags (see {@link Opcodes}). * @param name the field's name. * @param desc the field's descriptor (see {@link Type}). * @param signature the field's signature. May be null. * @param value the field's constant value. May be null. */ FieldWriter( final ClassWriter cw, final int access, final String name, final String desc, final String signature, final Object value) { if (cw.firstField == null) { cw.firstField = this; } else { cw.lastField.next = this; } cw.lastField = this; this.cw = cw; this.access = access; this.name = cw.newUTF8(name); this.desc = cw.newUTF8(desc); if (ClassReader.SIGNATURES && signature != null) { this.signature = cw.newUTF8(signature); } if (value != null) { this.value = cw.newConstItem(value).index; } } // ------------------------------------------------------------------------ // Implementation of the FieldVisitor interface // ------------------------------------------------------------------------ public AnnotationVisitor visitAnnotation( final String desc, final boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, 2); if (visible) { aw.next = anns; anns = aw; } else { aw.next = ianns; ianns = aw; } return aw; } public void visitAttribute(final Attribute attr) { attr.next = attrs; attrs = attr; } public void visitEnd() { } // ------------------------------------------------------------------------ // Utility methods // ------------------------------------------------------------------------ /** * Returns the size of this field. * * @return the size of this field. */ int getSize() { int size = 8; if (value != 0) { cw.newUTF8("ConstantValue"); size += 8; } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0)) { cw.newUTF8("Synthetic"); size += 6; } if ((access & Opcodes.ACC_DEPRECATED) != 0) { cw.newUTF8("Deprecated"); size += 6; } if (ClassReader.SIGNATURES && signature != 0) { cw.newUTF8("Signature"); size += 8; } if (ClassReader.ANNOTATIONS && anns != null) { cw.newUTF8("RuntimeVisibleAnnotations"); size += 8 + anns.getSize(); } if (ClassReader.ANNOTATIONS && ianns != null) { cw.newUTF8("RuntimeInvisibleAnnotations"); size += 8 + ianns.getSize(); } if (attrs != null) { size += attrs.getSize(cw, null, 0, -1, -1); } return size; } /** * Puts the content of this field into the given byte vector. * * @param out where the content of this field must be put. */ void put(final ByteVector out) { int mask = Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC)); out.putShort(access & ~mask).putShort(name).putShort(desc); int attributeCount = 0; if (value != 0) { ++attributeCount; } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0)) { ++attributeCount; } if ((access & Opcodes.ACC_DEPRECATED) != 0) { ++attributeCount; } if (ClassReader.SIGNATURES && signature != 0) { ++attributeCount; } if (ClassReader.ANNOTATIONS && anns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && ianns != null) { ++attributeCount; } if (attrs != null) { attributeCount += attrs.getCount(); } out.putShort(attributeCount); if (value != 0) { out.putShort(cw.newUTF8("ConstantValue")); out.putInt(2).putShort(value); } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0)) { out.putShort(cw.newUTF8("Synthetic")).putInt(0); } if ((access & Opcodes.ACC_DEPRECATED) != 0) { out.putShort(cw.newUTF8("Deprecated")).putInt(0); } if (ClassReader.SIGNATURES && signature != 0) { out.putShort(cw.newUTF8("Signature")); out.putInt(2).putShort(signature); } if (ClassReader.ANNOTATIONS && anns != null) { out.putShort(cw.newUTF8("RuntimeVisibleAnnotations")); anns.put(out); } if (ClassReader.ANNOTATIONS && ianns != null) { out.putShort(cw.newUTF8("RuntimeInvisibleAnnotations")); ianns.put(out); } if (attrs != null) { attrs.put(cw, null, 0, -1, -1, out); } } } Frame.java000066400000000000000000001375521167051330000407720ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * Information about the input and output stack map frames of a basic block. * * @author Eric Bruneton */ final class Frame { /* * Frames are computed in a two steps process: during the visit of each * instruction, the state of the frame at the end of current basic block is * updated by simulating the action of the instruction on the previous state * of this so called "output frame". In visitMaxs, a fix point algorithm is * used to compute the "input frame" of each basic block, i.e. the stack map * frame at the beginning of the basic block, starting from the input frame * of the first basic block (which is computed from the method descriptor), * and by using the previously computed output frames to compute the input * state of the other blocks. * * All output and input frames are stored as arrays of integers. Reference * and array types are represented by an index into a type table (which is * not the same as the constant pool of the class, in order to avoid adding * unnecessary constants in the pool - not all computed frames will end up * being stored in the stack map table). This allows very fast type * comparisons. * * Output stack map frames are computed relatively to the input frame of the * basic block, which is not yet known when output frames are computed. It * is therefore necessary to be able to represent abstract types such as * "the type at position x in the input frame locals" or "the type at * position x from the top of the input frame stack" or even "the type at * position x in the input frame, with y more (or less) array dimensions". * This explains the rather complicated type format used in output frames. * * This format is the following: DIM KIND VALUE (4, 4 and 24 bits). DIM is a * signed number of array dimensions (from -8 to 7). KIND is either BASE, * LOCAL or STACK. BASE is used for types that are not relative to the input * frame. LOCAL is used for types that are relative to the input local * variable types. STACK is used for types that are relative to the input * stack types. VALUE depends on KIND. For LOCAL types, it is an index in * the input local variable types. For STACK types, it is a position * relatively to the top of input frame stack. For BASE types, it is either * one of the constants defined in FrameVisitor, or for OBJECT and * UNINITIALIZED types, a tag and an index in the type table. * * Output frames can contain types of any kind and with a positive or * negative dimension (and even unassigned types, represented by 0 - which * does not correspond to any valid type value). Input frames can only * contain BASE types of positive or null dimension. In all cases the type * table contains only internal type names (array type descriptors are * forbidden - dimensions must be represented through the DIM field). * * The LONG and DOUBLE types are always represented by using two slots (LONG + * TOP or DOUBLE + TOP), for local variable types as well as in the operand * stack. This is necessary to be able to simulate DUPx_y instructions, * whose effect would be dependent on the actual type values if types were * always represented by a single slot in the stack (and this is not * possible, since actual type values are not always known - cf LOCAL and * STACK type kinds). */ /** * Mask to get the dimension of a frame type. This dimension is a signed * integer between -8 and 7. */ static final int DIM = 0xF0000000; /** * Constant to be added to a type to get a type with one more dimension. */ static final int ARRAY_OF = 0x10000000; /** * Constant to be added to a type to get a type with one less dimension. */ static final int ELEMENT_OF = 0xF0000000; /** * Mask to get the kind of a frame type. * * @see #BASE * @see #LOCAL * @see #STACK */ static final int KIND = 0xF000000; /** * Flag used for LOCAL and STACK types. Indicates that if this type happens * to be a long or double type (during the computations of input frames), * then it must be set to TOP because the second word of this value has * been reused to store other data in the basic block. Hence the first word * no longer stores a valid long or double value. */ static final int TOP_IF_LONG_OR_DOUBLE = 0x800000; /** * Mask to get the value of a frame type. */ static final int VALUE = 0x7FFFFF; /** * Mask to get the kind of base types. */ static final int BASE_KIND = 0xFF00000; /** * Mask to get the value of base types. */ static final int BASE_VALUE = 0xFFFFF; /** * Kind of the types that are not relative to an input stack map frame. */ static final int BASE = 0x1000000; /** * Base kind of the base reference types. The BASE_VALUE of such types is an * index into the type table. */ static final int OBJECT = BASE | 0x700000; /** * Base kind of the uninitialized base types. The BASE_VALUE of such types * in an index into the type table (the Item at that index contains both an * instruction offset and an internal class name). */ static final int UNINITIALIZED = BASE | 0x800000; /** * Kind of the types that are relative to the local variable types of an * input stack map frame. The value of such types is a local variable index. */ private static final int LOCAL = 0x2000000; /** * Kind of the the types that are relative to the stack of an input stack * map frame. The value of such types is a position relatively to the top of * this stack. */ private static final int STACK = 0x3000000; /** * The TOP type. This is a BASE type. */ static final int TOP = BASE | 0; /** * The BOOLEAN type. This is a BASE type mainly used for array types. */ static final int BOOLEAN = BASE | 9; /** * The BYTE type. This is a BASE type mainly used for array types. */ static final int BYTE = BASE | 10; /** * The CHAR type. This is a BASE type mainly used for array types. */ static final int CHAR = BASE | 11; /** * The SHORT type. This is a BASE type mainly used for array types. */ static final int SHORT = BASE | 12; /** * The INTEGER type. This is a BASE type. */ static final int INTEGER = BASE | 1; /** * The FLOAT type. This is a BASE type. */ static final int FLOAT = BASE | 2; /** * The DOUBLE type. This is a BASE type. */ static final int DOUBLE = BASE | 3; /** * The LONG type. This is a BASE type. */ static final int LONG = BASE | 4; /** * The NULL type. This is a BASE type. */ static final int NULL = BASE | 5; /** * The UNINITIALIZED_THIS type. This is a BASE type. */ static final int UNINITIALIZED_THIS = BASE | 6; /** * The stack size variation corresponding to each JVM instruction. This * stack variation is equal to the size of the values produced by an * instruction, minus the size of the values consumed by this instruction. */ static final int[] SIZE; /** * Computes the stack size variation corresponding to each JVM instruction. */ static { int i; int[] b = new int[202]; String s = "EFFFFFFFFGGFFFGGFFFEEFGFGFEEEEEEEEEEEEEEEEEEEEDEDEDDDDD" + "CDCDEEEEEEEEEEEEEEEEEEEEBABABBBBDCFFFGGGEDCDCDCDCDCDCDCDCD" + "CDCEEEEDDDDDDDCDCDCEFEFDDEEFFDEDEEEBDDBBDDDDDDCCCCCCCCEFED" + "DDCDCDEEEEEEEEEEFEEEEEEDDEEDDEE"; for (i = 0; i < b.length; ++i) { b[i] = s.charAt(i) - 'E'; } SIZE = b; // code to generate the above string // // int NA = 0; // not applicable (unused opcode or variable size opcode) // // b = new int[] { // 0, //NOP, // visitInsn // 1, //ACONST_NULL, // - // 1, //ICONST_M1, // - // 1, //ICONST_0, // - // 1, //ICONST_1, // - // 1, //ICONST_2, // - // 1, //ICONST_3, // - // 1, //ICONST_4, // - // 1, //ICONST_5, // - // 2, //LCONST_0, // - // 2, //LCONST_1, // - // 1, //FCONST_0, // - // 1, //FCONST_1, // - // 1, //FCONST_2, // - // 2, //DCONST_0, // - // 2, //DCONST_1, // - // 1, //BIPUSH, // visitIntInsn // 1, //SIPUSH, // - // 1, //LDC, // visitLdcInsn // NA, //LDC_W, // - // NA, //LDC2_W, // - // 1, //ILOAD, // visitVarInsn // 2, //LLOAD, // - // 1, //FLOAD, // - // 2, //DLOAD, // - // 1, //ALOAD, // - // NA, //ILOAD_0, // - // NA, //ILOAD_1, // - // NA, //ILOAD_2, // - // NA, //ILOAD_3, // - // NA, //LLOAD_0, // - // NA, //LLOAD_1, // - // NA, //LLOAD_2, // - // NA, //LLOAD_3, // - // NA, //FLOAD_0, // - // NA, //FLOAD_1, // - // NA, //FLOAD_2, // - // NA, //FLOAD_3, // - // NA, //DLOAD_0, // - // NA, //DLOAD_1, // - // NA, //DLOAD_2, // - // NA, //DLOAD_3, // - // NA, //ALOAD_0, // - // NA, //ALOAD_1, // - // NA, //ALOAD_2, // - // NA, //ALOAD_3, // - // -1, //IALOAD, // visitInsn // 0, //LALOAD, // - // -1, //FALOAD, // - // 0, //DALOAD, // - // -1, //AALOAD, // - // -1, //BALOAD, // - // -1, //CALOAD, // - // -1, //SALOAD, // - // -1, //ISTORE, // visitVarInsn // -2, //LSTORE, // - // -1, //FSTORE, // - // -2, //DSTORE, // - // -1, //ASTORE, // - // NA, //ISTORE_0, // - // NA, //ISTORE_1, // - // NA, //ISTORE_2, // - // NA, //ISTORE_3, // - // NA, //LSTORE_0, // - // NA, //LSTORE_1, // - // NA, //LSTORE_2, // - // NA, //LSTORE_3, // - // NA, //FSTORE_0, // - // NA, //FSTORE_1, // - // NA, //FSTORE_2, // - // NA, //FSTORE_3, // - // NA, //DSTORE_0, // - // NA, //DSTORE_1, // - // NA, //DSTORE_2, // - // NA, //DSTORE_3, // - // NA, //ASTORE_0, // - // NA, //ASTORE_1, // - // NA, //ASTORE_2, // - // NA, //ASTORE_3, // - // -3, //IASTORE, // visitInsn // -4, //LASTORE, // - // -3, //FASTORE, // - // -4, //DASTORE, // - // -3, //AASTORE, // - // -3, //BASTORE, // - // -3, //CASTORE, // - // -3, //SASTORE, // - // -1, //POP, // - // -2, //POP2, // - // 1, //DUP, // - // 1, //DUP_X1, // - // 1, //DUP_X2, // - // 2, //DUP2, // - // 2, //DUP2_X1, // - // 2, //DUP2_X2, // - // 0, //SWAP, // - // -1, //IADD, // - // -2, //LADD, // - // -1, //FADD, // - // -2, //DADD, // - // -1, //ISUB, // - // -2, //LSUB, // - // -1, //FSUB, // - // -2, //DSUB, // - // -1, //IMUL, // - // -2, //LMUL, // - // -1, //FMUL, // - // -2, //DMUL, // - // -1, //IDIV, // - // -2, //LDIV, // - // -1, //FDIV, // - // -2, //DDIV, // - // -1, //IREM, // - // -2, //LREM, // - // -1, //FREM, // - // -2, //DREM, // - // 0, //INEG, // - // 0, //LNEG, // - // 0, //FNEG, // - // 0, //DNEG, // - // -1, //ISHL, // - // -1, //LSHL, // - // -1, //ISHR, // - // -1, //LSHR, // - // -1, //IUSHR, // - // -1, //LUSHR, // - // -1, //IAND, // - // -2, //LAND, // - // -1, //IOR, // - // -2, //LOR, // - // -1, //IXOR, // - // -2, //LXOR, // - // 0, //IINC, // visitIincInsn // 1, //I2L, // visitInsn // 0, //I2F, // - // 1, //I2D, // - // -1, //L2I, // - // -1, //L2F, // - // 0, //L2D, // - // 0, //F2I, // - // 1, //F2L, // - // 1, //F2D, // - // -1, //D2I, // - // 0, //D2L, // - // -1, //D2F, // - // 0, //I2B, // - // 0, //I2C, // - // 0, //I2S, // - // -3, //LCMP, // - // -1, //FCMPL, // - // -1, //FCMPG, // - // -3, //DCMPL, // - // -3, //DCMPG, // - // -1, //IFEQ, // visitJumpInsn // -1, //IFNE, // - // -1, //IFLT, // - // -1, //IFGE, // - // -1, //IFGT, // - // -1, //IFLE, // - // -2, //IF_ICMPEQ, // - // -2, //IF_ICMPNE, // - // -2, //IF_ICMPLT, // - // -2, //IF_ICMPGE, // - // -2, //IF_ICMPGT, // - // -2, //IF_ICMPLE, // - // -2, //IF_ACMPEQ, // - // -2, //IF_ACMPNE, // - // 0, //GOTO, // - // 1, //JSR, // - // 0, //RET, // visitVarInsn // -1, //TABLESWITCH, // visiTableSwitchInsn // -1, //LOOKUPSWITCH, // visitLookupSwitch // -1, //IRETURN, // visitInsn // -2, //LRETURN, // - // -1, //FRETURN, // - // -2, //DRETURN, // - // -1, //ARETURN, // - // 0, //RETURN, // - // NA, //GETSTATIC, // visitFieldInsn // NA, //PUTSTATIC, // - // NA, //GETFIELD, // - // NA, //PUTFIELD, // - // NA, //INVOKEVIRTUAL, // visitMethodInsn // NA, //INVOKESPECIAL, // - // NA, //INVOKESTATIC, // - // NA, //INVOKEINTERFACE, // - // NA, //INVOKEDYNAMIC, // - // 1, //NEW, // visitTypeInsn // 0, //NEWARRAY, // visitIntInsn // 0, //ANEWARRAY, // visitTypeInsn // 0, //ARRAYLENGTH, // visitInsn // NA, //ATHROW, // - // 0, //CHECKCAST, // visitTypeInsn // 0, //INSTANCEOF, // - // -1, //MONITORENTER, // visitInsn // -1, //MONITOREXIT, // - // NA, //WIDE, // NOT VISITED // NA, //MULTIANEWARRAY, // visitMultiANewArrayInsn // -1, //IFNULL, // visitJumpInsn // -1, //IFNONNULL, // - // NA, //GOTO_W, // - // NA, //JSR_W, // - // }; // for (i = 0; i < b.length; ++i) { // System.err.print((char)('E' + b[i])); // } // System.err.println(); } /** * The label (i.e. basic block) to which these input and output stack map * frames correspond. */ Label owner; /** * The input stack map frame locals. */ int[] inputLocals; /** * The input stack map frame stack. */ int[] inputStack; /** * The output stack map frame locals. */ private int[] outputLocals; /** * The output stack map frame stack. */ private int[] outputStack; /** * Relative size of the output stack. The exact semantics of this field * depends on the algorithm that is used. * * When only the maximum stack size is computed, this field is the size of * the output stack relatively to the top of the input stack. * * When the stack map frames are completely computed, this field is the * actual number of types in {@link #outputStack}. */ private int outputStackTop; /** * Number of types that are initialized in the basic block. * * @see #initializations */ private int initializationCount; /** * The types that are initialized in the basic block. A constructor * invocation on an UNINITIALIZED or UNINITIALIZED_THIS type must replace * every occurence of this type in the local variables and in the * operand stack. This cannot be done during the first phase of the * algorithm since, during this phase, the local variables and the operand * stack are not completely computed. It is therefore necessary to store the * types on which constructors are invoked in the basic block, in order to * do this replacement during the second phase of the algorithm, where the * frames are fully computed. Note that this array can contain types that * are relative to input locals or to the input stack (see below for the * description of the algorithm). */ private int[] initializations; /** * Returns the output frame local variable type at the given index. * * @param local the index of the local that must be returned. * @return the output frame local variable type at the given index. */ private int get(final int local) { if (outputLocals == null || local >= outputLocals.length) { // this local has never been assigned in this basic block, // so it is still equal to its value in the input frame return LOCAL | local; } else { int type = outputLocals[local]; if (type == 0) { // this local has never been assigned in this basic block, // so it is still equal to its value in the input frame type = outputLocals[local] = LOCAL | local; } return type; } } /** * Sets the output frame local variable type at the given index. * * @param local the index of the local that must be set. * @param type the value of the local that must be set. */ private void set(final int local, final int type) { // creates and/or resizes the output local variables array if necessary if (outputLocals == null) { outputLocals = new int[10]; } int n = outputLocals.length; if (local >= n) { int[] t = new int[Math.max(local + 1, 2 * n)]; System.arraycopy(outputLocals, 0, t, 0, n); outputLocals = t; } // sets the local variable outputLocals[local] = type; } /** * Pushes a new type onto the output frame stack. * * @param type the type that must be pushed. */ private void push(final int type) { // creates and/or resizes the output stack array if necessary if (outputStack == null) { outputStack = new int[10]; } int n = outputStack.length; if (outputStackTop >= n) { int[] t = new int[Math.max(outputStackTop + 1, 2 * n)]; System.arraycopy(outputStack, 0, t, 0, n); outputStack = t; } // pushes the type on the output stack outputStack[outputStackTop++] = type; // updates the maximun height reached by the output stack, if needed int top = owner.inputStackTop + outputStackTop; if (top > owner.outputStackMax) { owner.outputStackMax = top; } } /** * Pushes a new type onto the output frame stack. * * @param cw the ClassWriter to which this label belongs. * @param desc the descriptor of the type to be pushed. Can also be a method * descriptor (in this case this method pushes its return type onto * the output frame stack). */ private void push(final ClassWriter cw, final String desc) { int type = type(cw, desc); if (type != 0) { push(type); if (type == LONG || type == DOUBLE) { push(TOP); } } } /** * Returns the int encoding of the given type. * * @param cw the ClassWriter to which this label belongs. * @param desc a type descriptor. * @return the int encoding of the given type. */ private static int type(final ClassWriter cw, final String desc) { String t; int index = desc.charAt(0) == '(' ? desc.indexOf(')') + 1 : 0; switch (desc.charAt(index)) { case 'V': return 0; case 'Z': case 'C': case 'B': case 'S': case 'I': return INTEGER; case 'F': return FLOAT; case 'J': return LONG; case 'D': return DOUBLE; case 'L': // stores the internal name, not the descriptor! t = desc.substring(index + 1, desc.length() - 1); return OBJECT | cw.addType(t); // case '[': default: // extracts the dimensions and the element type int data; int dims = index + 1; while (desc.charAt(dims) == '[') { ++dims; } switch (desc.charAt(dims)) { case 'Z': data = BOOLEAN; break; case 'C': data = CHAR; break; case 'B': data = BYTE; break; case 'S': data = SHORT; break; case 'I': data = INTEGER; break; case 'F': data = FLOAT; break; case 'J': data = LONG; break; case 'D': data = DOUBLE; break; // case 'L': default: // stores the internal name, not the descriptor t = desc.substring(dims + 1, desc.length() - 1); data = OBJECT | cw.addType(t); } return (dims - index) << 28 | data; } } /** * Pops a type from the output frame stack and returns its value. * * @return the type that has been popped from the output frame stack. */ private int pop() { if (outputStackTop > 0) { return outputStack[--outputStackTop]; } else { // if the output frame stack is empty, pops from the input stack return STACK | -(--owner.inputStackTop); } } /** * Pops the given number of types from the output frame stack. * * @param elements the number of types that must be popped. */ private void pop(final int elements) { if (outputStackTop >= elements) { outputStackTop -= elements; } else { // if the number of elements to be popped is greater than the number // of elements in the output stack, clear it, and pops the remaining // elements from the input stack. owner.inputStackTop -= elements - outputStackTop; outputStackTop = 0; } } /** * Pops a type from the output frame stack. * * @param desc the descriptor of the type to be popped. Can also be a method * descriptor (in this case this method pops the types corresponding * to the method arguments). */ private void pop(final String desc) { char c = desc.charAt(0); if (c == '(') { pop((Type.getArgumentsAndReturnSizes(desc) >> 2) - 1); } else if (c == 'J' || c == 'D') { pop(2); } else { pop(1); } } /** * Adds a new type to the list of types on which a constructor is invoked in * the basic block. * * @param var a type on a which a constructor is invoked. */ private void init(final int var) { // creates and/or resizes the initializations array if necessary if (initializations == null) { initializations = new int[2]; } int n = initializations.length; if (initializationCount >= n) { int[] t = new int[Math.max(initializationCount + 1, 2 * n)]; System.arraycopy(initializations, 0, t, 0, n); initializations = t; } // stores the type to be initialized initializations[initializationCount++] = var; } /** * Replaces the given type with the appropriate type if it is one of the * types on which a constructor is invoked in the basic block. * * @param cw the ClassWriter to which this label belongs. * @param t a type * @return t or, if t is one of the types on which a constructor is invoked * in the basic block, the type corresponding to this constructor. */ private int init(final ClassWriter cw, final int t) { int s; if (t == UNINITIALIZED_THIS) { s = OBJECT | cw.addType(cw.thisName); } else if ((t & (DIM | BASE_KIND)) == UNINITIALIZED) { String type = cw.typeTable[t & BASE_VALUE].strVal1; s = OBJECT | cw.addType(type); } else { return t; } for (int j = 0; j < initializationCount; ++j) { int u = initializations[j]; int dim = u & DIM; int kind = u & KIND; if (kind == LOCAL) { u = dim + inputLocals[u & VALUE]; } else if (kind == STACK) { u = dim + inputStack[inputStack.length - (u & VALUE)]; } if (t == u) { return s; } } return t; } /** * Initializes the input frame of the first basic block from the method * descriptor. * * @param cw the ClassWriter to which this label belongs. * @param access the access flags of the method to which this label belongs. * @param args the formal parameter types of this method. * @param maxLocals the maximum number of local variables of this method. */ void initInputFrame( final ClassWriter cw, final int access, final Type[] args, final int maxLocals) { inputLocals = new int[maxLocals]; inputStack = new int[0]; int i = 0; if ((access & Opcodes.ACC_STATIC) == 0) { if ((access & MethodWriter.ACC_CONSTRUCTOR) == 0) { inputLocals[i++] = OBJECT | cw.addType(cw.thisName); } else { inputLocals[i++] = UNINITIALIZED_THIS; } } for (int j = 0; j < args.length; ++j) { int t = type(cw, args[j].getDescriptor()); inputLocals[i++] = t; if (t == LONG || t == DOUBLE) { inputLocals[i++] = TOP; } } while (i < maxLocals) { inputLocals[i++] = TOP; } } /** * Simulates the action of the given instruction on the output stack frame. * * @param opcode the opcode of the instruction. * @param arg the operand of the instruction, if any. * @param cw the class writer to which this label belongs. * @param item the operand of the instructions, if any. */ void execute( final int opcode, final int arg, final ClassWriter cw, final Item item) { int t1, t2, t3, t4; switch (opcode) { case Opcodes.NOP: case Opcodes.INEG: case Opcodes.LNEG: case Opcodes.FNEG: case Opcodes.DNEG: case Opcodes.I2B: case Opcodes.I2C: case Opcodes.I2S: case Opcodes.GOTO: case Opcodes.RETURN: break; case Opcodes.ACONST_NULL: push(NULL); break; case Opcodes.ICONST_M1: case Opcodes.ICONST_0: case Opcodes.ICONST_1: case Opcodes.ICONST_2: case Opcodes.ICONST_3: case Opcodes.ICONST_4: case Opcodes.ICONST_5: case Opcodes.BIPUSH: case Opcodes.SIPUSH: case Opcodes.ILOAD: push(INTEGER); break; case Opcodes.LCONST_0: case Opcodes.LCONST_1: case Opcodes.LLOAD: push(LONG); push(TOP); break; case Opcodes.FCONST_0: case Opcodes.FCONST_1: case Opcodes.FCONST_2: case Opcodes.FLOAD: push(FLOAT); break; case Opcodes.DCONST_0: case Opcodes.DCONST_1: case Opcodes.DLOAD: push(DOUBLE); push(TOP); break; case Opcodes.LDC: switch (item.type) { case ClassWriter.INT: push(INTEGER); break; case ClassWriter.LONG: push(LONG); push(TOP); break; case ClassWriter.FLOAT: push(FLOAT); break; case ClassWriter.DOUBLE: push(DOUBLE); push(TOP); break; case ClassWriter.CLASS: push(OBJECT | cw.addType("java/lang/Class")); break; // case ClassWriter.STR: default: push(OBJECT | cw.addType("java/lang/String")); } break; case Opcodes.ALOAD: push(get(arg)); break; case Opcodes.IALOAD: case Opcodes.BALOAD: case Opcodes.CALOAD: case Opcodes.SALOAD: pop(2); push(INTEGER); break; case Opcodes.LALOAD: case Opcodes.D2L: pop(2); push(LONG); push(TOP); break; case Opcodes.FALOAD: pop(2); push(FLOAT); break; case Opcodes.DALOAD: case Opcodes.L2D: pop(2); push(DOUBLE); push(TOP); break; case Opcodes.AALOAD: pop(1); t1 = pop(); push(ELEMENT_OF + t1); break; case Opcodes.ISTORE: case Opcodes.FSTORE: case Opcodes.ASTORE: t1 = pop(); set(arg, t1); if (arg > 0) { t2 = get(arg - 1); // if t2 is of kind STACK or LOCAL we cannot know its size! if (t2 == LONG || t2 == DOUBLE) { set(arg - 1, TOP); } else if ((t2 & KIND) != BASE) { set(arg - 1, t2 | TOP_IF_LONG_OR_DOUBLE); } } break; case Opcodes.LSTORE: case Opcodes.DSTORE: pop(1); t1 = pop(); set(arg, t1); set(arg + 1, TOP); if (arg > 0) { t2 = get(arg - 1); // if t2 is of kind STACK or LOCAL we cannot know its size! if (t2 == LONG || t2 == DOUBLE) { set(arg - 1, TOP); } else if ((t2 & KIND) != BASE) { set(arg - 1, t2 | TOP_IF_LONG_OR_DOUBLE); } } break; case Opcodes.IASTORE: case Opcodes.BASTORE: case Opcodes.CASTORE: case Opcodes.SASTORE: case Opcodes.FASTORE: case Opcodes.AASTORE: pop(3); break; case Opcodes.LASTORE: case Opcodes.DASTORE: pop(4); break; case Opcodes.POP: case Opcodes.IFEQ: case Opcodes.IFNE: case Opcodes.IFLT: case Opcodes.IFGE: case Opcodes.IFGT: case Opcodes.IFLE: case Opcodes.IRETURN: case Opcodes.FRETURN: case Opcodes.ARETURN: case Opcodes.TABLESWITCH: case Opcodes.LOOKUPSWITCH: case Opcodes.ATHROW: case Opcodes.MONITORENTER: case Opcodes.MONITOREXIT: case Opcodes.IFNULL: case Opcodes.IFNONNULL: pop(1); break; case Opcodes.POP2: case Opcodes.IF_ICMPEQ: case Opcodes.IF_ICMPNE: case Opcodes.IF_ICMPLT: case Opcodes.IF_ICMPGE: case Opcodes.IF_ICMPGT: case Opcodes.IF_ICMPLE: case Opcodes.IF_ACMPEQ: case Opcodes.IF_ACMPNE: case Opcodes.LRETURN: case Opcodes.DRETURN: pop(2); break; case Opcodes.DUP: t1 = pop(); push(t1); push(t1); break; case Opcodes.DUP_X1: t1 = pop(); t2 = pop(); push(t1); push(t2); push(t1); break; case Opcodes.DUP_X2: t1 = pop(); t2 = pop(); t3 = pop(); push(t1); push(t3); push(t2); push(t1); break; case Opcodes.DUP2: t1 = pop(); t2 = pop(); push(t2); push(t1); push(t2); push(t1); break; case Opcodes.DUP2_X1: t1 = pop(); t2 = pop(); t3 = pop(); push(t2); push(t1); push(t3); push(t2); push(t1); break; case Opcodes.DUP2_X2: t1 = pop(); t2 = pop(); t3 = pop(); t4 = pop(); push(t2); push(t1); push(t4); push(t3); push(t2); push(t1); break; case Opcodes.SWAP: t1 = pop(); t2 = pop(); push(t1); push(t2); break; case Opcodes.IADD: case Opcodes.ISUB: case Opcodes.IMUL: case Opcodes.IDIV: case Opcodes.IREM: case Opcodes.IAND: case Opcodes.IOR: case Opcodes.IXOR: case Opcodes.ISHL: case Opcodes.ISHR: case Opcodes.IUSHR: case Opcodes.L2I: case Opcodes.D2I: case Opcodes.FCMPL: case Opcodes.FCMPG: pop(2); push(INTEGER); break; case Opcodes.LADD: case Opcodes.LSUB: case Opcodes.LMUL: case Opcodes.LDIV: case Opcodes.LREM: case Opcodes.LAND: case Opcodes.LOR: case Opcodes.LXOR: pop(4); push(LONG); push(TOP); break; case Opcodes.FADD: case Opcodes.FSUB: case Opcodes.FMUL: case Opcodes.FDIV: case Opcodes.FREM: case Opcodes.L2F: case Opcodes.D2F: pop(2); push(FLOAT); break; case Opcodes.DADD: case Opcodes.DSUB: case Opcodes.DMUL: case Opcodes.DDIV: case Opcodes.DREM: pop(4); push(DOUBLE); push(TOP); break; case Opcodes.LSHL: case Opcodes.LSHR: case Opcodes.LUSHR: pop(3); push(LONG); push(TOP); break; case Opcodes.IINC: set(arg, INTEGER); break; case Opcodes.I2L: case Opcodes.F2L: pop(1); push(LONG); push(TOP); break; case Opcodes.I2F: pop(1); push(FLOAT); break; case Opcodes.I2D: case Opcodes.F2D: pop(1); push(DOUBLE); push(TOP); break; case Opcodes.F2I: case Opcodes.ARRAYLENGTH: case Opcodes.INSTANCEOF: pop(1); push(INTEGER); break; case Opcodes.LCMP: case Opcodes.DCMPL: case Opcodes.DCMPG: pop(4); push(INTEGER); break; case Opcodes.JSR: case Opcodes.RET: throw new RuntimeException("JSR/RET are not supported with computeFrames option"); case Opcodes.GETSTATIC: push(cw, item.strVal3); break; case Opcodes.PUTSTATIC: pop(item.strVal3); break; case Opcodes.GETFIELD: pop(1); push(cw, item.strVal3); break; case Opcodes.PUTFIELD: pop(item.strVal3); pop(); break; case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: case Opcodes.INVOKESTATIC: case Opcodes.INVOKEINTERFACE: pop(item.strVal3); if (opcode != Opcodes.INVOKESTATIC) { t1 = pop(); if (opcode == Opcodes.INVOKESPECIAL && item.strVal2.charAt(0) == '<') { init(t1); } } push(cw, item.strVal3); break; case Opcodes.INVOKEDYNAMIC: pop(item.strVal2); push(cw, item.strVal2); break; case Opcodes.NEW: push(UNINITIALIZED | cw.addUninitializedType(item.strVal1, arg)); break; case Opcodes.NEWARRAY: pop(); switch (arg) { case Opcodes.T_BOOLEAN: push(ARRAY_OF | BOOLEAN); break; case Opcodes.T_CHAR: push(ARRAY_OF | CHAR); break; case Opcodes.T_BYTE: push(ARRAY_OF | BYTE); break; case Opcodes.T_SHORT: push(ARRAY_OF | SHORT); break; case Opcodes.T_INT: push(ARRAY_OF | INTEGER); break; case Opcodes.T_FLOAT: push(ARRAY_OF | FLOAT); break; case Opcodes.T_DOUBLE: push(ARRAY_OF | DOUBLE); break; // case Opcodes.T_LONG: default: push(ARRAY_OF | LONG); break; } break; case Opcodes.ANEWARRAY: String s = item.strVal1; pop(); if (s.charAt(0) == '[') { push(cw, '[' + s); } else { push(ARRAY_OF | OBJECT | cw.addType(s)); } break; case Opcodes.CHECKCAST: s = item.strVal1; pop(); if (s.charAt(0) == '[') { push(cw, s); } else { push(OBJECT | cw.addType(s)); } break; // case Opcodes.MULTIANEWARRAY: default: pop(arg); push(cw, item.strVal1); break; } } /** * Merges the input frame of the given basic block with the input and output * frames of this basic block. Returns true if the input frame of * the given label has been changed by this operation. * * @param cw the ClassWriter to which this label belongs. * @param frame the basic block whose input frame must be updated. * @param edge the kind of the {@link Edge} between this label and 'label'. * See {@link Edge#info}. * @return true if the input frame of the given label has been * changed by this operation. */ boolean merge(final ClassWriter cw, final Frame frame, final int edge) { boolean changed = false; int i, s, dim, kind, t; int nLocal = inputLocals.length; int nStack = inputStack.length; if (frame.inputLocals == null) { frame.inputLocals = new int[nLocal]; changed = true; } for (i = 0; i < nLocal; ++i) { if (outputLocals != null && i < outputLocals.length) { s = outputLocals[i]; if (s == 0) { t = inputLocals[i]; } else { dim = s & DIM; kind = s & KIND; if (kind == BASE) { t = s; } else { if (kind == LOCAL) { t = dim + inputLocals[s & VALUE]; } else { t = dim + inputStack[nStack - (s & VALUE)]; } if ((s & TOP_IF_LONG_OR_DOUBLE) != 0 && (t == LONG || t == DOUBLE)) { t = TOP; } } } } else { t = inputLocals[i]; } if (initializations != null) { t = init(cw, t); } changed |= merge(cw, t, frame.inputLocals, i); } if (edge > 0) { for (i = 0; i < nLocal; ++i) { t = inputLocals[i]; changed |= merge(cw, t, frame.inputLocals, i); } if (frame.inputStack == null) { frame.inputStack = new int[1]; changed = true; } changed |= merge(cw, edge, frame.inputStack, 0); return changed; } int nInputStack = inputStack.length + owner.inputStackTop; if (frame.inputStack == null) { frame.inputStack = new int[nInputStack + outputStackTop]; changed = true; } for (i = 0; i < nInputStack; ++i) { t = inputStack[i]; if (initializations != null) { t = init(cw, t); } changed |= merge(cw, t, frame.inputStack, i); } for (i = 0; i < outputStackTop; ++i) { s = outputStack[i]; dim = s & DIM; kind = s & KIND; if (kind == BASE) { t = s; } else { if (kind == LOCAL) { t = dim + inputLocals[s & VALUE]; } else { t = dim + inputStack[nStack - (s & VALUE)]; } if ((s & TOP_IF_LONG_OR_DOUBLE) != 0 && (t == LONG || t == DOUBLE)) { t = TOP; } } if (initializations != null) { t = init(cw, t); } changed |= merge(cw, t, frame.inputStack, nInputStack + i); } return changed; } /** * Merges the type at the given index in the given type array with the given * type. Returns true if the type array has been modified by this * operation. * * @param cw the ClassWriter to which this label belongs. * @param t the type with which the type array element must be merged. * @param types an array of types. * @param index the index of the type that must be merged in 'types'. * @return true if the type array has been modified by this * operation. */ private static boolean merge( final ClassWriter cw, int t, final int[] types, final int index) { int u = types[index]; if (u == t) { // if the types are equal, merge(u,t)=u, so there is no change return false; } if ((t & ~DIM) == NULL) { if (u == NULL) { return false; } t = NULL; } if (u == 0) { // if types[index] has never been assigned, merge(u,t)=t types[index] = t; return true; } int v; if ((u & BASE_KIND) == OBJECT || (u & DIM) != 0) { // if u is a reference type of any dimension if (t == NULL) { // if t is the NULL type, merge(u,t)=u, so there is no change return false; } else if ((t & (DIM | BASE_KIND)) == (u & (DIM | BASE_KIND))) { if ((u & BASE_KIND) == OBJECT) { // if t is also a reference type, and if u and t have the // same dimension merge(u,t) = dim(t) | common parent of the // element types of u and t v = (t & DIM) | OBJECT | cw.getMergedType(t & BASE_VALUE, u & BASE_VALUE); } else { // if u and t are array types, but not with the same element // type, merge(u,t)=java/lang/Object v = OBJECT | cw.addType("java/lang/Object"); } } else if ((t & BASE_KIND) == OBJECT || (t & DIM) != 0) { // if t is any other reference or array type, // merge(u,t)=java/lang/Object v = OBJECT | cw.addType("java/lang/Object"); } else { // if t is any other type, merge(u,t)=TOP v = TOP; } } else if (u == NULL) { // if u is the NULL type, merge(u,t)=t, // or TOP if t is not a reference type v = (t & BASE_KIND) == OBJECT || (t & DIM) != 0 ? t : TOP; } else { // if u is any other type, merge(u,t)=TOP whatever t v = TOP; } if (u != v) { types[index] = v; return true; } return false; } } Handler.java000066400000000000000000000046621167051330000413100ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * Information about an exception handler block. * * @author Eric Bruneton */ class Handler { /** * Beginning of the exception handler's scope (inclusive). */ Label start; /** * End of the exception handler's scope (exclusive). */ Label end; /** * Beginning of the exception handler's code. */ Label handler; /** * Internal name of the type of exceptions handled by this handler, or * null to catch any exceptions. */ String desc; /** * Constant pool index of the internal name of the type of exceptions * handled by this handler, or 0 to catch any exceptions. */ int type; /** * Next exception handler block info. */ Handler next; } Item.java000066400000000000000000000204531167051330000406250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * A constant pool item. Constant pool items can be created with the 'newXXX' * methods in the {@link ClassWriter} class. * * @author Eric Bruneton */ final class Item { /** * Index of this item in the constant pool. */ int index; /** * Type of this constant pool item. A single class is used to represent all * constant pool item types, in order to minimize the bytecode size of this * package. The value of this field is one of {@link ClassWriter#INT}, * {@link ClassWriter#LONG}, {@link ClassWriter#FLOAT}, * {@link ClassWriter#DOUBLE}, {@link ClassWriter#UTF8}, * {@link ClassWriter#STR}, {@link ClassWriter#CLASS}, * {@link ClassWriter#NAME_TYPE}, {@link ClassWriter#FIELD}, * {@link ClassWriter#METH}, {@link ClassWriter#IMETH}. * * Special Item types are used for Items that are stored in the ClassWriter * {@link ClassWriter#typeTable}, instead of the constant pool, in order to * avoid clashes with normal constant pool items in the ClassWriter constant * pool's hash table. These special item types are * {@link ClassWriter#TYPE_NORMAL}, {@link ClassWriter#TYPE_UNINIT} and * {@link ClassWriter#TYPE_MERGED}. */ int type; /** * Value of this item, for an integer item. */ int intVal; /** * Value of this item, for a long item. */ long longVal; /** * First part of the value of this item, for items that do not hold a * primitive value. */ String strVal1; /** * Second part of the value of this item, for items that do not hold a * primitive value. */ String strVal2; /** * Third part of the value of this item, for items that do not hold a * primitive value. */ String strVal3; /** * The hash code value of this constant pool item. */ int hashCode; /** * Link to another constant pool item, used for collision lists in the * constant pool's hash table. */ Item next; /** * Constructs an uninitialized {@link Item}. */ Item() { } /** * Constructs an uninitialized {@link Item} for constant pool element at * given position. * * @param index index of the item to be constructed. */ Item(final int index) { this.index = index; } /** * Constructs a copy of the given item. * * @param index index of the item to be constructed. * @param i the item that must be copied into the item to be constructed. */ Item(final int index, final Item i) { this.index = index; type = i.type; intVal = i.intVal; longVal = i.longVal; strVal1 = i.strVal1; strVal2 = i.strVal2; strVal3 = i.strVal3; hashCode = i.hashCode; } /** * Sets this item to an integer item. * * @param intVal the value of this item. */ void set(final int intVal) { this.type = ClassWriter.INT; this.intVal = intVal; this.hashCode = 0x7FFFFFFF & (type + intVal); } /** * Sets this item to a long item. * * @param longVal the value of this item. */ void set(final long longVal) { this.type = ClassWriter.LONG; this.longVal = longVal; this.hashCode = 0x7FFFFFFF & (type + (int) longVal); } /** * Sets this item to a float item. * * @param floatVal the value of this item. */ void set(final float floatVal) { this.type = ClassWriter.FLOAT; this.intVal = Float.floatToRawIntBits(floatVal); this.hashCode = 0x7FFFFFFF & (type + (int) floatVal); } /** * Sets this item to a double item. * * @param doubleVal the value of this item. */ void set(final double doubleVal) { this.type = ClassWriter.DOUBLE; this.longVal = Double.doubleToRawLongBits(doubleVal); this.hashCode = 0x7FFFFFFF & (type + (int) doubleVal); } /** * Sets this item to an item that do not hold a primitive value. * * @param type the type of this item. * @param strVal1 first part of the value of this item. * @param strVal2 second part of the value of this item. * @param strVal3 third part of the value of this item. */ void set( final int type, final String strVal1, final String strVal2, final String strVal3) { this.type = type; this.strVal1 = strVal1; this.strVal2 = strVal2; this.strVal3 = strVal3; switch (type) { case ClassWriter.UTF8: case ClassWriter.STR: case ClassWriter.CLASS: case ClassWriter.TYPE_NORMAL: hashCode = 0x7FFFFFFF & (type + strVal1.hashCode()); return; case ClassWriter.NAME_TYPE: hashCode = 0x7FFFFFFF & (type + strVal1.hashCode() * strVal2.hashCode()); return; // ClassWriter.FIELD: // ClassWriter.METH: // ClassWriter.IMETH: default: hashCode = 0x7FFFFFFF & (type + strVal1.hashCode() * strVal2.hashCode() * strVal3.hashCode()); } } /** * Indicates if the given item is equal to this one. This method assumes * that the two items have the same {@link #type}. * * @param i the item to be compared to this one. Both items must have the * same {@link #type}. * @return true if the given item if equal to this one, * false otherwise. */ boolean isEqualTo(final Item i) { switch (type) { case ClassWriter.UTF8: case ClassWriter.STR: case ClassWriter.CLASS: case ClassWriter.TYPE_NORMAL: return i.strVal1.equals(strVal1); case ClassWriter.TYPE_MERGED: case ClassWriter.LONG: case ClassWriter.DOUBLE: return i.longVal == longVal; case ClassWriter.INT: case ClassWriter.FLOAT: return i.intVal == intVal; case ClassWriter.TYPE_UNINIT: return i.intVal == intVal && i.strVal1.equals(strVal1); case ClassWriter.NAME_TYPE: return i.strVal1.equals(strVal1) && i.strVal2.equals(strVal2); // case ClassWriter.FIELD: // case ClassWriter.METH: // case ClassWriter.IMETH: default: return i.strVal1.equals(strVal1) && i.strVal2.equals(strVal2) && i.strVal3.equals(strVal3); } } } Label.java000066400000000000000000000532201167051330000407440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * A label represents a position in the bytecode of a method. Labels are used * for jump, goto, and switch instructions, and for try catch blocks. A label * designates the instruction that is just after. Note however that * there can be other elements between a label and the instruction it * designates (such as other labels, stack map frames, line numbers, etc.). * * @author Eric Bruneton */ public class Label { /** * Indicates if this label is only used for debug attributes. Such a label * is not the start of a basic block, the target of a jump instruction, or * an exception handler. It can be safely ignored in control flow graph * analysis algorithms (for optimization purposes). */ static final int DEBUG = 1; /** * Indicates if the position of this label is known. */ static final int RESOLVED = 2; /** * Indicates if this label has been updated, after instruction resizing. */ static final int RESIZED = 4; /** * Indicates if this basic block has been pushed in the basic block stack. * See {@link MethodWriter#visitMaxs visitMaxs}. */ static final int PUSHED = 8; /** * Indicates if this label is the target of a jump instruction, or the start * of an exception handler. */ static final int TARGET = 16; /** * Indicates if a stack map frame must be stored for this label. */ static final int STORE = 32; /** * Indicates if this label corresponds to a reachable basic block. */ static final int REACHABLE = 64; /** * Indicates if this basic block ends with a JSR instruction. */ static final int JSR = 128; /** * Indicates if this basic block ends with a RET instruction. */ static final int RET = 256; /** * Indicates if this basic block is the start of a subroutine. */ static final int SUBROUTINE = 512; /** * Indicates if this subroutine basic block has been visited by a * visitSubroutine(null, ...) call. */ static final int VISITED = 1024; /** * Indicates if this subroutine basic block has been visited by a * visitSubroutine(!null, ...) call. */ static final int VISITED2 = 2048; /** * Field used to associate user information to a label. Warning: this field * is used by the ASM tree package. In order to use it with the ASM tree * package you must override the {@link * org.sonatype.guice.bean.scanners.asm.tree.MethodNode#getLabelNode} method. */ public Object info; /** * Flags that indicate the status of this label. * * @see #DEBUG * @see #RESOLVED * @see #RESIZED * @see #PUSHED * @see #TARGET * @see #STORE * @see #REACHABLE * @see #JSR * @see #RET */ int status; /** * The line number corresponding to this label, if known. */ int line; /** * The position of this label in the code, if known. */ int position; /** * Number of forward references to this label, times two. */ private int referenceCount; /** * Informations about forward references. Each forward reference is * described by two consecutive integers in this array: the first one is the * position of the first byte of the bytecode instruction that contains the * forward reference, while the second is the position of the first byte of * the forward reference itself. In fact the sign of the first integer * indicates if this reference uses 2 or 4 bytes, and its absolute value * gives the position of the bytecode instruction. This array is also used * as a bitset to store the subroutines to which a basic block belongs. This * information is needed in {@linked MethodWriter#visitMaxs}, after all * forward references have been resolved. Hence the same array can be used * for both purposes without problems. */ private int[] srcAndRefPositions; // ------------------------------------------------------------------------ /* * Fields for the control flow and data flow graph analysis algorithms (used * to compute the maximum stack size or the stack map frames). A control * flow graph contains one node per "basic block", and one edge per "jump" * from one basic block to another. Each node (i.e., each basic block) is * represented by the Label object that corresponds to the first instruction * of this basic block. Each node also stores the list of its successors in * the graph, as a linked list of Edge objects. * * The control flow analysis algorithms used to compute the maximum stack * size or the stack map frames are similar and use two steps. The first * step, during the visit of each instruction, builds information about the * state of the local variables and the operand stack at the end of each * basic block, called the "output frame", relatively to the frame * state at the beginning of the basic block, which is called the "input * frame", and which is unknown during this step. The second step, * in {@link MethodWriter#visitMaxs}, is a fix point algorithm that * computes information about the input frame of each basic block, from the * input state of the first basic block (known from the method signature), * and by the using the previously computed relative output frames. * * The algorithm used to compute the maximum stack size only computes the * relative output and absolute input stack heights, while the algorithm * used to compute stack map frames computes relative output frames and * absolute input frames. */ /** * Start of the output stack relatively to the input stack. The exact * semantics of this field depends on the algorithm that is used. * * When only the maximum stack size is computed, this field is the number of * elements in the input stack. * * When the stack map frames are completely computed, this field is the * offset of the first output stack element relatively to the top of the * input stack. This offset is always negative or null. A null offset means * that the output stack must be appended to the input stack. A -n offset * means that the first n output stack elements must replace the top n input * stack elements, and that the other elements must be appended to the input * stack. */ int inputStackTop; /** * Maximum height reached by the output stack, relatively to the top of the * input stack. This maximum is always positive or null. */ int outputStackMax; /** * Information about the input and output stack map frames of this basic * block. This field is only used when {@link ClassWriter#COMPUTE_FRAMES} * option is used. */ Frame frame; /** * The successor of this label, in the order they are visited. This linked * list does not include labels used for debug info only. If * {@link ClassWriter#COMPUTE_FRAMES} option is used then, in addition, it * does not contain successive labels that denote the same bytecode position * (in this case only the first label appears in this list). */ Label successor; /** * The successors of this node in the control flow graph. These successors * are stored in a linked list of {@link Edge Edge} objects, linked to each * other by their {@link Edge#next} field. */ Edge successors; /** * The next basic block in the basic block stack. This stack is used in the * main loop of the fix point algorithm used in the second step of the * control flow analysis algorithms. It is also used in * {@link #visitSubroutine} to avoid using a recursive method. * * @see MethodWriter#visitMaxs */ Label next; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ /** * Constructs a new label. */ public Label() { } // ------------------------------------------------------------------------ // Methods to compute offsets and to manage forward references // ------------------------------------------------------------------------ /** * Returns the offset corresponding to this label. This offset is computed * from the start of the method's bytecode. This method is intended for * {@link Attribute} sub classes, and is normally not needed by class * generators or adapters. * * @return the offset corresponding to this label. * @throws IllegalStateException if this label is not resolved yet. */ public int getOffset() { if ((status & RESOLVED) == 0) { throw new IllegalStateException("Label offset position has not been resolved yet"); } return position; } /** * Puts a reference to this label in the bytecode of a method. If the * position of the label is known, the offset is computed and written * directly. Otherwise, a null offset is written and a new forward reference * is declared for this label. * * @param owner the code writer that calls this method. * @param out the bytecode of the method. * @param source the position of first byte of the bytecode instruction that * contains this label. * @param wideOffset true if the reference must be stored in 4 * bytes, or false if it must be stored with 2 bytes. * @throws IllegalArgumentException if this label has not been created by * the given code writer. */ void put( final MethodWriter owner, final ByteVector out, final int source, final boolean wideOffset) { if ((status & RESOLVED) == 0) { if (wideOffset) { addReference(-1 - source, out.length); out.putInt(-1); } else { addReference(source, out.length); out.putShort(-1); } } else { if (wideOffset) { out.putInt(position - source); } else { out.putShort(position - source); } } } /** * Adds a forward reference to this label. This method must be called only * for a true forward reference, i.e. only if this label is not resolved * yet. For backward references, the offset of the reference can be, and * must be, computed and stored directly. * * @param sourcePosition the position of the referencing instruction. This * position will be used to compute the offset of this forward * reference. * @param referencePosition the position where the offset for this forward * reference must be stored. */ private void addReference( final int sourcePosition, final int referencePosition) { if (srcAndRefPositions == null) { srcAndRefPositions = new int[6]; } if (referenceCount >= srcAndRefPositions.length) { int[] a = new int[srcAndRefPositions.length + 6]; System.arraycopy(srcAndRefPositions, 0, a, 0, srcAndRefPositions.length); srcAndRefPositions = a; } srcAndRefPositions[referenceCount++] = sourcePosition; srcAndRefPositions[referenceCount++] = referencePosition; } /** * Resolves all forward references to this label. This method must be called * when this label is added to the bytecode of the method, i.e. when its * position becomes known. This method fills in the blanks that where left * in the bytecode by each forward reference previously added to this label. * * @param owner the code writer that calls this method. * @param position the position of this label in the bytecode. * @param data the bytecode of the method. * @return true if a blank that was left for this label was to * small to store the offset. In such a case the corresponding jump * instruction is replaced with a pseudo instruction (using unused * opcodes) using an unsigned two bytes offset. These pseudo * instructions will need to be replaced with true instructions with * wider offsets (4 bytes instead of 2). This is done in * {@link MethodWriter#resizeInstructions}. * @throws IllegalArgumentException if this label has already been resolved, * or if it has not been created by the given code writer. */ boolean resolve( final MethodWriter owner, final int position, final byte[] data) { boolean needUpdate = false; this.status |= RESOLVED; this.position = position; int i = 0; while (i < referenceCount) { int source = srcAndRefPositions[i++]; int reference = srcAndRefPositions[i++]; int offset; if (source >= 0) { offset = position - source; if (offset < Short.MIN_VALUE || offset > Short.MAX_VALUE) { /* * changes the opcode of the jump instruction, in order to * be able to find it later (see resizeInstructions in * MethodWriter). These temporary opcodes are similar to * jump instruction opcodes, except that the 2 bytes offset * is unsigned (and can therefore represent values from 0 to * 65535, which is sufficient since the size of a method is * limited to 65535 bytes). */ int opcode = data[reference - 1] & 0xFF; if (opcode <= Opcodes.JSR) { // changes IFEQ ... JSR to opcodes 202 to 217 data[reference - 1] = (byte) (opcode + 49); } else { // changes IFNULL and IFNONNULL to opcodes 218 and 219 data[reference - 1] = (byte) (opcode + 20); } needUpdate = true; } data[reference++] = (byte) (offset >>> 8); data[reference] = (byte) offset; } else { offset = position + source + 1; data[reference++] = (byte) (offset >>> 24); data[reference++] = (byte) (offset >>> 16); data[reference++] = (byte) (offset >>> 8); data[reference] = (byte) offset; } } return needUpdate; } /** * Returns the first label of the series to which this label belongs. For an * isolated label or for the first label in a series of successive labels, * this method returns the label itself. For other labels it returns the * first label of the series. * * @return the first label of the series to which this label belongs. */ Label getFirst() { return !ClassReader.FRAMES || frame == null ? this : frame.owner; } // ------------------------------------------------------------------------ // Methods related to subroutines // ------------------------------------------------------------------------ /** * Returns true is this basic block belongs to the given subroutine. * * @param id a subroutine id. * @return true is this basic block belongs to the given subroutine. */ boolean inSubroutine(final long id) { if ((status & Label.VISITED) != 0) { return (srcAndRefPositions[(int) (id >>> 32)] & (int) id) != 0; } return false; } /** * Returns true if this basic block and the given one belong to a common * subroutine. * * @param block another basic block. * @return true if this basic block and the given one belong to a common * subroutine. */ boolean inSameSubroutine(final Label block) { if ((status & VISITED) == 0 || (block.status & VISITED) == 0) { return false; } for (int i = 0; i < srcAndRefPositions.length; ++i) { if ((srcAndRefPositions[i] & block.srcAndRefPositions[i]) != 0) { return true; } } return false; } /** * Marks this basic block as belonging to the given subroutine. * * @param id a subroutine id. * @param nbSubroutines the total number of subroutines in the method. */ void addToSubroutine(final long id, final int nbSubroutines) { if ((status & VISITED) == 0) { status |= VISITED; srcAndRefPositions = new int[(nbSubroutines - 1) / 32 + 1]; } srcAndRefPositions[(int) (id >>> 32)] |= (int) id; } /** * Finds the basic blocks that belong to a given subroutine, and marks these * blocks as belonging to this subroutine. This method follows the control * flow graph to find all the blocks that are reachable from the current * block WITHOUT following any JSR target. * * @param JSR a JSR block that jumps to this subroutine. If this JSR is not * null it is added to the successor of the RET blocks found in the * subroutine. * @param id the id of this subroutine. * @param nbSubroutines the total number of subroutines in the method. */ void visitSubroutine(final Label JSR, final long id, final int nbSubroutines) { // user managed stack of labels, to avoid using a recursive method // (recursivity can lead to stack overflow with very large methods) Label stack = this; while (stack != null) { // removes a label l from the stack Label l = stack; stack = l.next; l.next = null; if (JSR != null) { if ((l.status & VISITED2) != 0) { continue; } l.status |= VISITED2; // adds JSR to the successors of l, if it is a RET block if ((l.status & RET) != 0) { if (!l.inSameSubroutine(JSR)) { Edge e = new Edge(); e.info = l.inputStackTop; e.successor = JSR.successors.successor; e.next = l.successors; l.successors = e; } } } else { // if the l block already belongs to subroutine 'id', continue if (l.inSubroutine(id)) { continue; } // marks the l block as belonging to subroutine 'id' l.addToSubroutine(id, nbSubroutines); } // pushes each successor of l on the stack, except JSR targets Edge e = l.successors; while (e != null) { // if the l block is a JSR block, then 'l.successors.next' leads // to the JSR target (see {@link #visitJumpInsn}) and must // therefore not be followed if ((l.status & Label.JSR) == 0 || e != l.successors.next) { // pushes e.successor on the stack if it not already added if (e.successor.next == null) { e.successor.next = stack; stack = e.successor; } } e = e.next; } } } // ------------------------------------------------------------------------ // Overriden Object methods // ------------------------------------------------------------------------ /** * Returns a string representation of this label. * * @return a string representation of this label. */ public String toString() { return "L" + System.identityHashCode(this); } } MethodVisitor.java000066400000000000000000000446511167051330000425350ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * A visitor to visit a Java method. The methods of this interface must be * called in the following order: [ visitAnnotationDefault ] ( * visitAnnotation | visitParameterAnnotation | * visitAttribute )* [ visitCode ( visitFrame | * visitXInsn
| visitLabel | visitTryCatchBlock | * visitLocalVariable | visitLineNumber)* visitMaxs ] * visitEnd. In addition, the visitXInsn
* and visitLabel methods must be called in the sequential order of * the bytecode instructions of the visited code, visitTryCatchBlock * must be called before the labels passed as arguments have been * visited, and the visitLocalVariable and visitLineNumber * methods must be called after the labels passed as arguments have been * visited. * * @author Eric Bruneton */ public interface MethodVisitor { // ------------------------------------------------------------------------- // Annotations and non standard attributes // ------------------------------------------------------------------------- /** * Visits the default value of this annotation interface method. * * @return a visitor to the visit the actual default value of this * annotation interface method, or null if this visitor * is not interested in visiting this default value. The 'name' * parameters passed to the methods of this annotation visitor are * ignored. Moreover, exacly one visit method must be called on this * annotation visitor, followed by visitEnd. */ AnnotationVisitor visitAnnotationDefault(); /** * Visits an annotation of this method. * * @param desc the class descriptor of the annotation class. * @param visible true if the annotation is visible at runtime. * @return a visitor to visit the annotation values, or null if * this visitor is not interested in visiting this annotation. */ AnnotationVisitor visitAnnotation(String desc, boolean visible); /** * Visits an annotation of a parameter this method. * * @param parameter the parameter index. * @param desc the class descriptor of the annotation class. * @param visible true if the annotation is visible at runtime. * @return a visitor to visit the annotation values, or null if * this visitor is not interested in visiting this annotation. */ AnnotationVisitor visitParameterAnnotation( int parameter, String desc, boolean visible); /** * Visits a non standard attribute of this method. * * @param attr an attribute. */ void visitAttribute(Attribute attr); /** * Starts the visit of the method's code, if any (i.e. non abstract method). */ void visitCode(); /** * Visits the current state of the local variables and operand stack * elements. This method must(*) be called just before any * instruction i that follows an unconditional branch instruction * such as GOTO or THROW, that is the target of a jump instruction, or that * starts an exception handler block. The visited types must describe the * values of the local variables and of the operand stack elements just * before i is executed.

(*) this is mandatory only * for classes whose version is greater than or equal to * {@link Opcodes#V1_6 V1_6}.

Packed frames are basically * "deltas" from the state of the previous frame (very first frame is * implicitly defined by the method's parameters and access flags):
    *
  • {@link Opcodes#F_SAME} representing frame with exactly the same * locals as the previous frame and with the empty stack.
  • {@link Opcodes#F_SAME1} * representing frame with exactly the same locals as the previous frame and * with single value on the stack (nStack is 1 and * stack[0] contains value for the type of the stack item).
  • *
  • {@link Opcodes#F_APPEND} representing frame with current locals are * the same as the locals in the previous frame, except that additional * locals are defined (nLocal is 1, 2 or 3 and * local elements contains values representing added types).
  • *
  • {@link Opcodes#F_CHOP} representing frame with current locals are * the same as the locals in the previous frame, except that the last 1-3 * locals are absent and with the empty stack (nLocals is 1, * 2 or 3).
  • {@link Opcodes#F_FULL} representing complete frame * data.
* * @param type the type of this stack map frame. Must be * {@link Opcodes#F_NEW} for expanded frames, or * {@link Opcodes#F_FULL}, {@link Opcodes#F_APPEND}, * {@link Opcodes#F_CHOP}, {@link Opcodes#F_SAME} or * {@link Opcodes#F_APPEND}, {@link Opcodes#F_SAME1} for compressed * frames. * @param nLocal the number of local variables in the visited frame. * @param local the local variable types in this frame. This array must not * be modified. Primitive types are represented by * {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, * {@link Opcodes#FLOAT}, {@link Opcodes#LONG}, * {@link Opcodes#DOUBLE},{@link Opcodes#NULL} or * {@link Opcodes#UNINITIALIZED_THIS} (long and double are * represented by a single element). Reference types are represented * by String objects (representing internal names), and uninitialized * types by Label objects (this label designates the NEW instruction * that created this uninitialized value). * @param nStack the number of operand stack elements in the visited frame. * @param stack the operand stack types in this frame. This array must not * be modified. Its content has the same format as the "local" array. * @throws IllegalStateException if a frame is visited just after another * one, without any instruction between the two (unless this frame * is a Opcodes#F_SAME frame, in which case it is silently ignored). */ void visitFrame( int type, int nLocal, Object[] local, int nStack, Object[] stack); // ------------------------------------------------------------------------- // Normal instructions // ------------------------------------------------------------------------- /** * Visits a zero operand instruction. * * @param opcode the opcode of the instruction to be visited. This opcode is * either NOP, ACONST_NULL, ICONST_M1, ICONST_0, ICONST_1, ICONST_2, * ICONST_3, ICONST_4, ICONST_5, LCONST_0, LCONST_1, FCONST_0, * FCONST_1, FCONST_2, DCONST_0, DCONST_1, IALOAD, LALOAD, FALOAD, * DALOAD, AALOAD, BALOAD, CALOAD, SALOAD, IASTORE, LASTORE, FASTORE, * DASTORE, AASTORE, BASTORE, CASTORE, SASTORE, POP, POP2, DUP, * DUP_X1, DUP_X2, DUP2, DUP2_X1, DUP2_X2, SWAP, IADD, LADD, FADD, * DADD, ISUB, LSUB, FSUB, DSUB, IMUL, LMUL, FMUL, DMUL, IDIV, LDIV, * FDIV, DDIV, IREM, LREM, FREM, DREM, INEG, LNEG, FNEG, DNEG, ISHL, * LSHL, ISHR, LSHR, IUSHR, LUSHR, IAND, LAND, IOR, LOR, IXOR, LXOR, * I2L, I2F, I2D, L2I, L2F, L2D, F2I, F2L, F2D, D2I, D2L, D2F, I2B, * I2C, I2S, LCMP, FCMPL, FCMPG, DCMPL, DCMPG, IRETURN, LRETURN, * FRETURN, DRETURN, ARETURN, RETURN, ARRAYLENGTH, ATHROW, * MONITORENTER, or MONITOREXIT. */ void visitInsn(int opcode); /** * Visits an instruction with a single int operand. * * @param opcode the opcode of the instruction to be visited. This opcode is * either BIPUSH, SIPUSH or NEWARRAY. * @param operand the operand of the instruction to be visited.
When * opcode is BIPUSH, operand value should be between Byte.MIN_VALUE * and Byte.MAX_VALUE.
When opcode is SIPUSH, operand value * should be between Short.MIN_VALUE and Short.MAX_VALUE.
When * opcode is NEWARRAY, operand value should be one of * {@link Opcodes#T_BOOLEAN}, {@link Opcodes#T_CHAR}, * {@link Opcodes#T_FLOAT}, {@link Opcodes#T_DOUBLE}, * {@link Opcodes#T_BYTE}, {@link Opcodes#T_SHORT}, * {@link Opcodes#T_INT} or {@link Opcodes#T_LONG}. */ void visitIntInsn(int opcode, int operand); /** * Visits a local variable instruction. A local variable instruction is an * instruction that loads or stores the value of a local variable. * * @param opcode the opcode of the local variable instruction to be visited. * This opcode is either ILOAD, LLOAD, FLOAD, DLOAD, ALOAD, ISTORE, * LSTORE, FSTORE, DSTORE, ASTORE or RET. * @param var the operand of the instruction to be visited. This operand is * the index of a local variable. */ void visitVarInsn(int opcode, int var); /** * Visits a type instruction. A type instruction is an instruction that * takes the internal name of a class as parameter. * * @param opcode the opcode of the type instruction to be visited. This * opcode is either NEW, ANEWARRAY, CHECKCAST or INSTANCEOF. * @param type the operand of the instruction to be visited. This operand * must be the internal name of an object or array class (see {@link * Type#getInternalName() getInternalName}). */ void visitTypeInsn(int opcode, String type); /** * Visits a field instruction. A field instruction is an instruction that * loads or stores the value of a field of an object. * * @param opcode the opcode of the type instruction to be visited. This * opcode is either GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD. * @param owner the internal name of the field's owner class (see {@link * Type#getInternalName() getInternalName}). * @param name the field's name. * @param desc the field's descriptor (see {@link Type Type}). */ void visitFieldInsn(int opcode, String owner, String name, String desc); /** * Visits a method instruction. A method instruction is an instruction that * invokes a method. * * @param opcode the opcode of the type instruction to be visited. This * opcode is either INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC, * INVOKEINTERFACE or INVOKEDYNAMIC. * @param owner the internal name of the method's owner class (see {@link * Type#getInternalName() getInternalName}) * or {@link org.sonatype.guice.bean.scanners.asm.Opcodes#INVOKEDYNAMIC_OWNER}. * @param name the method's name. * @param desc the method's descriptor (see {@link Type Type}). */ void visitMethodInsn(int opcode, String owner, String name, String desc); /** * Visits a jump instruction. A jump instruction is an instruction that may * jump to another instruction. * * @param opcode the opcode of the type instruction to be visited. This * opcode is either IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, IF_ICMPEQ, * IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ, * IF_ACMPNE, GOTO, JSR, IFNULL or IFNONNULL. * @param label the operand of the instruction to be visited. This operand * is a label that designates the instruction to which the jump * instruction may jump. */ void visitJumpInsn(int opcode, Label label); /** * Visits a label. A label designates the instruction that will be visited * just after it. * * @param label a {@link Label Label} object. */ void visitLabel(Label label); // ------------------------------------------------------------------------- // Special instructions // ------------------------------------------------------------------------- /** * Visits a LDC instruction. * * @param cst the constant to be loaded on the stack. This parameter must be * a non null {@link Integer}, a {@link Float}, a {@link Long}, a * {@link Double} a {@link String} (or a {@link Type} for * .class constants, for classes whose version is 49.0 or * more). */ void visitLdcInsn(Object cst); /** * Visits an IINC instruction. * * @param var index of the local variable to be incremented. * @param increment amount to increment the local variable by. */ void visitIincInsn(int var, int increment); /** * Visits a TABLESWITCH instruction. * * @param min the minimum key value. * @param max the maximum key value. * @param dflt beginning of the default handler block. * @param labels beginnings of the handler blocks. labels[i] is * the beginning of the handler block for the min + i key. */ void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels); /** * Visits a LOOKUPSWITCH instruction. * * @param dflt beginning of the default handler block. * @param keys the values of the keys. * @param labels beginnings of the handler blocks. labels[i] is * the beginning of the handler block for the keys[i] key. */ void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels); /** * Visits a MULTIANEWARRAY instruction. * * @param desc an array type descriptor (see {@link Type Type}). * @param dims number of dimensions of the array to allocate. */ void visitMultiANewArrayInsn(String desc, int dims); // ------------------------------------------------------------------------- // Exceptions table entries, debug information, max stack and max locals // ------------------------------------------------------------------------- /** * Visits a try catch block. * * @param start beginning of the exception handler's scope (inclusive). * @param end end of the exception handler's scope (exclusive). * @param handler beginning of the exception handler's code. * @param type internal name of the type of exceptions handled by the * handler, or null to catch any exceptions (for "finally" * blocks). * @throws IllegalArgumentException if one of the labels has already been * visited by this visitor (by the {@link #visitLabel visitLabel} * method). */ void visitTryCatchBlock(Label start, Label end, Label handler, String type); /** * Visits a local variable declaration. * * @param name the name of a local variable. * @param desc the type descriptor of this local variable. * @param signature the type signature of this local variable. May be * null if the local variable type does not use generic * types. * @param start the first instruction corresponding to the scope of this * local variable (inclusive). * @param end the last instruction corresponding to the scope of this local * variable (exclusive). * @param index the local variable's index. * @throws IllegalArgumentException if one of the labels has not already * been visited by this visitor (by the * {@link #visitLabel visitLabel} method). */ void visitLocalVariable( String name, String desc, String signature, Label start, Label end, int index); /** * Visits a line number declaration. * * @param line a line number. This number refers to the source file from * which the class was compiled. * @param start the first instruction corresponding to this line number. * @throws IllegalArgumentException if start has not already been * visited by this visitor (by the {@link #visitLabel visitLabel} * method). */ void visitLineNumber(int line, Label start); /** * Visits the maximum stack size and the maximum number of local variables * of the method. * * @param maxStack maximum stack size of the method. * @param maxLocals maximum number of local variables for the method. */ void visitMaxs(int maxStack, int maxLocals); /** * Visits the end of the method. This method, which is the last one to be * called, is used to inform the visitor that all the annotations and * attributes of the method have been visited. */ void visitEnd(); } MethodWriter.java000066400000000000000000003036611167051330000423510ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * A {@link MethodVisitor} that generates methods in bytecode form. Each visit * method of this class appends the bytecode corresponding to the visited * instruction to a byte vector, in the order these methods are called. * * @author Eric Bruneton * @author Eugene Kuleshov */ class MethodWriter implements MethodVisitor { /** * Pseudo access flag used to denote constructors. */ static final int ACC_CONSTRUCTOR = 262144; /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is zero. */ static final int SAME_FRAME = 0; // to 63 (0-3f) /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is 1 */ static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64; // to 127 (40-7f) /** * Reserved for future use */ static final int RESERVED = 128; /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is 1. Offset is bigger then 63; */ static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247; // f7 /** * Frame where current locals are the same as the locals in the previous * frame, except that the k last locals are absent. The value of k is given * by the formula 251-frame_type. */ static final int CHOP_FRAME = 248; // to 250 (f8-fA) /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is zero. Offset is bigger then 63; */ static final int SAME_FRAME_EXTENDED = 251; // fb /** * Frame where current locals are the same as the locals in the previous * frame, except that k additional locals are defined. The value of k is * given by the formula frame_type-251. */ static final int APPEND_FRAME = 252; // to 254 // fc-fe /** * Full frame */ static final int FULL_FRAME = 255; // ff /** * Indicates that the stack map frames must be recomputed from scratch. In * this case the maximum stack size and number of local variables is also * recomputed from scratch. * * @see #compute */ private static final int FRAMES = 0; /** * Indicates that the maximum stack size and number of local variables must * be automatically computed. * * @see #compute */ private static final int MAXS = 1; /** * Indicates that nothing must be automatically computed. * * @see #compute */ private static final int NOTHING = 2; /** * Next method writer (see {@link ClassWriter#firstMethod firstMethod}). */ MethodWriter next; /** * The class writer to which this method must be added. */ final ClassWriter cw; /** * Access flags of this method. */ private int access; /** * The index of the constant pool item that contains the name of this * method. */ private final int name; /** * The index of the constant pool item that contains the descriptor of this * method. */ private final int desc; /** * The descriptor of this method. */ private final String descriptor; /** * The signature of this method. */ String signature; /** * If not zero, indicates that the code of this method must be copied from * the ClassReader associated to this writer in cw.cr. More * precisely, this field gives the index of the first byte to copied from * cw.cr.b. */ int classReaderOffset; /** * If not zero, indicates that the code of this method must be copied from * the ClassReader associated to this writer in cw.cr. More * precisely, this field gives the number of bytes to copied from * cw.cr.b. */ int classReaderLength; /** * Number of exceptions that can be thrown by this method. */ int exceptionCount; /** * The exceptions that can be thrown by this method. More precisely, this * array contains the indexes of the constant pool items that contain the * internal names of these exception classes. */ int[] exceptions; /** * The annotation default attribute of this method. May be null. */ private ByteVector annd; /** * The runtime visible annotations of this method. May be null. */ private AnnotationWriter anns; /** * The runtime invisible annotations of this method. May be null. */ private AnnotationWriter ianns; /** * The runtime visible parameter annotations of this method. May be * null. */ private AnnotationWriter[] panns; /** * The runtime invisible parameter annotations of this method. May be * null. */ private AnnotationWriter[] ipanns; /** * The number of synthetic parameters of this method. */ private int synthetics; /** * The non standard attributes of the method. */ private Attribute attrs; /** * The bytecode of this method. */ private ByteVector code = new ByteVector(); /** * Maximum stack size of this method. */ private int maxStack; /** * Maximum number of local variables for this method. */ private int maxLocals; /** * Number of local variables in the current stack map frame. */ private int currentLocals; /** * Number of stack map frames in the StackMapTable attribute. */ private int frameCount; /** * The StackMapTable attribute. */ private ByteVector stackMap; /** * The offset of the last frame that was written in the StackMapTable * attribute. */ private int previousFrameOffset; /** * The last frame that was written in the StackMapTable attribute. * * @see #frame */ private int[] previousFrame; /** * Index of the next element to be added in {@link #frame}. */ private int frameIndex; /** * The current stack map frame. The first element contains the offset of the * instruction to which the frame corresponds, the second element is the * number of locals and the third one is the number of stack elements. The * local variables start at index 3 and are followed by the operand stack * values. In summary frame[0] = offset, frame[1] = nLocal, frame[2] = * nStack, frame[3] = nLocal. All types are encoded as integers, with the * same format as the one used in {@link Label}, but limited to BASE types. */ private int[] frame; /** * Number of elements in the exception handler list. */ private int handlerCount; /** * The first element in the exception handler list. */ private Handler firstHandler; /** * The last element in the exception handler list. */ private Handler lastHandler; /** * Number of entries in the LocalVariableTable attribute. */ private int localVarCount; /** * The LocalVariableTable attribute. */ private ByteVector localVar; /** * Number of entries in the LocalVariableTypeTable attribute. */ private int localVarTypeCount; /** * The LocalVariableTypeTable attribute. */ private ByteVector localVarType; /** * Number of entries in the LineNumberTable attribute. */ private int lineNumberCount; /** * The LineNumberTable attribute. */ private ByteVector lineNumber; /** * The non standard attributes of the method's code. */ private Attribute cattrs; /** * Indicates if some jump instructions are too small and need to be resized. */ private boolean resize; /** * The number of subroutines in this method. */ private int subroutines; // ------------------------------------------------------------------------ /* * Fields for the control flow graph analysis algorithm (used to compute the * maximum stack size). A control flow graph contains one node per "basic * block", and one edge per "jump" from one basic block to another. Each * node (i.e., each basic block) is represented by the Label object that * corresponds to the first instruction of this basic block. Each node also * stores the list of its successors in the graph, as a linked list of Edge * objects. */ /** * Indicates what must be automatically computed. * * @see #FRAMES * @see #MAXS * @see #NOTHING */ private final int compute; /** * A list of labels. This list is the list of basic blocks in the method, * i.e. a list of Label objects linked to each other by their * {@link Label#successor} field, in the order they are visited by * {@link MethodVisitor#visitLabel}, and starting with the first basic block. */ private Label labels; /** * The previous basic block. */ private Label previousBlock; /** * The current basic block. */ private Label currentBlock; /** * The (relative) stack size after the last visited instruction. This size * is relative to the beginning of the current basic block, i.e., the true * stack size after the last visited instruction is equal to the * {@link Label#inputStackTop beginStackSize} of the current basic block * plus stackSize. */ private int stackSize; /** * The (relative) maximum stack size after the last visited instruction. * This size is relative to the beginning of the current basic block, i.e., * the true maximum stack size after the last visited instruction is equal * to the {@link Label#inputStackTop beginStackSize} of the current basic * block plus stackSize. */ private int maxStackSize; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ /** * Constructs a new {@link MethodWriter}. * * @param cw the class writer in which the method must be added. * @param access the method's access flags (see {@link Opcodes}). * @param name the method's name. * @param desc the method's descriptor (see {@link Type}). * @param signature the method's signature. May be null. * @param exceptions the internal names of the method's exceptions. May be * null. * @param computeMaxs true if the maximum stack size and number * of local variables must be automatically computed. * @param computeFrames true if the stack map tables must be * recomputed from scratch. */ MethodWriter( final ClassWriter cw, final int access, final String name, final String desc, final String signature, final String[] exceptions, final boolean computeMaxs, final boolean computeFrames) { if (cw.firstMethod == null) { cw.firstMethod = this; } else { cw.lastMethod.next = this; } cw.lastMethod = this; this.cw = cw; this.access = access; this.name = cw.newUTF8(name); this.desc = cw.newUTF8(desc); this.descriptor = desc; if (ClassReader.SIGNATURES) { this.signature = signature; } if (exceptions != null && exceptions.length > 0) { exceptionCount = exceptions.length; this.exceptions = new int[exceptionCount]; for (int i = 0; i < exceptionCount; ++i) { this.exceptions[i] = cw.newClass(exceptions[i]); } } this.compute = computeFrames ? FRAMES : (computeMaxs ? MAXS : NOTHING); if (computeMaxs || computeFrames) { if (computeFrames && "".equals(name)) { this.access |= ACC_CONSTRUCTOR; } // updates maxLocals int size = Type.getArgumentsAndReturnSizes(descriptor) >> 2; if ((access & Opcodes.ACC_STATIC) != 0) { --size; } maxLocals = size; currentLocals = size; // creates and visits the label for the first basic block labels = new Label(); labels.status |= Label.PUSHED; visitLabel(labels); } } // ------------------------------------------------------------------------ // Implementation of the MethodVisitor interface // ------------------------------------------------------------------------ public AnnotationVisitor visitAnnotationDefault() { if (!ClassReader.ANNOTATIONS) { return null; } annd = new ByteVector(); return new AnnotationWriter(cw, false, annd, null, 0); } public AnnotationVisitor visitAnnotation( final String desc, final boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, 2); if (visible) { aw.next = anns; anns = aw; } else { aw.next = ianns; ianns = aw; } return aw; } public AnnotationVisitor visitParameterAnnotation( final int parameter, final String desc, final boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); if ("Ljava/lang/Synthetic;".equals(desc)) { // workaround for a bug in javac with synthetic parameters // see ClassReader.readParameterAnnotations synthetics = Math.max(synthetics, parameter + 1); return new AnnotationWriter(cw, false, bv, null, 0); } // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, 2); if (visible) { if (panns == null) { panns = new AnnotationWriter[Type.getArgumentTypes(descriptor).length]; } aw.next = panns[parameter]; panns[parameter] = aw; } else { if (ipanns == null) { ipanns = new AnnotationWriter[Type.getArgumentTypes(descriptor).length]; } aw.next = ipanns[parameter]; ipanns[parameter] = aw; } return aw; } public void visitAttribute(final Attribute attr) { if (attr.isCodeAttribute()) { attr.next = cattrs; cattrs = attr; } else { attr.next = attrs; attrs = attr; } } public void visitCode() { } public void visitFrame( final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { if (!ClassReader.FRAMES || compute == FRAMES) { return; } if (type == Opcodes.F_NEW) { currentLocals = nLocal; startFrame(code.length, nLocal, nStack); for (int i = 0; i < nLocal; ++i) { if (local[i] instanceof String) { frame[frameIndex++] = Frame.OBJECT | cw.addType((String) local[i]); } else if (local[i] instanceof Integer) { frame[frameIndex++] = ((Integer) local[i]).intValue(); } else { frame[frameIndex++] = Frame.UNINITIALIZED | cw.addUninitializedType("", ((Label) local[i]).position); } } for (int i = 0; i < nStack; ++i) { if (stack[i] instanceof String) { frame[frameIndex++] = Frame.OBJECT | cw.addType((String) stack[i]); } else if (stack[i] instanceof Integer) { frame[frameIndex++] = ((Integer) stack[i]).intValue(); } else { frame[frameIndex++] = Frame.UNINITIALIZED | cw.addUninitializedType("", ((Label) stack[i]).position); } } endFrame(); } else { int delta; if (stackMap == null) { stackMap = new ByteVector(); delta = code.length; } else { delta = code.length - previousFrameOffset - 1; if (delta < 0) { if (type == Opcodes.F_SAME) { return; } else { throw new IllegalStateException(); } } } switch (type) { case Opcodes.F_FULL: currentLocals = nLocal; stackMap.putByte(FULL_FRAME) .putShort(delta) .putShort(nLocal); for (int i = 0; i < nLocal; ++i) { writeFrameType(local[i]); } stackMap.putShort(nStack); for (int i = 0; i < nStack; ++i) { writeFrameType(stack[i]); } break; case Opcodes.F_APPEND: currentLocals += nLocal; stackMap.putByte(SAME_FRAME_EXTENDED + nLocal) .putShort(delta); for (int i = 0; i < nLocal; ++i) { writeFrameType(local[i]); } break; case Opcodes.F_CHOP: currentLocals -= nLocal; stackMap.putByte(SAME_FRAME_EXTENDED - nLocal) .putShort(delta); break; case Opcodes.F_SAME: if (delta < 64) { stackMap.putByte(delta); } else { stackMap.putByte(SAME_FRAME_EXTENDED).putShort(delta); } break; case Opcodes.F_SAME1: if (delta < 64) { stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME + delta); } else { stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) .putShort(delta); } writeFrameType(stack[0]); break; } previousFrameOffset = code.length; ++frameCount; } maxStack = Math.max(maxStack, nStack); maxLocals = Math.max(maxLocals, currentLocals); } public void visitInsn(final int opcode) { // adds the instruction to the bytecode of the method code.putByte(opcode); // update currentBlock // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, 0, null, null); } else { // updates current and max stack sizes int size = stackSize + Frame.SIZE[opcode]; if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } // if opcode == ATHROW or xRETURN, ends current block (no successor) if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) { noSuccessor(); } } } public void visitIntInsn(final int opcode, final int operand) { // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, operand, null, null); } else if (opcode != Opcodes.NEWARRAY) { // updates current and max stack sizes only for NEWARRAY // (stack size variation = 0 for BIPUSH or SIPUSH) int size = stackSize + 1; if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method if (opcode == Opcodes.SIPUSH) { code.put12(opcode, operand); } else { // BIPUSH or NEWARRAY code.put11(opcode, operand); } } public void visitVarInsn(final int opcode, final int var) { // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, var, null, null); } else { // updates current and max stack sizes if (opcode == Opcodes.RET) { // no stack change, but end of current block (no successor) currentBlock.status |= Label.RET; // save 'stackSize' here for future use // (see {@link #findSubroutineSuccessors}) currentBlock.inputStackTop = stackSize; noSuccessor(); } else { // xLOAD or xSTORE int size = stackSize + Frame.SIZE[opcode]; if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } } if (compute != NOTHING) { // updates max locals int n; if (opcode == Opcodes.LLOAD || opcode == Opcodes.DLOAD || opcode == Opcodes.LSTORE || opcode == Opcodes.DSTORE) { n = var + 2; } else { n = var + 1; } if (n > maxLocals) { maxLocals = n; } } // adds the instruction to the bytecode of the method if (var < 4 && opcode != Opcodes.RET) { int opt; if (opcode < Opcodes.ISTORE) { /* ILOAD_0 */ opt = 26 + ((opcode - Opcodes.ILOAD) << 2) + var; } else { /* ISTORE_0 */ opt = 59 + ((opcode - Opcodes.ISTORE) << 2) + var; } code.putByte(opt); } else if (var >= 256) { code.putByte(196 /* WIDE */).put12(opcode, var); } else { code.put11(opcode, var); } if (opcode >= Opcodes.ISTORE && compute == FRAMES && handlerCount > 0) { visitLabel(new Label()); } } public void visitTypeInsn(final int opcode, final String type) { Item i = cw.newClassItem(type); // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, code.length, cw, i); } else if (opcode == Opcodes.NEW) { // updates current and max stack sizes only if opcode == NEW // (no stack change for ANEWARRAY, CHECKCAST, INSTANCEOF) int size = stackSize + 1; if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method code.put12(opcode, i.index); } public void visitFieldInsn( final int opcode, final String owner, final String name, final String desc) { Item i = cw.newFieldItem(owner, name, desc); // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, 0, cw, i); } else { int size; // computes the stack size variation char c = desc.charAt(0); switch (opcode) { case Opcodes.GETSTATIC: size = stackSize + (c == 'D' || c == 'J' ? 2 : 1); break; case Opcodes.PUTSTATIC: size = stackSize + (c == 'D' || c == 'J' ? -2 : -1); break; case Opcodes.GETFIELD: size = stackSize + (c == 'D' || c == 'J' ? 1 : 0); break; // case Constants.PUTFIELD: default: size = stackSize + (c == 'D' || c == 'J' ? -3 : -2); break; } // updates current and max stack sizes if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method code.put12(opcode, i.index); } public void visitMethodInsn( final int opcode, final String owner, final String name, final String desc) { boolean itf = opcode == Opcodes.INVOKEINTERFACE; Item i = (opcode == Opcodes.INVOKEDYNAMIC) ? cw.newNameTypeItem(name, desc): cw.newMethodItem(owner, name, desc, itf); int argSize = i.intVal; // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, 0, cw, i); } else { /* * computes the stack size variation. In order not to recompute * several times this variation for the same Item, we use the * intVal field of this item to store this variation, once it * has been computed. More precisely this intVal field stores * the sizes of the arguments and of the return value * corresponding to desc. */ if (argSize == 0) { // the above sizes have not been computed yet, // so we compute them... argSize = Type.getArgumentsAndReturnSizes(desc); // ... and we save them in order // not to recompute them in the future i.intVal = argSize; } int size; if (opcode == Opcodes.INVOKESTATIC || opcode == Opcodes.INVOKEDYNAMIC) { size = stackSize - (argSize >> 2) + (argSize & 0x03) + 1; } else { size = stackSize - (argSize >> 2) + (argSize & 0x03); } // updates current and max stack sizes if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method if (itf) { if (argSize == 0) { argSize = Type.getArgumentsAndReturnSizes(desc); i.intVal = argSize; } code.put12(Opcodes.INVOKEINTERFACE, i.index).put11(argSize >> 2, 0); } else { code.put12(opcode, i.index); if (opcode==Opcodes.INVOKEDYNAMIC) { code.putShort(0); } } } public void visitJumpInsn(final int opcode, final Label label) { Label nextInsn = null; // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, 0, null, null); // 'label' is the target of a jump instruction label.getFirst().status |= Label.TARGET; // adds 'label' as a successor of this basic block addSuccessor(Edge.NORMAL, label); if (opcode != Opcodes.GOTO) { // creates a Label for the next basic block nextInsn = new Label(); } } else { if (opcode == Opcodes.JSR) { if ((label.status & Label.SUBROUTINE) == 0) { label.status |= Label.SUBROUTINE; ++subroutines; } currentBlock.status |= Label.JSR; addSuccessor(stackSize + 1, label); // creates a Label for the next basic block nextInsn = new Label(); /* * note that, by construction in this method, a JSR block * has at least two successors in the control flow graph: * the first one leads the next instruction after the JSR, * while the second one leads to the JSR target. */ } else { // updates current stack size (max stack size unchanged // because stack size variation always negative in this // case) stackSize += Frame.SIZE[opcode]; addSuccessor(stackSize, label); } } } // adds the instruction to the bytecode of the method if ((label.status & Label.RESOLVED) != 0 && label.position - code.length < Short.MIN_VALUE) { /* * case of a backward jump with an offset < -32768. In this case we * automatically replace GOTO with GOTO_W, JSR with JSR_W and IFxxx * with IFNOTxxx GOTO_W , where IFNOTxxx is the * "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) and where * designates the instruction just after the GOTO_W. */ if (opcode == Opcodes.GOTO) { code.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { code.putByte(201); // JSR_W } else { // if the IF instruction is transformed into IFNOT GOTO_W the // next instruction becomes the target of the IFNOT instruction if (nextInsn != null) { nextInsn.status |= Label.TARGET; } code.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); code.putShort(8); // jump offset code.putByte(200); // GOTO_W } label.put(this, code, code.length - 1, true); } else { /* * case of a backward jump with an offset >= -32768, or of a forward * jump with, of course, an unknown offset. In these cases we store * the offset in 2 bytes (which will be increased in * resizeInstructions, if needed). */ code.putByte(opcode); label.put(this, code, code.length - 1, false); } if (currentBlock != null) { if (nextInsn != null) { // if the jump instruction is not a GOTO, the next instruction // is also a successor of this instruction. Calling visitLabel // adds the label of this next instruction as a successor of the // current block, and starts a new basic block visitLabel(nextInsn); } if (opcode == Opcodes.GOTO) { noSuccessor(); } } } public void visitLabel(final Label label) { // resolves previous forward references to label, if any resize |= label.resolve(this, code.length, code.data); // updates currentBlock if ((label.status & Label.DEBUG) != 0) { return; } if (compute == FRAMES) { if (currentBlock != null) { if (label.position == currentBlock.position) { // successive labels, do not start a new basic block currentBlock.status |= (label.status & Label.TARGET); label.frame = currentBlock.frame; return; } // ends current block (with one new successor) addSuccessor(Edge.NORMAL, label); } // begins a new current block currentBlock = label; if (label.frame == null) { label.frame = new Frame(); label.frame.owner = label; } // updates the basic block list if (previousBlock != null) { if (label.position == previousBlock.position) { previousBlock.status |= (label.status & Label.TARGET); label.frame = previousBlock.frame; currentBlock = previousBlock; return; } previousBlock.successor = label; } previousBlock = label; } else if (compute == MAXS) { if (currentBlock != null) { // ends current block (with one new successor) currentBlock.outputStackMax = maxStackSize; addSuccessor(stackSize, label); } // begins a new current block currentBlock = label; // resets the relative current and max stack sizes stackSize = 0; maxStackSize = 0; // updates the basic block list if (previousBlock != null) { previousBlock.successor = label; } previousBlock = label; } } public void visitLdcInsn(final Object cst) { Item i = cw.newConstItem(cst); // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(Opcodes.LDC, 0, cw, i); } else { int size; // computes the stack size variation if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) { size = stackSize + 2; } else { size = stackSize + 1; } // updates current and max stack sizes if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method int index = i.index; if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) { code.put12(20 /* LDC2_W */, index); } else if (index >= 256) { code.put12(19 /* LDC_W */, index); } else { code.put11(Opcodes.LDC, index); } } public void visitIincInsn(final int var, final int increment) { if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(Opcodes.IINC, var, null, null); } } if (compute != NOTHING) { // updates max locals int n = var + 1; if (n > maxLocals) { maxLocals = n; } } // adds the instruction to the bytecode of the method if ((var > 255) || (increment > 127) || (increment < -128)) { code.putByte(196 /* WIDE */) .put12(Opcodes.IINC, var) .putShort(increment); } else { code.putByte(Opcodes.IINC).put11(var, increment); } } public void visitTableSwitchInsn( final int min, final int max, final Label dflt, final Label[] labels) { // adds the instruction to the bytecode of the method int source = code.length; code.putByte(Opcodes.TABLESWITCH); code.putByteArray(null, 0, (4 - code.length % 4) % 4); dflt.put(this, code, source, true); code.putInt(min).putInt(max); for (int i = 0; i < labels.length; ++i) { labels[i].put(this, code, source, true); } // updates currentBlock visitSwitchInsn(dflt, labels); } public void visitLookupSwitchInsn( final Label dflt, final int[] keys, final Label[] labels) { // adds the instruction to the bytecode of the method int source = code.length; code.putByte(Opcodes.LOOKUPSWITCH); code.putByteArray(null, 0, (4 - code.length % 4) % 4); dflt.put(this, code, source, true); code.putInt(labels.length); for (int i = 0; i < labels.length; ++i) { code.putInt(keys[i]); labels[i].put(this, code, source, true); } // updates currentBlock visitSwitchInsn(dflt, labels); } private void visitSwitchInsn(final Label dflt, final Label[] labels) { // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(Opcodes.LOOKUPSWITCH, 0, null, null); // adds current block successors addSuccessor(Edge.NORMAL, dflt); dflt.getFirst().status |= Label.TARGET; for (int i = 0; i < labels.length; ++i) { addSuccessor(Edge.NORMAL, labels[i]); labels[i].getFirst().status |= Label.TARGET; } } else { // updates current stack size (max stack size unchanged) --stackSize; // adds current block successors addSuccessor(stackSize, dflt); for (int i = 0; i < labels.length; ++i) { addSuccessor(stackSize, labels[i]); } } // ends current block noSuccessor(); } } public void visitMultiANewArrayInsn(final String desc, final int dims) { Item i = cw.newClassItem(desc); // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(Opcodes.MULTIANEWARRAY, dims, cw, i); } else { // updates current stack size (max stack size unchanged because // stack size variation always negative or null) stackSize += 1 - dims; } } // adds the instruction to the bytecode of the method code.put12(Opcodes.MULTIANEWARRAY, i.index).putByte(dims); } public void visitTryCatchBlock( final Label start, final Label end, final Label handler, final String type) { ++handlerCount; Handler h = new Handler(); h.start = start; h.end = end; h.handler = handler; h.desc = type; h.type = type != null ? cw.newClass(type) : 0; if (lastHandler == null) { firstHandler = h; } else { lastHandler.next = h; } lastHandler = h; } public void visitLocalVariable( final String name, final String desc, final String signature, final Label start, final Label end, final int index) { if (signature != null) { if (localVarType == null) { localVarType = new ByteVector(); } ++localVarTypeCount; localVarType.putShort(start.position) .putShort(end.position - start.position) .putShort(cw.newUTF8(name)) .putShort(cw.newUTF8(signature)) .putShort(index); } if (localVar == null) { localVar = new ByteVector(); } ++localVarCount; localVar.putShort(start.position) .putShort(end.position - start.position) .putShort(cw.newUTF8(name)) .putShort(cw.newUTF8(desc)) .putShort(index); if (compute != NOTHING) { // updates max locals char c = desc.charAt(0); int n = index + (c == 'J' || c == 'D' ? 2 : 1); if (n > maxLocals) { maxLocals = n; } } } public void visitLineNumber(final int line, final Label start) { if (lineNumber == null) { lineNumber = new ByteVector(); } ++lineNumberCount; lineNumber.putShort(start.position); lineNumber.putShort(line); } public void visitMaxs(final int maxStack, final int maxLocals) { if (ClassReader.FRAMES && compute == FRAMES) { // completes the control flow graph with exception handler blocks Handler handler = firstHandler; while (handler != null) { Label l = handler.start.getFirst(); Label h = handler.handler.getFirst(); Label e = handler.end.getFirst(); // computes the kind of the edges to 'h' String t = handler.desc == null ? "java/lang/Throwable" : handler.desc; int kind = Frame.OBJECT | cw.addType(t); // h is an exception handler h.status |= Label.TARGET; // adds 'h' as a successor of labels between 'start' and 'end' while (l != e) { // creates an edge to 'h' Edge b = new Edge(); b.info = kind; b.successor = h; // adds it to the successors of 'l' b.next = l.successors; l.successors = b; // goes to the next label l = l.successor; } handler = handler.next; } // creates and visits the first (implicit) frame Frame f = labels.frame; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, this.maxLocals); visitFrame(f); /* * fix point algorithm: mark the first basic block as 'changed' * (i.e. put it in the 'changed' list) and, while there are changed * basic blocks, choose one, mark it as unchanged, and update its * successors (which can be changed in the process). */ int max = 0; Label changed = labels; while (changed != null) { // removes a basic block from the list of changed basic blocks Label l = changed; changed = changed.next; l.next = null; f = l.frame; // a reachable jump target must be stored in the stack map if ((l.status & Label.TARGET) != 0) { l.status |= Label.STORE; } // all visited labels are reachable, by definition l.status |= Label.REACHABLE; // updates the (absolute) maximum stack size int blockMax = f.inputStack.length + l.outputStackMax; if (blockMax > max) { max = blockMax; } // updates the successors of the current basic block Edge e = l.successors; while (e != null) { Label n = e.successor.getFirst(); boolean change = f.merge(cw, n.frame, e.info); if (change && n.next == null) { // if n has changed and is not already in the 'changed' // list, adds it to this list n.next = changed; changed = n; } e = e.next; } } // visits all the frames that must be stored in the stack map Label l = labels; while (l != null) { f = l.frame; if ((l.status & Label.STORE) != 0) { visitFrame(f); } if ((l.status & Label.REACHABLE) == 0) { // finds start and end of dead basic block Label k = l.successor; int start = l.position; int end = (k == null ? code.length : k.position) - 1; // if non empty basic block if (end >= start) { max = Math.max(max, 1); // replaces instructions with NOP ... NOP ATHROW for (int i = start; i < end; ++i) { code.data[i] = Opcodes.NOP; } code.data[end] = (byte) Opcodes.ATHROW; // emits a frame for this unreachable block startFrame(start, 0, 1); frame[frameIndex++] = Frame.OBJECT | cw.addType("java/lang/Throwable"); endFrame(); } } l = l.successor; } this.maxStack = max; } else if (compute == MAXS) { // completes the control flow graph with exception handler blocks Handler handler = firstHandler; while (handler != null) { Label l = handler.start; Label h = handler.handler; Label e = handler.end; // adds 'h' as a successor of labels between 'start' and 'end' while (l != e) { // creates an edge to 'h' Edge b = new Edge(); b.info = Edge.EXCEPTION; b.successor = h; // adds it to the successors of 'l' if ((l.status & Label.JSR) == 0) { b.next = l.successors; l.successors = b; } else { // if l is a JSR block, adds b after the first two edges // to preserve the hypothesis about JSR block successors // order (see {@link #visitJumpInsn}) b.next = l.successors.next.next; l.successors.next.next = b; } // goes to the next label l = l.successor; } handler = handler.next; } if (subroutines > 0) { // completes the control flow graph with the RET successors /* * first step: finds the subroutines. This step determines, for * each basic block, to which subroutine(s) it belongs. */ // finds the basic blocks that belong to the "main" subroutine int id = 0; labels.visitSubroutine(null, 1, subroutines); // finds the basic blocks that belong to the real subroutines Label l = labels; while (l != null) { if ((l.status & Label.JSR) != 0) { // the subroutine is defined by l's TARGET, not by l Label subroutine = l.successors.next.successor; // if this subroutine has not been visited yet... if ((subroutine.status & Label.VISITED) == 0) { // ...assigns it a new id and finds its basic blocks id += 1; subroutine.visitSubroutine(null, (id / 32L) << 32 | (1L << (id % 32)), subroutines); } } l = l.successor; } // second step: finds the successors of RET blocks l = labels; while (l != null) { if ((l.status & Label.JSR) != 0) { Label L = labels; while (L != null) { L.status &= ~Label.VISITED2; L = L.successor; } // the subroutine is defined by l's TARGET, not by l Label subroutine = l.successors.next.successor; subroutine.visitSubroutine(l, 0, subroutines); } l = l.successor; } } /* * control flow analysis algorithm: while the block stack is not * empty, pop a block from this stack, update the max stack size, * compute the true (non relative) begin stack size of the * successors of this block, and push these successors onto the * stack (unless they have already been pushed onto the stack). * Note: by hypothesis, the {@link Label#inputStackTop} of the * blocks in the block stack are the true (non relative) beginning * stack sizes of these blocks. */ int max = 0; Label stack = labels; while (stack != null) { // pops a block from the stack Label l = stack; stack = stack.next; // computes the true (non relative) max stack size of this block int start = l.inputStackTop; int blockMax = start + l.outputStackMax; // updates the global max stack size if (blockMax > max) { max = blockMax; } // analyzes the successors of the block Edge b = l.successors; if ((l.status & Label.JSR) != 0) { // ignores the first edge of JSR blocks (virtual successor) b = b.next; } while (b != null) { l = b.successor; // if this successor has not already been pushed... if ((l.status & Label.PUSHED) == 0) { // computes its true beginning stack size... l.inputStackTop = b.info == Edge.EXCEPTION ? 1 : start + b.info; // ...and pushes it onto the stack l.status |= Label.PUSHED; l.next = stack; stack = l; } b = b.next; } } this.maxStack = Math.max(maxStack, max); } else { this.maxStack = maxStack; this.maxLocals = maxLocals; } } public void visitEnd() { } // ------------------------------------------------------------------------ // Utility methods: control flow analysis algorithm // ------------------------------------------------------------------------ /** * Adds a successor to the {@link #currentBlock currentBlock} block. * * @param info information about the control flow edge to be added. * @param successor the successor block to be added to the current block. */ private void addSuccessor(final int info, final Label successor) { // creates and initializes an Edge object... Edge b = new Edge(); b.info = info; b.successor = successor; // ...and adds it to the successor list of the currentBlock block b.next = currentBlock.successors; currentBlock.successors = b; } /** * Ends the current basic block. This method must be used in the case where * the current basic block does not have any successor. */ private void noSuccessor() { if (compute == FRAMES) { Label l = new Label(); l.frame = new Frame(); l.frame.owner = l; l.resolve(this, code.length, code.data); previousBlock.successor = l; previousBlock = l; } else { currentBlock.outputStackMax = maxStackSize; } currentBlock = null; } // ------------------------------------------------------------------------ // Utility methods: stack map frames // ------------------------------------------------------------------------ /** * Visits a frame that has been computed from scratch. * * @param f the frame that must be visited. */ private void visitFrame(final Frame f) { int i, t; int nTop = 0; int nLocal = 0; int nStack = 0; int[] locals = f.inputLocals; int[] stacks = f.inputStack; // computes the number of locals (ignores TOP types that are just after // a LONG or a DOUBLE, and all trailing TOP types) for (i = 0; i < locals.length; ++i) { t = locals[i]; if (t == Frame.TOP) { ++nTop; } else { nLocal += nTop + 1; nTop = 0; } if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } // computes the stack size (ignores TOP types that are just after // a LONG or a DOUBLE) for (i = 0; i < stacks.length; ++i) { t = stacks[i]; ++nStack; if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } // visits the frame and its content startFrame(f.owner.position, nLocal, nStack); for (i = 0; nLocal > 0; ++i, --nLocal) { t = locals[i]; frame[frameIndex++] = t; if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } for (i = 0; i < stacks.length; ++i) { t = stacks[i]; frame[frameIndex++] = t; if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } endFrame(); } /** * Starts the visit of a stack map frame. * * @param offset the offset of the instruction to which the frame * corresponds. * @param nLocal the number of local variables in the frame. * @param nStack the number of stack elements in the frame. */ private void startFrame(final int offset, final int nLocal, final int nStack) { int n = 3 + nLocal + nStack; if (frame == null || frame.length < n) { frame = new int[n]; } frame[0] = offset; frame[1] = nLocal; frame[2] = nStack; frameIndex = 3; } /** * Checks if the visit of the current frame {@link #frame} is finished, and * if yes, write it in the StackMapTable attribute. */ private void endFrame() { if (previousFrame != null) { // do not write the first frame if (stackMap == null) { stackMap = new ByteVector(); } writeFrame(); ++frameCount; } previousFrame = frame; frame = null; } /** * Compress and writes the current frame {@link #frame} in the StackMapTable * attribute. */ private void writeFrame() { int clocalsSize = frame[1]; int cstackSize = frame[2]; if ((cw.version & 0xFFFF) < Opcodes.V1_6) { stackMap.putShort(frame[0]).putShort(clocalsSize); writeFrameTypes(3, 3 + clocalsSize); stackMap.putShort(cstackSize); writeFrameTypes(3 + clocalsSize, 3 + clocalsSize + cstackSize); return; } int localsSize = previousFrame[1]; int type = FULL_FRAME; int k = 0; int delta; if (frameCount == 0) { delta = frame[0]; } else { delta = frame[0] - previousFrame[0] - 1; } if (cstackSize == 0) { k = clocalsSize - localsSize; switch (k) { case -3: case -2: case -1: type = CHOP_FRAME; localsSize = clocalsSize; break; case 0: type = delta < 64 ? SAME_FRAME : SAME_FRAME_EXTENDED; break; case 1: case 2: case 3: type = APPEND_FRAME; break; } } else if (clocalsSize == localsSize && cstackSize == 1) { type = delta < 63 ? SAME_LOCALS_1_STACK_ITEM_FRAME : SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED; } if (type != FULL_FRAME) { // verify if locals are the same int l = 3; for (int j = 0; j < localsSize; j++) { if (frame[l] != previousFrame[l]) { type = FULL_FRAME; break; } l++; } } switch (type) { case SAME_FRAME: stackMap.putByte(delta); break; case SAME_LOCALS_1_STACK_ITEM_FRAME: stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME + delta); writeFrameTypes(3 + clocalsSize, 4 + clocalsSize); break; case SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED: stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) .putShort(delta); writeFrameTypes(3 + clocalsSize, 4 + clocalsSize); break; case SAME_FRAME_EXTENDED: stackMap.putByte(SAME_FRAME_EXTENDED).putShort(delta); break; case CHOP_FRAME: stackMap.putByte(SAME_FRAME_EXTENDED + k).putShort(delta); break; case APPEND_FRAME: stackMap.putByte(SAME_FRAME_EXTENDED + k).putShort(delta); writeFrameTypes(3 + localsSize, 3 + clocalsSize); break; // case FULL_FRAME: default: stackMap.putByte(FULL_FRAME) .putShort(delta) .putShort(clocalsSize); writeFrameTypes(3, 3 + clocalsSize); stackMap.putShort(cstackSize); writeFrameTypes(3 + clocalsSize, 3 + clocalsSize + cstackSize); } } /** * Writes some types of the current frame {@link #frame} into the * StackMapTableAttribute. This method converts types from the format used * in {@link Label} to the format used in StackMapTable attributes. In * particular, it converts type table indexes to constant pool indexes. * * @param start index of the first type in {@link #frame} to write. * @param end index of last type in {@link #frame} to write (exclusive). */ private void writeFrameTypes(final int start, final int end) { for (int i = start; i < end; ++i) { int t = frame[i]; int d = t & Frame.DIM; if (d == 0) { int v = t & Frame.BASE_VALUE; switch (t & Frame.BASE_KIND) { case Frame.OBJECT: stackMap.putByte(7) .putShort(cw.newClass(cw.typeTable[v].strVal1)); break; case Frame.UNINITIALIZED: stackMap.putByte(8).putShort(cw.typeTable[v].intVal); break; default: stackMap.putByte(v); } } else { StringBuffer buf = new StringBuffer(); d >>= 28; while (d-- > 0) { buf.append('['); } if ((t & Frame.BASE_KIND) == Frame.OBJECT) { buf.append('L'); buf.append(cw.typeTable[t & Frame.BASE_VALUE].strVal1); buf.append(';'); } else { switch (t & 0xF) { case 1: buf.append('I'); break; case 2: buf.append('F'); break; case 3: buf.append('D'); break; case 9: buf.append('Z'); break; case 10: buf.append('B'); break; case 11: buf.append('C'); break; case 12: buf.append('S'); break; default: buf.append('J'); } } stackMap.putByte(7).putShort(cw.newClass(buf.toString())); } } } private void writeFrameType(final Object type) { if (type instanceof String) { stackMap.putByte(7).putShort(cw.newClass((String) type)); } else if (type instanceof Integer) { stackMap.putByte(((Integer) type).intValue()); } else { stackMap.putByte(8).putShort(((Label) type).position); } } // ------------------------------------------------------------------------ // Utility methods: dump bytecode array // ------------------------------------------------------------------------ /** * Returns the size of the bytecode of this method. * * @return the size of the bytecode of this method. */ final int getSize() { if (classReaderOffset != 0) { return 6 + classReaderLength; } if (resize) { // replaces the temporary jump opcodes introduced by Label.resolve. if (ClassReader.RESIZE) { resizeInstructions(); } else { throw new RuntimeException("Method code too large!"); } } int size = 8; if (code.length > 0) { if (code.length > 65536) { throw new RuntimeException("Method code too large!"); } cw.newUTF8("Code"); size += 18 + code.length + 8 * handlerCount; if (localVar != null) { cw.newUTF8("LocalVariableTable"); size += 8 + localVar.length; } if (localVarType != null) { cw.newUTF8("LocalVariableTypeTable"); size += 8 + localVarType.length; } if (lineNumber != null) { cw.newUTF8("LineNumberTable"); size += 8 + lineNumber.length; } if (stackMap != null) { boolean zip = (cw.version & 0xFFFF) >= Opcodes.V1_6; cw.newUTF8(zip ? "StackMapTable" : "StackMap"); size += 8 + stackMap.length; } if (cattrs != null) { size += cattrs.getSize(cw, code.data, code.length, maxStack, maxLocals); } } if (exceptionCount > 0) { cw.newUTF8("Exceptions"); size += 8 + 2 * exceptionCount; } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0)) { cw.newUTF8("Synthetic"); size += 6; } if ((access & Opcodes.ACC_DEPRECATED) != 0) { cw.newUTF8("Deprecated"); size += 6; } if (ClassReader.SIGNATURES && signature != null) { cw.newUTF8("Signature"); cw.newUTF8(signature); size += 8; } if (ClassReader.ANNOTATIONS && annd != null) { cw.newUTF8("AnnotationDefault"); size += 6 + annd.length; } if (ClassReader.ANNOTATIONS && anns != null) { cw.newUTF8("RuntimeVisibleAnnotations"); size += 8 + anns.getSize(); } if (ClassReader.ANNOTATIONS && ianns != null) { cw.newUTF8("RuntimeInvisibleAnnotations"); size += 8 + ianns.getSize(); } if (ClassReader.ANNOTATIONS && panns != null) { cw.newUTF8("RuntimeVisibleParameterAnnotations"); size += 7 + 2 * (panns.length - synthetics); for (int i = panns.length - 1; i >= synthetics; --i) { size += panns[i] == null ? 0 : panns[i].getSize(); } } if (ClassReader.ANNOTATIONS && ipanns != null) { cw.newUTF8("RuntimeInvisibleParameterAnnotations"); size += 7 + 2 * (ipanns.length - synthetics); for (int i = ipanns.length - 1; i >= synthetics; --i) { size += ipanns[i] == null ? 0 : ipanns[i].getSize(); } } if (attrs != null) { size += attrs.getSize(cw, null, 0, -1, -1); } return size; } /** * Puts the bytecode of this method in the given byte vector. * * @param out the byte vector into which the bytecode of this method must be * copied. */ final void put(final ByteVector out) { int mask = Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC)); out.putShort(access & ~mask).putShort(name).putShort(desc); if (classReaderOffset != 0) { out.putByteArray(cw.cr.b, classReaderOffset, classReaderLength); return; } int attributeCount = 0; if (code.length > 0) { ++attributeCount; } if (exceptionCount > 0) { ++attributeCount; } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0)) { ++attributeCount; } if ((access & Opcodes.ACC_DEPRECATED) != 0) { ++attributeCount; } if (ClassReader.SIGNATURES && signature != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && annd != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && anns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && ianns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && panns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && ipanns != null) { ++attributeCount; } if (attrs != null) { attributeCount += attrs.getCount(); } out.putShort(attributeCount); if (code.length > 0) { int size = 12 + code.length + 8 * handlerCount; if (localVar != null) { size += 8 + localVar.length; } if (localVarType != null) { size += 8 + localVarType.length; } if (lineNumber != null) { size += 8 + lineNumber.length; } if (stackMap != null) { size += 8 + stackMap.length; } if (cattrs != null) { size += cattrs.getSize(cw, code.data, code.length, maxStack, maxLocals); } out.putShort(cw.newUTF8("Code")).putInt(size); out.putShort(maxStack).putShort(maxLocals); out.putInt(code.length).putByteArray(code.data, 0, code.length); out.putShort(handlerCount); if (handlerCount > 0) { Handler h = firstHandler; while (h != null) { out.putShort(h.start.position) .putShort(h.end.position) .putShort(h.handler.position) .putShort(h.type); h = h.next; } } attributeCount = 0; if (localVar != null) { ++attributeCount; } if (localVarType != null) { ++attributeCount; } if (lineNumber != null) { ++attributeCount; } if (stackMap != null) { ++attributeCount; } if (cattrs != null) { attributeCount += cattrs.getCount(); } out.putShort(attributeCount); if (localVar != null) { out.putShort(cw.newUTF8("LocalVariableTable")); out.putInt(localVar.length + 2).putShort(localVarCount); out.putByteArray(localVar.data, 0, localVar.length); } if (localVarType != null) { out.putShort(cw.newUTF8("LocalVariableTypeTable")); out.putInt(localVarType.length + 2).putShort(localVarTypeCount); out.putByteArray(localVarType.data, 0, localVarType.length); } if (lineNumber != null) { out.putShort(cw.newUTF8("LineNumberTable")); out.putInt(lineNumber.length + 2).putShort(lineNumberCount); out.putByteArray(lineNumber.data, 0, lineNumber.length); } if (stackMap != null) { boolean zip = (cw.version & 0xFFFF) >= Opcodes.V1_6; out.putShort(cw.newUTF8(zip ? "StackMapTable" : "StackMap")); out.putInt(stackMap.length + 2).putShort(frameCount); out.putByteArray(stackMap.data, 0, stackMap.length); } if (cattrs != null) { cattrs.put(cw, code.data, code.length, maxLocals, maxStack, out); } } if (exceptionCount > 0) { out.putShort(cw.newUTF8("Exceptions")) .putInt(2 * exceptionCount + 2); out.putShort(exceptionCount); for (int i = 0; i < exceptionCount; ++i) { out.putShort(exceptions[i]); } } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0)) { out.putShort(cw.newUTF8("Synthetic")).putInt(0); } if ((access & Opcodes.ACC_DEPRECATED) != 0) { out.putShort(cw.newUTF8("Deprecated")).putInt(0); } if (ClassReader.SIGNATURES && signature != null) { out.putShort(cw.newUTF8("Signature")) .putInt(2) .putShort(cw.newUTF8(signature)); } if (ClassReader.ANNOTATIONS && annd != null) { out.putShort(cw.newUTF8("AnnotationDefault")); out.putInt(annd.length); out.putByteArray(annd.data, 0, annd.length); } if (ClassReader.ANNOTATIONS && anns != null) { out.putShort(cw.newUTF8("RuntimeVisibleAnnotations")); anns.put(out); } if (ClassReader.ANNOTATIONS && ianns != null) { out.putShort(cw.newUTF8("RuntimeInvisibleAnnotations")); ianns.put(out); } if (ClassReader.ANNOTATIONS && panns != null) { out.putShort(cw.newUTF8("RuntimeVisibleParameterAnnotations")); AnnotationWriter.put(panns, synthetics, out); } if (ClassReader.ANNOTATIONS && ipanns != null) { out.putShort(cw.newUTF8("RuntimeInvisibleParameterAnnotations")); AnnotationWriter.put(ipanns, synthetics, out); } if (attrs != null) { attrs.put(cw, null, 0, -1, -1, out); } } // ------------------------------------------------------------------------ // Utility methods: instruction resizing (used to handle GOTO_W and JSR_W) // ------------------------------------------------------------------------ /** * Resizes and replaces the temporary instructions inserted by * {@link Label#resolve} for wide forward jumps, while keeping jump offsets * and instruction addresses consistent. This may require to resize other * existing instructions, or even to introduce new instructions: for * example, increasing the size of an instruction by 2 at the middle of a * method can increases the offset of an IFEQ instruction from 32766 to * 32768, in which case IFEQ 32766 must be replaced with IFNEQ 8 GOTO_W * 32765. This, in turn, may require to increase the size of another jump * instruction, and so on... All these operations are handled automatically * by this method.

This method must be called after all the method * that is being built has been visited. In particular, the * {@link Label Label} objects used to construct the method are no longer * valid after this method has been called. */ private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFDYNMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFDYNMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort(b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } /** * Reads an unsigned short value in the given byte array. * * @param b a byte array. * @param index the start index of the value to be read. * @return the read value. */ static int readUnsignedShort(final byte[] b, final int index) { return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF); } /** * Reads a signed short value in the given byte array. * * @param b a byte array. * @param index the start index of the value to be read. * @return the read value. */ static short readShort(final byte[] b, final int index) { return (short) (((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF)); } /** * Reads a signed int value in the given byte array. * * @param b a byte array. * @param index the start index of the value to be read. * @return the read value. */ static int readInt(final byte[] b, final int index) { return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16) | ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF); } /** * Writes a short value in the given byte array. * * @param b a byte array. * @param index where the first byte of the short value must be written. * @param s the value to be written in the given byte array. */ static void writeShort(final byte[] b, final int index, final int s) { b[index] = (byte) (s >>> 8); b[index + 1] = (byte) s; } /** * Computes the future value of a bytecode offset.

Note: it is possible * to have several entries for the same instruction in the indexes * and sizes: two entries (index=a,size=b) and (index=a,size=b') * are equivalent to a single entry (index=a,size=b+b'). * * @param indexes current positions of the instructions to be resized. Each * instruction must be designated by the index of its last * byte, plus one (or, in other words, by the index of the first * byte of the next instruction). * @param sizes the number of bytes to be added to the above * instructions. More precisely, for each i < len, * sizes[i] bytes will be added at the end of the * instruction designated by indexes[i] or, if * sizes[i] is negative, the last |sizes[i]| * bytes of the instruction will be removed (the instruction size * must not become negative or null). * @param begin index of the first byte of the source instruction. * @param end index of the first byte of the target instruction. * @return the future value of the given bytecode offset. */ static int getNewOffset( final int[] indexes, final int[] sizes, final int begin, final int end) { int offset = end - begin; for (int i = 0; i < indexes.length; ++i) { if (begin < indexes[i] && indexes[i] <= end) { // forward jump offset += sizes[i]; } else if (end < indexes[i] && indexes[i] <= begin) { // backward jump offset -= sizes[i]; } } return offset; } /** * Updates the offset of the given label. * * @param indexes current positions of the instructions to be resized. Each * instruction must be designated by the index of its last * byte, plus one (or, in other words, by the index of the first * byte of the next instruction). * @param sizes the number of bytes to be added to the above * instructions. More precisely, for each i < len, * sizes[i] bytes will be added at the end of the * instruction designated by indexes[i] or, if * sizes[i] is negative, the last |sizes[i]| * bytes of the instruction will be removed (the instruction size * must not become negative or null). * @param label the label whose offset must be updated. */ static void getNewOffset( final int[] indexes, final int[] sizes, final Label label) { if ((label.status & Label.RESIZED) == 0) { label.position = getNewOffset(indexes, sizes, 0, label.position); label.status |= Label.RESIZED; } } } Opcodes.java000066400000000000000000000252701167051330000413250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; /** * Defines the JVM opcodes, access flags and array type codes. This interface * does not define all the JVM opcodes because some opcodes are automatically * handled. For example, the xLOAD and xSTORE opcodes are automatically replaced * by xLOAD_n and xSTORE_n opcodes when possible. The xLOAD_n and xSTORE_n * opcodes are therefore not defined in this interface. Likewise for LDC, * automatically replaced by LDC_W or LDC2_W when necessary, WIDE, GOTO_W and * JSR_W. * * @author Eric Bruneton * @author Eugene Kuleshov */ public interface Opcodes { // versions int V1_1 = 3 << 16 | 45; int V1_2 = 0 << 16 | 46; int V1_3 = 0 << 16 | 47; int V1_4 = 0 << 16 | 48; int V1_5 = 0 << 16 | 49; int V1_6 = 0 << 16 | 50; int V1_7 = 0 << 16 | 51; // access flags int ACC_PUBLIC = 0x0001; // class, field, method int ACC_PRIVATE = 0x0002; // class, field, method int ACC_PROTECTED = 0x0004; // class, field, method int ACC_STATIC = 0x0008; // field, method int ACC_FINAL = 0x0010; // class, field, method int ACC_SUPER = 0x0020; // class int ACC_SYNCHRONIZED = 0x0020; // method int ACC_VOLATILE = 0x0040; // field int ACC_BRIDGE = 0x0040; // method int ACC_VARARGS = 0x0080; // method int ACC_TRANSIENT = 0x0080; // field int ACC_NATIVE = 0x0100; // method int ACC_INTERFACE = 0x0200; // class int ACC_ABSTRACT = 0x0400; // class, method int ACC_STRICT = 0x0800; // method int ACC_SYNTHETIC = 0x1000; // class, field, method int ACC_ANNOTATION = 0x2000; // class int ACC_ENUM = 0x4000; // class(?) field inner // ASM specific pseudo access flags int ACC_DEPRECATED = 0x20000; // class, field, method // types for NEWARRAY int T_BOOLEAN = 4; int T_CHAR = 5; int T_FLOAT = 6; int T_DOUBLE = 7; int T_BYTE = 8; int T_SHORT = 9; int T_INT = 10; int T_LONG = 11; // stack map frame types /** * Represents an expanded frame. See {@link ClassReader#EXPAND_FRAMES}. */ int F_NEW = -1; /** * Represents a compressed frame with complete frame data. */ int F_FULL = 0; /** * Represents a compressed frame where locals are the same as the locals in * the previous frame, except that additional 1-3 locals are defined, and * with an empty stack. */ int F_APPEND = 1; /** * Represents a compressed frame where locals are the same as the locals in * the previous frame, except that the last 1-3 locals are absent and with * an empty stack. */ int F_CHOP = 2; /** * Represents a compressed frame with exactly the same locals as the * previous frame and with an empty stack. */ int F_SAME = 3; /** * Represents a compressed frame with exactly the same locals as the * previous frame and with a single value on the stack. */ int F_SAME1 = 4; Integer TOP = Integer.valueOf(0); Integer INTEGER = Integer.valueOf(1); Integer FLOAT = Integer.valueOf(2); Integer DOUBLE = Integer.valueOf(3); Integer LONG = Integer.valueOf(4); Integer NULL = Integer.valueOf(5); Integer UNINITIALIZED_THIS = Integer.valueOf(6); /** * Represents a owner of an invokedynamic call. */ String INVOKEDYNAMIC_OWNER = "java/lang/dyn/Dynamic"; // opcodes // visit method (- = idem) int NOP = 0; // visitInsn int ACONST_NULL = 1; // - int ICONST_M1 = 2; // - int ICONST_0 = 3; // - int ICONST_1 = 4; // - int ICONST_2 = 5; // - int ICONST_3 = 6; // - int ICONST_4 = 7; // - int ICONST_5 = 8; // - int LCONST_0 = 9; // - int LCONST_1 = 10; // - int FCONST_0 = 11; // - int FCONST_1 = 12; // - int FCONST_2 = 13; // - int DCONST_0 = 14; // - int DCONST_1 = 15; // - int BIPUSH = 16; // visitIntInsn int SIPUSH = 17; // - int LDC = 18; // visitLdcInsn // int LDC_W = 19; // - // int LDC2_W = 20; // - int ILOAD = 21; // visitVarInsn int LLOAD = 22; // - int FLOAD = 23; // - int DLOAD = 24; // - int ALOAD = 25; // - // int ILOAD_0 = 26; // - // int ILOAD_1 = 27; // - // int ILOAD_2 = 28; // - // int ILOAD_3 = 29; // - // int LLOAD_0 = 30; // - // int LLOAD_1 = 31; // - // int LLOAD_2 = 32; // - // int LLOAD_3 = 33; // - // int FLOAD_0 = 34; // - // int FLOAD_1 = 35; // - // int FLOAD_2 = 36; // - // int FLOAD_3 = 37; // - // int DLOAD_0 = 38; // - // int DLOAD_1 = 39; // - // int DLOAD_2 = 40; // - // int DLOAD_3 = 41; // - // int ALOAD_0 = 42; // - // int ALOAD_1 = 43; // - // int ALOAD_2 = 44; // - // int ALOAD_3 = 45; // - int IALOAD = 46; // visitInsn int LALOAD = 47; // - int FALOAD = 48; // - int DALOAD = 49; // - int AALOAD = 50; // - int BALOAD = 51; // - int CALOAD = 52; // - int SALOAD = 53; // - int ISTORE = 54; // visitVarInsn int LSTORE = 55; // - int FSTORE = 56; // - int DSTORE = 57; // - int ASTORE = 58; // - // int ISTORE_0 = 59; // - // int ISTORE_1 = 60; // - // int ISTORE_2 = 61; // - // int ISTORE_3 = 62; // - // int LSTORE_0 = 63; // - // int LSTORE_1 = 64; // - // int LSTORE_2 = 65; // - // int LSTORE_3 = 66; // - // int FSTORE_0 = 67; // - // int FSTORE_1 = 68; // - // int FSTORE_2 = 69; // - // int FSTORE_3 = 70; // - // int DSTORE_0 = 71; // - // int DSTORE_1 = 72; // - // int DSTORE_2 = 73; // - // int DSTORE_3 = 74; // - // int ASTORE_0 = 75; // - // int ASTORE_1 = 76; // - // int ASTORE_2 = 77; // - // int ASTORE_3 = 78; // - int IASTORE = 79; // visitInsn int LASTORE = 80; // - int FASTORE = 81; // - int DASTORE = 82; // - int AASTORE = 83; // - int BASTORE = 84; // - int CASTORE = 85; // - int SASTORE = 86; // - int POP = 87; // - int POP2 = 88; // - int DUP = 89; // - int DUP_X1 = 90; // - int DUP_X2 = 91; // - int DUP2 = 92; // - int DUP2_X1 = 93; // - int DUP2_X2 = 94; // - int SWAP = 95; // - int IADD = 96; // - int LADD = 97; // - int FADD = 98; // - int DADD = 99; // - int ISUB = 100; // - int LSUB = 101; // - int FSUB = 102; // - int DSUB = 103; // - int IMUL = 104; // - int LMUL = 105; // - int FMUL = 106; // - int DMUL = 107; // - int IDIV = 108; // - int LDIV = 109; // - int FDIV = 110; // - int DDIV = 111; // - int IREM = 112; // - int LREM = 113; // - int FREM = 114; // - int DREM = 115; // - int INEG = 116; // - int LNEG = 117; // - int FNEG = 118; // - int DNEG = 119; // - int ISHL = 120; // - int LSHL = 121; // - int ISHR = 122; // - int LSHR = 123; // - int IUSHR = 124; // - int LUSHR = 125; // - int IAND = 126; // - int LAND = 127; // - int IOR = 128; // - int LOR = 129; // - int IXOR = 130; // - int LXOR = 131; // - int IINC = 132; // visitIincInsn int I2L = 133; // visitInsn int I2F = 134; // - int I2D = 135; // - int L2I = 136; // - int L2F = 137; // - int L2D = 138; // - int F2I = 139; // - int F2L = 140; // - int F2D = 141; // - int D2I = 142; // - int D2L = 143; // - int D2F = 144; // - int I2B = 145; // - int I2C = 146; // - int I2S = 147; // - int LCMP = 148; // - int FCMPL = 149; // - int FCMPG = 150; // - int DCMPL = 151; // - int DCMPG = 152; // - int IFEQ = 153; // visitJumpInsn int IFNE = 154; // - int IFLT = 155; // - int IFGE = 156; // - int IFGT = 157; // - int IFLE = 158; // - int IF_ICMPEQ = 159; // - int IF_ICMPNE = 160; // - int IF_ICMPLT = 161; // - int IF_ICMPGE = 162; // - int IF_ICMPGT = 163; // - int IF_ICMPLE = 164; // - int IF_ACMPEQ = 165; // - int IF_ACMPNE = 166; // - int GOTO = 167; // - int JSR = 168; // - int RET = 169; // visitVarInsn int TABLESWITCH = 170; // visiTableSwitchInsn int LOOKUPSWITCH = 171; // visitLookupSwitch int IRETURN = 172; // visitInsn int LRETURN = 173; // - int FRETURN = 174; // - int DRETURN = 175; // - int ARETURN = 176; // - int RETURN = 177; // - int GETSTATIC = 178; // visitFieldInsn int PUTSTATIC = 179; // - int GETFIELD = 180; // - int PUTFIELD = 181; // - int INVOKEVIRTUAL = 182; // visitMethodInsn int INVOKESPECIAL = 183; // - int INVOKESTATIC = 184; // - int INVOKEINTERFACE = 185; // - int INVOKEDYNAMIC = 186; // - int NEW = 187; // visitTypeInsn int NEWARRAY = 188; // visitIntInsn int ANEWARRAY = 189; // visitTypeInsn int ARRAYLENGTH = 190; // visitInsn int ATHROW = 191; // - int CHECKCAST = 192; // visitTypeInsn int INSTANCEOF = 193; // - int MONITORENTER = 194; // visitInsn int MONITOREXIT = 195; // - // int WIDE = 196; // NOT VISITED int MULTIANEWARRAY = 197; // visitMultiANewArrayInsn int IFNULL = 198; // visitJumpInsn int IFNONNULL = 199; // - // int GOTO_W = 200; // - // int JSR_W = 201; // - } Type.java000066400000000000000000000620221167051330000406460ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.sonatype.guice.bean.scanners.asm; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * A Java type. This class can be used to make it easier to manipulate type and * method descriptors. * * @author Eric Bruneton * @author Chris Nokleberg */ public class Type { /** * The sort of the void type. See {@link #getSort getSort}. */ public static final int VOID = 0; /** * The sort of the boolean type. See {@link #getSort getSort}. */ public static final int BOOLEAN = 1; /** * The sort of the char type. See {@link #getSort getSort}. */ public static final int CHAR = 2; /** * The sort of the byte type. See {@link #getSort getSort}. */ public static final int BYTE = 3; /** * The sort of the short type. See {@link #getSort getSort}. */ public static final int SHORT = 4; /** * The sort of the int type. See {@link #getSort getSort}. */ public static final int INT = 5; /** * The sort of the float type. See {@link #getSort getSort}. */ public static final int FLOAT = 6; /** * The sort of the long type. See {@link #getSort getSort}. */ public static final int LONG = 7; /** * The sort of the double type. See {@link #getSort getSort}. */ public static final int DOUBLE = 8; /** * The sort of array reference types. See {@link #getSort getSort}. */ public static final int ARRAY = 9; /** * The sort of object reference type. See {@link #getSort getSort}. */ public static final int OBJECT = 10; /** * The void type. */ public static final Type VOID_TYPE = new Type(VOID, null, ('V' << 24) | (5 << 16) | (0 << 8) | 0, 1); /** * The boolean type. */ public static final Type BOOLEAN_TYPE = new Type(BOOLEAN, null, ('Z' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The char type. */ public static final Type CHAR_TYPE = new Type(CHAR, null, ('C' << 24) | (0 << 16) | (6 << 8) | 1, 1); /** * The byte type. */ public static final Type BYTE_TYPE = new Type(BYTE, null, ('B' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The short type. */ public static final Type SHORT_TYPE = new Type(SHORT, null, ('S' << 24) | (0 << 16) | (7 << 8) | 1, 1); /** * The int type. */ public static final Type INT_TYPE = new Type(INT, null, ('I' << 24) | (0 << 16) | (0 << 8) | 1, 1); /** * The float type. */ public static final Type FLOAT_TYPE = new Type(FLOAT, null, ('F' << 24) | (2 << 16) | (2 << 8) | 1, 1); /** * The long type. */ public static final Type LONG_TYPE = new Type(LONG, null, ('J' << 24) | (1 << 16) | (1 << 8) | 2, 1); /** * The double type. */ public static final Type DOUBLE_TYPE = new Type(DOUBLE, null, ('D' << 24) | (3 << 16) | (3 << 8) | 2, 1); // ------------------------------------------------------------------------ // Fields // ------------------------------------------------------------------------ /** * The sort of this Java type. */ private final int sort; /** * A buffer containing the internal name of this Java type. This field is * only used for reference types. */ private final char[] buf; /** * The offset of the internal name of this Java type in {@link #buf buf} or, * for primitive types, the size, descriptor and getOpcode offsets for this * type (byte 0 contains the size, byte 1 the descriptor, byte 2 the offset * for IALOAD or IASTORE, byte 3 the offset for all other instructions). */ private final int off; /** * The length of the internal name of this Java type. */ private final int len; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Constructs a reference type. * * @param sort the sort of the reference type to be constructed. * @param buf a buffer containing the descriptor of the previous type. * @param off the offset of this descriptor in the previous buffer. * @param len the length of this descriptor. */ private Type(final int sort, final char[] buf, final int off, final int len) { this.sort = sort; this.buf = buf; this.off = off; this.len = len; } /** * Returns the Java type corresponding to the given type descriptor. * * @param typeDescriptor a type descriptor. * @return the Java type corresponding to the given type descriptor. */ public static Type getType(final String typeDescriptor) { return getType(typeDescriptor.toCharArray(), 0); } /** * Returns the Java type corresponding to the given internal name. * * @param internalName an internal name. * @return the Java type corresponding to the given internal name. */ public static Type getObjectType(final String internalName) { char[] buf = internalName.toCharArray(); return new Type(buf[0] == '[' ? ARRAY : OBJECT, buf, 0, buf.length); } /** * Returns the Java type corresponding to the given class. * * @param c a class. * @return the Java type corresponding to the given class. */ public static Type getType(final Class c) { if (c.isPrimitive()) { if (c == Integer.TYPE) { return INT_TYPE; } else if (c == Void.TYPE) { return VOID_TYPE; } else if (c == Boolean.TYPE) { return BOOLEAN_TYPE; } else if (c == Byte.TYPE) { return BYTE_TYPE; } else if (c == Character.TYPE) { return CHAR_TYPE; } else if (c == Short.TYPE) { return SHORT_TYPE; } else if (c == Double.TYPE) { return DOUBLE_TYPE; } else if (c == Float.TYPE) { return FLOAT_TYPE; } else /* if (c == Long.TYPE) */{ return LONG_TYPE; } } else { return getType(getDescriptor(c)); } } /** * Returns the Java types corresponding to the argument types of the given * method descriptor. * * @param methodDescriptor a method descriptor. * @return the Java types corresponding to the argument types of the given * method descriptor. */ public static Type[] getArgumentTypes(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); int off = 1; int size = 0; while (true) { char car = buf[off++]; if (car == ')') { break; } else if (car == 'L') { while (buf[off++] != ';') { } ++size; } else if (car != '[') { ++size; } } Type[] args = new Type[size]; off = 1; size = 0; while (buf[off] != ')') { args[size] = getType(buf, off); off += args[size].len + (args[size].sort == OBJECT ? 2 : 0); size += 1; } return args; } /** * Returns the Java types corresponding to the argument types of the given * method. * * @param method a method. * @return the Java types corresponding to the argument types of the given * method. */ public static Type[] getArgumentTypes(final Method method) { Class[] classes = method.getParameterTypes(); Type[] types = new Type[classes.length]; for (int i = classes.length - 1; i >= 0; --i) { types[i] = getType(classes[i]); } return types; } /** * Returns the Java type corresponding to the return type of the given * method descriptor. * * @param methodDescriptor a method descriptor. * @return the Java type corresponding to the return type of the given * method descriptor. */ public static Type getReturnType(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); return getType(buf, methodDescriptor.indexOf(')') + 1); } /** * Returns the Java type corresponding to the return type of the given * method. * * @param method a method. * @return the Java type corresponding to the return type of the given * method. */ public static Type getReturnType(final Method method) { return getType(method.getReturnType()); } /** * Computes the size of the arguments and of the return value of a method. * * @param desc the descriptor of a method. * @return the size of the arguments of the method (plus one for the * implicit this argument), argSize, and the size of its return * value, retSize, packed into a single int i = * (argSize << 2) | retSize (argSize is therefore equal * to i >> 2, and retSize to i & 0x03). */ public static int getArgumentsAndReturnSizes(final String desc) { int n = 1; int c = 1; while (true) { char car = desc.charAt(c++); if (car == ')') { car = desc.charAt(c); return n << 2 | (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1)); } else if (car == 'L') { while (desc.charAt(c++) != ';') { } n += 1; } else if (car == '[') { while ((car = desc.charAt(c)) == '[') { ++c; } if (car == 'D' || car == 'J') { n -= 1; } } else if (car == 'D' || car == 'J') { n += 2; } else { n += 1; } } } /** * Returns the Java type corresponding to the given type descriptor. * * @param buf a buffer containing a type descriptor. * @param off the offset of this descriptor in the previous buffer. * @return the Java type corresponding to the given type descriptor. */ private static Type getType(final char[] buf, final int off) { int len; switch (buf[off]) { case 'V': return VOID_TYPE; case 'Z': return BOOLEAN_TYPE; case 'C': return CHAR_TYPE; case 'B': return BYTE_TYPE; case 'S': return SHORT_TYPE; case 'I': return INT_TYPE; case 'F': return FLOAT_TYPE; case 'J': return LONG_TYPE; case 'D': return DOUBLE_TYPE; case '[': len = 1; while (buf[off + len] == '[') { ++len; } if (buf[off + len] == 'L') { ++len; while (buf[off + len] != ';') { ++len; } } return new Type(ARRAY, buf, off, len + 1); // case 'L': default: len = 1; while (buf[off + len] != ';') { ++len; } return new Type(OBJECT, buf, off + 1, len - 1); } } // ------------------------------------------------------------------------ // Accessors // ------------------------------------------------------------------------ /** * Returns the sort of this Java type. * * @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN}, * {@link #CHAR CHAR}, {@link #BYTE BYTE}, {@link #SHORT SHORT}, * {@link #INT INT}, {@link #FLOAT FLOAT}, {@link #LONG LONG}, * {@link #DOUBLE DOUBLE}, {@link #ARRAY ARRAY} or * {@link #OBJECT OBJECT}. */ public int getSort() { return sort; } /** * Returns the number of dimensions of this array type. This method should * only be used for an array type. * * @return the number of dimensions of this array type. */ public int getDimensions() { int i = 1; while (buf[off + i] == '[') { ++i; } return i; } /** * Returns the type of the elements of this array type. This method should * only be used for an array type. * * @return Returns the type of the elements of this array type. */ public Type getElementType() { return getType(buf, off + getDimensions()); } /** * Returns the binary name of the class corresponding to this type. * * @return the binary name of the class corresponding to this type. */ public String getClassName() { switch (sort) { case VOID: return "void"; case BOOLEAN: return "boolean"; case CHAR: return "char"; case BYTE: return "byte"; case SHORT: return "short"; case INT: return "int"; case FLOAT: return "float"; case LONG: return "long"; case DOUBLE: return "double"; case ARRAY: StringBuffer b = new StringBuffer(getElementType().getClassName()); for (int i = getDimensions(); i > 0; --i) { b.append("[]"); } return b.toString(); // case OBJECT: default: return new String(buf, off, len).replace('/', '.'); } } /** * Returns the internal name of the class corresponding to this object or * array type. The internal name of a class is its fully qualified name (as * returned by Class.getName(), where '.' are replaced by '/'. This method * should only be used for an object or array type. * * @return the internal name of the class corresponding to this object type. */ public String getInternalName() { return new String(buf, off, len); } // ------------------------------------------------------------------------ // Conversion to type descriptors // ------------------------------------------------------------------------ /** * Returns the descriptor corresponding to this Java type. * * @return the descriptor corresponding to this Java type. */ public String getDescriptor() { StringBuffer buf = new StringBuffer(); getDescriptor(buf); return buf.toString(); } /** * Returns the descriptor corresponding to the given argument and return * types. * * @param returnType the return type of the method. * @param argumentTypes the argument types of the method. * @return the descriptor corresponding to the given argument and return * types. */ public static String getMethodDescriptor( final Type returnType, final Type[] argumentTypes) { StringBuffer buf = new StringBuffer(); buf.append('('); for (int i = 0; i < argumentTypes.length; ++i) { argumentTypes[i].getDescriptor(buf); } buf.append(')'); returnType.getDescriptor(buf); return buf.toString(); } /** * Appends the descriptor corresponding to this Java type to the given * string buffer. * * @param buf the string buffer to which the descriptor must be appended. */ private void getDescriptor(final StringBuffer buf) { if (this.buf == null) { // descriptor is in byte 3 of 'off' for primitive types (buf == null) buf.append((char) ((off & 0xFF000000) >>> 24)); } else if (sort == ARRAY) { buf.append(this.buf, off, len); } else { // sort == OBJECT buf.append('L'); buf.append(this.buf, off, len); buf.append(';'); } } // ------------------------------------------------------------------------ // Direct conversion from classes to type descriptors, // without intermediate Type objects // ------------------------------------------------------------------------ /** * Returns the internal name of the given class. The internal name of a * class is its fully qualified name, as returned by Class.getName(), where * '.' are replaced by '/'. * * @param c an object or array class. * @return the internal name of the given class. */ public static String getInternalName(final Class c) { return c.getName().replace('.', '/'); } /** * Returns the descriptor corresponding to the given Java type. * * @param c an object class, a primitive class or an array class. * @return the descriptor corresponding to the given class. */ public static String getDescriptor(final Class c) { StringBuffer buf = new StringBuffer(); getDescriptor(buf, c); return buf.toString(); } /** * Returns the descriptor corresponding to the given constructor. * * @param c a {@link Constructor Constructor} object. * @return the descriptor of the given constructor. */ public static String getConstructorDescriptor(final Constructor c) { Class[] parameters = c.getParameterTypes(); StringBuffer buf = new StringBuffer(); buf.append('('); for (int i = 0; i < parameters.length; ++i) { getDescriptor(buf, parameters[i]); } return buf.append(")V").toString(); } /** * Returns the descriptor corresponding to the given method. * * @param m a {@link Method Method} object. * @return the descriptor of the given method. */ public static String getMethodDescriptor(final Method m) { Class[] parameters = m.getParameterTypes(); StringBuffer buf = new StringBuffer(); buf.append('('); for (int i = 0; i < parameters.length; ++i) { getDescriptor(buf, parameters[i]); } buf.append(')'); getDescriptor(buf, m.getReturnType()); return buf.toString(); } /** * Appends the descriptor of the given class to the given string buffer. * * @param buf the string buffer to which the descriptor must be appended. * @param c the class whose descriptor must be computed. */ private static void getDescriptor(final StringBuffer buf, final Class c) { Class d = c; while (true) { if (d.isPrimitive()) { char car; if (d == Integer.TYPE) { car = 'I'; } else if (d == Void.TYPE) { car = 'V'; } else if (d == Boolean.TYPE) { car = 'Z'; } else if (d == Byte.TYPE) { car = 'B'; } else if (d == Character.TYPE) { car = 'C'; } else if (d == Short.TYPE) { car = 'S'; } else if (d == Double.TYPE) { car = 'D'; } else if (d == Float.TYPE) { car = 'F'; } else /* if (d == Long.TYPE) */{ car = 'J'; } buf.append(car); return; } else if (d.isArray()) { buf.append('['); d = d.getComponentType(); } else { buf.append('L'); String name = d.getName(); int len = name.length(); for (int i = 0; i < len; ++i) { char car = name.charAt(i); buf.append(car == '.' ? '/' : car); } buf.append(';'); return; } } } // ------------------------------------------------------------------------ // Corresponding size and opcodes // ------------------------------------------------------------------------ /** * Returns the size of values of this type. * * @return the size of values of this type, i.e., 2 for long and * double, 0 for void and 1 otherwise. */ public int getSize() { // the size is in byte 0 of 'off' for primitive types (buf == null) return buf == null ? (off & 0xFF) : 1; } /** * Returns a JVM instruction opcode adapted to this Java type. * * @param opcode a JVM instruction opcode. This opcode must be one of ILOAD, * ISTORE, IALOAD, IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL, * ISHR, IUSHR, IAND, IOR, IXOR and IRETURN. * @return an opcode that is similar to the given opcode, but adapted to * this Java type. For example, if this type is float and * opcode is IRETURN, this method returns FRETURN. */ public int getOpcode(final int opcode) { if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) { // the offset for IALOAD or IASTORE is in byte 1 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF00) >> 8 : 4); } else { // the offset for other instructions is in byte 2 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF0000) >> 16 : 4); } } // ------------------------------------------------------------------------ // Equals, hashCode and toString // ------------------------------------------------------------------------ /** * Tests if the given object is equal to this type. * * @param o the object to be compared to this type. * @return true if the given object is equal to this type. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Type)) { return false; } Type t = (Type) o; if (sort != t.sort) { return false; } if (sort == OBJECT || sort == ARRAY) { if (len != t.len) { return false; } for (int i = off, j = t.off, end = i + len; i < end; i++, j++) { if (buf[i] != t.buf[j]) { return false; } } } return true; } /** * Returns a hash code value for this type. * * @return a hash code value for this type. */ public int hashCode() { int hc = 13 * sort; if (sort == OBJECT || sort == ARRAY) { for (int i = off, end = i + len; i < end; i++) { hc = 17 * (hc + buf[i]); } } return hc; } /** * Returns a string representation of this type. * * @return the descriptor of this type. */ public String toString() { return getDescriptor(); } } package-info.java000066400000000000000000000033721167051330000422540ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/asm/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /** * Repackaged subset of ASM classes. */ package org.sonatype.guice.bean.scanners.asm; 000077500000000000000000000000001167051330000374075ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/indexAbstractSisuIndex.java000066400000000000000000000117101167051330000436510ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/index/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners.index; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Skeleton class that generates a qualified class index. */ public abstract class AbstractSisuIndex { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Map> index = new HashMap>(); // ---------------------------------------------------------------------- // Common methods // ---------------------------------------------------------------------- /** * Adds a new annotated class entry to the index. * * @param anno The annotation name * @param clazz The class name */ protected synchronized final void addClassToIndex( final Object anno, final Object clazz ) { Set table = index.get( anno ); if ( null == table ) { table = readTable( anno ); index.put( anno, table ); } table.add( String.valueOf( clazz ) ); } /** * Writes the current index as a series of tables. */ protected synchronized final void flushIndex() { for ( final Entry> entry : index.entrySet() ) { writeTable( entry.getKey(), entry.getValue() ); } } // ---------------------------------------------------------------------- // Customizable methods // ---------------------------------------------------------------------- /** * Reports an informational message. * * @param message The message */ protected abstract void info( final String message ); /** * Reports a warning message. * * @param message The message */ protected abstract void warn( final String message ); /** * Creates a new reader for the given input path. * * @param path The input path * @return The relevant reader */ protected abstract Reader getReader( final String path ) throws IOException; /** * Creates a new writer for the given output path. * * @param path The output path * @return The relevant writer */ protected abstract Writer getWriter( final String path ) throws IOException; // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Reads the given index table from disk to memory. * * @param name The table name * @return Table elements */ private final Set readTable( final Object name ) { final Set table = new LinkedHashSet(); try { final BufferedReader reader = new BufferedReader( getReader( "META-INF/sisu/" + name ) ); try { for ( String line = reader.readLine(); line != null; line = reader.readLine() ) { table.add( line ); } } finally { reader.close(); } } catch ( final IOException e ) // NOPMD { // ignore missing index } return table; } /** * Writes the given index table from memory to disk. * * @param name The table name * @param table The elements */ private final void writeTable( final Object name, final Set table ) { try { final BufferedWriter writer = new BufferedWriter( getWriter( "META-INF/sisu/" + name ) ); try { for ( final String line : table ) { writer.write( line ); writer.newLine(); } } finally { writer.close(); } } catch ( final IOException e ) { warn( e.toString() ); } } } SisuIndex.java000066400000000000000000000115341167051330000421710ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/index/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners.index; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.lang.annotation.Annotation; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import javax.inject.Named; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.guice.bean.scanners.ClassSpaceScanner; import org.sonatype.guice.bean.scanners.QualifiedTypeListener; import org.sonatype.guice.bean.scanners.QualifiedTypeVisitor; /** * Command-line utility that generates a qualified class index for a space-separated list of JARs. */ public final class SisuIndex extends AbstractSisuIndex implements QualifiedTypeListener { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- public static final String NAMED = Named.class.getName(); // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final File targetDirectory; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public SisuIndex( final File targetDirectory ) { this.targetDirectory = targetDirectory; } // ---------------------------------------------------------------------- // Public entry points // ---------------------------------------------------------------------- public static void main( final String[] args ) { final List indexPath = new ArrayList( args.length ); for ( final String path : args ) { try { indexPath.add( new File( path ).toURI().toURL() ); } catch ( final MalformedURLException e ) { Logs.warn( "Bad classpath element: {}", path, e ); } } final ClassLoader parent = SisuIndex.class.getClassLoader(); final URL[] urls = indexPath.toArray( new URL[indexPath.size()] ); final ClassLoader loader = urls.length > 0 ? URLClassLoader.newInstance( urls, parent ) : parent; new SisuIndex( new File( "." ) ).index( new URLClassSpace( loader ) ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void index( final ClassSpace space ) { try { new ClassSpaceScanner( space ).accept( new QualifiedTypeVisitor( this ) ); } finally { flushIndex(); } } public void hear( final Annotation qualifier, final Class qualifiedType, final Object source ) { addClassToIndex( SisuIndex.NAMED, qualifiedType.getName() ); } // ---------------------------------------------------------------------- // Customized methods // ---------------------------------------------------------------------- @Override protected void info( final String message ) { System.out.println( "[INFO] " + message ); } @Override protected void warn( final String message ) { System.out.println( "[WARN] " + message ); } @Override protected Reader getReader( final String path ) throws IOException { return new FileReader( new File( targetDirectory, path ) ); } @Override protected Writer getWriter( final String path ) throws IOException { final File index = new File( targetDirectory, path ); final File parent = index.getParentFile(); if ( parent.isDirectory() || parent.mkdirs() ) { return new FileWriter( index ); } throw new IOException( "Error creating: " + parent ); } } SisuIndexAPT6.java000066400000000000000000000110051167051330000426150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/index/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners.index; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.util.Collections; import java.util.Set; import javax.annotation.processing.Completion; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.inject.Named; import javax.inject.Qualifier; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.tools.Diagnostic; import javax.tools.FileObject; import javax.tools.StandardLocation; /** * Java 6 Annotation {@link Processor} that generates a qualified class index for the current build. */ public final class SisuIndexAPT6 extends AbstractSisuIndex implements Processor { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private ProcessingEnvironment environment; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void init( final ProcessingEnvironment _environment ) { environment = _environment; } public boolean process( final Set annotations, final RoundEnvironment round ) { final Elements elementUtils = environment.getElementUtils(); for ( final TypeElement anno : annotations ) { if ( null != anno.getAnnotation( Qualifier.class ) ) { for ( final Element elem : round.getElementsAnnotatedWith( anno ) ) { if ( elem.getKind().isClass() ) { addClassToIndex( SisuIndex.NAMED, elementUtils.getBinaryName( (TypeElement) elem ) ); } } } } if ( round.processingOver() ) { flushIndex(); } return false; } public Iterable getCompletions( final Element element, final AnnotationMirror annotation, final ExecutableElement member, final String userText ) { return Collections.emptySet(); } public Set getSupportedAnnotationTypes() { return Collections.singleton( Named.class.getName() ); } public Set getSupportedOptions() { return Collections.emptySet(); } public SourceVersion getSupportedSourceVersion() { return SourceVersion.RELEASE_6; } // ---------------------------------------------------------------------- // Customized methods // ---------------------------------------------------------------------- @Override protected void info( final String msg ) { environment.getMessager().printMessage( Diagnostic.Kind.NOTE, msg ); } @Override protected void warn( final String msg ) { environment.getMessager().printMessage( Diagnostic.Kind.WARNING, msg ); } @Override protected Reader getReader( final String path ) throws IOException { final FileObject file = environment.getFiler().getResource( StandardLocation.CLASS_OUTPUT, "", path ); return new InputStreamReader( file.openInputStream() ); } @Override protected Writer getWriter( final String path ) throws IOException { return environment.getFiler().createResource( StandardLocation.CLASS_OUTPUT, "", path ).openWriter(); } } SisuIndexFinder.java000066400000000000000000000072561167051330000433270ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/index/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners.index; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.reflect.Streams; import org.sonatype.guice.bean.scanners.ClassFinder; /** * {@link ClassFinder} that uses the qualified class index to select implementations to scan. */ public final class SisuIndexFinder implements ClassFinder { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final boolean globalIndex; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public SisuIndexFinder( final boolean globalIndex ) { this.globalIndex = globalIndex; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Enumeration findClasses( final ClassSpace space ) { final List components = new ArrayList(); final Set visited = new HashSet(); final Enumeration indices; if ( globalIndex ) { indices = space.getResources( "META-INF/sisu/" + SisuIndex.NAMED ); } else { indices = space.findEntries( "META-INF/sisu/", SisuIndex.NAMED, false ); } while ( indices.hasMoreElements() ) { final URL url = indices.nextElement(); try { final BufferedReader reader = new BufferedReader( new InputStreamReader( Streams.open( url ) ) ); try { // each index file contains a list of classes with that qualifier, one per line for ( String line = reader.readLine(); line != null; line = reader.readLine() ) { if ( visited.add( line ) ) { final URL clazz = space.getResource( line.replace( '.', '/' ) + ".class" ); if ( null != clazz ) { components.add( clazz ); } } } } finally { reader.close(); } } catch ( final IOException e ) { Logs.warn( "Problem reading: {}", url, e ); } } return Collections.enumeration( components ); } } package-info.java000066400000000000000000000022551167051330000426020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/index/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * Qualified class index support (META-INF/sisu). * *

The principal members of this package are: *

*
{@link org.sonatype.guice.bean.scanners.index.SisuIndex} *
Command-line indexing tool. *
{@link org.sonatype.guice.bean.scanners.index.SisuIndexAPT6} *
Java 6 annotation processor. *
{@link org.sonatype.guice.bean.scanners.index.SisuIndexFinder} *
Index-driven {@link org.sonatype.guice.bean.scanners.ClassFinder}. *
*/ package org.sonatype.guice.bean.scanners.index; package-info.java000066400000000000000000000030511167051330000414660ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/main/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * ASM-based bean scanning. * *

The principal members of this package are: *

*
{@link org.sonatype.guice.bean.scanners.ClassSpaceVisitor} *
ASM-style visitor that can visit a {@link org.sonatype.guice.bean.reflect.ClassSpace}. *
{@link org.sonatype.guice.bean.scanners.ClassSpaceScanner} *
Makes a {@link org.sonatype.guice.bean.scanners.ClassSpaceVisitor} visit a {@link org.sonatype.guice.bean.reflect.ClassSpace}. *
{@link org.sonatype.guice.bean.scanners.QualifiedTypeListener} *
Listens out for types annotated with {@link javax.inject.Qualifier} annotations. *
{@link org.sonatype.guice.bean.scanners.QualifiedTypeVisitor} *
{@link org.sonatype.guice.bean.scanners.ClassSpaceVisitor} that reports types with {@link javax.inject.Qualifier} annotations. *
*/ package org.sonatype.guice.bean.scanners; sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/000077500000000000000000000000001167051330000272235ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/java/000077500000000000000000000000001167051330000301445ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/java/org/000077500000000000000000000000001167051330000307335ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/java/org/sonatype/000077500000000000000000000000001167051330000325755ustar00rootroot00000000000000000077500000000000000000000000001167051330000336125ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000345175ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/java/org/sonatype/guice/bean000077500000000000000000000000001167051330000363335ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/java/org/sonatype/guice/bean/scannersBrokenScanningExample.java000066400000000000000000000041701167051330000434150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.URLClassSpace; public class BrokenScanningExample { public BrokenScanningExample() throws MalformedURLException { final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); final URL badURL = new URL( "barf:up/" ); final ClassSpace brokenResourceSpace = new ClassSpace() { public Class loadClass( final String name ) { return space.loadClass( name ); } public DeferredClass deferLoadClass( final String name ) { return space.deferLoadClass( name ); } public Enumeration getResources( final String name ) { return space.getResources( name ); } public URL getResource( final String name ) { return badURL; } public Enumeration findEntries( final String path, final String glob, final boolean recurse ) { return space.findEntries( path, glob, recurse ); } }; new ClassSpaceScanner( brokenResourceSpace ).accept( new QualifiedTypeVisitor( null ) ); } } QualifiedScanningTest.java000066400000000000000000000305201167051330000434220ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/java/org/sonatype/guice/bean/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.inject.Named; import javax.inject.Qualifier; import javax.inject.Singleton; import junit.framework.TestCase; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.guice.bean.scanners.asm.AnnotationVisitor; import org.sonatype.guice.bean.scanners.asm.ClassVisitor; import org.sonatype.guice.bean.scanners.asm.Type; import org.sonatype.guice.bean.scanners.barf.Handler; import org.sonatype.guice.bean.scanners.index.SisuIndexFinder; public class QualifiedScanningTest extends TestCase { @Named interface A { } @Named static abstract class B { } @Named static class C { } @Qualifier @Retention( RetentionPolicy.RUNTIME ) public @interface Legacy { } @Named @Legacy static class D { } @Legacy @Named static class E { } static class F extends B { } @Singleton static class G { } static class TestListener implements QualifiedTypeListener { final List> clazzes = new ArrayList>(); final Set sources = new HashSet(); public void hear( final Annotation qualifier, final Class clazz, final Object source ) { clazzes.add( clazz ); sources.add( source ); } } public void testQualifiedScanning() { final TestListener listener = new TestListener(); final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); new ClassSpaceScanner( space ).accept( new QualifiedTypeVisitor( listener ) ); assertEquals( 3, listener.clazzes.size() ); assertTrue( listener.clazzes.contains( C.class ) ); assertTrue( listener.clazzes.contains( D.class ) ); assertTrue( listener.clazzes.contains( E.class ) ); } public void testAdaptedScanning() { final TestListener listener = new TestListener(); final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); final ClassSpaceVisitor visitor = new QualifiedTypeVisitor( listener ); new ClassSpaceScanner( space ).accept( new ClassSpaceVisitor() { public void visit( final ClassSpace _space ) { visitor.visit( _space ); } public ClassVisitor visitClass( final URL url ) { if ( url.toString().contains( "$D.class" ) ) { return null; } return visitor.visitClass( url ); } public void visitEnd() { visitor.visitEnd(); } } ); assertEquals( 2, listener.clazzes.size() ); assertTrue( listener.clazzes.contains( C.class ) ); assertTrue( listener.clazzes.contains( E.class ) ); } public void testFilteredScanning() { final TestListener listener = new TestListener(); final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); final ClassSpaceVisitor visitor = new QualifiedTypeVisitor( listener ); new ClassSpaceScanner( new ClassFinder() { public Enumeration findClasses( final ClassSpace space2 ) { return space2.findEntries( null, "*D.class", true ); } }, space ).accept( visitor ); assertEquals( 1, listener.clazzes.size() ); assertTrue( listener.clazzes.contains( D.class ) ); } public void testIndexedScanning() { final TestListener listener = new TestListener(); final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); final ClassSpaceVisitor visitor = new QualifiedTypeVisitor( listener ); new ClassSpaceScanner( new SisuIndexFinder( false ), space ).accept( visitor ); // we deliberately use a partial index assertEquals( 2, listener.clazzes.size() ); assertTrue( listener.clazzes.contains( C.class ) ); assertTrue( listener.clazzes.contains( D.class ) ); } public void testBrokenScanning() throws IOException { // System.setProperty( "java.protocol.handler.pkgs", getClass().getPackage().getName() ); URL.setURLStreamHandlerFactory( new URLStreamHandlerFactory() { public URLStreamHandler createURLStreamHandler( final String protocol ) { if ( "barf".equals( protocol ) ) { return new Handler(); } return null; } } ); final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); final URL badURL = new URL( "barf:up/" ); final ClassSpace brokenResourceSpace = new ClassSpace() { public Class loadClass( final String name ) { return space.loadClass( name ); } public DeferredClass deferLoadClass( final String name ) { return space.deferLoadClass( name ); } public Enumeration getResources( final String name ) { return space.getResources( name ); } public URL getResource( final String name ) { return badURL; } public Enumeration findEntries( final String path, final String glob, final boolean recurse ) { return Collections.enumeration( Collections.singleton( badURL ) ); } }; new ClassSpaceScanner( brokenResourceSpace ).accept( new QualifiedTypeVisitor( null ) ); final ClassSpace brokenLoadSpace = new ClassSpace() { public Class loadClass( final String name ) { throw new TypeNotPresentException( name, new ClassNotFoundException( name ) ); } public DeferredClass deferLoadClass( final String name ) { return space.deferLoadClass( name ); } public Enumeration getResources( final String name ) { return space.getResources( name ); } public URL getResource( final String name ) { return space.getResource( name ); } public Enumeration findEntries( final String path, final String glob, final boolean recurse ) { return space.findEntries( path, glob, recurse ); } }; new ClassSpaceScanner( brokenLoadSpace ).accept( new QualifiedTypeVisitor( null ) ); ClassSpaceScanner.accept( null, null ); assertFalse( new SisuIndexFinder( false ).findClasses( brokenResourceSpace ).hasMoreElements() ); } public void testSourceDetection() throws MalformedURLException { final TestListener listener = new TestListener(); final QualifiedTypeVisitor visitor = new QualifiedTypeVisitor( listener ); visitor.visit( new URLClassSpace( getClass().getClassLoader() ) ); assertEquals( 0, listener.sources.size() ); visitor.visitClass( new URL( "file:target/classes/java/lang/Object.class" ) ); visitor.visit( 0, 0, Type.getInternalName( Object.class ), null, null, null ); visitor.visitAnnotation( Type.getDescriptor( Named.class ), true ); visitor.visitEnd(); assertEquals( 1, listener.sources.size() ); assertTrue( listener.sources.contains( "target/classes/" ) ); visitor.visitClass( new URL( "jar:file:bar.jar!/java/lang/String.class" ) ); visitor.visit( 0, 0, Type.getInternalName( String.class ), null, null, null ); visitor.visitAnnotation( Type.getDescriptor( Named.class ), true ); visitor.visitEnd(); assertEquals( 2, listener.sources.size() ); assertTrue( listener.sources.contains( "target/classes/" ) ); assertTrue( listener.sources.contains( "file:bar.jar!/" ) ); visitor.visitClass( new URL( "file:some/obfuscated/location" ) ); visitor.visit( 0, 0, Type.getInternalName( Integer.class ), null, null, null ); visitor.visitAnnotation( Type.getDescriptor( Named.class ), true ); visitor.visitEnd(); assertEquals( 3, listener.sources.size() ); assertTrue( listener.sources.contains( "target/classes/" ) ); assertTrue( listener.sources.contains( "file:bar.jar!/" ) ); assertTrue( listener.sources.contains( "some/obfuscated/location" ) ); } public void testOptionalLogging() throws Exception { final Level level = Logger.getLogger( "" ).getLevel(); try { Logger.getLogger( "" ).setLevel( Level.SEVERE ); // check everything still works without any SLF4J jars final ClassLoader noLoggingLoader = new URLClassLoader( ( (URLClassLoader) getClass().getClassLoader() ).getURLs(), null ) { @Override protected synchronized Class loadClass( final String name, final boolean resolve ) throws ClassNotFoundException { if ( name.contains( "slf4j" ) ) { throw new ClassNotFoundException( name ); } if ( name.contains( "cobertura" ) ) { return QualifiedScanningTest.class.getClassLoader().loadClass( name ); } return super.loadClass( name, resolve ); } }; noLoggingLoader.loadClass( BrokenScanningExample.class.getName() ).newInstance(); } finally { Logger.getLogger( "" ).setLevel( level ); } } public void testEmptyMethods() { final AnnotationVisitor emptyAnnotationVisitor = new EmptyAnnotationVisitor(); emptyAnnotationVisitor.visit( null, null ); emptyAnnotationVisitor.visitEnum( null, null, null ); emptyAnnotationVisitor.visitAnnotation( null, null ); emptyAnnotationVisitor.visitArray( null ); emptyAnnotationVisitor.visitEnd(); final ClassVisitor emptyClassVisitor = new EmptyClassVisitor(); emptyClassVisitor.visit( 0, 0, null, null, null, null ); emptyClassVisitor.visitAnnotation( null, false ); emptyClassVisitor.visitAttribute( null ); emptyClassVisitor.visitSource( null, null ); emptyClassVisitor.visitEnd(); } public void testICU4J() { final ClassLoader loader = getClass().getClassLoader(); final URL[] urls = { loader.getResource( "icu4j-2.6.1.jar" ) }; final ClassSpace space = new URLClassSpace( loader, urls ); final TestListener listener = new TestListener(); new ClassSpaceScanner( space ).accept( new QualifiedTypeVisitor( listener ) ); assertEquals( 0, listener.clazzes.size() ); } } 000077500000000000000000000000001167051330000372455ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/java/org/sonatype/guice/bean/scanners/barfHandler.java000066400000000000000000000037031167051330000414700ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/java/org/sonatype/guice/bean/scanners/barf/******************************************************************************* * Copyright (c) 2009-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.bean.scanners.barf; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; public class Handler extends URLStreamHandler { @Override protected URLConnection openConnection( final URL url ) throws IOException { return new DodgyConnection( url ); } static class DodgyConnection extends URLConnection { DodgyConnection( final URL url ) { super( url ); } @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { final InputStream in = new ByteArrayInputStream( new byte[0] ); return new InputStream() { @Override public int read() throws IOException { return in.read(); } @Override public void close() throws IOException { throw new IOException(); } }; } } } sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/resources/000077500000000000000000000000001167051330000312355ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/resources/META-INF/000077500000000000000000000000001167051330000323755ustar00rootroot00000000000000000077500000000000000000000000001167051330000333015ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/resources/META-INF/sisujavax.inject.Named000066400000000000000000000003271167051330000366350ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/guice-bean-scanners/src/test/resources/META-INF/sisu# comment org.sonatype.guice.bean.scanners.QualifiedScanningTest$C some_missing_class org.sonatype.guice.bean.scanners.QualifiedScanningTest$D // comment org.sonatype.guice.bean.scanners.QualifiedScanningTest$C sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/pom.xml000066400000000000000000000057361167051330000231740ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject containers 2.3.0 pom guice-bean Sisu-Inject : Containers : Bean (JSR330) guice-bean-reflect guice-bean-inject guice-bean-scanners guice-bean-converters guice-bean-locators guice-bean-binders guice-bean-containers sisu-inject-bean org.sonatype.sisu.inject guice-bean-reflect ${project.version} org.sonatype.sisu.inject guice-bean-inject ${project.version} org.sonatype.sisu.inject guice-bean-scanners ${project.version} org.sonatype.sisu.inject guice-bean-converters ${project.version} org.sonatype.sisu.inject guice-bean-locators ${project.version} org.sonatype.sisu.inject guice-bean-binders ${project.version} org.sonatype.sisu.inject guice-bean-containers ${project.version} org.sonatype.sisu sisu-inject-bean ${project.version} sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/sisu-inject-bean/000077500000000000000000000000001167051330000250045ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/sisu-inject-bean/pom.xml000066400000000000000000000157201167051330000263260ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-bean 2.3.0 bundle org.sonatype.sisu sisu-inject-bean Sisu-Inject-Bean : Aggregate OSGi bundle org.sonatype.sisu sisu-guice no_aop javax.inject javax.inject aopalliance aopalliance org.sonatype.sisu.inject guice-bean-containers true org.slf4j slf4j-api true org.osgi org.osgi.core true org.osgi org.osgi.compendium true junit junit true org.testng testng true org.apache.felix maven-bundle-plugin true org.sonatype.guice.bean.containers.Main org.sonatype.inject;singleton:=true lazy org.sonatype.guice.bean.containers.SisuActivator org.slf4j javax.inject;javax.enterprise.inject;version=1, org.aopalliance.aop;org.aopalliance.intercept;version=1, org.sonatype.inject;-split-package:=merge-first;version=${project.version}, org.sonatype.guice.bean.*;x-internal:=true;version=${project.version} org.sonatype.sisu.guava, org.sonatype.sisu.guice javax.inject;javax.enterprise.inject, org.aopalliance.aop;org.aopalliance.intercept, !com.google.*, *;resolution:=optional release aggregate-sources maven-dependency-plugin aggregate-sources prepare-package unpack-dependencies sources false ${project.build.directory}/aggregate-sources javax/inject/*,javax/enterprise/inject/*, org/aopalliance/aop/*,org/aopalliance/intercept/*, org/sonatype/inject/**,org/sonatype/guice/bean/** maven-jar-plugin attach-sources prepare-package jar sources ${project.build.directory}/aggregate-sources maven-javadoc-plugin ${project.build.directory}/aggregate-sources m2e m2e.version org.sonatype.sisu.inject guice-bean-containers false sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/sisu-inject-bean/src/000077500000000000000000000000001167051330000255735ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/sisu-inject-bean/src/main/000077500000000000000000000000001167051330000265175ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/sisu-inject-bean/src/main/resources/000077500000000000000000000000001167051330000305315ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/sisu-inject-bean/src/main/resources/META-INF/000077500000000000000000000000001167051330000316715ustar00rootroot00000000000000000077500000000000000000000000001167051330000334355ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/sisu-inject-bean/src/main/resources/META-INF/servicesjavax.annotation.processing.Processor000066400000000000000000000000651167051330000427740ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/sisu-inject-bean/src/main/resources/META-INF/servicesorg.sonatype.guice.bean.scanners.index.SisuIndexAPT6 sisu-ioc-2.3.0/sisu-inject/containers/guice-bean/sisu-inject-bean/src/main/resources/plugin.xml000066400000000000000000000005041167051330000325500ustar00rootroot00000000000000 sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/000077500000000000000000000000001167051330000222575ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/000077500000000000000000000000001167051330000263155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/pom.xml000066400000000000000000000135661167051330000276450ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-plexus 2.3.0 guice-plexus-binders Sisu-Inject-Plexus : @Requirement auto-wiring org.codehaus.plexus plexus-component-annotations javax.inject javax.inject org.sonatype.sisu sisu-guice org.slf4j slf4j-api true org.sonatype.sisu.inject guice-bean-reflect org.sonatype.sisu.inject guice-bean-inject org.sonatype.sisu.inject guice-bean-scanners org.sonatype.sisu.inject guice-bean-locators org.sonatype.sisu.inject guice-bean-binders org.sonatype.sisu.inject guice-plexus-metadata org.sonatype.sisu.inject guice-plexus-scanners org.sonatype.sisu.inject guice-plexus-converters test org.sonatype.sisu.inject guice-plexus-locators test maven-dependency-plugin copy-old-annotations process-test-resources copy org.codehaus.plexus plexus-component-annotations 1.2.1 maven-clean-plugin remove-missing-class process-test-classes clean true ${project.build.testOutputDirectory} **/*MissingClass.class m2e m2e.version org.eclipse.m2e lifecycle-mapping 1.0.0 org.apache.maven.plugins maven-dependency-plugin [2.2,) copy org.apache.maven.plugins maven-clean-plugin [2.4.1,) clean sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/000077500000000000000000000000001167051330000271045ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/000077500000000000000000000000001167051330000300305ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/000077500000000000000000000000001167051330000307515ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/000077500000000000000000000000001167051330000315405ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/000077500000000000000000000000001167051330000334025ustar00rootroot00000000000000000077500000000000000000000000001167051330000344175ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000357375ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000373655ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/bindersOptionalPropertyBinding.java000066400000000000000000000035071167051330000450620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import javax.inject.Provider; import org.sonatype.guice.bean.inject.PropertyBinding; import org.sonatype.guice.bean.reflect.BeanProperty; /** * Represents a {@link BeanProperty} bound to an optional {@link Provider}. */ final class OptionalPropertyBinding implements PropertyBinding { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final BeanProperty property; private final Provider provider; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- OptionalPropertyBinding( final BeanProperty property, final Provider provider ) { this.property = property; this.provider = provider; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void injectProperty( final B bean ) { try { property.set( bean, provider.get() ); } catch ( final RuntimeException e ) // NOPMD { // binding is optional, ignore failures } } } PlexusAnnotatedBeanModule.java000066400000000000000000000102041167051330000452770ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import java.util.Map; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.guice.bean.binders.SpaceModule; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.scanners.ClassSpaceVisitor; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; import org.sonatype.guice.plexus.config.PlexusBeanModule; import org.sonatype.guice.plexus.config.PlexusBeanSource; import org.sonatype.guice.plexus.scanners.PlexusAnnotatedMetadata; import org.sonatype.guice.plexus.scanners.PlexusTypeVisitor; import org.sonatype.inject.BeanScanning; import com.google.inject.Binder; /** * {@link PlexusBeanModule} that registers Plexus beans by scanning classes for runtime annotations. */ public final class PlexusAnnotatedBeanModule implements PlexusBeanModule { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final ClassSpace space; private final Map variables; private final BeanScanning scanning; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- /** * Creates a bean source that scans the given class space for Plexus annotations using the given scanner. * * @param space The local class space * @param variables The filter variables */ public PlexusAnnotatedBeanModule( final ClassSpace space, final Map variables ) { this( space, variables, BeanScanning.ON ); } /** * Creates a bean source that scans the given class space for Plexus annotations using the given scanner. * * @param space The local class space * @param variables The filter variables * @param scanning The scanning options */ public PlexusAnnotatedBeanModule( final ClassSpace space, final Map variables, final BeanScanning scanning ) { this.space = space; this.variables = variables; this.scanning = scanning; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public PlexusBeanSource configure( final Binder binder ) { if ( null != space && scanning != BeanScanning.OFF ) { new PlexusSpaceModule( space, scanning ).configure( binder ); } return new PlexusAnnotatedBeanSource( variables ); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- private static final class PlexusSpaceModule extends SpaceModule { PlexusSpaceModule( final ClassSpace space, final BeanScanning scanning ) { super( space, scanning ); } @Override protected ClassSpaceVisitor visitor( final Binder binder ) { return new PlexusTypeVisitor( new PlexusTypeBinder( binder ) ); } } private static final class PlexusAnnotatedBeanSource implements PlexusBeanSource { private final PlexusBeanMetadata metadata; PlexusAnnotatedBeanSource( final Map variables ) { metadata = new PlexusAnnotatedMetadata( variables ); } public PlexusBeanMetadata getBeanMetadata( final Class implementation ) { return implementation.isAnnotationPresent( Component.class ) ? metadata : null; } } } PlexusBeanBinder.java000066400000000000000000000052231167051330000434240ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import java.util.List; import org.sonatype.guice.bean.inject.BeanBinder; import org.sonatype.guice.bean.inject.PropertyBinder; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; import org.sonatype.guice.plexus.config.PlexusBeanSource; import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; /** * {@link BeanBinder} that binds bean properties according to Plexus metadata. */ final class PlexusBeanBinder implements BeanBinder, InjectionListener { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final PlexusBeanManager manager; private final PlexusBeanSource[] sources; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- PlexusBeanBinder( final PlexusBeanManager manager, final List sources ) { this.manager = manager; this.sources = sources.toArray( new PlexusBeanSource[sources.size()] ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public PropertyBinder bindBean( final TypeLiteral type, final TypeEncounter encounter ) { final Class clazz = type.getRawType(); if ( null != manager && manager.manage( clazz ) ) { encounter.register( this ); } for ( final PlexusBeanSource source : sources ) { // use first source that has metadata for the given implementation final PlexusBeanMetadata metadata = source.getBeanMetadata( clazz ); if ( metadata != null ) { return new PlexusPropertyBinder( manager, encounter, metadata ); } } return null; // no need to auto-bind } public void afterInjection( final Object bean ) { manager.manage( bean ); } } PlexusBeanManager.java000066400000000000000000000037441167051330000436010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import org.sonatype.guice.bean.inject.PropertyBinding; import org.sonatype.guice.bean.reflect.BeanProperty; /** * Service that manages the lifecycle of Plexus beans. */ public interface PlexusBeanManager { /** * Decides whether instances of the given Plexus bean type should be reported to this manager. * * @param clazz The Plexus bean type * @return {@code true} if instances of the bean should be reported; otherwise {@code false} */ boolean manage( Class clazz ); /** * Asks this manager to manage the given bean property. * * @param property The bean property * @return Non-null binding if the bean property was managed; otherwise {@code null} */ PropertyBinding manage( BeanProperty property ); /** * Asks this manager to manage the given Plexus bean instance. * * @param bean The Plexus bean instance * @return {@code true} if the bean instance was managed; otherwise {@code false} */ boolean manage( Object bean ); /** * Asks this manager to unmanage the given Plexus bean instance. * * @param bean The Plexus bean instance * @return {@code true} if the bean instance was unmanaged; otherwise {@code false} */ boolean unmanage( Object bean ); /** * Asks this manager to unmanage all the Plexus bean instances it knows about. * * @return {@code true} if any bean instances were unmanaged; otherwise {@code false} */ boolean unmanage(); } PlexusBindingModule.java000066400000000000000000000056011167051330000441530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.sonatype.guice.bean.inject.BeanListener; import org.sonatype.guice.plexus.config.PlexusBeanModule; import org.sonatype.guice.plexus.config.PlexusBeanSource; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.matcher.Matchers; import com.google.inject.spi.ProvisionListener; /** * Guice {@link Module} that supports registration, injection, and management of Plexus beans. */ public final class PlexusBindingModule implements Module { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final PlexusBeanManager manager; private final PlexusBeanModule[] modules; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public PlexusBindingModule( final PlexusBeanManager manager, final PlexusBeanModule... modules ) { this.manager = manager; this.modules = modules.clone(); } public PlexusBindingModule( final PlexusBeanManager manager, final Collection modules ) { this.manager = manager; this.modules = modules.toArray( new PlexusBeanModule[modules.size()] ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void configure( final Binder binder ) { final List sources = new ArrayList( modules.length ); for ( final PlexusBeanModule module : modules ) { final PlexusBeanSource source = module.configure( binder ); if ( null != source ) { sources.add( source ); } } // attach custom logic to support Plexus requirements/configuration/lifecycle final PlexusBeanBinder plexusBinder = new PlexusBeanBinder( manager, sources ); binder.bindListener( Matchers.any(), new BeanListener( plexusBinder ) ); if ( manager instanceof ProvisionListener ) { binder.bindListener( Matchers.any(), (ProvisionListener) manager ); } } } PlexusConfigurations.java000066400000000000000000000071651167051330000444340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import javax.inject.Provider; import org.codehaus.plexus.component.annotations.Configuration; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import com.google.inject.TypeLiteral; import com.google.inject.spi.TypeEncounter; /** * Creates {@link Provider}s for properties with @{@link Configuration} metadata. */ final class PlexusConfigurations { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Provider converterProvider; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- PlexusConfigurations( final TypeEncounter encounter ) { converterProvider = encounter.getProvider( PlexusBeanConverter.class ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- /** * Creates a {@link Provider} that provides values that match the given property configuration. * * @param configuration The Plexus configuration * @param property The bean property * @return Provider that provides configured values for the given property */ public Provider lookup( final Configuration configuration, final BeanProperty property ) { return new ConfigurationProvider( converterProvider, property.getType(), configuration.value() ); } // ---------------------------------------------------------------------- // Implementation classes // ---------------------------------------------------------------------- /** * {@link Provider} of Plexus configurations. */ private static final class ConfigurationProvider implements Provider { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Provider converterProvider; private final TypeLiteral type; private final String value; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ConfigurationProvider( final Provider converterProvider, final TypeLiteral type, final String value ) { this.converterProvider = converterProvider; this.type = type; this.value = value; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public T get() { return converterProvider.get().convert( type, value ); } } } PlexusPropertyBinder.java000066400000000000000000000106441167051330000444060ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import javax.inject.Provider; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.bean.inject.PropertyBinder; import org.sonatype.guice.bean.inject.PropertyBinding; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; import com.google.inject.spi.TypeEncounter; /** * {@link BeanPropertyBinder} that auto-binds properties according to Plexus metadata. */ final class PlexusPropertyBinder implements PropertyBinder { // ---------------------------------------------------------------------- // Static initialization // ---------------------------------------------------------------------- static { boolean optionalSupported = true; try { // support both old and new forms of @Requirement Requirement.class.getDeclaredMethod( "optional" ); } catch ( final Exception e ) { optionalSupported = false; } catch ( final LinkageError e ) { optionalSupported = false; } OPTIONAL_SUPPORTED = optionalSupported; } // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final boolean OPTIONAL_SUPPORTED; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final PlexusBeanManager manager; private final PlexusBeanMetadata metadata; private final PlexusConfigurations configurations; private final PlexusRequirements requirements; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- PlexusPropertyBinder( final PlexusBeanManager manager, final TypeEncounter encounter, final PlexusBeanMetadata metadata ) { this.manager = manager; this.metadata = metadata; configurations = new PlexusConfigurations( encounter ); requirements = new PlexusRequirements( encounter ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public PropertyBinding bindProperty( final BeanProperty property ) { if ( metadata.isEmpty() ) { return PropertyBinder.LAST_BINDING; } /* * @Configuration binding */ final Configuration configuration = metadata.getConfiguration( property ); if ( null != configuration ) { final Provider valueProvider = configurations.lookup( configuration, property ); return new ProvidedPropertyBinding( property, valueProvider ); } /* * @Requirement binding */ final Requirement requirement = metadata.getRequirement( property ); if ( null != requirement ) { if ( null != manager ) { final PropertyBinding managedBinding = manager.manage( property ); if ( null != managedBinding ) { return managedBinding; // the bean manager will handle this property } } final Provider roleProvider = requirements.lookup( requirement, property ); if ( OPTIONAL_SUPPORTED && requirement.optional() ) { return new OptionalPropertyBinding( property, roleProvider ); } return new ProvidedPropertyBinding( property, roleProvider ); } return null; // nothing to bind } } PlexusRequirements.java000066400000000000000000000200431167051330000441130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.inject.Provider; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.bean.locators.EntryListAdapter; import org.sonatype.guice.bean.locators.EntryMapAdapter; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.plexus.config.Hints; import org.sonatype.guice.plexus.config.PlexusBeanLocator; import org.sonatype.guice.plexus.config.Roles; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; import com.google.inject.spi.TypeEncounter; /** * Creates {@link Provider}s for properties with @{@link Requirement} metadata. */ final class PlexusRequirements { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Provider locatorProvider; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- PlexusRequirements( final TypeEncounter encounter ) { locatorProvider = encounter.getProvider( PlexusBeanLocator.class ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- /** * Creates a {@link Provider} that provides Plexus components that match the given property requirement. * * @param requirement The Plexus requirement * @param property The bean property * @return Provider that provides required Plexus components for the given property */ @SuppressWarnings( { "unchecked", "rawtypes" } ) public Provider lookup( final Requirement requirement, final BeanProperty property ) { try { // deduce lookup from metadata + property details final TypeLiteral expectedType = property.getType(); final TypeLiteral roleType = (TypeLiteral) Roles.roleType( requirement, expectedType ); final Class rawType = expectedType.getRawType(); final String[] hints = Hints.canonicalHints( requirement ); if ( Map.class == rawType ) { return new RequirementMapProvider( locatorProvider, roleType, hints ); } else if ( List.class == rawType ) { return new RequirementListProvider( locatorProvider, roleType, hints ); } return new RequirementProvider( locatorProvider, roleType, hints ); } catch ( final RuntimeException e ) { // defer until later... return new Provider() { public T get() { throw new ProvisionException( "Error in requirement: " + property, e ); } }; } } // ---------------------------------------------------------------------- // Implementation classes // ---------------------------------------------------------------------- /** * Abstract {@link Provider} that locates Plexus beans on-demand. */ private static abstract class AbstractRequirementProvider implements Provider { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Provider locatorProvider; final TypeLiteral type; private final String[] hints; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- AbstractRequirementProvider( final Provider locatorProvider, final TypeLiteral type, final String[] hints ) { this.locatorProvider = locatorProvider; this.type = type; this.hints = hints; } // ---------------------------------------------------------------------- // Locally-shared methods // ---------------------------------------------------------------------- final Iterable> locate() { return locatorProvider.get().locate( type, hints ); } } /** * {@link Provider} of Plexus requirement maps. */ private static final class RequirementMapProvider extends AbstractRequirementProvider, T> { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- RequirementMapProvider( final Provider locatorProvider, final TypeLiteral type, final String[] hints ) { super( locatorProvider, type, hints ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Map get() { return new EntryMapAdapter( locate() ); } } /** * {@link Provider} of Plexus requirement lists. */ private static final class RequirementListProvider extends AbstractRequirementProvider, T> { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- RequirementListProvider( final Provider locatorProvider, final TypeLiteral type, final String[] hints ) { super( locatorProvider, type, hints ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public List get() { return new EntryListAdapter( locate() ); } } /** * {@link Provider} of a single Plexus requirement. */ private static final class RequirementProvider extends AbstractRequirementProvider { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- RequirementProvider( final Provider locatorProvider, final TypeLiteral type, final String[] hints ) { super( locatorProvider, type, hints ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public T get() { // pick first bean: supports both specific and wildcard lookup final Iterator> i = locate().iterator(); if ( i.hasNext() ) { return i.next().getValue(); } return Roles.throwMissingComponentException( type, null ); } } } PlexusTypeBinder.java000066400000000000000000000113361167051330000435020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import java.lang.annotation.Annotation; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.guice.bean.binders.QualifiedTypeBinder; import org.sonatype.guice.bean.locators.BeanDescription; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.scanners.QualifiedTypeListener; import org.sonatype.guice.plexus.config.Roles; import org.sonatype.guice.plexus.config.Strategies; import org.sonatype.guice.plexus.scanners.PlexusTypeListener; import com.google.inject.Binder; import com.google.inject.Key; import com.google.inject.Scopes; import com.google.inject.binder.ScopedBindingBuilder; public final class PlexusTypeBinder implements PlexusTypeListener { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Binder binder; private final QualifiedTypeListener qualifiedTypeBinder; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public PlexusTypeBinder( final Binder binder ) { this.binder = binder; qualifiedTypeBinder = new QualifiedTypeBinder( binder ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void hear( final Annotation qualifier, final Class qualifiedType, final Object source ) { qualifiedTypeBinder.hear( qualifier, qualifiedType, source ); } @SuppressWarnings( { "unchecked", "rawtypes" } ) public void hear( final Component component, final DeferredClass clazz, final Object source ) { final Key roleKey = Roles.componentKey( component ); final String strategy = component.instantiationStrategy(); final Class role = component.role(); final ScopedBindingBuilder sbb; final Binder componentBinder = componentBinder( source, component.description() ); // special case when role is the implementation if ( role.getName().equals( clazz.getName() ) ) { if ( roleKey.getAnnotation() != null ) { sbb = componentBinder.bind( roleKey ).to( role ); } else { sbb = componentBinder.bind( roleKey ); } } else if ( Strategies.LOAD_ON_START.equals( strategy ) ) { sbb = componentBinder.bind( roleKey ).to( clazz.load() ); // no need to defer } else { sbb = componentBinder.bind( roleKey ).toProvider( clazz.asProvider() ); } if ( Strategies.LOAD_ON_START.equals( strategy ) ) { sbb.asEagerSingleton(); } else if ( !Strategies.PER_LOOKUP.equals( strategy ) ) { sbb.in( Scopes.SINGLETON ); } } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private Binder componentBinder( final Object source, final String description ) { if ( null != description && description.length() > 0 ) { return binder.withSource( new PlexusBeanDescription( source, description ) ); } return binder.withSource( source ); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- private static final class PlexusBeanDescription implements BeanDescription { private final Object source; private final String description; PlexusBeanDescription( final Object source, final String description ) { this.source = source; this.description = description; } public String getDescription() { return description; } @Override public String toString() { return source.toString(); } } } PlexusXmlBeanModule.java000066400000000000000000000105241167051330000441270ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; import org.sonatype.guice.plexus.config.PlexusBeanModule; import org.sonatype.guice.plexus.config.PlexusBeanSource; import org.sonatype.guice.plexus.scanners.PlexusXmlScanner; import com.google.inject.Binder; /** * {@link PlexusBeanModule} that collects {@link PlexusBeanMetadata} by scanning XML resources. */ public final class PlexusXmlBeanModule implements PlexusBeanModule { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final ClassSpace space; private final Map variables; private final URL plexusXml; private final boolean root; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- /** * Creates a bean source that scans all the surrounding class spaces for XML resources. * * @param space The main class space * @param variables The filter variables * @param plexusXml The plexus.xml URL */ public PlexusXmlBeanModule( final ClassSpace space, final Map variables, final URL plexusXml ) { this.space = space; this.variables = variables; this.plexusXml = plexusXml; root = true; } /** * Creates a bean source that only scans the local class space for XML resources. * * @param space The local class space * @param variables The filter variables */ public PlexusXmlBeanModule( final ClassSpace space, final Map variables ) { this.space = space; this.variables = variables; plexusXml = null; root = false; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public PlexusBeanSource configure( final Binder binder ) { binder.bind( ClassSpace.class ).toInstance( space ); final PlexusTypeBinder plexusTypeBinder = new PlexusTypeBinder( binder ); final Map metadataMap = new HashMap(); final PlexusXmlScanner scanner = new PlexusXmlScanner( variables, plexusXml, metadataMap ); final String source = space.toString(); for ( final Entry> entry : scanner.scan( space, root ).entrySet() ) { plexusTypeBinder.hear( entry.getKey(), entry.getValue(), source ); } return new PlexusXmlBeanSource( metadataMap ); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- private static final class PlexusXmlBeanSource implements PlexusBeanSource { private Map metadataMap; PlexusXmlBeanSource( final Map metadataMap ) { this.metadataMap = metadataMap; } public PlexusBeanMetadata getBeanMetadata( final Class implementation ) { if ( null == metadataMap ) { return null; } final PlexusBeanMetadata metadata = metadataMap.remove( implementation.getName() ); if ( metadataMap.isEmpty() ) { metadataMap = null; } return metadata; } } } ProvidedPropertyBinding.java000066400000000000000000000032351167051330000450470ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/main/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import javax.inject.Provider; import org.sonatype.guice.bean.inject.PropertyBinding; import org.sonatype.guice.bean.reflect.BeanProperty; /** * Represents a {@link BeanProperty} bound to a {@link Provider}. */ final class ProvidedPropertyBinding implements PropertyBinding { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final BeanProperty property; private final Provider provider; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- ProvidedPropertyBinding( final BeanProperty property, final Provider provider ) { this.property = property; this.provider = provider; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void injectProperty( final B bean ) { property.set( bean, provider.get() ); } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/000077500000000000000000000000001167051330000300635ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/000077500000000000000000000000001167051330000310045ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/org/000077500000000000000000000000001167051330000315735ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/org/sonatype/000077500000000000000000000000001167051330000334355ustar00rootroot00000000000000000077500000000000000000000000001167051330000344525ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000357725ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000374205ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/org/sonatype/guice/plexus/bindersPlexusBeanMetadataTest.java000066400000000000000000000166771167051330000446530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import javax.inject.Inject; import javax.inject.Named; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.bean.inject.PropertyBinding; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.guice.plexus.annotations.ConfigurationImpl; import org.sonatype.guice.plexus.annotations.RequirementImpl; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import org.sonatype.guice.plexus.config.PlexusBeanLocator; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; import org.sonatype.guice.plexus.config.PlexusBeanModule; import org.sonatype.guice.plexus.config.PlexusBeanSource; import org.sonatype.guice.plexus.converters.PlexusDateTypeConverter; import org.sonatype.guice.plexus.converters.PlexusXmlBeanConverter; import org.sonatype.guice.plexus.locators.DefaultPlexusBeanLocator; import com.google.inject.AbstractModule; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.name.Names; public class PlexusBeanMetadataTest extends TestCase { @Inject @Named( "2" ) Bean bean; @Inject Injector injector; @Override protected void setUp() { Guice.createInjector( new AbstractModule() { @Override protected void configure() { install( new PlexusDateTypeConverter() ); bind( PlexusBeanLocator.class ).to( DefaultPlexusBeanLocator.class ); bind( PlexusBeanConverter.class ).to( PlexusXmlBeanConverter.class ); bindConstant().annotatedWith( Names.named( "KEY1" ) ).to( "REQUIREMENT" ); final PlexusBeanManager manager = new TestBeanManager(); install( new PlexusBindingModule( null, new BeanSourceA() ) ); install( new PlexusBindingModule( manager, new BeanSourceB() ) ); install( new PlexusBindingModule( null, new BeanSourceC() ) ); install( new PlexusBindingModule( null, new CustomizedBeanSource() ) ); requestInjection( PlexusBeanMetadataTest.this ); } } ); } static class TestBeanManager implements PlexusBeanManager { public boolean manage( final Class clazz ) { return false; } public PropertyBinding manage( final BeanProperty property ) { return null; } public boolean manage( final Object bean ) { return false; } public boolean unmanage( final Object bean ) { return false; } public boolean unmanage() { return false; } } interface Bean { Object getExtraMetadata(); void setExtraMetadata( Object metadata ); } static class DefaultBean1 implements Bean { Object extraMetadata; public Object getExtraMetadata() { return extraMetadata; } public void setExtraMetadata( final Object metadata ) { extraMetadata = metadata; } } static class DefaultBean2 { String extraMetadata; String leftovers; } static class BeanSourceA implements PlexusBeanModule { public PlexusBeanSource configure( final Binder binder ) { binder.withSource( "A" ).bind( Bean.class ).annotatedWith( Names.named( "2" ) ).to( DefaultBean1.class ).asEagerSingleton(); return null; } } static class BeanSourceB implements PlexusBeanModule { public PlexusBeanSource configure( final Binder binder ) { binder.withSource( "B" ).bind( DefaultBean2.class ); return null; } } static class BeanSourceC implements PlexusBeanModule { public PlexusBeanSource configure( final Binder binder ) { binder.withSource( "C" ).bind( DefaultBean2.class ).annotatedWith( Names.named( "2" ) ).to( DefaultBean2.class ); return null; } } static class CustomizedBeanSource implements PlexusBeanModule, PlexusBeanSource { public PlexusBeanSource configure( final Binder binder ) { return this; } public PlexusBeanMetadata getBeanMetadata( final Class implementation ) { if ( DefaultBean1.class.equals( implementation ) ) { return new PlexusBeanMetadata() { public boolean isEmpty() { return false; } @SuppressWarnings( "deprecation" ) public Requirement getRequirement( final BeanProperty property ) { if ( "extraMetadata".equals( property.getName() ) ) { return new RequirementImpl( String.class, false, "KEY1" ); } return null; } public Configuration getConfiguration( final BeanProperty property ) { return null; } }; } if ( DefaultBean2.class.equals( implementation ) ) { return new PlexusBeanMetadata() { private boolean used = false; public boolean isEmpty() { return used; } public Requirement getRequirement( final BeanProperty property ) { return null; } public Configuration getConfiguration( final BeanProperty property ) { if ( "extraMetadata".equals( property.getName() ) ) { used = true; return new ConfigurationImpl( "KEY2", "CONFIGURATION" ); } return null; } }; } return null; } } public void testExtraMetadata() { assertEquals( "REQUIREMENT", bean.getExtraMetadata() ); assertEquals( "CONFIGURATION", injector.getInstance( DefaultBean2.class ).extraMetadata ); assertSame( bean, injector.getInstance( Key.get( Bean.class, Names.named( "2" ) ) ) ); } static DeferredClass defer( final Class clazz ) { return new URLClassSpace( TestCase.class.getClassLoader() ).deferLoadClass( clazz.getName() ); } } PlexusConfigurationTest.java000066400000000000000000000105771167051330000451450ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import javax.inject.Inject; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Configuration; import org.sonatype.guice.bean.inject.PropertyBinding; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import org.sonatype.guice.plexus.config.PlexusBeanLocator; import org.sonatype.guice.plexus.converters.PlexusDateTypeConverter; import org.sonatype.guice.plexus.converters.PlexusXmlBeanConverter; import org.sonatype.guice.plexus.locators.DefaultPlexusBeanLocator; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.ProvisionException; public class PlexusConfigurationTest extends TestCase { @Inject ConfiguredComponent component; @Inject Injector injector; static class ComponentManager implements PlexusBeanManager { static int SEEN; public boolean manage( final Class clazz ) { return ConfiguredComponent.class.isAssignableFrom( clazz ); } public PropertyBinding manage( final BeanProperty property ) { return null; } public boolean manage( final Object bean ) { SEEN++; return true; } public boolean unmanage( final Object bean ) { return false; } public boolean unmanage() { return false; } } @Override protected void setUp() { Guice.createInjector( new AbstractModule() { @Override protected void configure() { install( new PlexusDateTypeConverter() ); bind( PlexusBeanLocator.class ).to( DefaultPlexusBeanLocator.class ); bind( PlexusBeanConverter.class ).to( PlexusXmlBeanConverter.class ); install( new PlexusBindingModule( new ComponentManager(), new PlexusAnnotatedBeanModule( null, null ) ) ); requestInjection( PlexusConfigurationTest.this ); } } ); } @Component( role = Object.class ) static class ConfiguredComponent { @Configuration( "1" ) String a; @Configuration( "2" ) Integer b; @Configuration( "3" ) int c; @Configuration( "4" ) Double d; @Configuration( "5" ) double e; } @Component( role = Object.class ) static class MisconfiguredComponent { @Configuration( "misconfigured" ) SomeBean bean; } public static class SomeBean { public SomeBean( final String data ) { if ( "misconfigured".equals( data ) ) { throw new NoClassDefFoundError(); } } } public void testConfiguration() { assertEquals( "1", component.a ); assertEquals( Integer.valueOf( 2 ), component.b ); assertEquals( 3, component.c ); assertEquals( Double.valueOf( 4.0 ), component.d ); assertEquals( 5.0, component.e, 0 ); assertEquals( 1, ComponentManager.SEEN ); final ConfiguredComponent jitComponent = injector.getInstance( ConfiguredComponent.class ); assertEquals( "1", jitComponent.a ); assertEquals( Integer.valueOf( 2 ), jitComponent.b ); assertEquals( 3, jitComponent.c ); assertEquals( Double.valueOf( 4.0 ), jitComponent.d ); assertEquals( 5.0, jitComponent.e, 0 ); assertEquals( 2, ComponentManager.SEEN ); try { injector.getInstance( MisconfiguredComponent.class ); fail( "Expected ProvisionException" ); } catch ( final ProvisionException e ) { } assertEquals( 2, ComponentManager.SEEN ); } } PlexusLoggingTest.java000066400000000000000000000063731167051330000437230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import javax.inject.Inject; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonatype.guice.bean.inject.PropertyBinding; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import org.sonatype.guice.plexus.config.PlexusBeanLocator; import org.sonatype.guice.plexus.converters.PlexusDateTypeConverter; import org.sonatype.guice.plexus.converters.PlexusXmlBeanConverter; import org.sonatype.guice.plexus.locators.DefaultPlexusBeanLocator; import com.google.inject.AbstractModule; import com.google.inject.Guice; public class PlexusLoggingTest extends TestCase { static class LoggerManager implements PlexusBeanManager { public boolean manage( final Class clazz ) { return false; } @SuppressWarnings( "rawtypes" ) public PropertyBinding manage( final BeanProperty property ) { if ( Logger.class.equals( property.getType().getRawType() ) ) { return new PropertyBinding() { @SuppressWarnings( "unchecked" ) public void injectProperty( final B bean ) { property.set( bean, LoggerFactory.getLogger( bean.getClass() ) ); } }; } return null; } public boolean manage( final Object bean ) { return false; } public boolean unmanage( final Object bean ) { return false; } public boolean unmanage() { return false; } } @Override protected void setUp() { Guice.createInjector( new AbstractModule() { @Override protected void configure() { install( new PlexusDateTypeConverter() ); bind( PlexusBeanLocator.class ).to( DefaultPlexusBeanLocator.class ); bind( PlexusBeanConverter.class ).to( PlexusXmlBeanConverter.class ); install( new PlexusBindingModule( new LoggerManager(), new PlexusAnnotatedBeanModule( null, null ) ) ); requestInjection( PlexusLoggingTest.this ); } } ); } @Component( role = Object.class ) static class SomeComponent { @Requirement Logger logger; } @Inject SomeComponent component; public void testLogging() { assertNotNull( component.logger ); assertEquals( SomeComponent.class.getName(), component.logger.getName() ); } } PlexusRequirementTest.java000066400000000000000000000377311167051330000446370ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.inject.Inject; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.guice.plexus.config.Hints; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import org.sonatype.guice.plexus.config.PlexusBeanLocator; import org.sonatype.guice.plexus.config.PlexusBeanModule; import org.sonatype.guice.plexus.config.PlexusBeanSource; import org.sonatype.guice.plexus.config.Strategies; import org.sonatype.guice.plexus.converters.PlexusDateTypeConverter; import org.sonatype.guice.plexus.converters.PlexusXmlBeanConverter; import org.sonatype.guice.plexus.locators.DefaultPlexusBeanLocator; import com.google.inject.AbstractModule; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Injector; import com.google.inject.ProvisionException; import com.google.inject.Scopes; import com.google.inject.name.Names; public class PlexusRequirementTest extends TestCase { @Inject Component1 component; @Inject Injector injector; @Override protected void setUp() { Guice.createInjector( new AbstractModule() { @Override @SuppressWarnings( "unchecked" ) protected void configure() { final ClassSpace space = new URLClassSpace( TestCase.class.getClassLoader() ); final DeferredClass deferA = (DeferredClass) space.deferLoadClass( BrokenAImpl.class.getName() ); install( new PlexusDateTypeConverter() ); bind( PlexusBeanLocator.class ).to( DefaultPlexusBeanLocator.class ); bind( PlexusBeanConverter.class ).to( PlexusXmlBeanConverter.class ); bind( A.class ).annotatedWith( Names.named( "AA" ) ).to( AAImpl.class ); bind( A.class ).annotatedWith( Names.named( "broken" ) ).toProvider( deferA.asProvider() ); bind( A.class ).annotatedWith( Names.named( "AB" ) ).to( ABImpl.class ); bind( A.class ).to( AImpl.class ).in( Scopes.SINGLETON ); bind( A.class ).annotatedWith( Names.named( "AC" ) ).to( ACImpl.class ); bind( B.class ).annotatedWith( Names.named( "B" ) ).to( BImpl.class ); bind( D.class ).annotatedWith( Names.named( "" ) ).to( DImpl.class ); install( new PlexusBindingModule( null, new PlexusBeanModule() { public PlexusBeanSource configure( final Binder binder ) { binder.bind( Alpha.class ).to( AlphaImpl.class ).in( Scopes.SINGLETON ); binder.bind( Omega.class ).to( OmegaImpl.class ).in( Scopes.SINGLETON ); final DeferredClass gammaProvider = (DeferredClass) space.deferLoadClass( "some-broken-class" ).asProvider(); binder.bind( Gamma.class ).toProvider( gammaProvider.asProvider() ).in( Scopes.SINGLETON ); return null; } }, new PlexusAnnotatedBeanModule( null, null ) ) ); requestInjection( PlexusRequirementTest.this ); } } ); } @ImplementedBy( AImpl.class ) interface A { } interface B { } interface C { } interface D { } static class AImpl implements A { } static class BImpl implements B { } static class DImpl implements D { } static class AAImpl extends AImpl { } static class ABImpl extends AImpl { } static class ACImpl extends AImpl { } static class BrokenAImpl extends AImpl { public BrokenAImpl( @SuppressWarnings( "unused" ) final MissingClass missing ) { } } static class MissingClass { } @Component( role = Component1.class, instantiationStrategy = Strategies.PER_LOOKUP ) static class Component1 { @Requirement A testField; A testSetter; @Requirement( hints = { "default" } ) void setValue( final A a ) { testSetter = a; } @Requirement( role = A.class ) Object testRole; @Requirement( hint = "AB", optional = true ) A testHint; @Requirement( hint = "MISSING", optional = true ) A testOptional = new ACImpl(); @Requirement( role = A.class ) Map testMap; @Requirement( hints = { "AC", "AB" } ) Map testSubMap; @Requirement Map testEmptyMap; @Requirement( role = A.class ) List testList; @Requirement( hints = { "AC", "AA" } ) List testSubList; @Requirement List testEmptyList; @Requirement B testWildcard; @Requirement( optional = true ) C optionalRequirement; } @Component( role = Component2.class ) static class Component2 { @Requirement void testZeroArgSetter() { throw new RuntimeException(); } } @Component( role = Component3.class ) static class Component3 { @Requirement @SuppressWarnings( "unused" ) void testMultiArgSetter( final A a1, final A a2 ) { throw new RuntimeException(); } } @Component( role = Component4.class ) static class Component4 { @Requirement C testMissingRequirement; } @Component( role = Component5.class ) static class Component5 { @Requirement( hint = "B!" ) B testNoSuchHint; } @Component( role = Component6.class ) static class Component6 { @Requirement( hints = { "AA", "AZ", "A!" } ) Map testNoSuchHint; } @Component( role = Component7.class ) static class Component7 { @Requirement( hints = { "AA", "AZ", "A!" } ) List testNoSuchHint; } @Component( role = Component8.class ) static class Component8 { @Requirement( hints = { "" } ) List testWildcardHint; } @Component( role = Component9.class ) static class Component9 { @Requirement( hint = "default" ) B testNoDefault; } public void testRepeatInjection() { final Component1 duplicate = injector.getInstance( Component1.class ); assertSame( component.testField, duplicate.testField ); assertSame( component.testSetter, duplicate.testSetter ); assertSame( component.testRole, duplicate.testRole ); } public void testSingleRequirement() { assertEquals( AImpl.class, component.testField.getClass() ); assertEquals( AImpl.class, component.testSetter.getClass() ); assertEquals( AImpl.class, component.testRole.getClass() ); assertEquals( ABImpl.class, component.testHint.getClass() ); assertEquals( ACImpl.class, component.testOptional.getClass() ); assertEquals( BImpl.class, component.testWildcard.getClass() ); } public void testRequirementMap() { assertEquals( 5, component.testMap.size() ); assertEquals( 0, component.testEmptyMap.size() ); // check mapping assertEquals( AImpl.class, component.testMap.get( "default" ).getClass() ); assertEquals( AAImpl.class, component.testMap.get( "AA" ).getClass() ); assertEquals( ABImpl.class, component.testMap.get( "AB" ).getClass() ); assertEquals( ACImpl.class, component.testMap.get( "AC" ).getClass() ); // check key ordering is same as original map-binder final Iterator keys = component.testMap.keySet().iterator(); assertEquals( Hints.DEFAULT_HINT, keys.next() ); assertEquals( "AA", keys.next() ); assertEquals( "broken", keys.next() ); assertEquals( "AB", keys.next() ); assertEquals( "AC", keys.next() ); assertFalse( keys.hasNext() ); // check value ordering is same as original map-binder final Iterator values = component.testMap.values().iterator(); assertEquals( AImpl.class, values.next().getClass() ); assertEquals( AAImpl.class, values.next().getClass() ); try { values.next(); fail( "Expected NoClassDefFoundError" ); } catch ( final NoClassDefFoundError e ) { } assertEquals( ABImpl.class, values.next().getClass() ); assertEquals( ACImpl.class, values.next().getClass() ); assertFalse( values.hasNext() ); } public void testRequirementSubMap() { assertEquals( 2, component.testSubMap.size() ); // check mapping assertEquals( ABImpl.class, component.testSubMap.get( "AB" ).getClass() ); assertEquals( ACImpl.class, component.testSubMap.get( "AC" ).getClass() ); // check key ordering is same as original map-binder final Iterator keys = component.testSubMap.keySet().iterator(); assertEquals( "AC", keys.next() ); assertEquals( "AB", keys.next() ); assertFalse( keys.hasNext() ); // check value ordering is same as hints final Iterator values = component.testSubMap.values().iterator(); assertEquals( ACImpl.class, values.next().getClass() ); assertEquals( ABImpl.class, values.next().getClass() ); assertFalse( values.hasNext() ); } public void testRequirementList() { assertEquals( 5, component.testList.size() ); assertEquals( 0, component.testEmptyList.size() ); // check ordering is same as original map-binder final Iterator i = component.testList.iterator(); assertEquals( AImpl.class, i.next().getClass() ); assertEquals( AAImpl.class, i.next().getClass() ); try { i.next(); fail( "Expected NoClassDefFoundError" ); } catch ( final NoClassDefFoundError e ) { } assertEquals( ABImpl.class, i.next().getClass() ); assertEquals( ACImpl.class, i.next().getClass() ); assertFalse( i.hasNext() ); } public void testRequirementSubList() { assertEquals( 2, component.testSubList.size() ); // check ordering is same as hints final Iterator i = component.testSubList.iterator(); assertEquals( ACImpl.class, i.next().getClass() ); assertEquals( AAImpl.class, i.next().getClass() ); assertFalse( i.hasNext() ); } public void testZeroArgSetterError() { injector.getInstance( Component2.class ); } public void testMultiArgSetterError() { injector.getInstance( Component3.class ); } public void testMissingRequirement() { try { injector.getInstance( Component4.class ); fail( "Expected error for missing requirement" ); } catch ( final ProvisionException e ) { } } public void testNoSuchHint() { try { injector.getInstance( Component5.class ); fail( "Expected error for no such hint" ); } catch ( final ProvisionException e ) { } } public void testNoSuchMapHint() { try { injector.getInstance( Component6.class ).testNoSuchHint.toString(); fail( "Expected error for no such hint" ); } catch ( final ProvisionException e ) { } } public void testNoSuchListHint() { try { injector.getInstance( Component7.class ).testNoSuchHint.toString(); fail( "Expected error for no such hint" ); } catch ( final ProvisionException e ) { } } public void testWildcardHint() { final List testList = injector.getInstance( Component8.class ).testWildcardHint; assertEquals( 5, testList.size() ); // check ordering is same as original map-binder final Iterator i = testList.iterator(); assertEquals( AImpl.class, i.next().getClass() ); assertEquals( AAImpl.class, i.next().getClass() ); try { i.next(); fail( "Expected NoClassDefFoundError" ); } catch ( final NoClassDefFoundError e ) { } assertEquals( ABImpl.class, i.next().getClass() ); assertEquals( ACImpl.class, i.next().getClass() ); assertFalse( i.hasNext() ); } public void testNoDefault() { try { injector.getInstance( Component9.class ); fail( "Expected error for missing default requirement" ); } catch ( final ProvisionException e ) { } } interface Alpha { } interface Omega { } interface Gamma { } @Component( role = Alpha.class ) static class AlphaImpl implements Alpha { @Requirement Omega omega; } @Component( role = Omega.class ) static class OmegaImpl implements Omega { @Requirement Alpha alpha; } @Inject Alpha alpha; @Inject Omega omega; public void testCircularity() { assertNotNull( ( (OmegaImpl) omega ).alpha ); assertNotNull( ( (AlphaImpl) alpha ).omega ); assertSame( alpha, ( (OmegaImpl) omega ).alpha ); assertSame( omega, ( (AlphaImpl) alpha ).omega ); } public void testBadDeferredRole() { try { injector.getInstance( Gamma.class ); fail( "Expected ProvisionException" ); } catch ( final ProvisionException e ) { } } public void testPlexus121Compatibility() throws Exception { final List urls = new ArrayList(); urls.add( new File( "target/dependency/plexus-component-annotations-1.2.1.jar" ).toURI().toURL() ); Collections.addAll( urls, ( (URLClassLoader) getClass().getClassLoader() ).getURLs() ); // check binding works with Plexus 1.2.1 annotations: @Requirement does not have optional setting final ClassLoader legacyLoader = new URLClassLoader( urls.toArray( new URL[urls.size()] ), null ) { @Override protected synchronized Class loadClass( final String name, final boolean resolve ) throws ClassNotFoundException { if ( name.contains( "cobertura" ) ) { return PlexusRequirementTest.class.getClassLoader().loadClass( name ); } return super.loadClass( name, resolve ); } }; legacyLoader.loadClass( SimpleRequirementExample.class.getName() ).newInstance(); } @SuppressWarnings( "unchecked" ) static DeferredClass defer( final Class clazz ) { return (DeferredClass) new URLClassSpace( TestCase.class.getClassLoader() ).deferLoadClass( clazz.getName() ); } } SimpleRequirementExample.java000066400000000000000000000035751167051330000452630ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-binders/src/test/java/org/sonatype/guice/plexus/binders/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.binders; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import org.sonatype.guice.plexus.config.PlexusBeanLocator; import org.sonatype.guice.plexus.converters.PlexusXmlBeanConverter; import org.sonatype.guice.plexus.locators.DefaultPlexusBeanLocator; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.name.Names; public class SimpleRequirementExample { public SimpleRequirementExample() { final String requirement = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( PlexusBeanLocator.class ).to( DefaultPlexusBeanLocator.class ); bind( PlexusBeanConverter.class ).to( PlexusXmlBeanConverter.class ); install( new PlexusBindingModule( null, new PlexusAnnotatedBeanModule( null, null ) ) ); bindConstant().annotatedWith( Names.named( "example" ) ).to( "TEST" ); } } ).getInstance( Bean.class ).requirement; if ( !requirement.equals( "TEST" ) ) { throw new AssertionError(); } } @Component( role = Bean.class ) static class Bean { @Requirement( hint = "example" ) String requirement; } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/000077500000000000000000000000001167051330000270615ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/pom.xml000066400000000000000000000027631167051330000304060ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-plexus 2.3.0 guice-plexus-converters Sisu-Inject-Plexus : @Configuration conversion javax.inject javax.inject org.sonatype.sisu sisu-guice org.sonatype.sisu.inject guice-bean-reflect org.sonatype.sisu.inject guice-plexus-metadata org.codehaus.plexus plexus-utils sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/000077500000000000000000000000001167051330000276505ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/main/000077500000000000000000000000001167051330000305745ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/main/java/000077500000000000000000000000001167051330000315155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/main/java/org/000077500000000000000000000000001167051330000323045ustar00rootroot00000000000000000077500000000000000000000000001167051330000340675ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/main/java/org/sonatype000077500000000000000000000000001167051330000351635ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000365035ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/main/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000406755ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/main/java/org/sonatype/guice/plexus/convertersPlexusDateTypeConverter.java000066400000000000000000000053571167051330000463620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/main/java/org/sonatype/guice/plexus/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.converters; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.google.inject.matcher.AbstractMatcher; import com.google.inject.spi.TypeConverter; /** * {@link TypeConverter} {@link Module} that converts Plexus formatted date strings into {@link Date}s. */ public final class PlexusDateTypeConverter extends AbstractMatcher> implements TypeConverter, Module { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final DateFormat[] PLEXUS_DATE_FORMATS = { new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss.S a" ), new SimpleDateFormat( "yyyy-MM-dd hh:mm:ssa" ), new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.S" ), new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ) }; private static final String CONVERSION_ERROR = "Cannot convert: \"%s\" to: %s"; // ---------------------------------------------------------------------- // Guice binding // ---------------------------------------------------------------------- public void configure( final Binder binder ) { // we're both matcher and converter binder.convertToTypes( this, this ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean matches( final TypeLiteral type ) { return Date.class == type.getRawType(); } public Object convert( final String value, final TypeLiteral toType ) { for ( final DateFormat f : PLEXUS_DATE_FORMATS ) { try { synchronized ( f ) // formats are not thread-safe! { return f.parse( value ); } } catch ( final ParseException e ) { continue; // try another format } } throw new IllegalArgumentException( String.format( CONVERSION_ERROR, value, Date.class ) ); } } PlexusXmlBeanConverter.java000066400000000000000000000371141167051330000461650ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/main/java/org/sonatype/guice/plexus/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.converters; import java.io.StringReader; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.inject.Inject; import javax.inject.Singleton; import org.codehaus.plexus.util.xml.pull.MXParser; import org.codehaus.plexus.util.xml.pull.XmlPullParser; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.sonatype.guice.bean.reflect.BeanProperties; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.reflect.TypeParameters; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import org.sonatype.guice.plexus.config.Roles; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.google.inject.spi.TypeConverter; import com.google.inject.spi.TypeConverterBinding; /** * {@link PlexusBeanConverter} {@link Module} that converts Plexus formatted XML into beans. */ @Singleton public final class PlexusXmlBeanConverter implements PlexusBeanConverter { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String CONVERSION_ERROR = "Cannot convert: \"%s\" to: %s"; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private Collection typeConverterBindings; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @SuppressWarnings( { "unchecked", "rawtypes" } ) public Object convert( final TypeLiteral role, final String value ) { if ( value.trim().startsWith( "<" ) ) { try { final MXParser parser = new MXParser(); parser.setInput( new StringReader( value ) ); parser.nextTag(); return parse( parser, role ); } catch ( final Exception e ) { throw new IllegalArgumentException( String.format( CONVERSION_ERROR, value, role ), e ); } } return convertText( value, role ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Records all {@link TypeConverterBinding}s registered with the {@link Injector}. * * @param injector The injector */ @Inject void setTypeConverterBindings( final Injector injector ) { typeConverterBindings = injector.getTypeConverterBindings(); } /** * Parses a sequence of XML elements and converts them to the given target type. * * @param parser The XML parser * @param toType The target type * @return Converted instance of the target type */ private Object parse( final MXParser parser, final TypeLiteral toType ) throws Exception { parser.require( XmlPullParser.START_TAG, null, null ); final Class rawType = toType.getRawType(); if ( Properties.class.isAssignableFrom( rawType ) ) { return parseProperties( parser ); } if ( Map.class.isAssignableFrom( rawType ) ) { return parseMap( parser, TypeParameters.get( toType.getSupertype( Map.class ), 1 ) ); } if ( Collection.class.isAssignableFrom( rawType ) ) { return parseCollection( parser, TypeParameters.get( toType.getSupertype( Collection.class ), 0 ) ); } if ( rawType.isArray() ) { return parseArray( parser, TypeParameters.get( toType, 0 ) ); } return parseBean( parser, toType, rawType ); } /** * Parses a sequence of XML elements and converts them to the appropriate {@link Properties} type. * * @param parser The XML parser * @return Converted Properties instance */ private static Properties parseProperties( final XmlPullParser parser ) throws Exception { final Properties properties = newImplementation( parser, Properties.class ); while ( parser.nextTag() == XmlPullParser.START_TAG ) { parser.nextTag(); // 'name-then-value' or 'value-then-name' if ( "name".equals( parser.getName() ) ) { final String name = parser.nextText(); parser.nextTag(); properties.put( name, parser.nextText() ); } else { final String value = parser.nextText(); parser.nextTag(); properties.put( parser.nextText(), value ); } parser.nextTag(); } return properties; } /** * Parses a sequence of XML elements and converts them to the appropriate {@link Map} type. * * @param parser The XML parser * @return Converted Map instance */ private Map parseMap( final MXParser parser, final TypeLiteral toType ) throws Exception { @SuppressWarnings( "unchecked" ) final Map map = newImplementation( parser, HashMap.class ); while ( parser.nextTag() == XmlPullParser.START_TAG ) { map.put( parser.getName(), parse( parser, toType ) ); } return map; } /** * Parses a sequence of XML elements and converts them to the appropriate {@link Collection} type. * * @param parser The XML parser * @return Converted Collection instance */ private Collection parseCollection( final MXParser parser, final TypeLiteral toType ) throws Exception { @SuppressWarnings( "unchecked" ) final Collection collection = newImplementation( parser, ArrayList.class ); while ( parser.nextTag() == XmlPullParser.START_TAG ) { collection.add( parse( parser, toType ) ); } return collection; } /** * Parses a sequence of XML elements and converts them to the appropriate array type. * * @param parser The XML parser * @return Converted array instance */ private Object parseArray( final MXParser parser, final TypeLiteral toType ) throws Exception { // convert to a collection first then convert that into an array final Collection collection = parseCollection( parser, toType ); final Object array = Array.newInstance( toType.getRawType(), collection.size() ); int i = 0; for ( final Object element : collection ) { Array.set( array, i++, element ); } return array; } /** * Parses a sequence of XML elements and converts them to the appropriate bean type. * * @param parser The XML parser * @return Converted bean instance */ private Object parseBean( final MXParser parser, final TypeLiteral toType, final Class rawType ) throws Exception { final Class clazz = loadImplementation( parseImplementation( parser ), rawType ); // simple bean? assumes string constructor if ( parser.next() == XmlPullParser.TEXT ) { final String text = parser.getText(); // confirm element doesn't contain nested XML if ( parser.next() != XmlPullParser.START_TAG ) { return convertText( text, clazz == rawType ? toType : TypeLiteral.get( clazz ) ); } } if ( String.class == clazz ) { // mimic plexus: discard any strings containing nested XML while ( parser.getEventType() == XmlPullParser.START_TAG ) { final String pos = parser.getPositionDescription(); Logs.warn( "Expected TEXT, not XML: {}", pos, new Throwable() ); parser.skipSubTree(); parser.nextTag(); } return ""; } final Object bean = newImplementation( clazz ); // build map of all known bean properties belonging to the chosen implementation final Map> propertyMap = new HashMap>(); for ( final BeanProperty property : new BeanProperties( clazz ) ) { final String name = property.getName(); if ( !propertyMap.containsKey( name ) ) { propertyMap.put( name, property ); } } while ( parser.getEventType() == XmlPullParser.START_TAG ) { // update properties inside the bean, guided by the cached property map final BeanProperty property = propertyMap.get( Roles.camelizeName( parser.getName() ) ); if ( property != null ) { property.set( bean, parse( parser, property.getType() ) ); parser.nextTag(); } else { throw new XmlPullParserException( "Unknown bean property: " + parser.getName(), parser, null ); } } return bean; } /** * Parses an XML element looking for the name of a custom implementation. * * @param parser The XML parser * @return Name of the custom implementation; otherwise {@code null} */ private static String parseImplementation( final XmlPullParser parser ) { return parser.getAttributeValue( null, "implementation" ); } /** * Attempts to load the named implementation, uses default implementation if no name is given. * * @param name The optional implementation name * @param defaultClazz The default implementation type * @return Custom implementation type if one was given; otherwise default implementation type */ private static Class loadImplementation( final String name, final Class defaultClazz ) { if ( null == name ) { return defaultClazz; // just use the default type } // TCCL allows surrounding container to influence class loading policy final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); if ( tccl != null ) { try { return tccl.loadClass( name ); } catch ( final Exception e ) { // drop through... } catch ( final LinkageError e ) { // drop through... } } // assume custom type is in same class space as default final ClassLoader peer = defaultClazz.getClassLoader(); if ( peer != null ) { try { return peer.loadClass( name ); } catch ( final Exception e ) { // drop through... } catch ( final LinkageError e ) { // drop through... } } try { // last chance - classic model return Class.forName( name ); } catch ( final Exception e ) { throw new TypeNotPresentException( name, e ); } catch ( final LinkageError e ) { throw new TypeNotPresentException( name, e ); } } /** * Creates an instance of the given implementation using the default constructor. * * @param clazz The implementation type * @return Instance of given implementation */ private static T newImplementation( final Class clazz ) { try { return clazz.newInstance(); } catch ( final Exception e ) { throw new IllegalArgumentException( "Cannot create instance of: " + clazz, e ); } catch ( final LinkageError e ) { throw new IllegalArgumentException( "Cannot create instance of: " + clazz, e ); } } /** * Creates an instance of the given implementation using the given string, assumes a public string constructor. * * @param clazz The implementation type * @param value The string argument * @return Instance of given implementation, constructed using the the given string */ private static T newImplementation( final Class clazz, final String value ) { try { return clazz.getConstructor( String.class ).newInstance( value ); } catch ( final Exception e ) { final Throwable cause = e instanceof InvocationTargetException ? e.getCause() : e; throw new IllegalArgumentException( String.format( CONVERSION_ERROR, value, clazz ), cause ); } catch ( final LinkageError e ) { throw new IllegalArgumentException( String.format( CONVERSION_ERROR, value, clazz ), e ); } } /** * Creates an instance of the implementation named in the current XML element, or the default if no name is given. * * @param parser The XML parser * @param defaultClazz The default implementation type * @return Instance of custom implementation if one was given; otherwise instance of default type */ @SuppressWarnings( "unchecked" ) private static T newImplementation( final XmlPullParser parser, final Class defaultClazz ) { return (T) newImplementation( loadImplementation( parseImplementation( parser ), defaultClazz ) ); } /** * Converts the given string to the target type, using {@link TypeConverter}s registered with the {@link Injector}. * * @param value The string value * @param toType The target type * @return Converted instance of the target type */ private Object convertText( final String value, final TypeLiteral toType ) { final String text = value.trim(); final Class rawType = toType.getRawType(); if ( rawType.isAssignableFrom( String.class ) ) { return text; // compatible type => no conversion needed } // use temporary Key as quick way to auto-box primitive types into their equivalent object types final TypeLiteral boxedType = rawType.isPrimitive() ? Key.get( rawType ).getTypeLiteral() : toType; for ( final TypeConverterBinding b : typeConverterBindings ) { if ( b.getTypeMatcher().matches( boxedType ) ) { return b.getTypeConverter().convert( text, toType ); } } // last chance => attempt to create an instance of the expected type: use the string if non-empty return text.length() == 0 ? newImplementation( rawType ) : newImplementation( rawType, text ); } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/000077500000000000000000000000001167051330000306275ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/000077500000000000000000000000001167051330000315505ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/000077500000000000000000000000001167051330000323375ustar00rootroot00000000000000000077500000000000000000000000001167051330000341225ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/sonatype000077500000000000000000000000001167051330000352165ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000365365ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000407305ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/sonatype/guice/plexus/convertersArrayConstantTest.java000066400000000000000000000061751167051330000452340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/sonatype/guice/plexus/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.converters; import java.net.URI; import java.util.Arrays; import javax.inject.Inject; import javax.inject.Named; import junit.framework.TestCase; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.name.Names; public class ArrayConstantTest extends TestCase { @Override protected void setUp() throws Exception { Guice.createInjector( new AbstractModule() { private void bind( final String name, final String value ) { bindConstant().annotatedWith( Names.named( name ) ).to( value ); } @Override protected void configure() { bind( "Empty", "" ); bind( "Custom", "true" + "file:temp" + "8.1" ); bind( "Text", "123" ); bind( "Numbers", "456" ); bind( "Multi", "123456" ); bind( PlexusBeanConverter.class ).to( PlexusXmlBeanConverter.class ); install( new ConfigurationConverter() ); } } ).injectMembers( this ); } @Inject @Named( "Empty" ) char[] empty; @Inject @Named( "Custom" ) Object[] custom; @Inject @Named( "Text" ) String[] text; @Inject @Named( "Numbers" ) int[] numbers; @Inject @Named( "Multi" ) Integer[][] multi1; @Inject @Named( "Multi" ) double[][] multi2; public void testEmptyArray() { assertEquals( 0, empty.length ); } @SuppressWarnings( "boxing" ) public void testCustomArray() { assertTrue( Arrays.equals( new Object[] { true, URI.create( "file:temp" ), 8.1f }, custom ) ); } public void testStringArray() { assertTrue( Arrays.equals( new String[] { "1", "2", "3" }, text ) ); } public void testPrimitiveArray() { assertTrue( Arrays.equals( new int[] { 4, 5, 6 }, numbers ) ); } @SuppressWarnings( "boxing" ) public void testMultiArrays() { assertTrue( Arrays.deepEquals( new Integer[][] { { 1, 2 }, { 3, 4 }, { 5, 6 } }, multi1 ) ); assertTrue( Arrays.deepEquals( new double[][] { { 1, 2 }, { 3, 4 }, { 5, 6 } }, multi2 ) ); } } BeanConstantTest.java000066400000000000000000000165701167051330000450230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/sonatype/guice/plexus/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.converters; import java.io.File; import java.net.URL; import java.util.Calendar; import java.util.Date; import javax.inject.Inject; import junit.framework.TestCase; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import com.google.inject.AbstractModule; import com.google.inject.ConfigurationException; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; public class BeanConstantTest extends TestCase { @Override protected void setUp() throws Exception { Guice.createInjector( new AbstractModule() { private void bindBean( final String name, final String clazzName, final String content ) { final String xml = "" + content + ""; bindConstant().annotatedWith( Names.named( name ) ).to( xml ); } @Override protected void configure() { bindBean( "EmptyBean", EmptyBean.class.getName(), " " ); bindBean( "MissingType", "some.unknown.type", "" ); bindBean( "BeanWithProperty", BeanWithProperties.class.getName(), "4.2" ); bindBean( "MissingProperty", EmptyBean.class.getName(), " 4.2" ); bindBean( "MissingDefaultConstructor", MissingDefaultConstructor.class.getName(), "" ); bindBean( "BrokenDefaultConstructor", BrokenDefaultConstructor.class.getName(), "" ); bindBean( "MissingStringConstructor", MissingStringConstructor.class.getName(), "text" ); bindBean( "BrokenStringConstructor", BrokenStringConstructor.class.getName(), "text" ); bindConstant().annotatedWith( Names.named( "README" ) ).to( "some/temp/readme.txt" ); bindConstant().annotatedWith( Names.named( "SITE" ) ).to( "http://www.sonatype.org" ); bindConstant().annotatedWith( Names.named( "DATE" ) ).to( "2009-11-15 18:02:00" ); install( new PlexusDateTypeConverter() ); bind( PlexusBeanConverter.class ).to( PlexusXmlBeanConverter.class ); install( new ConfigurationConverter() ); } } ).injectMembers( this ); } static class EmptyBean { } static class BeanWithProperties { float value; void setValue( final float _value ) { value = _value; } String text; } static class MissingDefaultConstructor { private MissingDefaultConstructor() { } } static class BrokenDefaultConstructor { public BrokenDefaultConstructor() { throw new RuntimeException(); } } static class MissingStringConstructor { } static class BrokenStringConstructor { public BrokenStringConstructor( final String text ) { throw new RuntimeException( text ); } } @Inject Injector injector; public void testEmptyBeanConversion() { assertEquals( EmptyBean.class, getBean( "EmptyBean", Object.class ).getClass() ); } public void testMissingType() { testFailedConversion( "MissingType", EmptyBean.class ); } public void testPeerClassLoader1() { final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( null ); assertEquals( EmptyBean.class, getBean( "EmptyBean", EmptyBean.class ).getClass() ); } finally { Thread.currentThread().setContextClassLoader( tccl ); } } public void testPeerClassLoader2() { final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( null ); assertEquals( EmptyBean.class, getBean( "EmptyBean", Object.class ).getClass() ); } finally { Thread.currentThread().setContextClassLoader( tccl ); } } public void testBeanWithPropertiesConversion() { final BeanWithProperties beanWithProperties = (BeanWithProperties) getBean( "BeanWithProperty", Object.class ); assertEquals( 4.2f, beanWithProperties.value, 0f ); assertEquals( beanWithProperties.text.length(), 0 ); } public void testMissingPropertyConversion() { testFailedConversion( "MissingProperty", Object.class ); } public void testStringXMLConversion() { final PlexusBeanConverter configurator = injector.getInstance( PlexusBeanConverter.class ); assertEquals( configurator.convert( TypeLiteral.get( String.class ), "" ).length(), 0 ); } public void testMissingDefaultConstructor() { testFailedConversion( "MissingDefaultConstructor", Object.class ); } public void testBrokenDefaultConstructor() { testFailedConversion( "BrokenDefaultConstructor", Object.class ); } public void testMissingStringConstructor() { testFailedConversion( "MissingStringConstructor", Object.class ); } public void testBrokenStringConstructor() { testFailedConversion( "BrokenStringConstructor", Object.class ); } public void testSimpleFileBean() { assertEquals( "readme.txt", injector.getInstance( Key.get( File.class, Names.named( "README" ) ) ).getName() ); } public void testSimpleUrlBean() { assertEquals( "www.sonatype.org", injector.getInstance( Key.get( URL.class, Names.named( "SITE" ) ) ).getHost() ); } public void testNonBean() { final Calendar calendar = Calendar.getInstance(); calendar.setTime( injector.getInstance( Key.get( Date.class, Names.named( "DATE" ) ) ) ); assertEquals( 15, calendar.get( Calendar.DAY_OF_MONTH ) ); assertEquals( Calendar.NOVEMBER, calendar.get( Calendar.MONTH ) ); assertEquals( 2009, calendar.get( Calendar.YEAR ) ); } @SuppressWarnings( "boxing" ) public void testConfigurator() { final PlexusBeanConverter configurator = injector.getInstance( PlexusBeanConverter.class ); final float value = configurator.convert( TypeLiteral.get( float.class ), "4.2" ); assertEquals( 4.2f, value, 0 ); } private Object getBean( final String bindingName, final Class clazz ) { return injector.getInstance( Key.get( clazz, Names.named( bindingName ) ) ); } private void testFailedConversion( final String bindingName, final Class clazz ) { try { getBean( bindingName, clazz ); fail( "Expected ConfigurationException" ); } catch ( final ConfigurationException e ) { } } } CollectionConstantTest.java000066400000000000000000000057571167051330000462560ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/sonatype/guice/plexus/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.converters; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import junit.framework.TestCase; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.name.Names; public class CollectionConstantTest extends TestCase { @Override protected void setUp() throws Exception { Guice.createInjector( new AbstractModule() { private void bind( final String name, final String value ) { bindConstant().annotatedWith( Names.named( name ) ).to( value ); } @Override protected void configure() { bind( "Empty", "" ); bind( "Custom", "" + "FOOBAR" ); bind( "Animals", "catdogaardvark" ); bind( "Numbers", "123456" ); bind( PlexusBeanConverter.class ).to( PlexusXmlBeanConverter.class ); install( new ConfigurationConverter() ); } } ).injectMembers( this ); } @Inject @Named( "Empty" ) List empty; @Inject @Named( "Custom" ) Set custom; @Inject @Named( "Animals" ) Collection animals; @Inject @Named( "Numbers" ) Collection> numbers; public void testEmptyCollection() { assertTrue( empty.isEmpty() ); } public void testCustomCollections() { assertEquals( LinkedHashSet.class, custom.getClass() ); final Iterator i = custom.iterator(); assertEquals( new File( "FOO" ), i.next() ); assertEquals( "BAR", i.next() ); assertFalse( i.hasNext() ); } public void testStringCollection() { assertEquals( Arrays.asList( "cat", "dog", "aardvark" ), animals ); } @SuppressWarnings( { "unchecked", "boxing" } ) public void testPrimitiveCollection() { assertEquals( Arrays.asList( Arrays.asList( 1, 2 ), Arrays.asList( 3, 4 ), Arrays.asList( 5, 6 ) ), numbers ); } } ConfigurationConverter.java000066400000000000000000000044731167051330000463020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/sonatype/guice/plexus/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.converters; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import com.google.inject.Binder; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.google.inject.matcher.AbstractMatcher; import com.google.inject.spi.TypeConverter; import com.google.inject.spi.TypeConverterBinding; public class ConfigurationConverter extends AbstractMatcher> implements TypeConverter, Module { private Collection otherConverterBindings; @Inject private PlexusBeanConverter beanConverter; private boolean available = true; public void configure( final Binder binder ) { binder.convertToTypes( this, this ); binder.requestInjection( this ); } public boolean matches( final TypeLiteral type ) { for ( final TypeConverterBinding b : otherConverterBindings ) { if ( b.getTypeMatcher().matches( type ) ) { return false; } } return available; } public Object convert( final String value, final TypeLiteral toType ) { available = false; try { return beanConverter.convert( toType, value ); } finally { available = true; } } @Inject void setTypeConverterBindings( final Injector injector ) { otherConverterBindings = new ArrayList(); for ( final TypeConverterBinding b : injector.getTypeConverterBindings() ) { if ( false == b.getTypeConverter() instanceof ConfigurationConverter ) { otherConverterBindings.add( b ); } } } } DateConstantTest.java000066400000000000000000000046211167051330000450250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/sonatype/guice/plexus/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.converters; import java.text.SimpleDateFormat; import java.util.Date; import javax.inject.Inject; import javax.inject.Named; import junit.framework.TestCase; import com.google.inject.AbstractModule; import com.google.inject.ConfigurationException; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.name.Names; public class DateConstantTest extends TestCase { @Override protected void setUp() throws Exception { Guice.createInjector( new AbstractModule() { private void bind( final String name, final String value ) { bindConstant().annotatedWith( Names.named( name ) ).to( value ); } @Override protected void configure() { bind( "Format1", "2005-10-06 2:22:55.1 PM" ); bind( "Format2", "2005-10-06 2:22:55PM" ); bind( "BadFormat", "2005-10-06" ); install( new PlexusDateTypeConverter() ); } } ).injectMembers( this ); } @Inject @Named( "Format1" ) String dateText1; @Inject @Named( "Format1" ) Date date1; @Inject @Named( "Format2" ) String dateText2; @Inject @Named( "Format2" ) Date date2; @Inject Injector injector; public void testDateFormat1() { assertEquals( dateText1, new SimpleDateFormat( "yyyy-MM-dd h:mm:ss.S a" ).format( date1 ) ); } public void testDateFormat2() { assertEquals( dateText2, new SimpleDateFormat( "yyyy-MM-dd h:mm:ssa" ).format( date2 ) ); } public void testBadDateFormat() { try { injector.getInstance( Key.get( Date.class, Names.named( "BadFormat" ) ) ); fail( "Expected ConfigurationException" ); } catch ( final ConfigurationException e ) { } } } MapConstantTest.java000066400000000000000000000057751167051330000447000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-converters/src/test/java/org/sonatype/guice/plexus/converters/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.converters; import java.io.File; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import javax.inject.Inject; import javax.inject.Named; import junit.framework.TestCase; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.name.Names; public class MapConstantTest extends TestCase { @Override protected void setUp() throws Exception { Guice.createInjector( new AbstractModule() { private void bind( final String name, final String value ) { bindConstant().annotatedWith( Names.named( name ) ).to( value ); } @Override protected void configure() { bind( "Empty", "" ); bind( "Custom", "" + "TEST" + "TEST" + "" ); bind( "Map", "value1value2" ); bind( "Properties", "key1value1" + "value2key2" ); bind( PlexusBeanConverter.class ).to( PlexusXmlBeanConverter.class ); install( new ConfigurationConverter() ); } } ).injectMembers( this ); } @Inject @Named( "Empty" ) Map empty; @Inject @Named( "Custom" ) Map custom; @Inject @Named( "Map" ) Map map; @Inject @Named( "Properties" ) Properties properties; public void testEmptyMap() { assertTrue( empty.isEmpty() ); } public void testCustomMap() { assertEquals( LinkedHashMap.class, custom.getClass() ); assertEquals( "TEST", custom.get( "builder" ).toString() ); assertEquals( StringBuilder.class, custom.get( "builder" ).getClass() ); assertEquals( new File( "TEST" ), custom.get( "file" ) ); } public void testMapAndProperties() { final HashMap testMap = new HashMap(); testMap.put( "key1", "value1" ); testMap.put( "key2", "value2" ); assertEquals( testMap, map ); assertEquals( testMap, properties ); } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/000077500000000000000000000000001167051330000270115ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/pom.xml000066400000000000000000000032071167051330000303300ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-plexus 2.3.0 guice-plexus-lifecycles Sisu-Inject-Plexus : @Component lifecycles javax.inject javax.inject org.sonatype.sisu sisu-guice org.slf4j slf4j-api true org.sonatype.sisu.inject guice-bean-reflect org.sonatype.sisu.inject guice-bean-inject org.sonatype.sisu.inject guice-plexus-binders sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/000077500000000000000000000000001167051330000276005ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/000077500000000000000000000000001167051330000305245ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/000077500000000000000000000000001167051330000314455ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/000077500000000000000000000000001167051330000322345ustar00rootroot00000000000000000077500000000000000000000000001167051330000337505ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus000077500000000000000000000000001167051330000352705ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus000077500000000000000000000000001167051330000367545ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/contextContext.java000066400000000000000000000013301167051330000412400ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/context/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.context; import java.util.Map; public interface Context { boolean contains( Object key ); void put( Object key, Object value ); Object get( Object key ) throws ContextException; Map getContextData(); } ContextException.java000066400000000000000000000014641167051330000431270ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/context/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.context; public final class ContextException extends Exception { private static final long serialVersionUID = 1L; public ContextException( final String message ) { super( message ); } public ContextException( final String message, final Throwable detail ) { super( message, detail ); } } 000077500000000000000000000000001167051330000367165ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/loggingAbstractLogger.java000066400000000000000000000051611167051330000424670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/logging/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.logging; public abstract class AbstractLogger implements Logger { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final String name; private int threshold; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public AbstractLogger( final int threshold, final String name ) { this.name = name; if ( threshold < LEVEL_DEBUG || LEVEL_DISABLED < threshold ) { throw new IllegalArgumentException( "Threshold " + threshold + " is not valid" ); } this.threshold = threshold; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public final void debug( final String message ) { debug( message, null ); } public boolean isDebugEnabled() { return threshold <= LEVEL_DEBUG; } public final void info( final String message ) { info( message, null ); } public boolean isInfoEnabled() { return threshold <= LEVEL_INFO; } public final void warn( final String message ) { warn( message, null ); } public boolean isWarnEnabled() { return threshold <= LEVEL_WARN; } public final void error( final String message ) { error( message, null ); } public boolean isErrorEnabled() { return threshold <= LEVEL_ERROR; } public final void fatalError( final String message ) { fatalError( message, null ); } public boolean isFatalErrorEnabled() { return threshold <= LEVEL_FATAL; } public final int getThreshold() { return threshold; } public final void setThreshold( final int threshold ) { this.threshold = threshold; } public final String getName() { return name; } } LogEnabled.java000066400000000000000000000010641167051330000415560ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/logging/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.logging; public interface LogEnabled { void enableLogging( Logger logger ); } Logger.java000066400000000000000000000036531167051330000410070ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/logging/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.logging; public interface Logger { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- int LEVEL_DEBUG = 0; int LEVEL_INFO = 1; int LEVEL_WARN = 2; int LEVEL_ERROR = 3; int LEVEL_FATAL = 4; int LEVEL_DISABLED = 5; // ---------------------------------------------------------------------- // Logging methods // ---------------------------------------------------------------------- void debug( String message ); void debug( String message, Throwable throwable ); boolean isDebugEnabled(); void info( String message ); void info( String message, Throwable throwable ); boolean isInfoEnabled(); void warn( String message ); void warn( String message, Throwable throwable ); boolean isWarnEnabled(); void error( String message ); void error( String message, Throwable throwable ); boolean isErrorEnabled(); void fatalError( String message ); void fatalError( String message, Throwable throwable ); boolean isFatalErrorEnabled(); // ---------------------------------------------------------------------- // Management methods // ---------------------------------------------------------------------- int getThreshold(); void setThreshold( int threshold ); Logger getChildLogger( String name ); String getName(); } LoggerManager.java000066400000000000000000000016521167051330000422770ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/logging/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.logging; public interface LoggerManager { String ROLE = LoggerManager.class.getName(); Logger getLoggerForComponent( String role ); Logger getLoggerForComponent( String role, String hint ); void returnComponentLogger( String role ); void returnComponentLogger( String role, String hint ); int getThreshold(); void setThreshold( int threshold ); void setThresholds( int threshold ); int getActiveLoggerCount(); } 000077500000000000000000000000001167051330000403605ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/logging/consoleConsoleLogger.java000066400000000000000000000056751167051330000440020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/logging/console/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.logging.console; import org.codehaus.plexus.logging.AbstractLogger; import org.codehaus.plexus.logging.Logger; public final class ConsoleLogger extends AbstractLogger { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String[] TAGS = { "[DEBUG] ", "[INFO] ", "[WARNING] ", "[ERROR] ", "[FATAL ERROR] " }; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public ConsoleLogger( final int threshold, final String name ) { super( threshold, name ); } public ConsoleLogger() { this( Logger.LEVEL_INFO, "console" ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void debug( final String message, final Throwable throwable ) { if ( isDebugEnabled() ) { log( LEVEL_DEBUG, message, throwable ); } } public void info( final String message, final Throwable throwable ) { if ( isInfoEnabled() ) { log( LEVEL_INFO, message, throwable ); } } public void warn( final String message, final Throwable throwable ) { if ( isWarnEnabled() ) { log( LEVEL_WARN, message, throwable ); } } public void error( final String message, final Throwable throwable ) { if ( isErrorEnabled() ) { log( LEVEL_ERROR, message, throwable ); } } public void fatalError( final String message, final Throwable throwable ) { if ( isFatalErrorEnabled() ) { log( LEVEL_FATAL, message, throwable ); } } public Logger getChildLogger( final String name ) { return this; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static void log( final int level, final String message, final Throwable throwable ) { System.out.println( TAGS[level].concat( message ) ); if ( throwable != null ) { throwable.printStackTrace( System.out ); } } } 000077500000000000000000000000001167051330000376415ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality000077500000000000000000000000001167051330000411615ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality/plexus000077500000000000000000000000001167051330000431205ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle000077500000000000000000000000001167051330000442205ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phaseContextualizable.java000066400000000000000000000013311167051330000503760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; public interface Contextualizable { void contextualize( Context context ) throws ContextException; } Disposable.java000066400000000000000000000010721167051330000471500ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; public interface Disposable { void dispose(); } Initializable.java000066400000000000000000000011471167051330000476460ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; public interface Initializable { void initialize() throws InitializationException; } InitializationException.java000066400000000000000000000015421167051330000517330ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; public final class InitializationException extends Exception { private static final long serialVersionUID = 1L; public InitializationException( final String message ) { super( message ); } public InitializationException( final String message, final Throwable cause ) { super( message, cause ); } } Startable.java000066400000000000000000000012131167051330000470010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; public interface Startable { void start() throws StartingException; void stop() throws StoppingException; } StartingException.java000066400000000000000000000015201167051330000505330ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; public final class StartingException extends Exception { private static final long serialVersionUID = 1L; public StartingException( final String message ) { super( message ); } public StartingException( final String message, final Throwable cause ) { super( message, cause ); } } StoppingException.java000066400000000000000000000015201167051330000505430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; public final class StoppingException extends Exception { private static final long serialVersionUID = 1L; public StoppingException( final String message ) { super( message ); } public StoppingException( final String message, final Throwable cause ) { super( message, cause ); } } 000077500000000000000000000000001167051330000340175ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/sonatype000077500000000000000000000000001167051330000351135ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000364335ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000405555ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/sonatype/guice/plexus/lifecyclesPlexusLifecycleManager.java000066400000000000000000000312261167051330000460170ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-lifecycles/src/main/java/org/sonatype/guice/plexus/lifecycles/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.lifecycles; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Provider; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.logging.LogEnabled; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.LoggerManager; import org.codehaus.plexus.logging.console.ConsoleLogger; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Disposable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; import org.sonatype.guice.bean.inject.PropertyBinding; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.plexus.binders.PlexusBeanManager; import com.google.inject.spi.ProvisionListener; /** * {@link PlexusBeanManager} that manages Plexus components requiring lifecycle management. */ public final class PlexusLifecycleManager implements PlexusBeanManager, ProvisionListener { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final Class[] LIFECYCLE_TYPES = { LogEnabled.class, Contextualizable.class, Initializable.class, Startable.class, Disposable.class }; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private static final ThreadLocal[]> pendingHolder = new ThreadLocal[]>() { @Override protected List[] initialValue() { return new List[1]; } }; private final List startableBeans = new ArrayList(); private final List disposableBeans = new ArrayList(); private final Logger consoleLogger = new ConsoleLogger(); private final Provider plexusContextProvider; private final Provider plexusLoggerManagerProvider; private final Provider slf4jLoggerFactoryProvider; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public PlexusLifecycleManager( final Provider plexusContextProvider, final Provider plexusLoggerManagerProvider, final Provider slf4jLoggerFactoryProvider ) { this.plexusContextProvider = plexusContextProvider; this.plexusLoggerManagerProvider = plexusLoggerManagerProvider; this.slf4jLoggerFactoryProvider = slf4jLoggerFactoryProvider; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean manage( final Class clazz ) { for ( final Class lifecycleType : LIFECYCLE_TYPES ) { if ( lifecycleType.isAssignableFrom( clazz ) ) { return true; } } return false; } @SuppressWarnings( "rawtypes" ) public PropertyBinding manage( final BeanProperty property ) { final Class clazz = property.getType().getRawType(); if ( "org.slf4j.Logger".equals( clazz.getName() ) ) { return new PropertyBinding() { @SuppressWarnings( "unchecked" ) public void injectProperty( final B bean ) { property.set( bean, getSLF4JLogger( bean ) ); } }; } if ( Logger.class.equals( clazz ) ) { return new PropertyBinding() { @SuppressWarnings( "unchecked" ) public void injectProperty( final B bean ) { property.set( bean, getPlexusLogger( bean ) ); } }; } return null; } public void onProvision( final ProvisionInvocation pi ) { final List[] holder = pendingHolder.get(); if ( null == holder[0] ) { List beans; holder[0] = Collections.EMPTY_LIST; try { pi.provision(); } finally { beans = holder[0]; holder[0] = null; } for ( int i = 0, size = beans.size(); i < size; i++ ) { manageLifecycle( beans.get( i ) ); } } } @SuppressWarnings( { "rawtypes", "unchecked" } ) public boolean manage( final Object bean ) { if ( bean instanceof Disposable ) { synchronizedAdd( disposableBeans, (Disposable) bean ); } if ( bean instanceof LogEnabled ) { ( (LogEnabled) bean ).enableLogging( getPlexusLogger( bean ) ); } if ( bean instanceof Contextualizable || bean instanceof Initializable || bean instanceof Startable ) { final List[] holder = pendingHolder.get(); List beans = holder[0]; if ( null == beans || beans.isEmpty() ) { holder[0] = beans = new ArrayList(); } beans.add( bean ); } return true; } public boolean unmanage( final Object bean ) { if ( synchronizedRemove( startableBeans, bean ) ) { stop( (Startable) bean ); } if ( synchronizedRemove( disposableBeans, bean ) ) { dispose( (Disposable) bean ); } return true; } public boolean unmanage() { for ( Startable bean; ( bean = synchronizedRemoveLast( startableBeans ) ) != null; ) { stop( bean ); } for ( Disposable bean; ( bean = synchronizedRemoveLast( disposableBeans ) ) != null; ) { dispose( bean ); } pendingHolder.remove(); return true; } public PlexusBeanManager manageChild() { return this; } // ---------------------------------------------------------------------- // Shared implementation methods // ---------------------------------------------------------------------- Logger getPlexusLogger( final Object bean ) { final String name = bean.getClass().getName(); try { return plexusLoggerManagerProvider.get().getLoggerForComponent( name, null ); } catch ( final RuntimeException e ) { return consoleLogger; } } Object getSLF4JLogger( final Object bean ) { final String name = bean.getClass().getName(); try { return ( (org.slf4j.ILoggerFactory) slf4jLoggerFactoryProvider.get() ).getLogger( name ); } catch ( final RuntimeException e ) { return org.slf4j.LoggerFactory.getLogger( name ); } } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static boolean synchronizedAdd( final List list, final T element ) { synchronized ( list ) { return list.add( element ); } } private static boolean synchronizedRemove( final List list, final Object element ) { synchronized ( list ) { return list.remove( element ); } } private static T synchronizedRemoveLast( final List list ) { synchronized ( list ) { final int size = list.size(); if ( size > 0 ) { return list.remove( size - 1 ); } return null; } } private void manageLifecycle( final Object bean ) { final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { for ( Class clazz = bean.getClass(); clazz != null; clazz = clazz.getSuperclass() ) { // need to check hierarchy in case bean is proxied final ClassLoader loader = clazz.getClassLoader(); if ( loader instanceof URLClassLoader ) { Thread.currentThread().setContextClassLoader( loader ); break; } } /* * Run through the startup phase of the standard plexus "personality" */ if ( bean instanceof Contextualizable ) { contextualize( (Contextualizable) bean ); } if ( bean instanceof Initializable ) { initialize( (Initializable) bean ); } if ( bean instanceof Startable ) { // register before calling start in case it fails final Startable startableBean = (Startable) bean; synchronizedAdd( startableBeans, startableBean ); start( startableBean ); } } finally { Thread.currentThread().setContextClassLoader( tccl ); } } private void contextualize( final Contextualizable bean ) { Logs.debug( "Contextualize: <>", bean, null ); try { bean.contextualize( plexusContextProvider.get() ); } catch ( final Throwable e ) { Logs.catchThrowable( e ); try { getPlexusLogger( this ).warn( "Error contextualizing: " + Logs.identityToString( bean ), e ); } finally { Logs.throwUnchecked( e ); } } } private void initialize( final Initializable bean ) { Logs.debug( "Initialize: <>", bean, null ); try { bean.initialize(); } catch ( final Throwable e ) { Logs.catchThrowable( e ); try { getPlexusLogger( this ).warn( "Error initializing: " + Logs.identityToString( bean ), e ); } finally { Logs.throwUnchecked( e ); } } } private void start( final Startable bean ) { Logs.debug( "Start: <>", bean, null ); try { bean.start(); } catch ( final Throwable e ) { Logs.catchThrowable( e ); try { getPlexusLogger( this ).warn( "Error starting: " + Logs.identityToString( bean ), e ); } finally { Logs.throwUnchecked( e ); } } } @SuppressWarnings( "finally" ) private void stop( final Startable bean ) { Logs.debug( "Stop: <>", bean, null ); try { bean.stop(); } catch ( final Throwable e ) { Logs.catchThrowable( e ); try { getPlexusLogger( this ).warn( "Problem stopping: " + Logs.identityToString( bean ), e ); } finally { return; // ignore any logging exceptions and continue with shutdown } } } @SuppressWarnings( "finally" ) private void dispose( final Disposable bean ) { Logs.debug( "Dispose: <>", bean, null ); try { bean.dispose(); } catch ( final Throwable e ) { Logs.catchThrowable( e ); try { getPlexusLogger( this ).warn( "Problem disposing: " + Logs.identityToString( bean ), e ); } finally { return; // ignore any logging exceptions and continue with shutdown } } } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/000077500000000000000000000000001167051330000265155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/pom.xml000066400000000000000000000027571167051330000300450ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-plexus 2.3.0 guice-plexus-locators Sisu-Inject-Plexus : Dynamic bindings javax.inject javax.inject org.sonatype.sisu sisu-guice org.sonatype.sisu.inject guice-bean-locators org.sonatype.sisu.inject guice-plexus-metadata org.codehaus.plexus plexus-classworlds sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/000077500000000000000000000000001167051330000273045ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/000077500000000000000000000000001167051330000302305ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/000077500000000000000000000000001167051330000311515ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/000077500000000000000000000000001167051330000317405ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/000077500000000000000000000000001167051330000336025ustar00rootroot00000000000000000077500000000000000000000000001167051330000346175ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000361375ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000377655ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/guice/plexus/locatorsClassRealmUtils.java000066400000000000000000000102021167051330000436720ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/guice/plexus/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.locators; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.sonatype.guice.bean.reflect.Weak; public final class ClassRealmUtils { // ---------------------------------------------------------------------- // Static initialization // ---------------------------------------------------------------------- static { boolean getImportRealmsSupported = true; try { // support both old and new forms of Plexus class realms ClassRealm.class.getDeclaredMethod( "getImportRealms" ); } catch ( final Exception e ) { getImportRealmsSupported = false; } catch ( final LinkageError e ) { getImportRealmsSupported = false; } GET_IMPORT_REALMS_SUPPORTED = getImportRealmsSupported; } // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final boolean GET_IMPORT_REALMS_SUPPORTED; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private ClassRealmUtils() { // static utility class, not allowed to create instances } // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private static Map> namesCache = Weak.concurrentKeys(); // ---------------------------------------------------------------------- // Utility methods // ---------------------------------------------------------------------- public static ClassRealm contextRealm() { for ( ClassLoader tccl = Thread.currentThread().getContextClassLoader(); tccl != null; tccl = tccl.getParent() ) { if ( tccl instanceof ClassRealm ) { return (ClassRealm) tccl; } } return null; } public static Set visibleRealmNames( final ClassRealm contextRealm ) { if ( GET_IMPORT_REALMS_SUPPORTED && null != contextRealm ) { Set names = namesCache.get( contextRealm ); if ( null == names ) { namesCache.put( contextRealm, names = computeVisibleNames( contextRealm ) ); } return names; } return null; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- @SuppressWarnings( "unchecked" ) private static Set computeVisibleNames( final ClassRealm forRealm ) { final Set visibleRealmNames = new HashSet(); final List searchRealms = new ArrayList(); searchRealms.add( forRealm ); for ( int i = 0; i < searchRealms.size(); i++ ) { final ClassRealm realm = searchRealms.get( i ); if ( visibleRealmNames.add( realm.toString() ) ) { searchRealms.addAll( realm.getImportRealms() ); final ClassRealm parent = realm.getParentRealm(); if ( null != parent ) { searchRealms.add( parent ); } } } return visibleRealmNames; } } DefaultPlexusBeanLocator.java000066400000000000000000000055011167051330000455300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/guice/plexus/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.locators; import javax.inject.Inject; import javax.inject.Singleton; import org.sonatype.guice.bean.locators.BeanLocator; import org.sonatype.guice.plexus.config.PlexusBean; import org.sonatype.guice.plexus.config.PlexusBeanLocator; import org.sonatype.inject.BeanEntry; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; import com.google.inject.name.Names; /** * {@link PlexusBeanLocator} that locates beans of various types from zero or more {@link Injector}s. */ @Singleton public final class DefaultPlexusBeanLocator implements PlexusBeanLocator { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String REALM_VISIBILITY = "realm"; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final BeanLocator beanLocator; private final String visibility; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- @Inject public DefaultPlexusBeanLocator( final BeanLocator beanLocator ) { this( beanLocator, REALM_VISIBILITY ); } public DefaultPlexusBeanLocator( final BeanLocator beanLocator, final String visibility ) { this.beanLocator = beanLocator; this.visibility = visibility; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterable> locate( final TypeLiteral role, final String... hints ) { final Key key = hints.length == 1 ? Key.get( role, Names.named( hints[0] ) ) : Key.get( role, Named.class ); Iterable> beans = beanLocator.locate( key ); if ( REALM_VISIBILITY.equalsIgnoreCase( visibility ) ) { beans = new RealmFilter( beans ); } return hints.length <= 1 ? new DefaultPlexusBeans( beans ) : new HintedPlexusBeans( beans, role, hints ); } } DefaultPlexusBeans.java000066400000000000000000000041501167051330000443660ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/guice/plexus/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.locators; import java.util.Iterator; import org.sonatype.guice.plexus.config.PlexusBean; import org.sonatype.inject.BeanEntry; import com.google.inject.name.Named; final class DefaultPlexusBeans implements Iterable> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- Iterable> beans; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- DefaultPlexusBeans( final Iterable> beans ) { this.beans = beans; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterator> iterator() { return new Itr(); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- final class Itr implements Iterator> { private final Iterator> itr = beans.iterator(); public boolean hasNext() { return itr.hasNext(); } public PlexusBean next() { return new LazyPlexusBean( itr.next() ); } public void remove() { throw new UnsupportedOperationException(); } } } HintedPlexusBeans.java000066400000000000000000000052771167051330000442300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/guice/plexus/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.locators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.sonatype.guice.plexus.config.PlexusBean; import org.sonatype.inject.BeanEntry; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; final class HintedPlexusBeans implements Iterable> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Iterable> beans; private final List> missingPlexusBeans; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- HintedPlexusBeans( final Iterable> beans, final TypeLiteral role, final String[] hints ) { this.beans = beans; missingPlexusBeans = new ArrayList>( hints.length ); for ( final String h : hints ) { missingPlexusBeans.add( new MissingPlexusBean( role, h ) ); } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterator> iterator() { final List> plexusBeans = new ArrayList>( missingPlexusBeans ); final int size = plexusBeans.size(); final Iterator> itr = beans.iterator(); for ( int numFound = 0; numFound < size && itr.hasNext(); ) { final BeanEntry candidate = itr.next(); final String hint = candidate.getKey().value(); for ( int i = 0; i < size; i++ ) { final PlexusBean element = plexusBeans.get( i ); if ( element instanceof MissingPlexusBean && hint.equals( element.getKey() ) ) { plexusBeans.set( i, new LazyPlexusBean( candidate ) ); numFound++; } } } return plexusBeans.iterator(); } } LazyPlexusBean.java000066400000000000000000000040221167051330000435340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/guice/plexus/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.locators; import java.util.Map.Entry; import org.sonatype.guice.plexus.config.PlexusBean; import org.sonatype.inject.BeanEntry; import com.google.inject.name.Named; /** * {@link Entry} representing a lazy @{@link Named} Plexus bean; the bean is only retrieved when the value is requested. */ final class LazyPlexusBean implements PlexusBean { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final BeanEntry bean; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- LazyPlexusBean( final BeanEntry bean ) { this.bean = bean; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public String getKey() { return bean.getKey().value(); } public T getValue() { return bean.getValue(); } public T setValue( final T value ) { throw new UnsupportedOperationException(); } public String getDescription() { return bean.getDescription(); } public Class getImplementationClass() { return bean.getImplementationClass(); } @Override public String toString() { return getKey() + "=" + getValue(); } } MissingPlexusBean.java000066400000000000000000000040711167051330000442320ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/guice/plexus/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.locators; import java.util.Map.Entry; import org.sonatype.guice.plexus.config.PlexusBean; import org.sonatype.guice.plexus.config.Roles; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; /** * {@link Entry} representing a missing @{@link Named} Plexus bean. */ final class MissingPlexusBean implements PlexusBean { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final TypeLiteral role; private final String hint; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- MissingPlexusBean( final TypeLiteral role, final String hint ) { this.role = role; this.hint = hint; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public String getKey() { return hint; } public T getValue() { return Roles.throwMissingComponentException( role, hint ); } public T setValue( final T value ) { throw new UnsupportedOperationException(); } public String getDescription() { return null; } public Class getImplementationClass() { return null; } @Override public String toString() { return getKey() + "="; } } RealmFilter.java000066400000000000000000000063531167051330000430450ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/main/java/org/sonatype/guice/plexus/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.locators; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import org.sonatype.inject.BeanEntry; import com.google.inject.name.Named; final class RealmFilter implements Iterable> { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- final Iterable> beans; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- RealmFilter( final Iterable> beans ) { this.beans = beans; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Iterator> iterator() { final Set realmNames = ClassRealmUtils.visibleRealmNames( ClassRealmUtils.contextRealm() ); if ( null != realmNames && realmNames.size() > 0 ) { return new FilteredItr( realmNames ); } return beans.iterator(); } // ---------------------------------------------------------------------- // Implementation types // ---------------------------------------------------------------------- final class FilteredItr implements Iterator> { private final Iterator> itr = beans.iterator(); private final Set realmNames; private BeanEntry nextBean; public FilteredItr( final Set realmNames ) { this.realmNames = realmNames; } public boolean hasNext() { if ( null != nextBean ) { return true; } while ( itr.hasNext() ) { nextBean = itr.next(); final String source = nextBean.getSource().toString(); if ( !source.startsWith( "ClassRealm" ) || realmNames.contains( source ) ) { return true; } } nextBean = null; return false; } public BeanEntry next() { if ( hasNext() ) { // populated by hasNext() final BeanEntry bean = nextBean; nextBean = null; return bean; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/test/000077500000000000000000000000001167051330000302635ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/test/java/000077500000000000000000000000001167051330000312045ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/test/java/org/000077500000000000000000000000001167051330000317735ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/test/java/org/sonatype/000077500000000000000000000000001167051330000336355ustar00rootroot00000000000000000077500000000000000000000000001167051330000346525ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000361725ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/test/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000400205ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/test/java/org/sonatype/guice/plexus/locatorsPlexusBeanLocatorTest.java000066400000000000000000000446041167051330000451250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-locators/src/test/java/org/sonatype/guice/plexus/locators/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.locators; import java.util.Iterator; import java.util.Map.Entry; import junit.framework.TestCase; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.ClassWorldException; import org.codehaus.plexus.classworlds.realm.DuplicateRealmException; import org.codehaus.plexus.classworlds.realm.NoSuchRealmException; import org.sonatype.guice.bean.locators.DefaultBeanLocator; import org.sonatype.guice.bean.locators.HiddenBinding; import org.sonatype.guice.bean.locators.MutableBeanLocator; import com.google.inject.AbstractModule; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; @SuppressWarnings( "deprecation" ) public class PlexusBeanLocatorTest extends TestCase { static final HiddenBinding TEST_HIDDEN_SOURCE = new HiddenBinding() { }; @ImplementedBy( BeanImpl.class ) interface Bean { } static class BeanImpl implements Bean { } Injector parent; Injector child1; Injector child2; Injector child3; @Override public void setUp() throws Exception { parent = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "A" ) ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Names.named( "-" ) ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Names.named( "Z" ) ).to( BeanImpl.class ); } } ); child1 = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "M1" ) ).to( BeanImpl.class ); final Binder hiddenBinder = binder().withSource( TEST_HIDDEN_SOURCE ); hiddenBinder.bind( Bean.class ).annotatedWith( Names.named( "!" ) ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Names.named( "N1" ) ).to( BeanImpl.class ); } } ); child2 = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { } } ); child3 = parent.createChildInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "M3" ) ).to( BeanImpl.class ); bind( Bean.class ).annotatedWith( Names.named( "N3" ) ).to( BeanImpl.class ); } } ); } public void testInjectorOrdering() { final MutableBeanLocator locator = new DefaultBeanLocator(); final Iterable> roles = new DefaultPlexusBeanLocator( locator ).locate( TypeLiteral.get( Bean.class ) ); locator.add( parent, 0 ); locator.add( child1, 1 ); locator.add( child2, 2 ); locator.add( child3, 3 ); locator.remove( child1 ); locator.add( child1, 4 ); Iterator> i; i = roles.iterator(); assertEquals( "M1", i.next().getKey() ); assertEquals( "N1", i.next().getKey() ); assertEquals( "M3", i.next().getKey() ); assertEquals( "N3", i.next().getKey() ); assertEquals( "A", i.next().getKey() ); assertEquals( "-", i.next().getKey() ); assertEquals( "Z", i.next().getKey() ); assertFalse( i.hasNext() ); locator.remove( child2 ); locator.remove( child2 ); i = roles.iterator(); assertEquals( "M1", i.next().getKey() ); assertEquals( "N1", i.next().getKey() ); assertEquals( "M3", i.next().getKey() ); assertEquals( "N3", i.next().getKey() ); assertEquals( "A", i.next().getKey() ); assertEquals( "-", i.next().getKey() ); assertEquals( "Z", i.next().getKey() ); assertFalse( i.hasNext() ); locator.remove( child3 ); locator.add( child3, 5 ); locator.add( child3, 5 ); i = roles.iterator(); assertEquals( "M3", i.next().getKey() ); assertEquals( "N3", i.next().getKey() ); assertEquals( "M1", i.next().getKey() ); assertEquals( "N1", i.next().getKey() ); assertEquals( "A", i.next().getKey() ); assertEquals( "-", i.next().getKey() ); assertEquals( "Z", i.next().getKey() ); assertFalse( i.hasNext() ); locator.remove( parent ); i = roles.iterator(); assertEquals( "M3", i.next().getKey() ); assertEquals( "N3", i.next().getKey() ); assertEquals( "M1", i.next().getKey() ); assertEquals( "N1", i.next().getKey() ); assertFalse( i.hasNext() ); locator.remove( child1 ); locator.remove( child3 ); i = roles.iterator(); assertFalse( i.hasNext() ); } public void testExistingInjectors() { final MutableBeanLocator locator = new DefaultBeanLocator(); locator.add( parent, 0 ); locator.add( child1, 1 ); final Iterable> roles = new DefaultPlexusBeanLocator( locator ).locate( TypeLiteral.get( Bean.class ) ); locator.add( child2, 2 ); locator.add( child3, 3 ); Iterator> i; i = roles.iterator(); assertEquals( "M3", i.next().getKey() ); assertEquals( "N3", i.next().getKey() ); assertEquals( "M1", i.next().getKey() ); assertEquals( "N1", i.next().getKey() ); assertEquals( "A", i.next().getKey() ); assertEquals( "-", i.next().getKey() ); assertEquals( "Z", i.next().getKey() ); assertFalse( i.hasNext() ); } public void testRoleHintLookup() { final MutableBeanLocator locator = new DefaultBeanLocator(); final Iterable> roles = new DefaultPlexusBeanLocator( locator ).locate( TypeLiteral.get( Bean.class ), "A", "M1", "N3", "-", "!", "-", "M3", "N1", "Z" ); Iterator> i; i = roles.iterator(); assertEquals( "A", i.next().getKey() ); assertEquals( "M1", i.next().getKey() ); assertEquals( "N3", i.next().getKey() ); assertEquals( "-", i.next().getKey() ); final Entry pling = i.next(); assertEquals( "!", pling.getKey() ); assertEquals( "-", i.next().getKey() ); assertEquals( "M3", i.next().getKey() ); assertEquals( "N1", i.next().getKey() ); assertEquals( "Z", i.next().getKey() ); assertFalse( i.hasNext() ); assertEquals( "!=", pling.toString() ); try { pling.getValue(); fail( "Expected ProvisionException" ); } catch ( final ProvisionException e ) { } try { pling.setValue( null ); fail( "Expected UnsupportedOperationException" ); } catch ( final UnsupportedOperationException e ) { } locator.add( parent, 0 ); locator.add( child1, 1 ); locator.add( child2, 2 ); locator.add( child3, 3 ); locator.add( parent.createChildInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "M1" ) ).toProvider( new Provider() { public Bean get() { return null; } } ); bind( Bean.class ).annotatedWith( Names.named( "M3" ) ).toProvider( new Provider() { public Bean get() { return null; } } ); } } ), 4 ); Entry m1, dash1, dash2, m3; i = roles.iterator(); assertEquals( "A", i.next().getKey() ); m1 = i.next(); assertEquals( "M1", m1.getKey() ); assertEquals( "N3", i.next().getKey() ); dash1 = i.next(); assertEquals( "-", dash1.getKey() ); assertEquals( "!", i.next().getKey() ); dash2 = i.next(); assertEquals( "-", dash2.getKey() ); m3 = i.next(); assertEquals( "M3", m3.getKey() ); assertEquals( "N1", i.next().getKey() ); assertEquals( "Z", i.next().getKey() ); assertFalse( i.hasNext() ); assertNull( m1.getValue() ); assertSame( dash1.getValue(), dash2.getValue() ); assertNull( m3.getValue() ); locator.remove( child1 ); locator.add( child1, 5 ); i = roles.iterator(); assertEquals( "A", i.next().getKey() ); m1 = i.next(); assertEquals( "M1", m1.getKey() ); assertEquals( "N3", i.next().getKey() ); dash1 = i.next(); assertEquals( "-", dash1.getKey() ); assertEquals( "!", i.next().getKey() ); dash2 = i.next(); assertEquals( "-", dash2.getKey() ); m3 = i.next(); assertEquals( "M3", m3.getKey() ); assertEquals( "N1", i.next().getKey() ); assertEquals( "Z", i.next().getKey() ); assertFalse( i.hasNext() ); assertEquals( "M1=" + m1.getValue(), m1.toString() ); assertEquals( BeanImpl.class, m1.getValue().getClass() ); assertSame( m1.getValue(), m1.getValue() ); assertSame( dash1.getValue(), dash2.getValue() ); assertNull( m3.getValue() ); } public void testInjectorVisibility() throws NoSuchRealmException { final MutableBeanLocator locator = new DefaultBeanLocator(); final ClassWorld world = new ClassWorld(); locator.add( Guice.createInjector( new Module() { public void configure( final Binder binder ) { try { binder.withSource( world.newRealm( "A" ) ).bind( Bean.class ).annotatedWith( Names.named( "A" ) ).to( BeanImpl.class ); } catch ( final DuplicateRealmException e ) { throw new RuntimeException( e ); } } } ), 1 ); locator.add( Guice.createInjector( new Module() { public void configure( final Binder binder ) { try { binder.withSource( world.newRealm( "B" ) ).bind( Bean.class ).annotatedWith( Names.named( "B" ) ).to( BeanImpl.class ); } catch ( final DuplicateRealmException e ) { throw new RuntimeException( e ); } } } ), 2 ); locator.add( Guice.createInjector( new Module() { public void configure( final Binder binder ) { try { binder.withSource( world.newRealm( "C" ) ).bind( Bean.class ).annotatedWith( Names.named( "C" ) ).to( BeanImpl.class ); } catch ( final DuplicateRealmException e ) { throw new RuntimeException( e ); } } } ), 3 ); locator.add( Guice.createInjector( new Module() { public void configure( final Binder binder ) { try { binder.withSource( world.getRealm( "B" ).createChildRealm( "B1" ) ).bind( Bean.class ).annotatedWith( Names.named( "B1" ) ).to( BeanImpl.class ); } catch ( final ClassWorldException e ) { throw new RuntimeException( e ); } } } ), 4 ); locator.add( Guice.createInjector( new Module() { public void configure( final Binder binder ) { try { binder.withSource( world.getRealm( "B" ).createChildRealm( "B2" ) ).bind( Bean.class ).annotatedWith( Names.named( "B2" ) ).to( BeanImpl.class ); } catch ( final ClassWorldException e ) { throw new RuntimeException( e ); } } } ), 5 ); locator.add( Guice.createInjector( new Module() { public void configure( final Binder binder ) { try { binder.withSource( world.getRealm( "B" ).createChildRealm( "B3" ) ).bind( Bean.class ).annotatedWith( Names.named( "B3" ) ).to( BeanImpl.class ); } catch ( final ClassWorldException e ) { throw new RuntimeException( e ); } } } ), 6 ); locator.add( Guice.createInjector( new Module() { public void configure( final Binder binder ) { try { binder.withSource( world.getRealm( "B2" ).createChildRealm( "B2B" ) ).bind( Bean.class ).annotatedWith( Names.named( "B2B" ) ).to( BeanImpl.class ); } catch ( final ClassWorldException e ) { throw new RuntimeException( e ); } } } ), 7 ); locator.add( Guice.createInjector( new Module() { public void configure( final Binder binder ) { try { binder.withSource( world.newRealm( "?" ) ).bind( Bean.class ).annotatedWith( Names.named( "?" ) ).to( BeanImpl.class ); } catch ( final DuplicateRealmException e ) { throw new RuntimeException( e ); } } } ), 8 ); world.getRealm( "B" ).importFrom( "A", "A" ); world.getRealm( "B" ).importFrom( "C", "C" ); world.getRealm( "B2" ).importFrom( "B1", "B1" ); world.getRealm( "B2" ).importFrom( "B3", "B3" ); locator.add( Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind( Bean.class ).annotatedWith( Names.named( "!" ) ).to( BeanImpl.class ); } } ), 9 ); final Iterable> beans = new DefaultPlexusBeanLocator( locator ).locate( TypeLiteral.get( Bean.class ) ); Iterator> i; Thread.currentThread().setContextClassLoader( world.getClassRealm( "A" ) ); i = beans.iterator(); assertTrue( i.hasNext() ); assertEquals( "!", i.next().getKey() ); assertEquals( "A", i.next().getKey() ); assertFalse( i.hasNext() ); Thread.currentThread().setContextClassLoader( world.getClassRealm( "B" ) ); i = beans.iterator(); assertTrue( i.hasNext() ); assertEquals( "!", i.next().getKey() ); assertEquals( "C", i.next().getKey() ); assertEquals( "B", i.next().getKey() ); assertEquals( "A", i.next().getKey() ); assertFalse( i.hasNext() ); Thread.currentThread().setContextClassLoader( world.getClassRealm( "B2" ) ); i = beans.iterator(); assertTrue( i.hasNext() ); assertEquals( "!", i.next().getKey() ); assertEquals( "B3", i.next().getKey() ); assertEquals( "B2", i.next().getKey() ); assertEquals( "B1", i.next().getKey() ); assertEquals( "C", i.next().getKey() ); assertEquals( "B", i.next().getKey() ); assertEquals( "A", i.next().getKey() ); assertFalse( i.hasNext() ); Thread.currentThread().setContextClassLoader( world.getClassRealm( "B2B" ) ); i = beans.iterator(); assertTrue( i.hasNext() ); assertEquals( "!", i.next().getKey() ); assertEquals( "B2B", i.next().getKey() ); assertEquals( "B3", i.next().getKey() ); assertEquals( "B2", i.next().getKey() ); assertEquals( "B1", i.next().getKey() ); assertEquals( "C", i.next().getKey() ); assertEquals( "B", i.next().getKey() ); assertEquals( "A", i.next().getKey() ); assertFalse( i.hasNext() ); Thread.currentThread().setContextClassLoader( world.getClassRealm( "B3" ) ); i = beans.iterator(); assertTrue( i.hasNext() ); assertEquals( "!", i.next().getKey() ); assertEquals( "B3", i.next().getKey() ); assertEquals( "C", i.next().getKey() ); assertEquals( "B", i.next().getKey() ); assertEquals( "A", i.next().getKey() ); assertFalse( i.hasNext() ); Thread.currentThread().setContextClassLoader( world.getClassRealm( "C" ) ); i = beans.iterator(); assertTrue( i.hasNext() ); assertEquals( "!", i.next().getKey() ); assertEquals( "C", i.next().getKey() ); assertFalse( i.hasNext() ); Thread.currentThread().setContextClassLoader( null ); i = beans.iterator(); assertTrue( i.hasNext() ); assertEquals( "!", i.next().getKey() ); assertEquals( "?", i.next().getKey() ); assertEquals( "B2B", i.next().getKey() ); assertEquals( "B3", i.next().getKey() ); assertEquals( "B2", i.next().getKey() ); assertEquals( "B1", i.next().getKey() ); assertEquals( "C", i.next().getKey() ); assertEquals( "B", i.next().getKey() ); assertEquals( "A", i.next().getKey() ); assertFalse( i.hasNext() ); } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/000077500000000000000000000000001167051330000264475ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/pom.xml000066400000000000000000000023741167051330000277720ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-plexus 2.3.0 guice-plexus-metadata Sisu-Inject-Plexus : @Component metadata org.codehaus.plexus plexus-component-annotations org.sonatype.sisu sisu-guice org.sonatype.sisu.inject guice-bean-reflect sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/000077500000000000000000000000001167051330000272365ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/000077500000000000000000000000001167051330000301625ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/000077500000000000000000000000001167051330000311035ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/000077500000000000000000000000001167051330000316725ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/000077500000000000000000000000001167051330000335345ustar00rootroot00000000000000000077500000000000000000000000001167051330000345515ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000360715ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000404265ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/annotationsComponentImpl.java000066400000000000000000000117651167051330000440670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/annotations/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.annotations; import java.lang.annotation.Annotation; import org.codehaus.plexus.component.annotations.Component; /** * Partial runtime implementation of Plexus @{@link Component} annotation, supporting the most common attributes. */ public final class ComponentImpl implements Component { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- // computed hashCode representing hard-coded attributes private static final int HASH_CODE_OFFSET = 0x685499F5; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Class role; private final String hint; private final String instantiationStrategy; private final String description; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public ComponentImpl( final Class role, final String hint, final String instantiationStrategy, final String description ) { if ( null == role || null == hint || null == instantiationStrategy || null == description ) { throw new IllegalArgumentException( "@Component cannot contain null values" ); } this.role = role; this.hint = hint; this.instantiationStrategy = instantiationStrategy; this.description = description; } // ---------------------------------------------------------------------- // Annotation properties // ---------------------------------------------------------------------- public Class role() { return role; } public String hint() { return hint; } public String instantiationStrategy() { return instantiationStrategy; } public String description() { return description; } public boolean isolatedRealm() { return false; } public String alias() { return ""; } public String composer() { return ""; } public String configurator() { return ""; } public String factory() { return ""; } public String lifecycleHandler() { return ""; } public String profile() { return ""; } public String type() { return ""; } public String version() { return ""; } // ---------------------------------------------------------------------- // Standard annotation behaviour // ---------------------------------------------------------------------- @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof Component ) { final Component cmp = (Component) rhs; if ( role.equals( cmp.role() ) && hint.equals( cmp.hint() ) && instantiationStrategy.equals( cmp.instantiationStrategy() ) && description.equals( cmp.description() ) ) { // optimization: we hard-code all these attributes to be empty final String hardCodedAttributes = cmp.alias() + cmp.composer() + cmp.configurator() + cmp.factory() + cmp.lifecycleHandler() + cmp.profile() + cmp.type() + cmp.version(); return hardCodedAttributes.length() == 0 && !cmp.isolatedRealm(); } } return false; } @Override public int hashCode() { return HASH_CODE_OFFSET + ( 127 * "role".hashCode() ^ role.hashCode() ) + ( 127 * "hint".hashCode() ^ hint.hashCode() ) + ( 127 * "instantiationStrategy".hashCode() ^ instantiationStrategy.hashCode() ) + ( 127 * "description".hashCode() ^ description.hashCode() ); } @Override public String toString() { return String.format( "@%s(isolatedRealm=false, composer=, configurator=, alias=, description=%s, " + "instantiationStrategy=%s, factory=, hint=%s, type=, lifecycleHandler=, version=, " + "profile=, role=%s)", Component.class.getName(), description, instantiationStrategy, hint, role ); } public Class annotationType() { return Component.class; } } ConfigurationImpl.java000066400000000000000000000053361167051330000447310ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/annotations/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.annotations; import java.lang.annotation.Annotation; import org.codehaus.plexus.component.annotations.Configuration; /** * Runtime implementation of Plexus @{@link Configuration} annotation. */ public final class ConfigurationImpl implements Configuration { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final String name; private final String value; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public ConfigurationImpl( final String name, final String value ) { if ( null == name || null == value ) { throw new IllegalArgumentException( "@Configuration cannot contain null values" ); } this.name = name; this.value = value; } // ---------------------------------------------------------------------- // Annotation properties // ---------------------------------------------------------------------- public String name() { return name; } public String value() { return value; } // ---------------------------------------------------------------------- // Standard annotation behaviour // ---------------------------------------------------------------------- @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof Configuration ) { final Configuration conf = (Configuration) rhs; return name.equals( conf.name() ) && value.equals( conf.value() ); } return false; } @Override public int hashCode() { return ( 127 * "name".hashCode() ^ name.hashCode() ) + ( 127 * "value".hashCode() ^ value.hashCode() ); } @Override public String toString() { return String.format( "@%s(name=%s, value=%s)", Configuration.class.getName(), name, value ); } public Class annotationType() { return Configuration.class; } } RequirementImpl.java000066400000000000000000000102511167051330000444120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/annotations/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.annotations; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.List; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.LoadedClass; import org.sonatype.guice.plexus.config.Hints; /** * Runtime implementation of Plexus @{@link Requirement} annotation. */ public final class RequirementImpl implements Requirement { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final DeferredClass role; private final boolean optional; private final String hint; private final String[] hints; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public RequirementImpl( final DeferredClass role, final boolean optional, final List hints ) { if ( null == role || null == hints || hints.contains( null ) ) { throw new IllegalArgumentException( "@Requirement cannot contain null values" ); } this.role = role; this.optional = optional; final int length = hints.size(); if ( length == 0 ) { hint = ""; this.hints = Hints.NO_HINTS; } else if ( length == 1 ) { hint = hints.get( 0 ); this.hints = Hints.NO_HINTS; } else { hint = ""; this.hints = hints.toArray( new String[length] ); } } /** * For testing purposes only. */ @Deprecated public RequirementImpl( final Class role, final boolean optional, final String... hints ) { this( new LoadedClass( role ), optional, Arrays.asList( hints ) ); } // ---------------------------------------------------------------------- // Annotation properties // ---------------------------------------------------------------------- public Class role() { return role.load(); } public boolean optional() { return optional; } public String hint() { return hint; } public String[] hints() { return hints.clone(); } // ---------------------------------------------------------------------- // Standard annotation behaviour // ---------------------------------------------------------------------- @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof Requirement ) { final Requirement req = (Requirement) rhs; return role().equals( req.role() ) && optional == req.optional() && hint.equals( req.hint() ) && Arrays.equals( hints, req.hints() ); } return false; } @Override public int hashCode() { return ( 127 * "role".hashCode() ^ role().hashCode() ) + ( 127 * "optional".hashCode() ^ Boolean.valueOf( optional ).hashCode() ) + ( 127 * "hint".hashCode() ^ hint.hashCode() ) + ( 127 * "hints".hashCode() ^ Arrays.hashCode( hints ) ); } @Override public String toString() { return String.format( "@%s(hints=%s, optional=%b, role=%s, hint=%s)", Requirement.class.getName(), Arrays.toString( hints ), Boolean.valueOf( optional ), role(), hint ); } public Class annotationType() { return Requirement.class; } } 000077500000000000000000000000001167051330000373365ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/configHints.java000066400000000000000000000076551167051330000413030ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; import java.util.Arrays; import java.util.List; import org.codehaus.plexus.component.annotations.Requirement; /** * Constants and utility methods for dealing with Plexus hints. */ public final class Hints { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- public static final String[] NO_HINTS = {}; public static final String DEFAULT_HINT = "default"; private static final List NO_HINTS_LIST = Arrays.asList( NO_HINTS ); // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private Hints() { // static utility class, not allowed to create instances } // ---------------------------------------------------------------------- // Utility methods // ---------------------------------------------------------------------- /** * Returns the canonical form of the given Plexus hint. * * @param hint The Plexus hint * @return Canonical hint denoting the same component as the given hint */ public static String canonicalHint( final String hint ) { // interning hints is a good idea because there's a lot of duplication return null == hint || hint.length() == 0 ? DEFAULT_HINT : hint.intern(); } /** * Determines if the given Plexus hint denotes the default component. * * @param hint The Plexus hint * @return {@code true} if the given hint denotes the default component */ public static boolean isDefaultHint( final String hint ) { return DEFAULT_HINT.equals( hint ) || null == hint || hint.length() == 0; } /** * Returns the canonical form of the given Plexus hints. * * @param hints The Plexus hints * @return Array of canonical hints */ public static String[] canonicalHints( final String... hints ) { final int length = hints.length; if ( length == 0 || length == 1 && hints[0].length() == 0 ) { return NO_HINTS; } for ( int i = 0; i < length; i++ ) { hints[i] = canonicalHint( hints[i] ); } return hints; } /** * Returns the canonical form of the given Plexus hints. * * @param hints The Plexus hints * @return List of canonical hints */ public static List canonicalHints( final List hints ) { final int length = hints.size(); if ( length == 0 || length == 1 && hints.get( 0 ).length() == 0 ) { return NO_HINTS_LIST; } for ( int i = 0; i < length; i++ ) { hints.set( i, canonicalHint( hints.get( i ) ) ); } return hints; } /** * Returns the Plexus hints contained in the given @{@link Requirement}. * * @param requirement The Plexus requirement * @return Array of canonical hints */ public static String[] canonicalHints( final Requirement requirement ) { final String[] hints = requirement.hints(); if ( hints.length > 0 ) { return canonicalHints( hints ); } final String hint = requirement.hint(); if ( hint.length() > 0 ) { return canonicalHints( hint ); } return NO_HINTS; } } PlexusBean.java000066400000000000000000000014721167051330000422530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; import java.util.Map.Entry; /** * Plexus bean mapping; from hint->instance. */ public interface PlexusBean extends Entry { /** * @return Human readable description */ String getDescription(); /** * @return Bean implementation class */ Class getImplementationClass(); } PlexusBeanConverter.java000066400000000000000000000017241167051330000441430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; import com.google.inject.TypeLiteral; /** * Service that converts values into various beans by following Plexus configuration rules. */ public interface PlexusBeanConverter { /** * Converts the given constant value to a bean of the given type. * * @param role The expected bean type * @param value The constant value * @return Bean of the given type, based on the given constant value */ T convert( TypeLiteral role, String value ); } PlexusBeanLocator.java000066400000000000000000000020221167051330000435670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; import com.google.inject.TypeLiteral; /** * Service that locates beans of various types, using optional Plexus hints as a guide. */ public interface PlexusBeanLocator { /** * Locates beans of the given type, optionally filtered using the given named hints. * * @param role The expected bean type * @param hints The optional (canonical) hints * @return Sequence of Plexus bean mappings; ordered according to the given hints */ Iterable> locate( TypeLiteral role, String... hints ); } PlexusBeanMetadata.java000066400000000000000000000027651167051330000437220ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.bean.reflect.BeanProperty; /** * Supplies metadata associated with a particular Plexus bean implementation. */ public interface PlexusBeanMetadata { /** * @return {@code true} if there is no more metadata; otherwise {@code false} */ boolean isEmpty(); /** * Returns @{@link Configuration} metadata for the given property of the Plexus bean. * * @param property The bean property * @return Configuration metadata; {@code null} if no such metadata is available */ Configuration getConfiguration( BeanProperty property ); /** * Returns @{@link Requirement} metadata for the given property of the Plexus bean. * * @param property The bean property * @return Requirement metadata; {@code null} if no such metadata is available */ Requirement getRequirement( BeanProperty property ); } PlexusBeanModule.java000066400000000000000000000011511167051330000434130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; import com.google.inject.Binder; public interface PlexusBeanModule { PlexusBeanSource configure( Binder binder ); } PlexusBeanSource.java000066400000000000000000000015601167051330000434320ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; /** * Source of Plexus component beans and associated metadata. */ public interface PlexusBeanSource { /** * Returns metadata associated with the given Plexus bean implementation. * * @param implementation The bean implementation * @return Metadata associated with the given bean */ PlexusBeanMetadata getBeanMetadata( Class implementation ); } Roles.java000066400000000000000000000147751167051330000413030ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.bean.reflect.TypeParameters; import com.google.inject.Key; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; /** * Utility methods for dealing with Plexus roles. */ public final class Roles { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String MISSING_COMPONENT_ERROR = "No implementation for %s was bound."; private static final String MISSING_COMPONENT_WITH_HINT_ERROR = "No implementation for %s annotated with @Named(value=%s) was bound."; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- private Roles() { // static utility class, not allowed to create instances } // ---------------------------------------------------------------------- // Utility methods // ---------------------------------------------------------------------- /** * Returns the canonical form of the given Plexus role-hint. * * @param role The Plexus role * @param hint The Plexus hint * @return Canonical role-hint denoting the same component as the given role-hint */ public static String canonicalRoleHint( final String role, final String hint ) { return Hints.isDefaultHint( hint ) ? role : role + ':' + hint; } /** * Returns the canonical role-hint for the given Plexus component. * * @param component The Plexus component * @return Canonical role-hint denoting the given component */ public static String canonicalRoleHint( final Component component ) { return canonicalRoleHint( component.role().getName(), component.hint() ); } /** * Deduces the role type based on the given @{@link Requirement} and expected type. * * @param requirement The Plexus requirement * @param asType The expected type * @return "Best-fit" role type */ public static TypeLiteral roleType( final Requirement requirement, final TypeLiteral asType ) { final Type role = requirement.role(); if ( role != Object.class && role != Map.class && role != List.class ) { return TypeLiteral.get( role ); } final Class rawType = asType.getRawType(); if ( Map.class == rawType ) { // Map --> T return TypeParameters.get( asType, 1 ); } if ( List.class == rawType ) { // List --> T return TypeParameters.get( asType, 0 ); } return asType; } /** * Returns the component binding {@link Key} for the given Plexus component. * * @param component The Plexus component * @return Component binding key denoting the given component */ public static Key componentKey( final Component component ) { return componentKey( component.role(), component.hint() ); } /** * Returns the component binding {@link Key} for the given Plexus role-hint. * * @param role The Plexus role * @param hint The Plexus hint * @return Component binding key denoting the given role-hint */ public static Key componentKey( final Class role, final String hint ) { if ( Hints.isDefaultHint( hint ) ) { return Key.get( role ); } return Key.get( role, Names.named( Hints.canonicalHint( hint ) ) ); } /** * Returns the component binding {@link Key} for the given Plexus role-hint. * * @param role The Plexus role * @param hint The Plexus hint * @return Component binding key denoting the given role-hint */ @SuppressWarnings( "unchecked" ) public static Key componentKey( final TypeLiteral role, final String hint ) { return (Key) componentKey( role.getRawType(), hint ); } /** * Throws a {@link ProvisionException} detailing the missing Plexus component. * * @param role The Plexus role * @param hint The Plexus hint */ public static T throwMissingComponentException( final TypeLiteral role, final String hint ) { if ( Hints.isDefaultHint( hint ) ) { throw new ProvisionException( String.format( MISSING_COMPONENT_ERROR, role ) ); } throw new ProvisionException( String.format( MISSING_COMPONENT_WITH_HINT_ERROR, role, hint ) ); } /** * Removes any non-Java identifiers from the name and converts it to camelCase. * * @param name The element name * @return CamelCased name with no dashes */ public static String camelizeName( final String name ) { StringBuilder buf = null; final int length = name.length(); for ( int i = 0; i < length; i++ ) { if ( !Character.isJavaIdentifierPart( name.charAt( i ) ) ) { buf = new StringBuilder( name.substring( 0, i ) ); break; } } if ( null == buf ) { return name; // nothing to camelize } boolean capitalize = true; for ( int i = buf.length() + 1; i < length; i++ ) { final char c = name.charAt( i ); if ( !Character.isJavaIdentifierPart( c ) ) { capitalize = true; } else if ( capitalize ) { buf.append( Character.toUpperCase( c ) ); capitalize = false; } else { buf.append( c ); } } return buf.toString(); } } Strategies.java000066400000000000000000000016031167051330000423130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/main/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; /** * Constants representing supported Plexus instantiation strategies. */ public interface Strategies { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- String LOAD_ON_START = "load-on-start"; String PER_LOOKUP = "per-lookup"; String SINGLETON = "singleton"; } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/000077500000000000000000000000001167051330000302155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/000077500000000000000000000000001167051330000311365ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/000077500000000000000000000000001167051330000317255ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/sonatype/000077500000000000000000000000001167051330000335675ustar00rootroot00000000000000000077500000000000000000000000001167051330000346045ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000361245ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000404615ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/sonatype/guice/plexus/annotationsComponentAnnotationTest.java000066400000000000000000000105721167051330000461660ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/sonatype/guice/plexus/annotations/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.annotations; import java.util.Arrays; import java.util.HashSet; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.guice.plexus.config.Strategies; public class ComponentAnnotationTest extends TestCase { interface A { } @Component( role = A.class ) static class DefaultA implements A { } @Component( role = A.class, hint = "Named" ) static class NamedA implements A { } @Component( role = A.class, description = "Something" ) static class DescribedA implements A { } @Component( role = A.class, instantiationStrategy = Strategies.PER_LOOKUP ) static class PrototypeA implements A { } @Component( role = A.class, hint = "Named", instantiationStrategy = Strategies.PER_LOOKUP ) static class NamedPrototypeA implements A { } @Component( role = Simple.class ) static class Simple { } @Component( role = Simple.class, version = "2" ) static class Simple2 extends Simple { } @Component( role = Simple.class, isolatedRealm = true ) static class Simple3 extends Simple { } public void testComponentImpl() throws ClassNotFoundException { checkBehaviour( "DefaultA" ); checkBehaviour( "NamedA" ); checkBehaviour( "PrototypeA" ); checkBehaviour( "NamedPrototypeA" ); checkBehaviour( "DescribedA" ); assertFalse( replicate( getComponent( "DefaultA" ) ).equals( getComponent( "NamedA" ) ) ); assertFalse( replicate( getComponent( "DefaultA" ) ).equals( getComponent( "PrototypeA" ) ) ); assertFalse( replicate( getComponent( "DefaultA" ) ).equals( getComponent( "DescribedA" ) ) ); assertFalse( replicate( getComponent( "Simple" ) ).equals( getComponent( "DefaultA" ) ) ); assertFalse( replicate( getComponent( "Simple" ) ).equals( getComponent( "Simple2" ) ) ); assertFalse( replicate( getComponent( "Simple" ) ).equals( getComponent( "Simple3" ) ) ); } private static void checkBehaviour( final String name ) throws ClassNotFoundException { final Component orig = getComponent( name ); final Component clone = replicate( orig ); assertTrue( orig.equals( clone ) ); assertTrue( clone.equals( orig ) ); assertTrue( clone.equals( clone ) ); assertFalse( clone.equals( "" ) ); assertEquals( orig.hashCode(), clone.hashCode() ); assertEquals( new HashSet( Arrays.asList( orig.toString().split( "[(, )]" ) ) ), new HashSet( Arrays.asList( clone.toString().split( "[(, )]" ) ) ) ); assertEquals( orig.annotationType(), clone.annotationType() ); } private static Component getComponent( final String name ) throws ClassNotFoundException { return Class.forName( ComponentAnnotationTest.class.getName() + '$' + name ).getAnnotation( Component.class ); } private static Component replicate( final Component orig ) { return new ComponentImpl( orig.role(), orig.hint(), orig.instantiationStrategy(), orig.description() ); } public void testNullChecks() { checkNullNotAllowed( null, "", "", "" ); checkNullNotAllowed( Object.class, null, "", "" ); checkNullNotAllowed( Object.class, "", null, "" ); checkNullNotAllowed( Object.class, "", "", null ); } private static void checkNullNotAllowed( final Class role, final String hint, final String instantationStrategy, final String description ) { try { new ComponentImpl( role, hint, instantationStrategy, description ); fail( "Expected IllegalArgumentException" ); } catch ( final IllegalArgumentException e ) { } } } ConfigurationAnnotationTest.java000066400000000000000000000055561167051330000470410ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/sonatype/guice/plexus/annotations/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.annotations; import java.util.Arrays; import java.util.HashSet; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Configuration; public class ConfigurationAnnotationTest extends TestCase { @Configuration( "Default" ) String defaultConfig; @Configuration( name = "Name", value = "Default" ) String namedConfig; @Configuration( "${property}" ) String propertyConfig; public void testConfigurationImpl() throws NoSuchFieldException { checkBehaviour( "defaultConfig" ); checkBehaviour( "namedConfig" ); checkBehaviour( "propertyConfig" ); assertFalse( replicate( getConfiguration( "defaultConfig" ) ).equals( getConfiguration( "namedConfig" ) ) ); assertFalse( replicate( getConfiguration( "defaultConfig" ) ).equals( getConfiguration( "propertyConfig" ) ) ); } private static void checkBehaviour( final String name ) throws NoSuchFieldException { final Configuration orig = getConfiguration( name ); final Configuration clone = replicate( orig ); assertTrue( orig.equals( clone ) ); assertTrue( clone.equals( orig ) ); assertTrue( clone.equals( clone ) ); assertFalse( clone.equals( "" ) ); assertEquals( orig.hashCode(), clone.hashCode() ); assertEquals( new HashSet( Arrays.asList( orig.toString().split( "[(, )]" ) ) ), new HashSet( Arrays.asList( clone.toString().split( "[(, )]" ) ) ) ); assertEquals( orig.annotationType(), clone.annotationType() ); } private static Configuration getConfiguration( final String name ) throws NoSuchFieldException { return ConfigurationAnnotationTest.class.getDeclaredField( name ).getAnnotation( Configuration.class ); } private static Configuration replicate( final Configuration orig ) { return new ConfigurationImpl( orig.name(), orig.value() ); } public void testNullChecks() { checkNullNotAllowed( null, "" ); checkNullNotAllowed( "", null ); } private static void checkNullNotAllowed( final String name, final String value ) { try { new ConfigurationImpl( name, value ); fail( "Expected IllegalArgumentException" ); } catch ( final IllegalArgumentException e ) { } } } RequirementAnnotationTest.java000066400000000000000000000072351167051330000465260ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/sonatype/guice/plexus/annotations/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.annotations; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashSet; import java.util.List; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Requirement; public class RequirementAnnotationTest extends TestCase { @Requirement String defaultReq; @Requirement( role = String.class ) String stringReq; @Requirement( hint = "named" ) String namedReq; @Requirement( optional = true ) String optionalReq; @Requirement( hints = { "A", "B", "C" } ) List namedListReq; @Requirement( role = String.class, hint = "named" ) String namedStringReq; @Requirement( role = String.class, hints = { "A", "B", "C" } ) List namedStringListReq; public void testRequirementImpl() throws NoSuchFieldException { checkBehaviour( "defaultReq" ); checkBehaviour( "stringReq" ); checkBehaviour( "namedReq" ); checkBehaviour( "optionalReq" ); checkBehaviour( "namedListReq" ); checkBehaviour( "namedStringReq" ); checkBehaviour( "namedStringListReq" ); assertFalse( replicate( getRequirement( "defaultReq" ) ).equals( getRequirement( "stringReq" ) ) ); assertFalse( replicate( getRequirement( "stringReq" ) ).equals( getRequirement( "namedStringReq" ) ) ); assertFalse( replicate( getRequirement( "defaultReq" ) ).equals( getRequirement( "namedListReq" ) ) ); assertFalse( replicate( getRequirement( "defaultReq" ) ).equals( getRequirement( "optionalReq" ) ) ); } private static void checkBehaviour( final String name ) throws NoSuchFieldException { final Requirement orig = getRequirement( name ); final Requirement clone = replicate( orig ); assertTrue( orig.equals( clone ) ); assertTrue( clone.equals( orig ) ); assertTrue( clone.equals( clone ) ); assertFalse( clone.equals( "" ) ); assertEquals( orig.hashCode(), clone.hashCode() ); assertEquals( new HashSet( Arrays.asList( orig.toString().split( "[(, )]" ) ) ), new HashSet( Arrays.asList( clone.toString().split( "[(, )]" ) ) ) ); assertEquals( orig.annotationType(), clone.annotationType() ); try { final Field role = RequirementImpl.class.getDeclaredField( "role" ); final Method getName = role.getType().getMethod( "getName" ); role.setAccessible( true ); assertEquals( orig.role().getName(), getName.invoke( role.get( clone ) ) ); } catch ( final Exception e ) { fail( e.toString() ); } } private static Requirement getRequirement( final String name ) throws NoSuchFieldException { return RequirementAnnotationTest.class.getDeclaredField( name ).getAnnotation( Requirement.class ); } @SuppressWarnings( "deprecation" ) private static Requirement replicate( final Requirement orig ) { final String h = orig.hint(); return new RequirementImpl( orig.role(), orig.optional(), h.length() > 0 ? new String[] { h } : orig.hints() ); } } 000077500000000000000000000000001167051330000373715ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/sonatype/guice/plexus/configHintsTest.java000066400000000000000000000072461167051330000421720ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; import java.util.Arrays; import java.util.Collections; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.plexus.annotations.RequirementImpl; public class HintsTest extends TestCase { public void testCanonicalHint() { assertEquals( "default", Hints.canonicalHint( null ) ); assertEquals( "default", Hints.canonicalHint( "" ) ); assertEquals( "default", Hints.canonicalHint( new String( "default" ) ) ); assertEquals( "foo", Hints.canonicalHint( "foo" ) ); } public void testCanonicalHints() { assertArrayEquals( new String[0], Hints.canonicalHints() ); assertArrayEquals( new String[0], Hints.canonicalHints( requirement() ) ); assertArrayEquals( new String[0], Hints.canonicalHints( requirement( "" ) ) ); assertArrayEquals( new String[] { "default" }, Hints.canonicalHints( requirement( "default" ) ) ); assertArrayEquals( new String[] { "foo" }, Hints.canonicalHints( requirement( "foo" ) ) ); assertArrayEquals( new String[] { "default", "foo" }, Hints.canonicalHints( requirement( "", "foo" ) ) ); assertArrayEquals( new String[] { "foo", "default" }, Hints.canonicalHints( requirement( "foo", "" ) ) ); } public void testCanonicalHintList() { assertEquals( Collections.emptyList(), Hints.canonicalHints( Arrays. asList() ) ); assertEquals( Collections.emptyList(), Hints.canonicalHints( Arrays.asList( "" ) ) ); assertEquals( Arrays.asList( Hints.DEFAULT_HINT ), Hints.canonicalHints( Arrays.asList( "default" ) ) ); assertEquals( Arrays.asList( "foo" ), Hints.canonicalHints( Arrays.asList( "foo" ) ) ); assertEquals( Arrays.asList( "default", "foo" ), Hints.canonicalHints( Arrays.asList( "", "foo" ) ) ); assertEquals( Arrays.asList( "foo", "default" ), Hints.canonicalHints( Arrays.asList( "foo", "" ) ) ); } public void testHintsAreInterned() { assertSame( "hint", Hints.canonicalHint( new String( "hint" ) ) ); assertSame( "hint", Hints.canonicalHints( requirement( new String( "hint" ) ) )[0] ); final Requirement requirement = requirement( new String( "foo" ), new String( "bar" ) ); assertSame( "foo", Hints.canonicalHints( requirement )[0] ); assertSame( "bar", Hints.canonicalHints( requirement )[1] ); assertNotSame( new String( "hint" ), Hints.canonicalHint( "hint" ) ); assertEquals( new String( "hint" ), Hints.canonicalHint( "hint" ) ); } public void testIsDefaultHint() { assertTrue( Hints.isDefaultHint( null ) ); assertTrue( Hints.isDefaultHint( "" ) ); assertTrue( Hints.isDefaultHint( new String( "default" ) ) ); assertFalse( Hints.isDefaultHint( "foo" ) ); } private static void assertArrayEquals( final T[] a, final T[] b ) { assertTrue( "Expected: " + Arrays.toString( a ) + "but was: " + Arrays.toString( b ), Arrays.equals( a, b ) ); } @SuppressWarnings( "deprecation" ) private static Requirement requirement( final String... hints ) { return new RequirementImpl( Object.class, true, hints ); } } RolesTest.java000066400000000000000000000122341167051330000421620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-metadata/src/test/java/org/sonatype/guice/plexus/config/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.config; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.plexus.annotations.ComponentImpl; import org.sonatype.guice.plexus.annotations.RequirementImpl; import com.google.inject.Key; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; import com.google.inject.util.Types; public class RolesTest extends TestCase { private static final TypeLiteral OBJECT_LITERAL = TypeLiteral.get( Object.class ); private static final TypeLiteral STRING_LITERAL = TypeLiteral.get( String.class ); private static final TypeLiteral INTEGER_LITERAL = TypeLiteral.get( Integer.class ); private static final Key OBJECT_COMPONENT_KEY = Key.get( Object.class ); private static final Key OBJECT_FOO_COMPONENT_KEY = Key.get( Object.class, Names.named( "foo" ) ); public void testCanonicalRoleHint() { assertEquals( OBJECT_LITERAL + "", Roles.canonicalRoleHint( Object.class.getName(), null ) ); assertEquals( OBJECT_LITERAL + "", Roles.canonicalRoleHint( Object.class.getName(), "" ) ); assertEquals( OBJECT_LITERAL + "", Roles.canonicalRoleHint( Object.class.getName(), "default" ) ); assertEquals( OBJECT_LITERAL + ":foo", Roles.canonicalRoleHint( Object.class.getName(), "foo" ) ); assertEquals( OBJECT_LITERAL + "", Roles.canonicalRoleHint( component( "" ) ) ); assertEquals( OBJECT_LITERAL + "", Roles.canonicalRoleHint( component( "default" ) ) ); assertEquals( OBJECT_LITERAL + ":foo", Roles.canonicalRoleHint( component( "foo" ) ) ); } public void testDefaultComponentKeys() { assertEquals( OBJECT_COMPONENT_KEY, Roles.componentKey( Object.class, null ) ); assertEquals( OBJECT_COMPONENT_KEY, Roles.componentKey( OBJECT_LITERAL, "" ) ); assertEquals( OBJECT_COMPONENT_KEY, Roles.componentKey( Object.class, "default" ) ); assertEquals( OBJECT_COMPONENT_KEY, Roles.componentKey( component( "" ) ) ); assertEquals( OBJECT_COMPONENT_KEY, Roles.componentKey( component( "default" ) ) ); } public void testComponentKeys() { assertEquals( OBJECT_FOO_COMPONENT_KEY, Roles.componentKey( Object.class, "foo" ) ); assertEquals( OBJECT_FOO_COMPONENT_KEY, Roles.componentKey( component( "foo" ) ) ); } public void testRoleAnalysis() { assertEquals( STRING_LITERAL, Roles.roleType( requirement( String.class ), OBJECT_LITERAL ) ); assertEquals( STRING_LITERAL, Roles.roleType( requirement( Object.class ), STRING_LITERAL ) ); assertEquals( STRING_LITERAL, Roles.roleType( requirement( Object.class ), TypeLiteral.get( Types.listOf( String.class ) ) ) ); assertEquals( STRING_LITERAL, Roles.roleType( requirement( List.class ), TypeLiteral.get( Types.listOf( String.class ) ) ) ); assertEquals( INTEGER_LITERAL, Roles.roleType( requirement( Object.class ), TypeLiteral.get( Types.mapOf( String.class, Integer.class ) ) ) ); assertEquals( INTEGER_LITERAL, Roles.roleType( requirement( Map.class ), TypeLiteral.get( Types.mapOf( String.class, Integer.class ) ) ) ); } private static Component component( final String hint ) { return new ComponentImpl( Object.class, hint, Strategies.PER_LOOKUP, "" ); } @SuppressWarnings( "deprecation" ) private static Requirement requirement( final Class role ) { return new RequirementImpl( role, false ); } public void testMissingComponentExceptions() { try { Roles.throwMissingComponentException( STRING_LITERAL, null ); fail( "Expected ProvisionException" ); } catch ( final ProvisionException e ) { } try { Roles.throwMissingComponentException( STRING_LITERAL, "foo" ); fail( "Expected ProvisionException" ); } catch ( final ProvisionException e ) { } } public void testCamelization() { assertSame( "thisIsATest", Roles.camelizeName( "thisIsATest" ) ); assertEquals( "thisIsATest", Roles.camelizeName( "this-is-a-test" ) ); assertEquals( "TestingA", Roles.camelizeName( "-testing-a" ) ); assertEquals( "testingB", Roles.camelizeName( "testing-b-" ) ); assertEquals( "TestingC", Roles.camelizeName( "--testing--c--" ) ); } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/000077500000000000000000000000001167051330000265035ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/pom.xml000066400000000000000000000032121167051330000300160ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-plexus 2.3.0 guice-plexus-scanners Sisu-Inject-Plexus : @Component scanning org.codehaus.plexus plexus-component-annotations org.sonatype.sisu sisu-guice org.sonatype.sisu.inject guice-bean-reflect org.sonatype.sisu.inject guice-bean-scanners org.sonatype.sisu.inject guice-plexus-metadata org.codehaus.plexus plexus-utils sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/000077500000000000000000000000001167051330000272725ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/000077500000000000000000000000001167051330000302165ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/000077500000000000000000000000001167051330000311375ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/000077500000000000000000000000001167051330000317265ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/000077500000000000000000000000001167051330000335705ustar00rootroot00000000000000000077500000000000000000000000001167051330000346055ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000361255ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000377415ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/guice/plexus/scannersCloningClassLoader.java000066400000000000000000000067441167051330000443250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import java.lang.reflect.Modifier; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.scanners.asm.ClassWriter; import org.sonatype.guice.bean.scanners.asm.MethodVisitor; import org.sonatype.guice.bean.scanners.asm.Opcodes; final class CloningClassLoader extends ClassLoader { private static final String CLONE_MARKER = "$__plexus"; private final ClassSpace space; CloningClassLoader( final ClassSpace space ) { this.space = space; } @Override protected synchronized Class loadClass( final String name, final boolean resolve ) throws ClassNotFoundException { if ( !name.contains( CLONE_MARKER ) ) { try { return space.loadClass( name ); } catch ( final TypeNotPresentException e ) { throw new ClassNotFoundException( name ); } } return super.loadClass( name, resolve ); } static String proxyName( final String realName, final int cloneId ) { final StringBuilder buf = new StringBuilder(); if ( realName.startsWith( "java" ) ) { buf.append( '$' ); } return buf.append( realName ).append( CloningClassLoader.CLONE_MARKER ).append( cloneId ).toString(); } static String getRealName( final String proxyName ) { final int cloneMarker = proxyName.lastIndexOf( CLONE_MARKER ); if ( cloneMarker < 0 ) { return proxyName; } for ( int i = cloneMarker + CLONE_MARKER.length(), end = proxyName.length(); i < end; i++ ) { final char c = proxyName.charAt( i ); if ( c < '0' || c > '9' ) { return proxyName; // belongs to someone else, don't truncate the name } } return proxyName.substring( '$' == proxyName.charAt( 0 ) ? 1 : 0, cloneMarker ); } @Override protected Class findClass( final String name ) throws ClassNotFoundException { final String proxyName = name.replace( '.', '/' ); final String superName = getRealName( proxyName ); if ( superName.equals( proxyName ) ) { throw new ClassNotFoundException( name ); } final ClassWriter cw = new ClassWriter( ClassWriter.COMPUTE_MAXS ); cw.visit( Opcodes.V1_5, Modifier.PUBLIC, proxyName, null, superName, null ); final MethodVisitor mv = cw.visitMethod( Modifier.PUBLIC, "", "()V", null, null ); mv.visitCode(); mv.visitVarInsn( Opcodes.ALOAD, 0 ); mv.visitMethodInsn( Opcodes.INVOKESPECIAL, superName, "", "()V" ); mv.visitInsn( Opcodes.RETURN ); mv.visitMaxs( 0, 0 ); mv.visitEnd(); cw.visitEnd(); final byte[] buf = cw.toByteArray(); return defineClass( name, buf, 0, buf.length ); } @Override public String toString() { return space.toString(); } } PlexusAnnotatedMetadata.java000066400000000000000000000054041167051330000453660ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import java.util.Map; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.plexus.annotations.ConfigurationImpl; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; /** * Runtime {@link PlexusBeanMetadata} based on {@link BeanProperty} annotations. */ public final class PlexusAnnotatedMetadata implements PlexusBeanMetadata { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Map variables; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- /** * Provides runtime Plexus metadata based on simple property annotations. * * @param variables The filter variables */ public PlexusAnnotatedMetadata( final Map variables ) { this.variables = variables; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean isEmpty() { return false; // metadata comes from the properties themselves } public Configuration getConfiguration( final BeanProperty property ) { final Configuration configuration = property.getAnnotation( Configuration.class ); if ( configuration != null && variables != null ) { // support runtime interpolation of @Configuration values final String uninterpolatedValue = configuration.value(); final String value = StringUtils.interpolate( uninterpolatedValue, variables ); if ( !value.equals( uninterpolatedValue ) ) { return new ConfigurationImpl( configuration.name(), value ); } } return configuration; } public Requirement getRequirement( final BeanProperty property ) { return property.getAnnotation( Requirement.class ); } } PlexusTypeListener.java000066400000000000000000000022121167051330000444310ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.scanners.QualifiedTypeListener; /** * {@link QualifiedTypeListener} that also listens for Plexus components. */ public interface PlexusTypeListener extends QualifiedTypeListener { /** * Invoked when the {@link PlexusTypeListener} finds a Plexus component. * * @param component The Plexus component * @param implementation The implementation * @param source The source of this component */ void hear( Component component, DeferredClass implementation, Object source ); } PlexusTypeRegistry.java000066400000000000000000000170561167051330000444700ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.guice.plexus.annotations.ComponentImpl; import org.sonatype.guice.plexus.config.Hints; import org.sonatype.guice.plexus.config.Roles; import org.sonatype.guice.plexus.config.Strategies; /** * Enhanced Plexus component map with additional book-keeping. */ final class PlexusTypeRegistry { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final Component LOAD_ON_START_PLACEHOLDER = new ComponentImpl( Object.class, "", Strategies.LOAD_ON_START, "" ); // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Map components = new HashMap(); private final Map> implementations = new HashMap>(); private final Set deferredNames = new HashSet(); final ClassSpace space; private ClassSpace cloningClassSpace; private int cloneCounter; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- PlexusTypeRegistry( final ClassSpace space ) { this.space = space; } // ---------------------------------------------------------------------- // Locally-shared methods // ---------------------------------------------------------------------- /** * @return Current class space */ ClassSpace getSpace() { return space; } /** * Records that the given Plexus component should be loaded when the container starts. * * @param role The Plexus role * @param hint The Plexus hint */ void loadOnStart( final String role, final String hint ) { final String key = Roles.canonicalRoleHint( role, hint ); final Component c = components.get( key ); if ( null == c ) { components.put( key, LOAD_ON_START_PLACEHOLDER ); } else if ( !Strategies.LOAD_ON_START.equals( c.instantiationStrategy() ) ) { components.put( key, new ComponentImpl( c.role(), c.hint(), Strategies.LOAD_ON_START, c.description() ) ); } } /** * Registers the given component, automatically disambiguating between implementations bound multiple times. * * @param role The Plexus role * @param hint The Plexus hint * @param instantiationStrategy The instantiation strategy * @param description The component description * @param implementation The implementation * @return The implementation the component was successfully registered with; otherwise {@code null} */ String addComponent( final String role, final String hint, final String instantiationStrategy, final String description, final String implementation ) { final Class roleType = loadRole( role, implementation ); if ( null == roleType ) { return null; } final String canonicalHint = Hints.canonicalHint( hint ); final String key = Roles.canonicalRoleHint( role, canonicalHint ); /* * COMPONENT... */ final Component oldComponent = components.get( key ); if ( null == oldComponent ) { components.put( key, new ComponentImpl( roleType, canonicalHint, instantiationStrategy, description ) ); } else if ( LOAD_ON_START_PLACEHOLDER == oldComponent ) { components.put( key, new ComponentImpl( roleType, canonicalHint, Strategies.LOAD_ON_START, description ) ); } /* * ...IMPLEMENTATION */ DeferredClass implementationType = implementations.get( key ); if ( null == implementationType ) { if ( deferredNames.add( implementation ) ) { implementationType = space.deferLoadClass( implementation ); } else { // type already used for another role, so we must clone it implementationType = cloneImplementation( implementation ); } implementations.put( key, implementationType ); return implementationType.getName(); } final String oldImplementation = implementationType.getName(); if ( implementation.equals( CloningClassLoader.getRealName( oldImplementation ) ) ) { return oldImplementation; // merge configuration } Logs.debug( "Duplicate implementations for Plexus role: {}", key, null ); Logs.debug( "Using: {} ignoring: {}", oldImplementation, implementation ); return null; } /** * @return Plexus component map */ Map> getComponents() { final Map> map = new HashMap>(); for ( final Entry> i : implementations.entrySet() ) { map.put( components.get( i.getKey() ), i.getValue() ); } return map; } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Attempts to load the given Plexus role, checks constructors for concrete types. * * @param role The Plexus role * @param implementation The implementation * @return Loaded Plexus role */ private Class loadRole( final String role, final String implementation ) { try { return space.loadClass( role ); } catch ( final TypeNotPresentException e ) { Logs.debug( "Ignoring Plexus role: {}", role, e ); } return null; } private DeferredClass cloneImplementation( final String implementation ) { if ( null == cloningClassSpace ) { cloningClassSpace = new URLClassSpace( AccessController.doPrivileged( new PrivilegedAction() { public ClassLoader run() { return new CloningClassLoader( space ); } } ), null ); } return cloningClassSpace.deferLoadClass( CloningClassLoader.proxyName( implementation, ++cloneCounter ) ); } } PlexusTypeVisitor.java000066400000000000000000000140551167051330000443130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import java.net.URL; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.LoadedClass; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.scanners.ClassSpaceScanner; import org.sonatype.guice.bean.scanners.ClassSpaceVisitor; import org.sonatype.guice.bean.scanners.EmptyAnnotationVisitor; import org.sonatype.guice.bean.scanners.EmptyClassVisitor; import org.sonatype.guice.bean.scanners.QualifiedTypeVisitor; import org.sonatype.guice.bean.scanners.asm.AnnotationVisitor; import org.sonatype.guice.bean.scanners.asm.ClassVisitor; import org.sonatype.guice.bean.scanners.asm.Opcodes; import org.sonatype.guice.bean.scanners.asm.Type; import org.sonatype.guice.plexus.annotations.ComponentImpl; import org.sonatype.guice.plexus.config.Hints; import org.sonatype.guice.plexus.config.Strategies; /** * {@link ClassSpaceVisitor} that reports Plexus bean classes annotated with @{@link Component}. */ public final class PlexusTypeVisitor extends EmptyClassVisitor implements ClassSpaceVisitor { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String COMPONENT_DESC = Type.getDescriptor( Component.class ); // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final ComponentAnnotationVisitor componentVisitor = new ComponentAnnotationVisitor(); private final PlexusTypeListener plexusTypeListener; private final QualifiedTypeVisitor qualifiedTypeVisitor; private ClassSpace space; private String source; private String implementation; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public PlexusTypeVisitor( final PlexusTypeListener listener ) { plexusTypeListener = listener; qualifiedTypeVisitor = new QualifiedTypeVisitor( listener ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void visit( final ClassSpace _space ) { space = _space; source = _space.toString(); qualifiedTypeVisitor.visit( _space ); if ( Logs.DEBUG_ENABLED ) { ClassSpaceScanner.verify( _space, Component.class ); } } public ClassVisitor visitClass( final URL url ) { componentVisitor.reset(); implementation = null; qualifiedTypeVisitor.visitClass( url ); return this; } @Override public void visit( final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces ) { if ( ( access & ( Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_SYNTHETIC ) ) == 0 ) { implementation = name.replace( '/', '.' ); } qualifiedTypeVisitor.visit( version, access, name, signature, superName, interfaces ); } @Override public AnnotationVisitor visitAnnotation( final String desc, final boolean visible ) { if ( COMPONENT_DESC.equals( desc ) ) { return componentVisitor; } return qualifiedTypeVisitor.visitAnnotation( desc, visible ); } @Override public void visitEnd() { if ( null != implementation ) { final Component component = componentVisitor.getComponent( space ); if ( null != component ) { final LoadedClass clazz = new LoadedClass( space.loadClass( implementation ) ); plexusTypeListener.hear( component, clazz, source ); } else { qualifiedTypeVisitor.visitEnd(); } implementation = null; } } // ---------------------------------------------------------------------- // Component annotation scanner // ---------------------------------------------------------------------- static final class ComponentAnnotationVisitor extends EmptyAnnotationVisitor { private String role; private String hint; private String strategy; private String description; public void reset() { role = null; hint = Hints.DEFAULT_HINT; strategy = Strategies.SINGLETON; description = ""; } @Override public void visit( final String name, final Object value ) { if ( "role".equals( name ) ) { role = ( (Type) value ).getClassName(); } else if ( "hint".equals( name ) ) { hint = Hints.canonicalHint( (String) value ); } else if ( "instantiationStrategy".equals( name ) ) { strategy = (String) value; } else if ( "description".equals( name ) ) { description = (String) value; } } public Component getComponent( final ClassSpace space ) { return null != role ? new ComponentImpl( space.loadClass( role ), hint, strategy, description ) : null; } } } PlexusXmlMetadata.java000066400000000000000000000102171167051330000442070ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; /** * Consumable {@link PlexusBeanMetadata} that uses {@link BeanProperty} names as keys. */ final class PlexusXmlMetadata implements PlexusBeanMetadata { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private Map configurationMap = Collections.emptyMap(); private Map requirementMap = Collections.emptyMap(); // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- PlexusXmlMetadata( final Map configurationMap, final Map requirementMap ) { merge( configurationMap, requirementMap ); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean isEmpty() { return configurationMap.isEmpty() && requirementMap.isEmpty(); } public Configuration getConfiguration( final BeanProperty property ) { return configurationMap.remove( property.getName() ); } public Requirement getRequirement( final BeanProperty property ) { Requirement requirement = requirementMap.remove( property.getName() ); if ( null == requirement ) { // perhaps requirement uses the fully-qualified role name (see PlexusXmlScanner) requirement = requirementMap.remove( property.getType().getRawType().getName() ); } return requirement; } // ---------------------------------------------------------------------- // Locally-shared methods // ---------------------------------------------------------------------- /** * Merges the given configuration and requirements with the current metadata, without overwriting existing entries. * * @param extraConfiguration The extra configuration * @param extraRequirements The extra requirements */ void merge( final Map extraConfiguration, final Map extraRequirements ) { configurationMap = addIfMissing( configurationMap, extraConfiguration ); requirementMap = addIfMissing( requirementMap, extraRequirements ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Looks for keys that exist in the secondary map, but not the primary, and adds their mappings to the primary map. * * @param primary The primary map * @param secondary The secondary map */ private static Map addIfMissing( final Map primary, final Map secondary ) { // nothing to add? if ( secondary.isEmpty() ) { return primary; } // nothing to merge? if ( primary.isEmpty() ) { return secondary; } // primary mappings always override secondary mappings final Map tempMap = new HashMap( secondary ); tempMap.putAll( primary ); return tempMap; } } PlexusXmlScanner.java000066400000000000000000000403471167051330000440670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/main/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.InterpolationFilterReader; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.xml.pull.MXParser; import org.codehaus.plexus.util.xml.pull.XmlPullParser; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.Logs; import org.sonatype.guice.bean.reflect.Streams; import org.sonatype.guice.plexus.annotations.ConfigurationImpl; import org.sonatype.guice.plexus.annotations.RequirementImpl; import org.sonatype.guice.plexus.config.Hints; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; import org.sonatype.guice.plexus.config.Roles; import org.sonatype.guice.plexus.config.Strategies; public final class PlexusXmlScanner { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Map variables; private final URL plexusXml; private final Map metadata; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- /** * Creates an XML scanner that also accumulates Plexus bean metadata in the given map. * * @param variables The filter variables * @param plexusXml The plexus.xml URL * @param metadata The metadata map */ public PlexusXmlScanner( final Map variables, final URL plexusXml, final Map metadata ) { this.variables = variables; this.plexusXml = plexusXml; this.metadata = metadata; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public Map> scan( final ClassSpace space, final boolean root ) { final PlexusTypeRegistry registry = new PlexusTypeRegistry( space ); if ( null != plexusXml ) { parsePlexusXml( plexusXml, registry ); } final Enumeration e; if ( root ) { e = space.getResources( "META-INF/plexus/components.xml" ); } else { e = space.findEntries( "META-INF/plexus", "components.xml", false ); } while ( e.hasMoreElements() ) { parseComponentsXml( e.nextElement(), registry ); } return registry.getComponents(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- /** * Wraps the given {@link InputStream} as a {@link Reader} with XML encoding detection and optional interpolation. * * @param in The input stream * @param variables The filter variables * @return Reader that can automatically detect XML encodings and optionally interpolate variables */ private static Reader filteredXmlReader( final InputStream in, final Map variables ) throws IOException { final Reader reader = ReaderFactory.newXmlReader( in ); if ( null != variables ) { return new InterpolationFilterReader( reader, variables ); } return reader; } /** * Parses a {@code plexus.xml} resource into load-on-start settings and Plexus bean metadata. * * @param url The plexus.xml URL * @param registry The parsed components */ private void parsePlexusXml( final URL url, final PlexusTypeRegistry registry ) { try { final InputStream in = Streams.open( url ); try { final MXParser parser = new MXParser(); parser.setInput( filteredXmlReader( in, variables ) ); parser.nextTag(); parser.require( XmlPullParser.START_TAG, null, null ); // this may be or while ( parser.nextTag() == XmlPullParser.START_TAG ) { final String name = parser.getName(); if ( Strategies.LOAD_ON_START.equals( name ) ) { while ( parser.nextTag() == XmlPullParser.START_TAG ) { parseLoadOnStart( parser, registry ); } } else if ( "components".equals( name ) ) { while ( parser.nextTag() == XmlPullParser.START_TAG ) { parseComponent( parser, registry ); } } else { parser.skipSubTree(); } } } finally { IOUtil.close( in ); } } catch ( final Exception e ) { Logs.debug( "Problem parsing: {}", url, e ); } } /** * Parses a {@code components.xml} resource into a series of Plexus bean metadata. * * @param url The components.xml URL * @param registry The parsed components */ private void parseComponentsXml( final URL url, final PlexusTypeRegistry registry ) { try { final InputStream in = Streams.open( url ); try { final MXParser parser = new MXParser(); parser.setInput( filteredXmlReader( in, variables ) ); parser.nextTag(); parser.require( XmlPullParser.START_TAG, null, null ); // this may be or parser.nextTag(); parser.require( XmlPullParser.START_TAG, null, "components" ); while ( parser.nextTag() == XmlPullParser.START_TAG ) { parseComponent( parser, registry ); } } finally { IOUtil.close( in ); } } catch ( final Exception e ) { Logs.debug( "Problem parsing: {}", url, e ); } } /** * Parses a load-on-start <component> XML stanza into a Plexus role-hint. * * @param parser The XML parser * @param registry The parsed components */ private static void parseLoadOnStart( final MXParser parser, final PlexusTypeRegistry registry ) throws XmlPullParserException, IOException { if ( "component".equals( parser.getName() ) ) { String role = null; String hint = ""; while ( parser.nextTag() == XmlPullParser.START_TAG ) { if ( "role".equals( parser.getName() ) ) { role = TEXT( parser ); } else if ( "role-hint".equals( parser.getName() ) ) { hint = TEXT( parser ); } else { parser.skipSubTree(); } } if ( null == role ) { throw new XmlPullParserException( "Missing element.", parser, null ); } registry.loadOnStart( role, hint ); } else { parser.skipSubTree(); } } /** * Parses a <component> XML stanza into a deferred implementation, configuration, and requirements. * * @param parser The XML parser * @param registry The parsed components */ private void parseComponent( final MXParser parser, final PlexusTypeRegistry registry ) throws XmlPullParserException, IOException { String role = null; String hint = ""; String instantiationStrategy = Strategies.SINGLETON; String description = ""; String implementation = null; final Map requirementMap = new HashMap(); final Map configurationMap = new HashMap(); final ClassSpace space = registry.getSpace(); parser.require( XmlPullParser.START_TAG, null, "component" ); while ( parser.nextTag() == XmlPullParser.START_TAG ) { final String name = parser.getName(); if ( "requirements".equals( name ) ) { while ( parser.nextTag() == XmlPullParser.START_TAG ) { parseRequirement( parser, space, requirementMap ); } } else if ( "configuration".equals( name ) ) { while ( parser.nextTag() == XmlPullParser.START_TAG ) { parseConfiguration( parser, configurationMap ); } } else if ( "role".equals( name ) ) { role = TEXT( parser ).intern(); } else if ( "role-hint".equals( name ) ) { hint = TEXT( parser ); } else if ( "instantiation-strategy".equals( name ) ) { instantiationStrategy = TEXT( parser ).intern(); } else if ( "description".equals( name ) ) { description = TEXT( parser ); } else if ( "implementation".equals( name ) ) { implementation = TEXT( parser ).intern(); } else { parser.skipSubTree(); } } if ( null == implementation ) { throw new XmlPullParserException( "Missing element.", parser, null ); } if ( null == role ) { role = implementation; } implementation = registry.addComponent( role, hint, instantiationStrategy, description, implementation ); if ( null != implementation ) { updatePlexusBeanMetadata( implementation, configurationMap, requirementMap ); } } /** * Updates the shared Plexus bean metadata with the given local information. * * @param implementation The component implementation * @param configurationMap The field -> @{@link Configuration} map * @param requirementMap The field -> @{@link Requirement} map */ private void updatePlexusBeanMetadata( final String implementation, final Map configurationMap, final Map requirementMap ) { if ( null != metadata && ( !configurationMap.isEmpty() || !requirementMap.isEmpty() ) ) { final PlexusXmlMetadata beanMetadata = (PlexusXmlMetadata) metadata.get( implementation ); if ( beanMetadata != null ) { beanMetadata.merge( configurationMap, requirementMap ); } else { metadata.put( implementation, new PlexusXmlMetadata( configurationMap, requirementMap ) ); } } } /** * Parses a <requirement> XML stanza into a mapping from a field name to a @{@link Requirement}. * * @param parser The XML parser * @param space The class space * @param requirementMap The field -> @{@link Requirement} map */ private static void parseRequirement( final MXParser parser, final ClassSpace space, final Map requirementMap ) throws XmlPullParserException, IOException { String role = null; final List hintList = new ArrayList(); String fieldName = null; boolean optional = false; parser.require( XmlPullParser.START_TAG, null, "requirement" ); while ( parser.nextTag() == XmlPullParser.START_TAG ) { final String name = parser.getName(); if ( "role".equals( name ) ) { role = TEXT( parser ).intern(); } else if ( "role-hint".equals( name ) ) { hintList.add( TEXT( parser ) ); } else if ( "role-hints".equals( name ) ) { while ( parser.nextTag() == XmlPullParser.START_TAG ) { hintList.add( TEXT( parser ) ); } } else if ( "field-name".equals( name ) ) { fieldName = TEXT( parser ); } else if ( "optional".equals( name ) ) { optional = Boolean.parseBoolean( TEXT( parser ) ); } else { parser.skipSubTree(); } } if ( null == role ) { throw new XmlPullParserException( "Missing element.", parser, null ); } if ( null == fieldName ) { fieldName = role; // use fully-qualified role as the field name (see PlexusXmlMetadata) } requirementMap.put( fieldName, new RequirementImpl( space.deferLoadClass( role ), optional, Hints.canonicalHints( hintList ) ) ); } /** * Parses a <configuration> XML stanza into a mapping from a field name to a @{@link Configuration}. * * @param parser The XML parser * @param configurationMap The field -> @{@link Configuration} map */ private static void parseConfiguration( final MXParser parser, final Map configurationMap ) throws XmlPullParserException, IOException { final String name = parser.getName(); // make sure we have a valid Java identifier final String fieldName = Roles.camelizeName( name ); final StringBuilder buf = new StringBuilder(); final String header = parser.getText().trim(); final int depth = parser.getDepth(); while ( parser.next() != XmlPullParser.END_TAG || parser.getDepth() > depth ) { // combine children into single string buf.append( parser.getText().trim() ); } // add header+footer when there's nested XML or attributes if ( buf.indexOf( "<" ) == 0 || header.indexOf( '=' ) > 0 ) { buf.insert( 0, header ); if ( !header.endsWith( "/>" ) ) { // follow up with basic footer buf.append( "' ); } } configurationMap.put( fieldName, new ConfigurationImpl( fieldName, buf.toString() ) ); } /** * Returns the text contained inside the current XML element, without any surrounding whitespace. * * @param parser The XML parser * @return Trimmed TEXT element */ private static String TEXT( final XmlPullParser parser ) throws XmlPullParserException, IOException { return parser.nextText().trim(); } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/000077500000000000000000000000001167051330000302515ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/000077500000000000000000000000001167051330000311725ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/org/000077500000000000000000000000001167051330000317615ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/org/sonatype/000077500000000000000000000000001167051330000336235ustar00rootroot00000000000000000077500000000000000000000000001167051330000346405ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/org/sonatype/guice000077500000000000000000000000001167051330000361605ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000377745ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/org/sonatype/guice/plexus/scannersBadBean.java000066400000000000000000000011471167051330000421160ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import org.codehaus.plexus.component.annotations.Component; @Component( role = int.class ) public class BadBean { } PlexusAnnotatedBeanMetadataTest.java000066400000000000000000000103121167051330000470410ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import java.util.Collections; import java.util.Iterator; import java.util.Map; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.bean.reflect.BeanProperties; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.plexus.annotations.ConfigurationImpl; import org.sonatype.guice.plexus.annotations.RequirementImpl; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; public class PlexusAnnotatedBeanMetadataTest extends TestCase { @Component( role = Bean.class ) protected static class Bean { @Configuration( name = "1", value = "BLANK" ) String fixed; @Configuration( name = "2", value = "${some.value}" ) String variable; String dummy1; @Requirement( role = Bean.class, hint = "mock", optional = true ) Bean self; String dummy2; } @SuppressWarnings( "deprecation" ) public void testRawAnnotations() { final PlexusBeanMetadata metadata = new PlexusAnnotatedMetadata( null ); assertFalse( metadata.isEmpty() ); final Iterator> propertyIterator = new BeanProperties( Bean.class ).iterator(); final Requirement requirement2 = metadata.getRequirement( propertyIterator.next() ); final Requirement requirement1 = metadata.getRequirement( propertyIterator.next() ); final Configuration configuration3 = metadata.getConfiguration( propertyIterator.next() ); final Configuration configuration2 = metadata.getConfiguration( propertyIterator.next() ); final Configuration configuration1 = metadata.getConfiguration( propertyIterator.next() ); assertFalse( propertyIterator.hasNext() ); assertFalse( configuration1 instanceof ConfigurationImpl ); assertEquals( new ConfigurationImpl( "1", "BLANK" ), configuration1 ); assertFalse( configuration2 instanceof ConfigurationImpl ); assertEquals( new ConfigurationImpl( "2", "${some.value}" ), configuration2 ); assertNull( configuration3 ); assertEquals( new RequirementImpl( Bean.class, true, "mock" ), requirement1 ); assertNull( requirement2 ); } @SuppressWarnings( "deprecation" ) public void testInterpolatedAnnotations() { final Map variables = Collections.singletonMap( "some.value", "INTERPOLATED" ); final PlexusBeanMetadata metadata = new PlexusAnnotatedMetadata( variables ); assertFalse( metadata.isEmpty() ); final Iterator> propertyIterator = new BeanProperties( Bean.class ).iterator(); final Requirement requirement2 = metadata.getRequirement( propertyIterator.next() ); final Requirement requirement1 = metadata.getRequirement( propertyIterator.next() ); final Configuration configuration3 = metadata.getConfiguration( propertyIterator.next() ); final Configuration configuration2 = metadata.getConfiguration( propertyIterator.next() ); final Configuration configuration1 = metadata.getConfiguration( propertyIterator.next() ); assertFalse( propertyIterator.hasNext() ); assertFalse( configuration1 instanceof ConfigurationImpl ); assertEquals( new ConfigurationImpl( "1", "BLANK" ), configuration1 ); assertTrue( configuration2 instanceof ConfigurationImpl ); assertEquals( new ConfigurationImpl( "2", "INTERPOLATED" ), configuration2 ); assertNull( configuration3 ); assertEquals( new RequirementImpl( Bean.class, true, "mock" ), requirement1 ); assertNull( requirement2 ); } } PlexusXmlScannerTest.java000066400000000000000000000401731167051330000447570ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.net.URL; import java.net.URLClassLoader; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import junit.framework.TestCase; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.DeferredProvider; import org.sonatype.guice.bean.reflect.LoadedClass; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.guice.bean.scanners.asm.ClassWriter; import org.sonatype.guice.bean.scanners.asm.MethodVisitor; import org.sonatype.guice.bean.scanners.asm.Opcodes; import org.sonatype.guice.plexus.annotations.ComponentImpl; import org.sonatype.guice.plexus.annotations.ConfigurationImpl; import org.sonatype.guice.plexus.annotations.RequirementImpl; import org.sonatype.guice.plexus.config.Hints; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; import org.sonatype.guice.plexus.config.Strategies; import com.google.inject.TypeLiteral; public class PlexusXmlScannerTest extends TestCase { static class NamedProperty implements BeanProperty { final String name; final TypeLiteral type; public NamedProperty( final String name ) { this.name = name; type = TypeLiteral.get( Object.class ); } @SuppressWarnings( { "unchecked", "rawtypes" } ) public NamedProperty( final String name, final TypeLiteral type ) { this.name = name; this.type = type; } public A getAnnotation( final Class annotationType ) { return null; } public String getName() { return name; } public TypeLiteral getType() { return type; } public void set( final B bean, final Object value ) { } } interface Bean { } protected static class DefaultBean { } static class DebugBean { } static class AnotherBean { } static class EmptyClassSpace implements ClassSpace { public Class loadClass( final String name ) { try { return Class.forName( name ); } catch ( final ClassNotFoundException e ) { throw new TypeNotPresentException( name, e ); } } @SuppressWarnings( { "unchecked", "rawtypes" } ) public DeferredClass deferLoadClass( final String name ) { return new LoadedClass( loadClass( name ) ); } public URL getResource( final String name ) { return null; } public Enumeration getResources( final String name ) { // hide components.xml so we can just test plexus.xml parsing return Collections.enumeration( Collections. emptyList() ); } public Enumeration findEntries( final String path, final String glob, final boolean recurse ) { // hide components.xml so we can just test plexus.xml parsing return Collections.enumeration( Collections. emptyList() ); } } public void testLoadOnStart() { final URL plexusXml = getClass().getResource( "/META-INF/plexus/plexus.xml" ); final PlexusXmlScanner scanner = new PlexusXmlScanner( null, plexusXml, null ); final Map> componentMap = scanner.scan( new EmptyClassSpace(), true ); assertEquals( 2, componentMap.size() ); final Component component1 = new ComponentImpl( DefaultBean.class, Hints.DEFAULT_HINT, Strategies.LOAD_ON_START, "" ); assertEquals( DefaultBean.class, componentMap.get( component1 ).load() ); final Component component2 = new ComponentImpl( Bean.class, "debug", Strategies.LOAD_ON_START, "For debugging" ); assertEquals( DebugBean.class, componentMap.get( component2 ).load() ); } public void testBadPlexusXml() { final ClassSpace space = new URLClassSpace( PlexusXmlScannerTest.class.getClassLoader() ); final URL plexusXml = getClass().getResource( "/META-INF/plexus/bad_plexus_1.xml" ); new PlexusXmlScanner( null, plexusXml, null ).scan( space, true ); } @SuppressWarnings( "deprecation" ) public void testComponents() { final ClassSpace space = new URLClassSpace( PlexusXmlScannerTest.class.getClassLoader() ); final Map metadata = new HashMap(); final PlexusXmlScanner scanner = new PlexusXmlScanner( null, null, metadata ); final Map> componentMap = scanner.scan( space, true ); assertEquals( 4, componentMap.size() ); final Component component1 = new ComponentImpl( DefaultBean.class, Hints.DEFAULT_HINT, Strategies.PER_LOOKUP, "" ); assertEquals( DefaultBean.class, componentMap.get( component1 ).load() ); final Component component2 = new ComponentImpl( Bean.class, "debug", Strategies.SINGLETON, "For debugging" ); assertEquals( DebugBean.class, componentMap.get( component2 ).load() ); final Component component3 = new ComponentImpl( Bean.class, Hints.DEFAULT_HINT, Strategies.SINGLETON, "" ); assertEquals( AnotherBean.class, componentMap.get( component3 ).load() ); final Component component4 = new ComponentImpl( Bean.class, "clone", Strategies.SINGLETON, "" ); assertEquals( DefaultBean.class, componentMap.get( component4 ).load().getSuperclass() ); final Class proxy = CustomTestClassLoader.proxy( componentMap.get( component4 ).load() ); try { assertNotNull( proxy.getMethod( "TestMe" ) ); } catch ( final NoSuchMethodException e ) { fail( "Proxied class is missing 'TestMe' method" ); } final PlexusBeanMetadata metadata1 = metadata.get( DefaultBean.class.getName() ); assertFalse( metadata1.isEmpty() ); assertEquals( new ConfigurationImpl( "someFieldName", "PRIMARY" ), metadata1.getConfiguration( new NamedProperty( "someFieldName" ) ) ); assertEquals( new ConfigurationImpl( "simple", "value" ), metadata1.getConfiguration( new NamedProperty( "simple" ) ) ); assertEquals( new ConfigurationImpl( "value", "" ), metadata1.getConfiguration( new NamedProperty( "value" ) ) ); assertEquals( new ConfigurationImpl( "emptyValue1", "" ), metadata1.getConfiguration( new NamedProperty( "emptyValue1" ) ) ); assertEquals( new ConfigurationImpl( "emptyValue2", "" ), metadata1.getConfiguration( new NamedProperty( "emptyValue2" ) ) ); assertFalse( metadata1.isEmpty() ); assertEquals( new RequirementImpl( Bean.class, true, "debug" ), metadata1.getRequirement( new NamedProperty( "bean", TypeLiteral.get( Bean.class ) ) ) ); assertFalse( metadata1.isEmpty() ); metadata1.getConfiguration( new NamedProperty( "foo" ) ); assertEquals( new RequirementImpl( Bean.class, false, Hints.DEFAULT_HINT, "debug" ), metadata1.getRequirement( new NamedProperty( "beanMap" ) ) ); assertFalse( metadata1.isEmpty() ); assertEquals( new RequirementImpl( Bean.class, false ), metadata1.getRequirement( new NamedProperty( "beanField" ) ) ); assertTrue( metadata1.isEmpty() ); assertNotNull( metadata.get( AnotherBean.class.getName() ) ); assertNull( metadata.get( DebugBean.class.getName() ) ); } static class FixedClassSpace implements ClassSpace { final String fixedResourceName; FixedClassSpace( final String fixedResourceName ) { this.fixedResourceName = fixedResourceName; } public Class loadClass( final String name ) { try { return Class.forName( name ); } catch ( final ClassNotFoundException e ) { throw new TypeNotPresentException( name, e ); } } @SuppressWarnings( "rawtypes" ) public DeferredClass deferLoadClass( final String name ) { return new DeferredClass() { public Class load() { return loadClass( name ); } public String getName() { return name; } public DeferredProvider asProvider() { throw new UnsupportedOperationException(); } }; } public URL getResource( final String name ) { return getClass().getResource( fixedResourceName ); } public Enumeration getResources( final String name ) { return Collections.enumeration( Collections.singleton( getClass().getResource( fixedResourceName ) ) ); } public Enumeration findEntries( final String path, final String glob, final boolean recurse ) { return Collections.enumeration( Collections.singleton( getClass().getResource( fixedResourceName ) ) ); } } public void testBadComponentsXml() { ClassSpace space; space = new FixedClassSpace( "/META-INF/plexus/bad_components_1.xml" ); new PlexusXmlScanner( null, null, null ).scan( space, true ); space = new FixedClassSpace( "/META-INF/plexus/bad_components_2.xml" ); new PlexusXmlScanner( null, null, null ).scan( space, true ); try { space = new FixedClassSpace( "/META-INF/plexus/bad_components_3.xml" ); final Map metadata = new HashMap(); final PlexusXmlScanner scanner = new PlexusXmlScanner( null, null, metadata ); scanner.scan( space, true ); final Requirement badReq = metadata.get( DefaultBean.class.getName() ).getRequirement( new NamedProperty( "no.such.class" ) ); badReq.role(); fail( "Expected TypeNotPresentException" ); } catch ( final TypeNotPresentException e ) { } space = new FixedClassSpace( "/META-INF/plexus/bad_components_4.xml" ); final PlexusXmlScanner scanner = new PlexusXmlScanner( null, null, null ); assertTrue( scanner.scan( space, true ).isEmpty() ); } public void testInterpolatedComponentsXml() { final ClassSpace space = new FixedClassSpace( "/META-INF/plexus/variable_components.xml" ); final Map metadata = new HashMap(); new PlexusXmlScanner( null, null, metadata ).scan( space, true ); assertEquals( "${some.value}", metadata.get( DefaultBean.class.getName() ).getConfiguration( new NamedProperty( "variable" ) ).value() ); final Map variables = Collections.singletonMap( "some.value", "INTERPOLATED" ); new PlexusXmlScanner( variables, null, metadata ).scan( space, true ); assertEquals( "INTERPOLATED", metadata.get( DefaultBean.class.getName() ).getConfiguration( new NamedProperty( "variable" ) ).value() ); } public void testLocalizedXmlScanning() { final ClassSpace space = new URLClassSpace( PlexusXmlScannerTest.class.getClassLoader(), null ); assertFalse( new PlexusXmlScanner( null, null, null ).scan( space, true ).isEmpty() ); assertTrue( new PlexusXmlScanner( null, null, null ).scan( space, false ).isEmpty() ); } public void testOptionalLogging() throws Exception { final Level level = Logger.getLogger( "" ).getLevel(); try { Logger.getLogger( "" ).setLevel( Level.SEVERE ); // check everything still works without any SLF4J jars final ClassLoader noLoggingLoader = new URLClassLoader( ( (URLClassLoader) getClass().getClassLoader() ).getURLs(), null ) { @Override protected synchronized Class loadClass( final String name, final boolean resolve ) throws ClassNotFoundException { if ( name.contains( "slf4j" ) ) { throw new ClassNotFoundException( name ); } if ( name.contains( "cobertura" ) ) { return PlexusXmlScannerTest.class.getClassLoader().loadClass( name ); } return super.loadClass( name, resolve ); } }; noLoggingLoader.loadClass( SimpleScanningExample.class.getName() ).newInstance(); } finally { Logger.getLogger( "" ).setLevel( level ); } } static final class CustomTestClassLoader extends ClassLoader { private static final String PROXY_MARKER = "$proxy"; CustomTestClassLoader( final ClassLoader parent ) { super( parent ); } static Class proxy( final Class clazz ) { try { return new CustomTestClassLoader( clazz.getClassLoader() ).loadClass( clazz.getName() + PROXY_MARKER ); } catch ( final ClassNotFoundException e ) { throw new TypeNotPresentException( clazz.getName(), e ); } } @Override protected synchronized Class loadClass( final String name, final boolean resolve ) throws ClassNotFoundException { return super.loadClass( name, resolve ); } @Override protected Class findClass( final String name ) throws ClassNotFoundException { final String proxyName = name.replace( '.', '/' ); final String superName = proxyName.substring( 0, proxyName.length() - PROXY_MARKER.length() ); final ClassWriter cw = new ClassWriter( ClassWriter.COMPUTE_MAXS ); cw.visit( Opcodes.V1_5, Modifier.PUBLIC | Modifier.FINAL, proxyName, null, superName, null ); MethodVisitor mv = cw.visitMethod( Modifier.PUBLIC, "", "()V", null, null ); mv.visitCode(); mv.visitVarInsn( Opcodes.ALOAD, 0 ); mv.visitMethodInsn( Opcodes.INVOKESPECIAL, superName, "", "()V" ); mv.visitInsn( Opcodes.RETURN ); mv.visitMaxs( 0, 0 ); mv.visitEnd(); mv = cw.visitMethod( Modifier.PUBLIC, "TestMe", "()V", null, null ); mv.visitCode(); mv.visitInsn( Opcodes.RETURN ); mv.visitMaxs( 0, 0 ); mv.visitEnd(); cw.visitEnd(); final byte[] buf = cw.toByteArray(); return defineClass( name, buf, 0, buf.length ); } } } SimpleScanningExample.java000066400000000000000000000015131167051330000450650ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.URLClassSpace; public class SimpleScanningExample { public SimpleScanningExample() { final ClassSpace space = new URLClassSpace( getClass().getClassLoader() ); new PlexusXmlScanner( null, null, null ).scan( space, true ); } } TestBean.java000066400000000000000000000015121167051330000423430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/java/org/sonatype/guice/plexus/scanners/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.scanners; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.guice.plexus.config.Strategies; @Component( role = Runnable.class, hint = "test", instantiationStrategy = Strategies.PER_LOOKUP, description = "Some Test", isolatedRealm = true ) public class TestBean implements Runnable { public void run() { } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/000077500000000000000000000000001167051330000322635ustar00rootroot00000000000000000077500000000000000000000000001167051330000333445ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/META-INF000077500000000000000000000000001167051330000346645ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/META-INF/plexusbad_components_1.xml000066400000000000000000000001231167051330000406150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/META-INF/plexus bad_components_2.xml000066400000000000000000000005731167051330000406270ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/META-INF/plexus org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean beanField bad_components_3.xml000066400000000000000000000005631167051330000406270ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/META-INF/plexus org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean no.such.class bad_components_4.xml000066400000000000000000000002501167051330000406210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/META-INF/plexus no.such.class bad_plexus_1.xml000066400000000000000000000001131167051330000377470ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/META-INF/plexus components.xml000066400000000000000000000067641167051330000376100ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/META-INF/plexus org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean per-lookup PRIMARY org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$Bean debug For debugging org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DebugBean org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean value SECONDARY org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$Bean debug True org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$Bean default debug beanMap org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$Bean beanField org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$Bean org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$AnotherBean org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$Bean org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$Bean org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$Bean clone org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean foo bar 1.0 plexus.xml000066400000000000000000000025321167051330000367300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/META-INF/plexus org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean per-lookup org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$Bean debug org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DebugBean For debugging org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$Bean debug org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean foo bar 1.0 variable_components.xml000066400000000000000000000014161167051330000414420ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-scanners/src/test/resources/META-INF/plexus org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean foo ${some.value} bar debug org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean again org.sonatype.guice.plexus.scanners.PlexusXmlScannerTest$DefaultBean sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/000077500000000000000000000000001167051330000256275ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/pom.xml000066400000000000000000000063551167051330000271550ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-plexus 2.3.0 guice-plexus-shim Sisu-Inject-Plexus : Container API org.codehaus.plexus plexus-component-annotations javax.inject javax.inject org.sonatype.sisu sisu-guice org.slf4j slf4j-api true org.sonatype.sisu.inject guice-bean-reflect org.sonatype.sisu.inject guice-bean-locators org.sonatype.sisu.inject guice-bean-binders org.sonatype.sisu.inject guice-plexus-metadata org.sonatype.sisu.inject guice-plexus-converters org.sonatype.sisu.inject guice-plexus-locators org.sonatype.sisu.inject guice-plexus-binders org.sonatype.sisu.inject guice-plexus-lifecycles org.codehaus.plexus plexus-classworlds org.codehaus.plexus plexus-utils junit junit true maven-surefire-plugin once **/Test*.java **/Abstract*.java sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/scan4use.sh000077500000000000000000000017331167051330000277170ustar00rootroot00000000000000#!/bin/sh if [ $# -lt 2 ] then echo "$0 packagename [ directory | jarfiles... ]" exit fi PKG=$1 shift if [ -d $1 ] then JARS=`find $1 -name "*.jar"` else JARS=$@ fi SEG="([./$][a-z0-9_][a-z0-9_]*)" CLZ="([./$][A-Z][A-Za-z0-9_]*)" MTH="([.][a-z][A-Za-z0-9_]*)" function scan { awk "/$PKG/ { while ( match( \$0, \"$PKG$SEG*$CLZ*$MTH?\" ) > 0 ) { USE=substr( \$0, RSTART, RLENGTH ); gsub( \"[/$]\", \".\", USE ); print( USE ); \$0 = substr( \$0, RSTART + RLENGTH ); } }" } SCRATCH=`mktemp --tmpdir -d "scan4use.XXXXXXXXXX"` LISTING=$SCRATCH.lst for f in $JARS do echo "@ $f" rm -fr $SCRATCH rm -f $LISTING unzip -q -d $SCRATCH $f for g in `find $SCRATCH -type f` do CLASSFILE=${g%.class} if [ "$CLASSFILE" != "$g" ] then ( cd $SCRATCH ; javap -v ${CLASSFILE#$SCRATCH} ) | scan >> $LISTING else strings $g | scan >> $LISTING fi done sort -u $LISTING done rm -fr $SCRATCH rm -f $LISTING sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/000077500000000000000000000000001167051330000264165ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/000077500000000000000000000000001167051330000273425ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/000077500000000000000000000000001167051330000302635ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/000077500000000000000000000000001167051330000310525ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/000077500000000000000000000000001167051330000326455ustar00rootroot00000000000000000077500000000000000000000000001167051330000341065ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexusComponentDescriptorBeanModule.java000066400000000000000000000201011167051330000427000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.inject.Inject; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.component.factory.ComponentFactory; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.ComponentRequirement; import org.sonatype.guice.bean.reflect.BeanProperty; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.DeferredProvider; import org.sonatype.guice.bean.reflect.LoadedClass; import org.sonatype.guice.plexus.annotations.ComponentImpl; import org.sonatype.guice.plexus.annotations.RequirementImpl; import org.sonatype.guice.plexus.binders.PlexusTypeBinder; import org.sonatype.guice.plexus.config.PlexusBeanMetadata; import org.sonatype.guice.plexus.config.PlexusBeanModule; import org.sonatype.guice.plexus.config.PlexusBeanSource; import org.sonatype.guice.plexus.locators.ClassRealmUtils; import com.google.inject.Binder; import com.google.inject.Injector; import com.google.inject.ProvisionException; final class ComponentDescriptorBeanModule implements PlexusBeanModule { private final ClassSpace space; private final Map> componentMap = new HashMap>(); private final Map metadataMap = new HashMap(); ComponentDescriptorBeanModule( final ClassSpace space, final List> descriptors ) { this.space = space; for ( int i = 0, size = descriptors.size(); i < size; i++ ) { final ComponentDescriptor cd = descriptors.get( i ); final Component component = newComponent( cd ); final String factory = cd.getComponentFactory(); if ( null == factory || "java".equals( factory ) ) { try { componentMap.put( component, new LoadedClass( cd.getImplementationClass() ) ); } catch ( final TypeNotPresentException e ) { componentMap.put( component, space.deferLoadClass( cd.getImplementation() ) ); } } else { componentMap.put( component, new DeferredFactoryClass( cd, factory ) ); } final List requirements = cd.getRequirements(); if ( !requirements.isEmpty() ) { metadataMap.put( cd.getImplementation(), new ComponentMetadata( space, requirements ) ); } } } public PlexusBeanSource configure( final Binder binder ) { final PlexusTypeBinder plexusTypeBinder = new PlexusTypeBinder( binder ); for ( final Entry> entry : componentMap.entrySet() ) { plexusTypeBinder.hear( entry.getKey(), entry.getValue(), space ); } return new PlexusDescriptorBeanSource( metadataMap ); } static Component newComponent( final ComponentDescriptor cd ) { return new ComponentImpl( cd.getRoleClass(), cd.getRoleHint(), cd.getInstantiationStrategy(), cd.getDescription() ); } static Requirement newRequirement( final ClassSpace space, final ComponentRequirement cr ) { return new RequirementImpl( space.deferLoadClass( cr.getRole() ), cr.isOptional(), Collections.singletonList( cr.getRoleHint() ) ); } private static final class DeferredFactoryClass implements DeferredClass, DeferredProvider { @Inject private PlexusContainer container; @Inject private Injector injector; private final ComponentDescriptor cd; private final String hint; DeferredFactoryClass( final ComponentDescriptor cd, final String hint ) { this.cd = cd; this.hint = hint; } @SuppressWarnings( { "unchecked", "rawtypes" } ) public Class load() throws TypeNotPresentException { return cd.getImplementationClass(); } public String getName() { return cd.getImplementation(); } public DeferredProvider asProvider() { return this; } public Object get() { try { ClassRealm contextRealm = container.getLookupRealm(); if ( null == contextRealm ) { contextRealm = ClassRealmUtils.contextRealm(); } if ( null == contextRealm ) { contextRealm = container.getContainerRealm(); } final ComponentFactory factory = container.lookup( ComponentFactory.class, hint ); final Object o = factory.newInstance( cd, contextRealm, container ); if ( null != o ) { injector.injectMembers( o ); } return o; } catch ( final Exception e ) { throw new ProvisionException( "Error in ComponentFactory:" + hint, e ); } } public DeferredClass getImplementationClass() { return this; } } private static final class ComponentMetadata implements PlexusBeanMetadata { private Map requirementMap = new HashMap(); ComponentMetadata( final ClassSpace space, final List requirements ) { for ( int i = 0, size = requirements.size(); i < size; i++ ) { final ComponentRequirement cr = requirements.get( i ); requirementMap.put( cr.getFieldName(), newRequirement( space, cr ) ); } } public boolean isEmpty() { return requirementMap.isEmpty(); } public Requirement getRequirement( final BeanProperty property ) { final Requirement requirement = requirementMap.get( property.getName() ); if ( null != requirement && requirementMap.isEmpty() ) { requirementMap = Collections.emptyMap(); } return requirement; } public Configuration getConfiguration( final BeanProperty property ) { return null; } } private static final class PlexusDescriptorBeanSource implements PlexusBeanSource { private Map metadataMap; PlexusDescriptorBeanSource( final Map metadataMap ) { this.metadataMap = metadataMap; } public PlexusBeanMetadata getBeanMetadata( final Class implementation ) { if ( null == metadataMap ) { return null; } final PlexusBeanMetadata metadata = metadataMap.remove( implementation.getName() ); if ( metadataMap.isEmpty() ) { metadataMap = null; } return metadata; } } } ContainerConfiguration.java000066400000000000000000000030571167051330000414300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus; import java.net.URL; import java.util.Map; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; public interface ContainerConfiguration { ContainerConfiguration setName( String name ); ContainerConfiguration setContainerConfiguration( String configurationPath ); String getContainerConfiguration(); ContainerConfiguration setContainerConfigurationURL( URL configurationUrl ); URL getContainerConfigurationURL(); ContainerConfiguration setClassWorld( ClassWorld classWorld ); ClassWorld getClassWorld(); ContainerConfiguration setRealm( ClassRealm classRealm ); ClassRealm getRealm(); ContainerConfiguration setContext( Map context ); Map getContext(); ContainerConfiguration setComponentVisibility( String visibility ); String getComponentVisibility(); ContainerConfiguration setAutoWiring( boolean on ); boolean getAutoWiring(); ContainerConfiguration setClassPathScanning( String scanning ); String getClassPathScanning(); } DefaultContainerConfiguration.java000066400000000000000000000071511167051330000427340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus; import java.net.URL; import java.util.Map; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; public final class DefaultContainerConfiguration implements ContainerConfiguration { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private String configurationPath; private URL configurationUrl; private ClassWorld classWorld; private ClassRealm classRealm; private Map contextData; private String componentVisibility = PlexusConstants.REALM_VISIBILITY; private String classPathScanning = PlexusConstants.SCANNING_OFF; private boolean autoWiring; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public ContainerConfiguration setName( final String name ) { return this; } public ContainerConfiguration setContainerConfiguration( final String configurationPath ) { this.configurationPath = configurationPath; return this; } public String getContainerConfiguration() { return configurationPath; } public ContainerConfiguration setContainerConfigurationURL( final URL configurationUrl ) { this.configurationUrl = configurationUrl; return this; } public URL getContainerConfigurationURL() { return configurationUrl; } public ContainerConfiguration setClassWorld( final ClassWorld classWorld ) { this.classWorld = classWorld; return this; } public ClassWorld getClassWorld() { return classWorld; } public ContainerConfiguration setRealm( final ClassRealm classRealm ) { this.classRealm = classRealm; return this; } public ClassRealm getRealm() { return classRealm; } public ContainerConfiguration setContext( final Map contextData ) { this.contextData = contextData; return this; } public Map getContext() { return contextData; } public ContainerConfiguration setComponentVisibility( final String componentVisibility ) { this.componentVisibility = componentVisibility; return this; } public String getComponentVisibility() { return componentVisibility; } public ContainerConfiguration setClassPathScanning( final String classPathScanning ) { this.classPathScanning = classPathScanning; if ( !PlexusConstants.SCANNING_OFF.equalsIgnoreCase( classPathScanning ) ) { autoWiring = true; } return this; } public String getClassPathScanning() { return classPathScanning; } public ContainerConfiguration setAutoWiring( final boolean autoWiring ) { this.autoWiring = autoWiring; return this; } public boolean getAutoWiring() { return autoWiring; } } DefaultPlexusContainer.java000066400000000000000000000730471167051330000414140ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import javax.inject.Provider; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.classworlds.realm.DuplicateRealmException; import org.codehaus.plexus.classworlds.realm.NoSuchRealmException; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextMapAdapter; import org.codehaus.plexus.context.DefaultContext; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.LoggerManager; import org.codehaus.plexus.logging.console.ConsoleLoggerManager; import org.sonatype.guice.bean.binders.MergedModule; import org.sonatype.guice.bean.binders.ParameterKeys; import org.sonatype.guice.bean.binders.WireModule; import org.sonatype.guice.bean.locators.DefaultBeanLocator; import org.sonatype.guice.bean.locators.DefaultRankingFunction; import org.sonatype.guice.bean.locators.EntryListAdapter; import org.sonatype.guice.bean.locators.EntryMapAdapter; import org.sonatype.guice.bean.locators.MutableBeanLocator; import org.sonatype.guice.bean.locators.RankingFunction; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.bean.reflect.DeferredClass; import org.sonatype.guice.bean.reflect.DeferredProvider; import org.sonatype.guice.bean.reflect.LoadedClass; import org.sonatype.guice.bean.reflect.URLClassSpace; import org.sonatype.guice.plexus.binders.PlexusAnnotatedBeanModule; import org.sonatype.guice.plexus.binders.PlexusBeanManager; import org.sonatype.guice.plexus.binders.PlexusBindingModule; import org.sonatype.guice.plexus.binders.PlexusXmlBeanModule; import org.sonatype.guice.plexus.config.Hints; import org.sonatype.guice.plexus.config.PlexusBean; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import org.sonatype.guice.plexus.config.PlexusBeanLocator; import org.sonatype.guice.plexus.config.PlexusBeanModule; import org.sonatype.guice.plexus.converters.PlexusDateTypeConverter; import org.sonatype.guice.plexus.converters.PlexusXmlBeanConverter; import org.sonatype.guice.plexus.lifecycles.PlexusLifecycleManager; import org.sonatype.guice.plexus.locators.ClassRealmUtils; import org.sonatype.guice.plexus.locators.DefaultPlexusBeanLocator; import org.sonatype.inject.BeanScanning; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; import com.google.inject.util.Providers; /** * {@link PlexusContainer} shim that delegates to a Plexus-aware Guice {@link Injector}. */ @SuppressWarnings( { "unchecked", "rawtypes" } ) public final class DefaultPlexusContainer implements MutablePlexusContainer { // ---------------------------------------------------------------------- // Static initialization // ---------------------------------------------------------------------- static { System.setProperty( "guice.disable.misplaced.annotation.check", "true" ); } // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String DEFAULT_REALM_NAME = "plexus.core"; private static final Module[] NO_CUSTOM_MODULES = {}; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- final Set realmIds = new HashSet(); final AtomicInteger plexusRank = new AtomicInteger(); final Map>> descriptorMap = new IdentityHashMap>>(); final ThreadLocal lookupRealm = new ThreadLocal(); final LoggerManagerProvider loggerManagerProvider = new LoggerManagerProvider(); final MutableBeanLocator qualifiedBeanLocator = new DefaultBeanLocator(); final Context context; final Map variables; final ClassRealm containerRealm; final PlexusBeanLocator plexusBeanLocator; final PlexusBeanManager plexusBeanManager; private final String componentVisibility; private final boolean isAutoWiringEnabled; private final BeanScanning scanning; private final Module containerModule = new ContainerModule(); private final Module defaultsModule = new DefaultsModule(); private LoggerManager loggerManager = new ConsoleLoggerManager(); private Logger logger; private boolean disposing; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public DefaultPlexusContainer() throws PlexusContainerException { this( new DefaultContainerConfiguration() ); } public DefaultPlexusContainer( final ContainerConfiguration configuration ) throws PlexusContainerException { this( configuration, NO_CUSTOM_MODULES ); } @SuppressWarnings( "finally" ) public DefaultPlexusContainer( final ContainerConfiguration configuration, final Module... customModules ) throws PlexusContainerException { final URL plexusXml = lookupPlexusXml( configuration ); context = new DefaultContext( configuration.getContext() ); context.put( PlexusConstants.PLEXUS_KEY, this ); variables = new ContextMapAdapter( context ); containerRealm = lookupContainerRealm( configuration ); componentVisibility = configuration.getComponentVisibility(); isAutoWiringEnabled = configuration.getAutoWiring(); scanning = parseScanningOption( configuration.getClassPathScanning() ); plexusBeanLocator = new DefaultPlexusBeanLocator( qualifiedBeanLocator, componentVisibility ); plexusBeanManager = new PlexusLifecycleManager( Providers.of( context ), loggerManagerProvider, // new SLF4JLoggerFactoryProvider() ); // SLF4J (optional) realmIds.add( containerRealm.getId() ); setLookupRealm( containerRealm ); final List beanModules = new ArrayList(); final ClassSpace space = new URLClassSpace( containerRealm ); beanModules.add( new PlexusXmlBeanModule( space, variables, plexusXml ) ); final BeanScanning global = BeanScanning.INDEX == scanning ? BeanScanning.GLOBAL_INDEX : scanning; beanModules.add( new PlexusAnnotatedBeanModule( space, variables, global ) ); try { addPlexusInjector( beanModules, new BootModule( customModules ) ); } catch ( final RuntimeException e ) { try { dispose(); // cleanup as much as possible } finally { throw e; // always report original failure } } } // ---------------------------------------------------------------------- // Context methods // ---------------------------------------------------------------------- public Context getContext() { return context; } // ---------------------------------------------------------------------- // Lookup methods // ---------------------------------------------------------------------- public Object lookup( final String role ) throws ComponentLookupException { return lookup( role, "" ); } public Object lookup( final String role, final String hint ) throws ComponentLookupException { return lookup( null, role, hint ); } public T lookup( final Class role ) throws ComponentLookupException { return lookup( role, "" ); } public T lookup( final Class role, final String hint ) throws ComponentLookupException { return lookup( role, null, hint ); } public T lookup( final Class type, final String role, final String hint ) throws ComponentLookupException { try { return locate( role, type, hint ).iterator().next().getValue(); } catch ( final RuntimeException e ) { throw new ComponentLookupException( e, null != type ? type.getName() : role, hint ); } } public List lookupList( final String role ) throws ComponentLookupException { return new EntryListAdapter( locate( role, null ) ); } public List lookupList( final Class role ) throws ComponentLookupException { return new EntryListAdapter( locate( null, role ) ); } public Map lookupMap( final String role ) throws ComponentLookupException { return new EntryMapAdapter( locate( role, null ) ); } public Map lookupMap( final Class role ) throws ComponentLookupException { return new EntryMapAdapter( locate( null, role ) ); } // ---------------------------------------------------------------------- // Query methods // ---------------------------------------------------------------------- public boolean hasComponent( final String role ) { return hasComponent( role, "" ); } public boolean hasComponent( final String role, final String hint ) { return hasComponent( null, role, hint ); } public boolean hasComponent( final Class role ) { return hasComponent( role, "" ); } public boolean hasComponent( final Class role, final String hint ) { return hasComponent( role, null, hint ); } public boolean hasComponent( final Class type, final String role, final String hint ) { return hasPlexusBeans( locate( role, type, hint ) ); } // ---------------------------------------------------------------------- // Component descriptor methods // ---------------------------------------------------------------------- public void addComponent( final Object component, final String role ) { try { addComponent( component, component.getClass().getClassLoader().loadClass( role ), Hints.DEFAULT_HINT ); } catch ( final ClassNotFoundException e ) { throw new TypeNotPresentException( role, e ); } } @SuppressWarnings( "deprecation" ) public void addComponent( final T component, final Class role, final String hint ) { // this is only used in Maven3 tests, so keep it simple... qualifiedBeanLocator.add( Guice.createInjector( new Module() { public void configure( final Binder binder ) { if ( Hints.isDefaultHint( hint ) ) { binder.bind( (Class) role ).toInstance( component ); } else { binder.bind( (Class) role ).annotatedWith( Names.named( hint ) ).toInstance( component ); } } } ), plexusRank.incrementAndGet() ); } public void addComponentDescriptor( final ComponentDescriptor descriptor ) { ClassRealm realm = descriptor.getRealm(); if ( null == realm ) { realm = containerRealm; descriptor.setRealm( realm ); } synchronized ( descriptorMap ) { List> descriptors = descriptorMap.get( realm ); if ( null == descriptors ) { descriptors = new ArrayList>(); descriptorMap.put( realm, descriptors ); } descriptors.add( descriptor ); } if ( containerRealm == realm ) { discoverComponents( containerRealm ); // for Maven3 testing } } public ComponentDescriptor getComponentDescriptor( final String role, final String hint ) { return getComponentDescriptor( null, role, hint ); } public ComponentDescriptor getComponentDescriptor( final Class type, final String role, final String hint ) { final Iterator> i = locate( role, type, hint ).iterator(); if ( i.hasNext() ) { final PlexusBean bean = i.next(); if ( bean.getImplementationClass() != null ) { return newComponentDescriptor( role, bean ); } } return null; } public List getComponentDescriptorList( final String role ) { return getComponentDescriptorList( null, role ); } public List> getComponentDescriptorList( final Class type, final String role ) { final List> tempList = new ArrayList>(); for ( final PlexusBean bean : locate( role, type ) ) { tempList.add( newComponentDescriptor( role, bean ) ); } return tempList; } public Map getComponentDescriptorMap( final String role ) { return getComponentDescriptorMap( null, role ); } public Map> getComponentDescriptorMap( final Class type, final String role ) { final Map> tempMap = new LinkedHashMap>(); for ( final PlexusBean bean : locate( role, type ) ) { tempMap.put( bean.getKey(), newComponentDescriptor( role, bean ) ); } return tempMap; } public List> discoverComponents( final ClassRealm realm ) { return discoverComponents( realm, NO_CUSTOM_MODULES ); } public List> discoverComponents( final ClassRealm realm, final Module... customModules ) { try { final List beanModules = new ArrayList(); synchronized ( descriptorMap ) { final ClassSpace space = new URLClassSpace( realm ); final List> descriptors = descriptorMap.remove( realm ); if ( null != descriptors ) { beanModules.add( new ComponentDescriptorBeanModule( space, descriptors ) ); } if ( realmIds.add( realm.getId() ) ) { beanModules.add( new PlexusXmlBeanModule( space, variables ) ); final BeanScanning local = BeanScanning.GLOBAL_INDEX == scanning ? BeanScanning.INDEX : scanning; beanModules.add( new PlexusAnnotatedBeanModule( space, variables, local ) ); } } if ( !beanModules.isEmpty() ) { addPlexusInjector( beanModules, customModules ); } } catch ( final RuntimeException e ) { getLogger().warn( realm.toString(), e ); } return null; // no-one actually seems to use or check the returned component list! } public void addPlexusInjector( final List beanModules, final Module... customModules ) { final List modules = new ArrayList(); modules.add( containerModule ); Collections.addAll( modules, customModules ); modules.add( new PlexusBindingModule( plexusBeanManager, beanModules ) ); modules.add( defaultsModule ); Guice.createInjector( isAutoWiringEnabled ? new WireModule( modules ) : new MergedModule( modules ) ); } // ---------------------------------------------------------------------- // Class realm methods // ---------------------------------------------------------------------- public ClassWorld getClassWorld() { return containerRealm.getWorld(); } public ClassRealm getContainerRealm() { return containerRealm; } public ClassRealm setLookupRealm( final ClassRealm realm ) { final ClassRealm oldRealm = lookupRealm.get(); lookupRealm.set( realm ); return oldRealm; } public ClassRealm getLookupRealm() { return lookupRealm.get(); } public ClassRealm createChildRealm( final String id ) { try { return containerRealm.createChildRealm( id ); } catch ( final DuplicateRealmException e1 ) { try { return getClassWorld().getRealm( id ); } catch ( final NoSuchRealmException e2 ) { return null; // should never happen! } } } // ---------------------------------------------------------------------- // Logger methods // ---------------------------------------------------------------------- public synchronized LoggerManager getLoggerManager() { return loggerManager; } @Inject( optional = true ) public synchronized void setLoggerManager( final LoggerManager loggerManager ) { if ( null != loggerManager ) { this.loggerManager = loggerManager; } else { this.loggerManager = new ConsoleLoggerManager(); } logger = null; // refresh our local logger } public synchronized Logger getLogger() { if ( null == logger ) { logger = loggerManager.getLoggerForComponent( PlexusContainer.class.getName(), null ); } return logger; } // ---------------------------------------------------------------------- // Shutdown methods // ---------------------------------------------------------------------- public void release( final Object component ) { plexusBeanManager.unmanage( component ); } public void releaseAll( final Map components ) { for ( final Object o : components.values() ) { release( o ); } } public void releaseAll( final List components ) { for ( final Object o : components ) { release( o ); } } public void dispose() { disposing = true; plexusBeanManager.unmanage(); containerRealm.setParentRealm( null ); qualifiedBeanLocator.clear(); lookupRealm.remove(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static BeanScanning parseScanningOption( final String scanning ) { for ( final BeanScanning option : BeanScanning.values() ) { if ( option.name().equalsIgnoreCase( scanning ) ) { return option; } } return BeanScanning.OFF; } /** * Finds container {@link ClassRealm}, taking existing {@link ClassWorld}s or {@link ClassLoader}s into account. * * @param configuration The container configuration * @return Container class realm */ private static ClassRealm lookupContainerRealm( final ContainerConfiguration configuration ) throws PlexusContainerException { ClassRealm realm = configuration.getRealm(); if ( null == realm ) { ClassWorld world = configuration.getClassWorld(); if ( null == world ) { world = new ClassWorld( DEFAULT_REALM_NAME, Thread.currentThread().getContextClassLoader() ); } try { realm = world.getRealm( DEFAULT_REALM_NAME ); } catch ( final NoSuchRealmException e ) { final Iterator realmIterator = world.getRealms().iterator(); if ( realmIterator.hasNext() ) { realm = (ClassRealm) realmIterator.next(); } } } if ( null == realm ) { throw new PlexusContainerException( "Missing container class realm: " + DEFAULT_REALM_NAME ); } return realm; } /** * Finds container configuration URL, may search the container {@link ClassRealm} and local file-system. * * @param configuration The container configuration * @return Local or remote URL */ private URL lookupPlexusXml( final ContainerConfiguration configuration ) { URL url = configuration.getContainerConfigurationURL(); if ( null == url ) { final String configurationPath = configuration.getContainerConfiguration(); if ( null != configurationPath ) { int index = 0; while ( index < configurationPath.length() && configurationPath.charAt( index ) == '/' ) { index++; } url = getClass().getClassLoader().getResource( configurationPath.substring( index ) ); if ( null == url ) { final File file = new File( configurationPath ); if ( file.isFile() ) { try { url = file.toURI().toURL(); } catch ( final MalformedURLException e ) // NOPMD { // drop through and recover } } } if ( null == url ) { getLogger().debug( "Missing container configuration: " + configurationPath ); } } } return url; } private Iterable> locate( final String role, final Class type, final String... hints ) { if ( disposing ) { return Collections.EMPTY_SET; } final String[] canonicalHints = Hints.canonicalHints( hints ); if ( null == role || null != type && type.getName().equals( role ) ) { return plexusBeanLocator.locate( TypeLiteral.get( type ), canonicalHints ); } final Set candidates = new HashSet(); for ( final ClassRealm realm : getVisibleRealms() ) { try { final Class clazz = realm.loadClass( role ); if ( candidates.add( clazz ) ) { final Iterable beans = plexusBeanLocator.locate( TypeLiteral.get( clazz ), canonicalHints ); if ( hasPlexusBeans( beans ) ) { return beans; } } } catch ( final Exception e ) { // drop through... } catch ( final LinkageError e ) { // drop through... } } return Collections.EMPTY_SET; } private Collection getVisibleRealms() { final Object[] realms = getClassWorld().getRealms().toArray(); final Set visibleRealms = new LinkedHashSet( realms.length ); final ClassRealm currentLookupRealm = getLookupRealm(); if ( null != currentLookupRealm ) { visibleRealms.add( currentLookupRealm ); } final ClassRealm threadContextRealm = ClassRealmUtils.contextRealm(); if ( null != threadContextRealm ) { visibleRealms.add( threadContextRealm ); } if ( PlexusConstants.REALM_VISIBILITY.equalsIgnoreCase( componentVisibility ) ) { final Collection realmNames = ClassRealmUtils.visibleRealmNames( threadContextRealm ); if ( null != realmNames && realmNames.size() > 0 ) { for ( int i = realms.length - 1; i >= 0; i-- ) { final ClassRealm r = (ClassRealm) realms[i]; if ( realmNames.contains( r.toString() ) ) { visibleRealms.add( r ); } } return visibleRealms; } } for ( int i = realms.length - 1; i >= 0; i-- ) { visibleRealms.add( (ClassRealm) realms[i] ); } return visibleRealms; } private static boolean hasPlexusBeans( final Iterable> beans ) { final Iterator> i = beans.iterator(); return i.hasNext() && i.next().getImplementationClass() != null; } private static ComponentDescriptor newComponentDescriptor( final String role, final PlexusBean bean ) { final ComponentDescriptor cd = new ComponentDescriptor(); cd.setRole( role ); cd.setRoleHint( bean.getKey() ); cd.setImplementationClass( bean.getImplementationClass() ); cd.setDescription( bean.getDescription() ); return cd; } final class BootModule implements Module { private final Module[] customBootModules; BootModule( final Module[] customBootModules ) { this.customBootModules = customBootModules; } public void configure( final Binder binder ) { binder.requestInjection( DefaultPlexusContainer.this ); for ( final Module m : customBootModules ) { binder.install( m ); } } } final class ContainerModule implements Module { public void configure( final Binder binder ) { binder.bind( Context.class ).toInstance( context ); binder.bind( ParameterKeys.PROPERTIES ).toInstance( variables ); binder.bind( MutableBeanLocator.class ).toInstance( qualifiedBeanLocator ); binder.bind( PlexusBeanLocator.class ).toInstance( plexusBeanLocator ); binder.bind( PlexusBeanManager.class ).toInstance( plexusBeanManager ); binder.bind( PlexusContainer.class ).to( MutablePlexusContainer.class ); binder.bind( MutablePlexusContainer.class ).to( DefaultPlexusContainer.class ); // use provider wrapper to avoid repeated injections later on when configuring plugin injectors binder.bind( DefaultPlexusContainer.class ).toProvider( Providers.of( DefaultPlexusContainer.this ) ); } } final class DefaultsModule implements Module { private final LoggerProvider loggerProvider = new LoggerProvider(); private final PlexusDateTypeConverter dateConverter = new PlexusDateTypeConverter(); private final PlexusXmlBeanConverter beanConverter = new PlexusXmlBeanConverter(); public void configure( final Binder binder ) { binder.bind( LoggerManager.class ).toProvider( loggerManagerProvider ); binder.bind( Logger.class ).toProvider( loggerProvider ); // allow plugins to override the default ranking function so we can support component profiles final Key plexusRankingKey = Key.get( RankingFunction.class, Names.named( "plexus" ) ); binder.bind( plexusRankingKey ).toInstance( new DefaultRankingFunction( plexusRank.incrementAndGet() ) ); binder.bind( RankingFunction.class ).to( plexusRankingKey ); binder.install( dateConverter ); binder.bind( PlexusBeanConverter.class ).toInstance( beanConverter ); } } final class LoggerManagerProvider implements DeferredProvider { public LoggerManager get() { return getLoggerManager(); } public DeferredClass getImplementationClass() { return new LoadedClass( get().getClass() ); } } final class LoggerProvider implements DeferredProvider { public Logger get() { return getLogger(); } public DeferredClass getImplementationClass() { return new LoadedClass( get().getClass() ); } } final class SLF4JLoggerFactoryProvider implements Provider { public Object get() { return plexusBeanLocator.locate( TypeLiteral.get( org.slf4j.ILoggerFactory.class ) ).iterator().next().getValue(); } } } MutablePlexusContainer.java000066400000000000000000000015271167051330000414130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.LoggerManager; public interface MutablePlexusContainer extends PlexusContainer { LoggerManager getLoggerManager(); void setLoggerManager( LoggerManager loggerManager ); Logger getLogger(); ClassWorld getClassWorld(); } PlexusConstants.java000066400000000000000000000015601167051330000401300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus; import org.sonatype.guice.plexus.config.Hints; public interface PlexusConstants { String PLEXUS_DEFAULT_HINT = Hints.DEFAULT_HINT; String PLEXUS_KEY = "plexus"; String GLOBAL_VISIBILITY = "global"; String REALM_VISIBILITY = "realm"; String SCANNING_ON = "on"; String SCANNING_OFF = "off"; String SCANNING_INDEX = "index"; String SCANNING_CACHE = "cache"; } PlexusContainer.java000066400000000000000000000066751167051330000401120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus; import java.util.List; import java.util.Map; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.composition.CycleDetectedInComponentGraphException; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.context.Context; public interface PlexusContainer { Context getContext(); Object lookup( String role ) throws ComponentLookupException; Object lookup( String role, String hint ) throws ComponentLookupException; T lookup( Class role ) throws ComponentLookupException; T lookup( Class role, String hint ) throws ComponentLookupException; T lookup( Class type, String role, String hint ) throws ComponentLookupException; List lookupList( String role ) throws ComponentLookupException; List lookupList( Class role ) throws ComponentLookupException; Map lookupMap( String role ) throws ComponentLookupException; Map lookupMap( Class role ) throws ComponentLookupException; boolean hasComponent( String role ); boolean hasComponent( String role, String hint ); boolean hasComponent( Class role ); boolean hasComponent( Class role, String hint ); boolean hasComponent( Class type, String role, String hint ); void addComponent( Object component, String role ); void addComponent( T component, Class role, String hint ); void addComponentDescriptor( ComponentDescriptor descriptor ) throws CycleDetectedInComponentGraphException; ComponentDescriptor getComponentDescriptor( String role, String hint ); ComponentDescriptor getComponentDescriptor( Class type, String role, String hint ); List> getComponentDescriptorList( String role ); List> getComponentDescriptorList( Class type, String role ); Map> getComponentDescriptorMap( String role ); Map> getComponentDescriptorMap( Class type, String role ); List> discoverComponents( ClassRealm classRealm ) throws PlexusConfigurationException; ClassRealm getContainerRealm(); ClassRealm setLookupRealm( ClassRealm realm ); ClassRealm getLookupRealm(); ClassRealm createChildRealm( String id ); void release( Object component ) throws ComponentLifecycleException; void releaseAll( Map components ) throws ComponentLifecycleException; void releaseAll( List components ) throws ComponentLifecycleException; void dispose(); } PlexusContainerException.java000066400000000000000000000015041167051330000417530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus; public final class PlexusContainerException extends Exception { private static final long serialVersionUID = 1L; public PlexusContainerException( final String message ) { super( message ); } public PlexusContainerException( final String message, final Throwable detail ) { super( message, detail ); } } PlexusTestCase.java000066400000000000000000000167671167051330000377060ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/* * Copyright 2001-2006 Codehaus Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.plexus; import java.io.File; import java.io.InputStream; import junit.framework.TestCase; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.DefaultContext; /** * @author Jason van Zyl * @author Trygve Laugstøl * @author Michal Maczka * @version $Id: PlexusTestCase.java 8420 2009-09-18 22:56:56Z hboutemy $ */ public abstract class PlexusTestCase extends TestCase { private PlexusContainer container; private static String basedir; @Override protected void setUp() throws Exception { basedir = getBasedir(); } protected void setupContainer() { // ---------------------------------------------------------------------------- // Context Setup // ---------------------------------------------------------------------------- final DefaultContext context = new DefaultContext(); context.put( "basedir", getBasedir() ); customizeContext( context ); final boolean hasPlexusHome = context.contains( "plexus.home" ); if ( !hasPlexusHome ) { final File f = getTestFile( "target/plexus-home" ); if ( !f.isDirectory() ) { f.mkdir(); } context.put( "plexus.home", f.getAbsolutePath() ); } // ---------------------------------------------------------------------------- // Configuration // ---------------------------------------------------------------------------- final String config = getCustomConfigurationName(); final ContainerConfiguration containerConfiguration = new DefaultContainerConfiguration().setName( "test" ).setContext( context.getContextData() ); if ( config != null ) { containerConfiguration.setContainerConfiguration( config ); } else { final String resource = getConfigurationName( null ); containerConfiguration.setContainerConfiguration( resource ); } customizeContainerConfiguration( containerConfiguration ); try { container = new DefaultPlexusContainer( containerConfiguration ); } catch ( final PlexusContainerException e ) { e.printStackTrace(); fail( "Failed to create plexus container." ); } } /** * Allow custom test case implementations do augment the default container configuration before executing tests. * * @param containerConfiguration */ protected void customizeContainerConfiguration( final ContainerConfiguration containerConfiguration ) { } protected void customizeContext( final Context context ) { } protected PlexusConfiguration customizeComponentConfiguration() { return null; } @Override protected void tearDown() throws Exception { if ( container != null ) { container.dispose(); container = null; } } protected PlexusContainer getContainer() { if ( container == null ) { setupContainer(); } return container; } protected InputStream getConfiguration() throws Exception { return getConfiguration( null ); } protected InputStream getConfiguration( final String subname ) throws Exception { return getResourceAsStream( getConfigurationName( subname ) ); } protected String getCustomConfigurationName() { return null; } /** * Allow the retrieval of a container configuration that is based on the name of the test class being run. So if you * have a test class called org.foo.FunTest, then this will produce a resource name of org/foo/FunTest.xml which * would be used to configure the Plexus container before running your test. * * @param subname * @return */ protected String getConfigurationName( final String subname ) { return getClass().getName().replace( '.', '/' ) + ".xml"; } protected InputStream getResourceAsStream( final String resource ) { return getClass().getResourceAsStream( resource ); } protected ClassLoader getClassLoader() { return getClass().getClassLoader(); } // ---------------------------------------------------------------------- // Container access // ---------------------------------------------------------------------- protected Object lookup( final String componentKey ) throws Exception { return getContainer().lookup( componentKey ); } protected Object lookup( final String role, final String roleHint ) throws Exception { return getContainer().lookup( role, roleHint ); } protected T lookup( final Class componentClass ) throws Exception { return getContainer().lookup( componentClass ); } protected T lookup( final Class componentClass, final String roleHint ) throws Exception { return getContainer().lookup( componentClass, roleHint ); } protected void release( final Object component ) throws Exception { getContainer().release( component ); } // ---------------------------------------------------------------------- // Helper methods for sub classes // ---------------------------------------------------------------------- public static File getTestFile( final String path ) { return new File( getBasedir(), path ); } public static File getTestFile( final String basedir, final String path ) { File basedirFile = new File( basedir ); if ( !basedirFile.isAbsolute() ) { basedirFile = getTestFile( basedir ); } return new File( basedirFile, path ); } public static String getTestPath( final String path ) { return getTestFile( path ).getAbsolutePath(); } public static String getTestPath( final String basedir, final String path ) { return getTestFile( basedir, path ).getAbsolutePath(); } public static String getBasedir() { if ( basedir != null ) { return basedir; } basedir = System.getProperty( "basedir" ); if ( basedir == null ) { basedir = new File( "" ).getAbsolutePath(); } return basedir; } public String getTestConfiguration() { return getTestConfiguration( getClass() ); } public static String getTestConfiguration( final Class clazz ) { final String s = clazz.getName().replace( '.', '/' ); return s.substring( 0, s.indexOf( "$" ) ) + ".xml"; } } 000077500000000000000000000000001167051330000361105ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/componentMapOrientedComponent.java000066400000000000000000000022261167051330000430470ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/* * Copyright 2001-2006 Codehaus Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.plexus.component; import java.util.Map; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.repository.ComponentRequirement; public interface MapOrientedComponent { void addComponentRequirement( ComponentRequirement requirementDescriptor, Object requirementValue ) throws ComponentConfigurationException; @SuppressWarnings( "rawtypes" ) void setComponentConfiguration( Map componentConfiguration ) throws ComponentConfigurationException; } 000077500000000000000000000000001167051330000404535ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/compositionCycleDetectedInComponentGraphException.java000066400000000000000000000016041167051330000510330ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/composition/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.composition; public final class CycleDetectedInComponentGraphException extends Exception { private static final long serialVersionUID = 1L; public CycleDetectedInComponentGraphException( final String message ) { super( message ); } public CycleDetectedInComponentGraphException( final String message, final Throwable detail ) { super( message, detail ); } } 000077500000000000000000000000001167051330000406125ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configuratorAbstractComponentConfigurator.java000066400000000000000000000131471167051330000474740ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.codehaus.classworlds.ClassRealmAdapter; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.converters.lookup.DefaultConverterLookup; import org.codehaus.plexus.component.configurator.expression.DefaultExpressionEvaluator; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Brett Porter * @version $Id: AbstractComponentConfigurator.java 8325 2009-08-07 14:10:05Z bentmann $ */ public abstract class AbstractComponentConfigurator implements ComponentConfigurator { /** * This is being instantiated here because there are old component factories (beanshell) that directly access the * converterLookup but do not yet state the ConverterLookup as a requirement in the component metadata. Once these * are wired up as standard components properly then we won't have to instantiate the converter lookup here and we * can let the container do it. * * @plexus.requirement */ protected ConverterLookup converterLookup = new DefaultConverterLookup(); public void configureComponent( final Object component, final PlexusConfiguration configuration, final ClassRealm containerRealm ) throws ComponentConfigurationException { configureComponent( component, configuration, new DefaultExpressionEvaluator(), containerRealm ); } public void configureComponent( final Object component, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm ) throws ComponentConfigurationException { configureComponent( component, configuration, expressionEvaluator, containerRealm, null ); } public void configureComponent( final Object component, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm, final ConfigurationListener listener ) throws ComponentConfigurationException { // ---------------------------------------------------------------------------- // For compatibility with old ComponentFactories that use old ClassWorlds // ---------------------------------------------------------------------------- final org.codehaus.classworlds.ClassRealm cr = ClassRealmAdapter.getInstance( containerRealm ); Method method; try { try { method = getClass().getMethod( "configureComponent", Object.class, PlexusConfiguration.class, ExpressionEvaluator.class, org.codehaus.classworlds.ClassRealm.class, ConfigurationListener.class ); method.invoke( this, component, configuration, expressionEvaluator, cr, listener ); } catch ( final NoSuchMethodException e ) { method = getClass().getMethod( "configureComponent", Object.class, PlexusConfiguration.class, ExpressionEvaluator.class, org.codehaus.classworlds.ClassRealm.class ); method.invoke( this, component, configuration, expressionEvaluator, cr ); } } catch ( final InvocationTargetException e ) { if ( e.getCause() instanceof ComponentConfigurationException ) { throw (ComponentConfigurationException) e.getCause(); } else if ( e.getCause() instanceof RuntimeException ) { throw (RuntimeException) e.getCause(); } else if ( e.getCause() instanceof Error ) { throw (Error) e.getCause(); } throw new ComponentConfigurationException( "Incompatible configurator " + getClass().getName(), e ); } catch ( final Exception e ) { throw new ComponentConfigurationException( "Incompatible configurator " + getClass().getName(), e ); } } } BasicComponentConfigurator.java000066400000000000000000000054711167051330000467530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.configurator.converters.composite.ObjectWithFieldsConverter; import org.codehaus.plexus.component.configurator.converters.special.ClassRealmConverter; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Jason van Zyl * @author Michal Maczka * @version $Id: BasicComponentConfigurator.java 6992 2007-10-23 05:31:36Z jvanzyl $ */ public class BasicComponentConfigurator extends AbstractComponentConfigurator { @Override public void configureComponent( final Object component, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm, final ConfigurationListener listener ) throws ComponentConfigurationException { // ---------------------------------------------------------------------- // We should probably take into consideration the realm that the component // came from in order to load the correct classes. // ---------------------------------------------------------------------- converterLookup.registerConverter( new ClassRealmConverter( containerRealm ) ); final ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter(); converter.processConfiguration( converterLookup, component, containerRealm, configuration, expressionEvaluator, listener ); } } ComponentConfigurationException.java000066400000000000000000000032761167051330000500360ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Jason van Zyl * @version $Id: ComponentConfigurationException.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ComponentConfigurationException extends Exception { private static final long serialVersionUID = 1L; private PlexusConfiguration failedConfiguration; public ComponentConfigurationException( final String message ) { super( message ); } public ComponentConfigurationException( final String message, final Throwable cause ) { super( message, cause ); } public ComponentConfigurationException( final Throwable cause ) { super( cause ); } public ComponentConfigurationException( final PlexusConfiguration failedConfiguration, final String message ) { super( message ); this.failedConfiguration = failedConfiguration; } public ComponentConfigurationException( final PlexusConfiguration failedConfiguration, final String message, final Throwable cause ) { super( message, cause ); this.failedConfiguration = failedConfiguration; } public ComponentConfigurationException( final PlexusConfiguration failedConfiguration, final Throwable cause ) { super( cause ); this.failedConfiguration = failedConfiguration; } public void setFailedConfiguration( final PlexusConfiguration failedConfiguration ) { this.failedConfiguration = failedConfiguration; } public PlexusConfiguration getFailedConfiguration() { return failedConfiguration; } } ComponentConfigurator.java000066400000000000000000000043571167051330000460130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Jason van Zyl * @version $Id: ComponentConfigurator.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface ComponentConfigurator { String ROLE = ComponentConfigurator.class.getName(); void configureComponent( Object component, PlexusConfiguration configuration, ClassRealm containerRealm ) throws ComponentConfigurationException; void configureComponent( Object component, PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm ) throws ComponentConfigurationException; void configureComponent( Object component, PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm, ConfigurationListener listener ) throws ComponentConfigurationException; } ConfigurationListener.java000066400000000000000000000037711167051330000460020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004-5, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Listen for configuration changes on an object. * * @author Brett Porter * @version $Id: ConfigurationListener.java 5127 2006-12-12 03:49:50Z jvanzyl $ */ public interface ConfigurationListener { /** * Notify the listener that a field has been set using its setter. * * @param fieldName the field * @param value the value set * @param target the target object */ void notifyFieldChangeUsingSetter( String fieldName, Object value, Object target ); /** * Notify the listener that a field has been set using private field injection. * * @param fieldName the field * @param value the value set * @param target the target object */ void notifyFieldChangeUsingReflection( String fieldName, Object value, Object target ); } MapOrientedComponentConfigurator.java000066400000000000000000000042001167051330000501260ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; import java.util.Map; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.MapOrientedComponent; import org.codehaus.plexus.component.configurator.converters.composite.MapConverter; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /* * Copyright 2001-2005 The Apache Software Foundation. * * 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. */ public class MapOrientedComponentConfigurator extends AbstractComponentConfigurator { @Override public void configureComponent( final Object component, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm, final ConfigurationListener listener ) throws ComponentConfigurationException { if ( !( component instanceof MapOrientedComponent ) ) { throw new ComponentConfigurationException( "This configurator can only process implementations of " + MapOrientedComponent.class.getName() ); } final MapConverter converter = new MapConverter(); @SuppressWarnings( "rawtypes" ) final Map context = (Map) converter.fromConfiguration( converterLookup, configuration, Map.class, component.getClass(), containerRealm, expressionEvaluator, listener ); ( (MapOrientedComponent) component ).setComponentConfiguration( context ); } } 000077500000000000000000000000001167051330000430045ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/convertersAbstractConfigurationConverter.java000066400000000000000000000227011167051330000520340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converterspackage org.codehaus.plexus.component.configurator.converters; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.lang.reflect.Array; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.util.StringUtils; /** * @author Michal Maczka * @version $Id: AbstractConfigurationConverter.java 7890 2008-11-29 17:14:01Z jvanzyl $ */ @SuppressWarnings( "rawtypes" ) public abstract class AbstractConfigurationConverter implements ConfigurationConverter { private static final String IMPLEMENTATION = "implementation"; /** * We will check if user has provided a hint which class should be used for given field. So we will check if * something like is present in configuraion. If 'implementation' hint was provided * we will try to load correspoding class If we are unable to do so error will be reported */ protected Class getClassForImplementationHint( final Class type, final PlexusConfiguration configuration, final ClassLoader classLoader ) throws ComponentConfigurationException { Class retValue = type; String implementation = configuration.getAttribute( IMPLEMENTATION, null ); if ( implementation != null ) { try { final boolean isArray = implementation.endsWith( "[]" ); if ( isArray ) { implementation = implementation.substring( 0, implementation.length() - 2 ); } retValue = classLoader.loadClass( implementation ); if ( isArray ) { retValue = Array.newInstance( retValue, 0 ).getClass(); } } catch ( final ClassNotFoundException e ) { final String msg = "ClassNotFoundException: Class name which was explicitly given in configuration using" + " 'implementation' attribute: '" + implementation + "' cannot be loaded"; throw new ComponentConfigurationException( msg, e ); } catch ( final UnsupportedClassVersionError e ) { final String msg = "UnsupportedClassVersionError: Class name which was explicitly given in configuration" + " using 'implementation' attribute: '" + implementation + "' cannot be loaded"; throw new ComponentConfigurationException( msg, e ); } catch ( final LinkageError e ) { final String msg = "LinkageError: Class name which was explicitly given in configuration using" + " 'implementation' attribute: '" + implementation + "' cannot be loaded"; throw new ComponentConfigurationException( msg, e ); } } return retValue; } protected Class loadClass( final String classname, final ClassLoader classLoader ) throws ComponentConfigurationException { Class retValue; try { retValue = classLoader.loadClass( classname ); } catch ( final ClassNotFoundException e ) { throw new ComponentConfigurationException( "Error loading class '" + classname + "'", e ); } return retValue; } protected Object instantiateObject( final String classname, final ClassLoader classLoader ) throws ComponentConfigurationException { final Class clazz = loadClass( classname, classLoader ); return instantiateObject( clazz ); } protected Object instantiateObject( final Class clazz ) throws ComponentConfigurationException { Object retValue; try { retValue = clazz.newInstance(); return retValue; } catch ( final IllegalAccessException e ) { throw new ComponentConfigurationException( "Class '" + clazz.getName() + "' cannot be instantiated", e ); } catch ( final InstantiationException e ) { throw new ComponentConfigurationException( "Abstract class or interface '" + clazz.getName() + "' cannot be instantiated", e ); } } // first-name --> firstName protected String fromXML( final String elementName ) { return StringUtils.lowercaseFirstLetter( StringUtils.removeAndHump( elementName, "-" ) ); } // firstName --> first-name protected String toXML( final String fieldName ) { return StringUtils.addAndDeHump( fieldName ); } protected void failIfNotTypeCompatible( final Object value, final Class type, final PlexusConfiguration configuration ) throws ComponentConfigurationException { if ( value != null && type != null && !type.isInstance( value ) ) { final String msg = "Cannot assign configuration entry '" + configuration.getName() + "' with value '" + configuration.getValue( null ) + "' of type " + value.getClass().getCanonicalName() + " to property of type " + type.getCanonicalName(); throw new ComponentConfigurationException( configuration, msg ); } } protected Object fromExpression( final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final Class type ) throws ComponentConfigurationException { final Object v = fromExpression( configuration, expressionEvaluator ); failIfNotTypeCompatible( v, type, configuration ); return v; } protected Object fromExpression( final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator ) throws ComponentConfigurationException { Object v = null; String value = configuration.getValue( null ); if ( value != null && value.length() > 0 ) { // Object is provided by an expression // This seems a bit ugly... canConvert really should return false in this instance, but it doesn't have the // configuration to know better try { v = expressionEvaluator.evaluate( value ); } catch ( final ExpressionEvaluationException e ) { final String msg = "Error evaluating the expression '" + value + "' for configuration value '" + configuration.getName() + "'"; throw new ComponentConfigurationException( configuration, msg, e ); } } if ( v == null ) { value = configuration.getAttribute( "default-value", null ); if ( value != null && value.length() > 0 ) { try { v = expressionEvaluator.evaluate( value ); } catch ( final ExpressionEvaluationException e ) { final String msg = "Error evaluating the expression '" + value + "' for configuration value '" + configuration.getName() + "'"; throw new ComponentConfigurationException( configuration, msg, e ); } } } return v; } public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator ) throws ComponentConfigurationException { return fromConfiguration( converterLookup, configuration, type, baseType, classLoader, expressionEvaluator, null ); } } ComponentValueSetter.java000066400000000000000000000273051167051330000500040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converterspackage org.codehaus.plexus.component.configurator.converters; /* * Copyright 2005-2007 Codehaus Foundation. * * 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. */ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.util.ReflectionUtils; import org.codehaus.plexus.util.StringUtils; /** @author Kenney Westerhof */ @SuppressWarnings( "rawtypes" ) public class ComponentValueSetter { private final Object object; private final String fieldName; private final ConverterLookup lookup; private Method setter; private Class setterParamType; private ConfigurationConverter setterTypeConverter; private Type[] setterTypeArguments; private Field field; private Class fieldType; private ConfigurationConverter fieldTypeConverter; private Type[] fieldTypeArguments; private final ConfigurationListener listener; public ComponentValueSetter( final String fieldName, final Object object, final ConverterLookup lookup ) throws ComponentConfigurationException { this( fieldName, object, lookup, null ); } public ComponentValueSetter( final String fieldName, final Object object, final ConverterLookup lookup, final ConfigurationListener listener ) throws ComponentConfigurationException { this( fieldName, null, object, lookup, listener ); } public ComponentValueSetter( final String fieldName, final Class implementation, final Object object, final ConverterLookup lookup, final ConfigurationListener listener ) throws ComponentConfigurationException { this.fieldName = fieldName; this.object = object; this.lookup = lookup; this.listener = listener; if ( object == null ) { throw new ComponentConfigurationException( "Component is null" ); } initSetter( implementation ); initField( implementation ); if ( setter == null && field == null ) { throw new ComponentConfigurationException( "Cannot find setter, adder nor field in " + object.getClass().getName() + " for '" + fieldName + "'" ); } if ( setterTypeConverter == null && fieldTypeConverter == null ) { throw new ComponentConfigurationException( "Cannot find converter for " + setterParamType.getName() + ( fieldType != null && !fieldType.equals( setterParamType ) ? " or " + fieldType.getName() : "" ) ); } } @SuppressWarnings( "unchecked" ) private void initSetter( final Class implementation ) { setter = ReflectionUtils.getSetter( fieldName, object.getClass() ); if ( setter == null ) { setter = getAdder( fieldName, object.getClass() ); if ( setter == null ) { return; } } setterParamType = setter.getParameterTypes()[0]; if ( implementation != null && setterParamType.isAssignableFrom( implementation ) ) { setterParamType = implementation; // more specific, compatible type } try { setterTypeConverter = lookup.lookupConverterForType( setterParamType ); if ( setterTypeConverter instanceof ParameterizedConfigurationConverter ) { setterTypeArguments = getTypeArguments( setter.getGenericParameterTypes()[0] ); } } catch ( final ComponentConfigurationException e ) { // ignore, handle later } } private static Method getAdder( final String fieldName, final Class clazz ) { final Method[] methods = clazz.getMethods(); final String adderName = "add" + StringUtils.capitalizeFirstLetter( fieldName ); for ( final Method method : methods ) { if ( adderName.equals( method.getName() ) && !Modifier.isStatic( method.getModifiers() ) && method.getParameterTypes().length == 1 ) { return method; } } return null; } @SuppressWarnings( "unchecked" ) private void initField( final Class implementation ) { field = ReflectionUtils.getFieldByNameIncludingSuperclasses( fieldName, object.getClass() ); if ( field == null ) { return; } fieldType = field.getType(); if ( implementation != null && fieldType.isAssignableFrom( implementation ) ) { fieldType = implementation; // more specific, compatible type } try { fieldTypeConverter = lookup.lookupConverterForType( fieldType ); if ( fieldTypeConverter instanceof ParameterizedConfigurationConverter ) { fieldTypeArguments = getTypeArguments( field.getGenericType() ); } } catch ( final ComponentConfigurationException e ) { // ignore, handle later } } private Type[] getTypeArguments( final Type type ) { if ( type instanceof ParameterizedType ) { return ( (ParameterizedType) type ).getActualTypeArguments(); } return null; } private void setValueUsingField( final Object value ) throws ComponentConfigurationException { try { final boolean wasAccessible = field.isAccessible(); if ( !wasAccessible ) { field.setAccessible( true ); } if ( listener != null ) { listener.notifyFieldChangeUsingReflection( fieldName, value, object ); } field.set( object, value ); if ( !wasAccessible ) { field.setAccessible( false ); } } catch ( final IllegalAccessException e ) { throw new ComponentConfigurationException( "Cannot access field: " + field, e ); } catch ( final IllegalArgumentException e ) { throw new ComponentConfigurationException( "Cannot assign value '" + value + "' (type: " + value.getClass() + ") to " + field, e ); } } private void setValueUsingSetter( final Object value ) throws ComponentConfigurationException { if ( setterParamType == null || setter == null ) { throw new ComponentConfigurationException( "No setter found" ); } final String exceptionInfo = object.getClass().getName() + "." + setter.getName() + "( " + setterParamType.getName() + " )"; if ( listener != null ) { listener.notifyFieldChangeUsingSetter( fieldName, value, object ); } try { setter.invoke( object, new Object[] { value } ); } catch ( final IllegalAccessException e ) { throw new ComponentConfigurationException( "Cannot access method: " + exceptionInfo, e ); } catch ( final IllegalArgumentException e ) { throw new ComponentConfigurationException( "Invalid parameter supplied while setting '" + value + "' to " + exceptionInfo, e ); } catch ( final InvocationTargetException e ) { throw new ComponentConfigurationException( "Setter " + exceptionInfo + " threw exception when called with parameter '" + value + "': " + e.getTargetException().getMessage(), e ); } } public void configure( final PlexusConfiguration config, final ClassLoader classLoader, final ExpressionEvaluator evaluator ) throws ComponentConfigurationException { Object value = null; // try setter converter + method first if ( setterTypeConverter != null ) { try { if ( setterTypeArguments != null ) { final ParameterizedConfigurationConverter converter = (ParameterizedConfigurationConverter) setterTypeConverter; value = converter.fromConfiguration( lookup, config, setterParamType, setterTypeArguments, object.getClass(), classLoader, evaluator, listener ); } else { value = setterTypeConverter.fromConfiguration( lookup, config, setterParamType, object.getClass(), classLoader, evaluator, listener ); } if ( value != null ) { setValueUsingSetter( value ); return; } } catch ( final ComponentConfigurationException e ) { if ( fieldTypeConverter == null || fieldTypeConverter.getClass().equals( setterTypeConverter.getClass() ) ) { throw e; } } } // try setting field using value found with method // converter, if present. ComponentConfigurationException savedEx = null; if ( value != null ) { try { setValueUsingField( value ); return; } catch ( final ComponentConfigurationException e ) { savedEx = e; } } // either no value or setting went wrong. Try // new converter. if ( fieldTypeArguments != null ) { final ParameterizedConfigurationConverter converter = (ParameterizedConfigurationConverter) fieldTypeConverter; value = converter.fromConfiguration( lookup, config, fieldType, fieldTypeArguments, object.getClass(), classLoader, evaluator, listener ); } else { value = fieldTypeConverter.fromConfiguration( lookup, config, fieldType, object.getClass(), classLoader, evaluator, listener ); } if ( value != null ) { setValueUsingField( value ); } // FIXME: need this? else if ( savedEx != null ) { throw savedEx; } } } ConfigurationConverter.java000066400000000000000000000066651167051330000503630ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converterspackage org.codehaus.plexus.component.configurator.converters; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; @SuppressWarnings( "rawtypes" ) public interface ConfigurationConverter { boolean canConvert( Class type ); /** * @param converterLookup Repository of available converters * @param configuration * @param type the type of object to read * @param baseType the type of object the the source is * @param classLoader ClassLoader which should be used for loading classes * @param expressionEvaluator the expression evaluator to use for expressions * @return the object * @throws ComponentConfigurationException * @todo a better way, instead of baseType, would be to pass in a factory for new classes that could be based from * the given package */ Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator ) throws ComponentConfigurationException; /** * @param converterLookup Repository of available converters * @param configuration * @param type the type of object to read * @param baseType the type of object the the source is * @param classLoader ClassLoader which should be used for loading classes * @param expressionEvaluator the expression evaluator to use for expressions * @return the object * @throws ComponentConfigurationException * @todo a better way, instead of baseType, would be to pass in a factory for new classes that could be based from * the given package */ Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, ConfigurationListener listener ) throws ComponentConfigurationException; } ParameterizedConfigurationConverter.java000066400000000000000000000051121167051330000530620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converterspackage org.codehaus.plexus.component.configurator.converters; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.lang.reflect.Type; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; public interface ParameterizedConfigurationConverter extends ConfigurationConverter { /** * @param converterLookup Repository of available converters * @param configuration * @param type the type of object to read * @param typeArguments The type arguments for the generic type being configured, may be {@code null}. * @param baseType the type of object the the source is * @param classLoader ClassLoader which should be used for loading classes * @param expressionEvaluator the expression evaluator to use for expressions * @return the object * @throws ComponentConfigurationException */ Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, Type[] typeArguments, Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, ConfigurationListener listener ) throws ComponentConfigurationException; } 000077500000000000000000000000001167051330000440655ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicAbstractBasicConverter.java000066400000000000000000000137171167051330000513360ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @version $Id: AbstractBasicConverter.java 8514 2009-10-22 10:25:03Z bentmann $ */ @SuppressWarnings( "rawtypes" ) public abstract class AbstractBasicConverter extends AbstractConfigurationConverter { protected abstract Object fromString( String str ) throws ComponentConfigurationException; @Override protected Object fromExpression( final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final Class type ) throws ComponentConfigurationException { Object v = null; String value = configuration.getValue( null ); if ( value != null && value.length() > 0 ) { // Object is provided by an expression // This seems a bit ugly... canConvert really should return false in this instance, but it doesn't have the // configuration to know better try { if ( expressionEvaluator instanceof TypeAwareExpressionEvaluator ) { v = ( (TypeAwareExpressionEvaluator) expressionEvaluator ).evaluate( value, type ); } else { v = expressionEvaluator.evaluate( value ); } } catch ( final ExpressionEvaluationException e ) { final String msg = "Error evaluating the expression '" + value + "' for configuration value '" + configuration.getName() + "'"; throw new ComponentConfigurationException( configuration, msg, e ); } } if ( v == null ) { value = configuration.getAttribute( "default-value", null ); if ( value != null && value.length() > 0 ) { try { if ( expressionEvaluator instanceof TypeAwareExpressionEvaluator ) { v = ( (TypeAwareExpressionEvaluator) expressionEvaluator ).evaluate( value, type ); } else { v = expressionEvaluator.evaluate( value ); } } catch ( final ExpressionEvaluationException e ) { final String msg = "Error evaluating the expression '" + value + "' for configuration value '" + configuration.getName() + "'"; throw new ComponentConfigurationException( configuration, msg, e ); } } } /* * NOTE: We don't check the type here which would be ugly to do correctly (e.g. value=Short -> type=int), the * reflective setter/field injection will fail by itself when the type didn't match. */ return v; } public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { if ( configuration.getChildCount() > 0 ) { throw new ComponentConfigurationException( "When configuring a basic element the configuration cannot " + "contain any child elements. " + "Configuration element '" + configuration.getName() + "'." ); } Object retValue = fromExpression( configuration, expressionEvaluator, type ); if ( retValue instanceof String ) { try { retValue = fromString( (String) retValue ); } catch ( final ComponentConfigurationException e ) { if ( e.getFailedConfiguration() == null ) { e.setFailedConfiguration( configuration ); } throw e; } } return retValue; } } BooleanConverter.java000066400000000000000000000031001167051330000501710ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class BooleanConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( boolean.class ) || type.equals( Boolean.class ); } @Override public Object fromString( final String str ) { return str.equals( "true" ) ? Boolean.TRUE : Boolean.FALSE; } } ByteConverter.java000066400000000000000000000035341167051330000475300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class ByteConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( byte.class ) || type.equals( Byte.class ); } @Override public Object fromString( final String str ) throws ComponentConfigurationException { try { return Byte.decode( str ); } catch ( final NumberFormatException e ) { throw new ComponentConfigurationException( "Not a number: '" + str + "'", e ); } } } CharConverter.java000066400000000000000000000030511167051330000474740ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class CharConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( char.class ) || type.equals( Character.class ); } @Override public Object fromString( final String str ) { return new Character( str.charAt( 0 ) ); } } ClassConverter.java000066400000000000000000000026001167051330000476630ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.component.configurator.ComponentConfigurationException; /** * @author Brett Porter */ public class ClassConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( Class.class ); } @Override public Object fromString( final String str ) throws ComponentConfigurationException { try { return Class.forName( str ); } catch ( final ClassNotFoundException e ) { throw new ComponentConfigurationException( "Unable to find class in conversion", e ); } } } Converter.java000066400000000000000000000031631167051330000467020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Translates the String representation of a class into an instance of the class and vice versa */ public interface Converter { @SuppressWarnings( "rawtypes" ) boolean canConvert( Class type ); /** * Parses a given String and return * * @param str String representation of the class * @return an instance of the class */ Object fromString( String str ); String toString( Object obj ); } DateConverter.java000066400000000000000000000043571167051330000475060ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateConverter extends AbstractBasicConverter { /*** * @todo DateFormat is not thread safe! */ private static final DateFormat[] formats = { new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.S a" ), new SimpleDateFormat( "yyyy-MM-dd HH:mm:ssa" ) }; @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( Date.class ); } @Override public Object fromString( final String str ) { for ( final DateFormat format : formats ) { try { return format.parse( str ); } catch ( final ParseException e ) { // no worries, let's try the next format. } } return null; } public String toString( final Object obj ) { final Date date = (Date) obj; return formats[0].format( date ); } } DoubleConverter.java000066400000000000000000000030371167051330000500350ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class DoubleConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( double.class ) || type.equals( Double.class ); } @Override public Object fromString( final String str ) { return Double.valueOf( str ); } } EnumConverter.java000066400000000000000000000062541167051330000475330ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Benjamin Bentmann */ @SuppressWarnings( "rawtypes" ) public class EnumConverter extends AbstractConfigurationConverter { public boolean canConvert( final Class type ) { return type.isEnum(); } @SuppressWarnings( "unchecked" ) public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { if ( configuration.getChildCount() > 0 ) { throw new ComponentConfigurationException( "When configuring a basic element the configuration cannot " + "contain any child elements. " + "Configuration element '" + configuration.getName() + "'." ); } Object retValue = fromExpression( configuration, expressionEvaluator ); if ( retValue instanceof String ) { try { retValue = Enum.valueOf( type, (String) retValue ); } catch ( final RuntimeException e ) { throw new ComponentConfigurationException( "Cannot assign value " + retValue + " to property " + configuration.getName() + " of " + baseType.getName() + ": " + e.getMessage(), e ); } } return retValue; } } FileConverter.java000066400000000000000000000055401167051330000475030ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.io.File; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Brett Porter */ @SuppressWarnings( "rawtypes" ) public class FileConverter extends AbstractBasicConverter { public boolean canConvert( final Class type ) { return type.equals( File.class ); } @Override public Object fromString( final String str ) { return new File( str.replace( '\\', File.separatorChar ).replace( '/', File.separatorChar ) ); } @Override public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { final File f = (File) super.fromConfiguration( converterLookup, configuration, type, baseType, classLoader, expressionEvaluator, listener ); if ( f != null ) { // Hmmm... is this cheating? Can't think of a better way right now return expressionEvaluator.alignToBaseDirectory( f ); } return null; } } FloatConverter.java000066400000000000000000000030331167051330000476640ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class FloatConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( float.class ) || type.equals( Float.class ); } @Override public Object fromString( final String str ) { return Float.valueOf( str ); } } IntConverter.java000066400000000000000000000035401167051330000473540ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class IntConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( int.class ) || type.equals( Integer.class ); } @Override public Object fromString( final String str ) throws ComponentConfigurationException { try { return Integer.decode( str ); } catch ( final NumberFormatException e ) { throw new ComponentConfigurationException( "Not a number: '" + str + "'", e ); } } } LongConverter.java000066400000000000000000000035341167051330000475240ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class LongConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( long.class ) || type.equals( Long.class ); } @Override public Object fromString( final String str ) throws ComponentConfigurationException { try { return Long.decode( str ); } catch ( final NumberFormatException e ) { throw new ComponentConfigurationException( "Not a number: '" + str + "'", e ); } } } ShortConverter.java000066400000000000000000000035401167051330000477210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class ShortConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( short.class ) || type.equals( Short.class ); } @Override public Object fromString( final String str ) throws ComponentConfigurationException { try { return Short.decode( str ); } catch ( final NumberFormatException e ) { throw new ComponentConfigurationException( "Not a number: '" + str + "'", e ); } } } StringBufferConverter.java000066400000000000000000000030151167051330000512170ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class StringBufferConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( StringBuffer.class ); } @Override public Object fromString( final String str ) { return new StringBuffer( str ); } } StringConverter.java000066400000000000000000000027561167051330000501000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class StringConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( String.class ); } @Override public Object fromString( final String str ) { return str; } } UriConverter.java000066400000000000000000000030361167051330000473610ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/* * Copyright (C) 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.plexus.component.configurator.converters.basic; import java.net.URI; import java.net.URISyntaxException; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; /** * Converter for {@link URI} objects. * * @version $Id: UriConverter.java 6935 2007-10-06 08:15:56Z user57 $ */ public class UriConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { assert type != null; return type.equals( URI.class ); } @Override public Object fromString( final String str ) throws ComponentConfigurationException { assert str != null; try { return new URI( str ); } catch ( final URISyntaxException e ) { throw new ComponentConfigurationException( "Unable to convert to URI: " + str, e ); } } } UrlConverter.java000066400000000000000000000037131167051330000473660ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/basicpackage org.codehaus.plexus.component.configurator.converters.basic; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.net.MalformedURLException; import java.net.URL; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; /** * @author Brett Porter */ public class UrlConverter extends AbstractBasicConverter { @SuppressWarnings( "rawtypes" ) public boolean canConvert( final Class type ) { return type.equals( URL.class ); } @Override public Object fromString( final String str ) throws ComponentConfigurationException { try { return new URL( str ); } catch ( final MalformedURLException e ) { throw new ComponentConfigurationException( "Unable to convert '" + str + "' to an URL", e ); } } } 000077500000000000000000000000001167051330000450065ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/compositeArrayConverter.java000066400000000000000000000201621167051330000506200ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/compositepackage org.codehaus.plexus.component.configurator.converters.composite; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.util.StringUtils; /** * @author Kenney Westerhof * @version $Id: ArrayConverter.java 8005 2009-01-04 19:41:09Z bentmann $ */ @SuppressWarnings( "rawtypes" ) public class ArrayConverter extends AbstractConfigurationConverter { public boolean canConvert( final Class type ) { return type.isArray(); } public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { Object retValue = fromExpression( configuration, expressionEvaluator ); if ( retValue != null ) { if ( retValue instanceof Collection ) { retValue = toArray( type, (Collection) retValue ); } else if ( retValue instanceof String && ( !retValue.equals( configuration.getValue() ) || "".equals( retValue ) ) ) { /* * NOTE: String input is supported for expressions only to avoid inconsistent merge behavior when * configuration DOMs mix cdata value with element content. */ final PlexusConfiguration syntheticConfiguration = toConfiguration( configuration.getName(), (String) retValue ); retValue = fromChildren( converterLookup, syntheticConfiguration, type, baseType, classLoader, expressionEvaluator, listener ); } else { failIfNotTypeCompatible( retValue, type, configuration ); } } else { retValue = fromChildren( converterLookup, configuration, type, baseType, classLoader, expressionEvaluator, listener ); } return retValue; } private PlexusConfiguration toConfiguration( final String name, final String value ) { final PlexusConfiguration configuration = new XmlPlexusConfiguration( name ); final String[] tokens = value != null && value.length() > 0 ? value.split( ",", -1 ) : new String[0]; for ( final String token : tokens ) { // use a name that can't accidentally clash with any existing bean class configuration.addChild( "#", token ); } return configuration; } private Object fromChildren( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { final List values = new ArrayList(); for ( int i = 0; i < configuration.getChildCount(); i++ ) { final PlexusConfiguration childConfiguration = configuration.getChild( i ); final Class childType = getChildType( childConfiguration, type, baseType, classLoader ); final ConfigurationConverter converter = converterLookup.lookupConverterForType( childType ); final Object object = converter.fromConfiguration( converterLookup, childConfiguration, childType, baseType, classLoader, expressionEvaluator, listener ); values.add( object ); } return toArray( type, values ); } private Class getChildType( final PlexusConfiguration childConfiguration, final Class arrayType, final Class baseType, final ClassLoader classLoader ) throws ComponentConfigurationException { final String configEntry = childConfiguration.getName(); final String name = fromXML( configEntry ); Class childType = getClassForImplementationHint( null, childConfiguration, classLoader ); // check if the name is a fully qualified classname if ( childType == null && name.indexOf( '.' ) > 0 ) { try { childType = classLoader.loadClass( name ); } catch ( final ClassNotFoundException e ) { // doesn't exist - continue processing } } if ( childType == null ) { // try to find the class in the package of the baseType // (which is the component being configured) final String baseTypeName = baseType.getName(); final int lastDot = baseTypeName.lastIndexOf( '.' ); String className; if ( lastDot == -1 ) { className = name; } else { final String basePackage = baseTypeName.substring( 0, lastDot ); className = basePackage + "." + StringUtils.capitalizeFirstLetter( name ); } try { childType = classLoader.loadClass( className ); } catch ( final ClassNotFoundException e ) { // doesn't exist, continue processing } } // finally just try the component type of the array if ( childType == null ) { childType = arrayType.getComponentType(); } return childType; } private Object toArray( final Class type, final Collection values ) throws ComponentConfigurationException { try { return values.toArray( (Object[]) Array.newInstance( type.getComponentType(), values.size() ) ); } catch ( final ArrayStoreException e ) { throw new ComponentConfigurationException( "Cannot assign configuration values to array of type " + type.getComponentType().getName() + ": " + values ); } } } CollectionConverter.java000066400000000000000000000272421167051330000516430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/compositepackage org.codehaus.plexus.component.configurator.converters.composite; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.ParameterizedConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.util.StringUtils; /** * @author Michal Maczka * @version $Id: CollectionConverter.java 8004 2009-01-04 18:39:40Z bentmann $ */ @SuppressWarnings( { "unchecked", "rawtypes" } ) public class CollectionConverter extends AbstractConfigurationConverter implements ParameterizedConfigurationConverter { public boolean canConvert( final Class type ) { return Collection.class.isAssignableFrom( type ) && !Map.class.isAssignableFrom( type ); } public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { return fromConfiguration( converterLookup, configuration, type, null, baseType, classLoader, expressionEvaluator, listener ); } public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Type[] typeArguments, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { Object retValue = fromExpression( configuration, expressionEvaluator ); if ( retValue != null ) { if ( retValue instanceof Object[] ) { final Collection collection = newCollection( configuration, type, classLoader ); Collections.addAll( collection, (Object[]) retValue ); retValue = collection; } else if ( retValue instanceof String && ( !retValue.equals( configuration.getValue() ) || "".equals( retValue ) ) ) { /* * NOTE: String input is supported for expressions only to avoid inconsistent merge behavior when * configuration DOMs mix cdata value with element content. */ final PlexusConfiguration syntheticConfiguration = toConfiguration( configuration.getName(), (String) retValue ); retValue = fromChildren( converterLookup, syntheticConfiguration, type, typeArguments, baseType, classLoader, expressionEvaluator, listener ); } else { failIfNotTypeCompatible( retValue, type, configuration ); } } else { retValue = fromChildren( converterLookup, configuration, type, typeArguments, baseType, classLoader, expressionEvaluator, listener ); } return retValue; } private PlexusConfiguration toConfiguration( final String name, final String value ) { final PlexusConfiguration configuration = new XmlPlexusConfiguration( name ); final String[] tokens = value != null && value.length() > 0 ? value.split( ",", -1 ) : new String[0]; for ( final String token : tokens ) { // use a name that can't accidentally clash with any existing bean class configuration.addChild( "#", token ); } return configuration; } private Object fromChildren( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Type[] typeArguments, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { final Collection retValue = newCollection( configuration, type, classLoader ); final Class elementType = getElementType( typeArguments ); for ( int i = 0; i < configuration.getChildCount(); i++ ) { final PlexusConfiguration c = configuration.getChild( i ); final Class childType = getChildType( c, elementType, baseType, classLoader ); final ConfigurationConverter converter = converterLookup.lookupConverterForType( childType ); final Object object = converter.fromConfiguration( converterLookup, c, childType, baseType, classLoader, expressionEvaluator, listener ); retValue.add( object ); } return retValue; } private Class getElementType( final Type[] typeArguments ) { Class elementType = null; if ( typeArguments != null && typeArguments.length > 0 ) { final Type typeArgument = typeArguments[0]; if ( typeArgument instanceof Class && !Object.class.equals( typeArgument ) ) { elementType = (Class) typeArgument; } } return elementType; } private Class getChildType( final PlexusConfiguration childConfiguration, final Class elementType, final Class baseType, final ClassLoader classLoader ) throws ComponentConfigurationException { final String configEntry = childConfiguration.getName(); final String name = fromXML( configEntry ); Class childType = getClassForImplementationHint( null, childConfiguration, classLoader ); if ( childType == null && name.indexOf( '.' ) > 0 ) { try { childType = classLoader.loadClass( name ); } catch ( final ClassNotFoundException e ) { // not found, continue processing } } if ( childType == null ) { // Some classloaders don't create Package objects for classes // so we have to resort to slicing up the class name final String baseTypeName = baseType.getName(); final int lastDot = baseTypeName.lastIndexOf( '.' ); String className; if ( lastDot == -1 ) { className = name; } else { final String basePackage = baseTypeName.substring( 0, lastDot ); className = basePackage + "." + StringUtils.capitalizeFirstLetter( name ); } try { childType = classLoader.loadClass( className ); } catch ( final ClassNotFoundException e ) { if ( elementType != null ) { childType = elementType; } else if ( childConfiguration.getChildCount() == 0 ) { // If no children, try a String. childType = String.class; } else { throw new ComponentConfigurationException( "Error loading class '" + className + "'", e ); } } } return childType; } private Collection newCollection( final PlexusConfiguration configuration, final Class type, final ClassLoader classLoader ) throws ComponentConfigurationException { Object collection; final Class implementation = getClassForImplementationHint( type, configuration, classLoader ); // we can have 2 cases here: // - provided collection class which is not abstract // like Vector, ArrayList, HashSet - so we will just instantantiate it // - we have an abtract class so we have to use default collection type if ( Modifier.isAbstract( implementation.getModifiers() ) ) { collection = getDefaultCollection( implementation ); } else { try { collection = instantiateObject( implementation ); } catch ( final ComponentConfigurationException e ) { if ( e.getFailedConfiguration() == null ) { e.setFailedConfiguration( configuration ); } throw e; } } try { return Collection.class.cast( collection ); } catch ( final ClassCastException e ) { throw new ComponentConfigurationException( configuration, "The class " + implementation.getName() + " used to configure the property '" + configuration.getName() + "' is not a collection", e ); } } protected Collection getDefaultCollection( final Class collectionType ) { Collection retValue = null; if ( List.class.isAssignableFrom( collectionType ) ) { retValue = new ArrayList(); } else if ( SortedSet.class.isAssignableFrom( collectionType ) ) { retValue = new TreeSet(); } else if ( Set.class.isAssignableFrom( collectionType ) ) { retValue = new HashSet(); } return retValue; } } ComponentDefaultValueSetter.java000066400000000000000000000114361167051330000533110ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/compositepackage org.codehaus.plexus.component.configurator.converters.composite; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.basic.AbstractBasicConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * Sets the default property of a component. The default property is denoted by a method with the signature * {@code set( arg)} . */ class ComponentDefaultValueSetter { private final Object object; private final ConverterLookup lookup; private final ConfigurationListener listener; private final Method setter; public ComponentDefaultValueSetter( final Object object, final ConverterLookup lookup, final ConfigurationListener listener ) throws ComponentConfigurationException { this.object = object; this.lookup = lookup; this.listener = listener; setter = getDefaultSetter( object ); } private static Method getDefaultSetter( final Object object ) { for ( final Method method : object.getClass().getMethods() ) { if ( "set".equals( method.getName() ) && method.getParameterTypes().length == 1 && !Modifier.isStatic( method.getModifiers() ) ) { return method; } } return null; } public void configure( final Object value, final PlexusConfiguration config, final ClassLoader classLoader, final ExpressionEvaluator evaluator ) throws ComponentConfigurationException { if ( setter == null ) { throw new ComponentConfigurationException( config, "Cannot configure instance of " + object.getClass().getName() + " from " + value ); } final Class propertyType = setter.getParameterTypes()[0]; Object propertyValue; if ( propertyType.isInstance( value ) ) { propertyValue = value; } else { final ConfigurationConverter converter = lookup.lookupConverterForType( propertyType ); if ( !( converter instanceof AbstractBasicConverter ) ) { throw new ComponentConfigurationException( config, "Cannot configure instance of " + object.getClass().getName() + " from " + value ); } propertyValue = converter.fromConfiguration( lookup, config, propertyType, object.getClass(), classLoader, evaluator, listener ); } if ( listener != null ) { listener.notifyFieldChangeUsingSetter( "", propertyValue, object ); } try { setter.invoke( object, propertyValue ); } catch ( final IllegalAccessException e ) { throw new ComponentConfigurationException( config, "Cannot access method " + setter, e ); } catch ( final InvocationTargetException e ) { throw new ComponentConfigurationException( config, "Could not invoke method " + setter + ": " + e.getCause(), e.getCause() ); } } } MapConverter.java000066400000000000000000000111641167051330000502610ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/compositepackage org.codehaus.plexus.component.configurator.converters.composite; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.lang.reflect.Modifier; import java.util.Map; import java.util.Properties; import java.util.TreeMap; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * Converter for java.util.Properties. * * @author Michal Maczka * @version $Id: MapConverter.java 7285 2008-04-14 20:27:40Z jdcasey $ */ @SuppressWarnings( "rawtypes" ) public class MapConverter extends AbstractConfigurationConverter { public boolean canConvert( final Class type ) { return Map.class.isAssignableFrom( type ) && !Properties.class.isAssignableFrom( type ); } public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { Object retValue = fromExpression( configuration, expressionEvaluator ); if ( retValue == null ) { final Map map = newMap( configuration, type, classLoader ); final PlexusConfiguration[] children = configuration.getChildren(); for ( final PlexusConfiguration child : children ) { final String name = child.getName(); map.put( name, fromExpression( child, expressionEvaluator ) ); } retValue = map; } return retValue; } @SuppressWarnings( "unchecked" ) private Map newMap( final PlexusConfiguration configuration, final Class type, final ClassLoader classLoader ) throws ComponentConfigurationException { Object map; final Class implementation = getClassForImplementationHint( type, configuration, classLoader ); if ( null == implementation || Modifier.isAbstract( implementation.getModifiers() ) ) { map = getDefaultMap( implementation ); } else { try { map = instantiateObject( implementation ); } catch ( final ComponentConfigurationException e ) { if ( e.getFailedConfiguration() == null ) { e.setFailedConfiguration( configuration ); } throw e; } } try { return Map.class.cast( map ); } catch ( final ClassCastException e ) { throw new ComponentConfigurationException( configuration, "The class " + implementation.getName() + " used to configure the property '" + configuration.getName() + "' is not a map", e ); } } private Map getDefaultMap( final Class mapType ) { return new TreeMap(); } } ObjectWithFieldsConverter.java000066400000000000000000000151531167051330000527370ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/compositepackage org.codehaus.plexus.component.configurator.converters.composite; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.util.Collection; import java.util.Dictionary; import java.util.Map; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.ComponentValueSetter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Michal Maczka * @version $Id: ObjectWithFieldsConverter.java 8512 2009-10-21 23:15:04Z bentmann $ */ @SuppressWarnings( "rawtypes" ) public class ObjectWithFieldsConverter extends AbstractConfigurationConverter { public boolean canConvert( final Class type ) { boolean retValue = true; if ( Dictionary.class.isAssignableFrom( type ) ) { retValue = false; } else if ( Map.class.isAssignableFrom( type ) ) { retValue = false; } else if ( Collection.class.isAssignableFrom( type ) ) { retValue = false; } return retValue; } public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { Object retValue = fromExpression( configuration, expressionEvaluator ); try { if ( retValue == null ) { // it is a "composite" - we compose it from its children. It does not have a value of its own final Class implementation = getClassForImplementationHint( type, configuration, classLoader ); if ( type == implementation && type.isInterface() && configuration.getChildCount() <= 0 ) { return null; } retValue = instantiateObject( implementation ); processConfiguration( converterLookup, retValue, classLoader, configuration, expressionEvaluator, listener ); } else if ( !type.isInstance( retValue ) ) { final Class implementation = getClassForImplementationHint( type, configuration, classLoader ); final Object propertyValue = retValue; retValue = instantiateObject( implementation ); final ComponentDefaultValueSetter valueSetter = new ComponentDefaultValueSetter( retValue, converterLookup, listener ); valueSetter.configure( propertyValue, configuration, classLoader, expressionEvaluator ); } } catch ( final ComponentConfigurationException e ) { if ( e.getFailedConfiguration() == null ) { e.setFailedConfiguration( configuration ); } throw e; } return retValue; } public void processConfiguration( final ConverterLookup converterLookup, final Object object, final ClassLoader classLoader, final PlexusConfiguration configuration ) throws ComponentConfigurationException { processConfiguration( converterLookup, object, classLoader, configuration, null ); } public void processConfiguration( final ConverterLookup converterLookup, final Object object, final ClassLoader classLoader, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator ) throws ComponentConfigurationException { processConfiguration( converterLookup, object, classLoader, configuration, expressionEvaluator, null ); } public void processConfiguration( final ConverterLookup converterLookup, final Object object, final ClassLoader classLoader, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { final int items = configuration.getChildCount(); for ( int i = 0; i < items; i++ ) { final PlexusConfiguration childConfiguration = configuration.getChild( i ); final String elementName = childConfiguration.getName(); Class implementation; try { implementation = getClassForImplementationHint( null, childConfiguration, classLoader ); } catch ( final Exception e ) { implementation = null; // fall back to original behavior } final ComponentValueSetter valueSetter = new ComponentValueSetter( fromXML( elementName ), implementation, object, converterLookup, listener ); valueSetter.configure( childConfiguration, classLoader, expressionEvaluator ); } } } PlexusConfigurationConverter.java000066400000000000000000000051071167051330000535540ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/compositepackage org.codehaus.plexus.component.configurator.converters.composite; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * Converter for org.codehaus.plexus.configuration.PlexusConfiguration * * @author Michal Maczka * @version $Id: PlexusConfigurationConverter.java 6064 2007-03-13 12:39:55Z trygvis $ */ @SuppressWarnings( "rawtypes" ) public class PlexusConfigurationConverter extends AbstractConfigurationConverter { public boolean canConvert( final Class type ) { return PlexusConfiguration.class.isAssignableFrom( type ); } public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { return configuration; } } PropertiesConverter.java000066400000000000000000000120101167051330000516670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/compositepackage org.codehaus.plexus.component.configurator.converters.composite; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.util.Properties; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * Converter for java.util.Properties. * * @author Michal Maczka * @version $Id: PropertiesConverter.java 8516 2009-10-26 12:54:02Z bentmann $ */ @SuppressWarnings( "rawtypes" ) public class PropertiesConverter extends AbstractConfigurationConverter { public boolean canConvert( final Class type ) { return Properties.class.isAssignableFrom( type ); } public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { Object retValue = fromExpression( configuration, expressionEvaluator, type ); if ( retValue == null ) { retValue = fromChildren( configuration, expressionEvaluator, listener ); } return retValue; } private Object fromChildren( final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { final String element = configuration.getName(); final Properties retValue = new Properties(); for ( int i = 0, n = configuration.getChildCount(); i < n; i++ ) { final PlexusConfiguration childConfiguration = configuration.getChild( i ); final Object name; final PlexusConfiguration value; if ( "property".equals( childConfiguration.getName() ) && childConfiguration.getChildCount() > 0 ) { // // key // val // name = fromExpression( childConfiguration.getChild( "name" ), expressionEvaluator ); value = childConfiguration.getChild( "value" ); } else if ( childConfiguration.getChildCount() <= 0 ) { // val name = childConfiguration.getName(); value = childConfiguration; } else { continue; } addEntry( retValue, element, name, value, expressionEvaluator ); } return retValue; } private void addEntry( final Properties properties, final String element, final Object name, final PlexusConfiguration valueConfiguration, final ExpressionEvaluator expressionEvaluator ) throws ComponentConfigurationException { final String key = name != null ? name.toString() : null; if ( key == null ) { final String msg = "Missing name for property of configuration element '" + element + "'"; throw new ComponentConfigurationException( msg ); } final Object value = fromExpression( valueConfiguration, expressionEvaluator ); if ( value == null ) { properties.setProperty( key, "" ); } else { properties.setProperty( key, value.toString() ); } } } 000077500000000000000000000000001167051330000443155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/lookupConverterLookup.java000066400000000000000000000032111167051330000503160ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/lookuppackage org.codehaus.plexus.component.configurator.converters.lookup; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; /** @version $Id: ConverterLookup.java 7828 2008-11-14 22:07:56Z dain $ */ public interface ConverterLookup { void registerConverter( ConfigurationConverter converter ); ConfigurationConverter lookupConverterForType( Class type ) throws ComponentConfigurationException; } DefaultConverterLookup.java000066400000000000000000000156301167051330000516330ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/lookuppackage org.codehaus.plexus.component.configurator.converters.lookup; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.basic.BooleanConverter; import org.codehaus.plexus.component.configurator.converters.basic.ByteConverter; import org.codehaus.plexus.component.configurator.converters.basic.CharConverter; import org.codehaus.plexus.component.configurator.converters.basic.DateConverter; import org.codehaus.plexus.component.configurator.converters.basic.DoubleConverter; import org.codehaus.plexus.component.configurator.converters.basic.EnumConverter; import org.codehaus.plexus.component.configurator.converters.basic.FileConverter; import org.codehaus.plexus.component.configurator.converters.basic.FloatConverter; import org.codehaus.plexus.component.configurator.converters.basic.IntConverter; import org.codehaus.plexus.component.configurator.converters.basic.LongConverter; import org.codehaus.plexus.component.configurator.converters.basic.ShortConverter; import org.codehaus.plexus.component.configurator.converters.basic.StringBufferConverter; import org.codehaus.plexus.component.configurator.converters.basic.StringConverter; import org.codehaus.plexus.component.configurator.converters.basic.UriConverter; import org.codehaus.plexus.component.configurator.converters.basic.UrlConverter; import org.codehaus.plexus.component.configurator.converters.composite.ArrayConverter; import org.codehaus.plexus.component.configurator.converters.composite.CollectionConverter; import org.codehaus.plexus.component.configurator.converters.composite.MapConverter; import org.codehaus.plexus.component.configurator.converters.composite.ObjectWithFieldsConverter; import org.codehaus.plexus.component.configurator.converters.composite.PlexusConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.composite.PropertiesConverter; public class DefaultConverterLookup implements ConverterLookup { private final List converters = new ArrayList(); private final List customConverters = new CopyOnWriteArrayList(); private final Map, ConfigurationConverter> converterMap = new ConcurrentHashMap, ConfigurationConverter>(); public DefaultConverterLookup() { registerDefaultBasicConverters(); registerDefaultCompositeConverters(); } public synchronized void registerConverter( final ConfigurationConverter converter ) { customConverters.add( converter ); } protected void registerDefaultConverter( final ConfigurationConverter converter ) { converters.add( converter ); } public ConfigurationConverter lookupConverterForType( final Class type ) throws ComponentConfigurationException { ConfigurationConverter retValue = converterMap.get( type ); if ( retValue == null ) { if ( customConverters != null ) { retValue = findConverterForType( customConverters, type ); } if ( retValue == null ) { retValue = findConverterForType( converters, type ); } if ( retValue == null ) { // this is highly irregular throw new ComponentConfigurationException( "Configuration converter lookup failed for type: " + type ); } converterMap.put( type, retValue ); } return retValue; } private static ConfigurationConverter findConverterForType( final List converters, final Class type ) { for ( final ConfigurationConverter converter : converters ) { if ( converter.canConvert( type ) ) { return converter; } } return null; } private void registerDefaultBasicConverters() { registerDefaultConverter( new BooleanConverter() ); registerDefaultConverter( new ByteConverter() ); registerDefaultConverter( new CharConverter() ); registerDefaultConverter( new DoubleConverter() ); registerDefaultConverter( new FloatConverter() ); registerDefaultConverter( new IntConverter() ); registerDefaultConverter( new LongConverter() ); registerDefaultConverter( new ShortConverter() ); registerDefaultConverter( new StringBufferConverter() ); registerDefaultConverter( new StringConverter() ); registerDefaultConverter( new DateConverter() ); registerDefaultConverter( new FileConverter() ); registerDefaultConverter( new UrlConverter() ); registerDefaultConverter( new UriConverter() ); registerDefaultConverter( new EnumConverter() ); } private void registerDefaultCompositeConverters() { registerDefaultConverter( new MapConverter() ); registerDefaultConverter( new ArrayConverter() ); registerDefaultConverter( new CollectionConverter() ); registerDefaultConverter( new PropertiesConverter() ); registerDefaultConverter( new PlexusConfigurationConverter() ); // this converter should be always registred as the last one registerDefaultConverter( new ObjectWithFieldsConverter() ); } void setCustomConverters( final List c ) { customConverters.addAll( c ); } } 000077500000000000000000000000001167051330000444245ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/specialClassRealmConverter.java000066400000000000000000000063751167051330000512200ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/converters/specialpackage org.codehaus.plexus.component.configurator.converters.special; import org.codehaus.classworlds.ClassRealmAdapter; import org.codehaus.classworlds.ClassRealmReverseAdapter; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * ConfigurationConverter to set up ClassRealm component fields. * * @author Kenney Westerhof */ @SuppressWarnings( "rawtypes" ) public class ClassRealmConverter extends AbstractConfigurationConverter { public static final String ROLE = ConfigurationConverter.class.getName(); private ClassRealm classRealm; /** * Constructs this ClassRealmConverter with the given ClassRealm. If there's a way to automatically configure this * component using the current classrealm, this method can go away. * * @param classRealm */ public ClassRealmConverter( final ClassRealm classRealm ) { setClassRealm( classRealm ); } @Deprecated public ClassRealmConverter( final org.codehaus.classworlds.ClassRealm classRealm ) { setClassRealm( classRealm ); } public void setClassRealm( final ClassRealm classRealm ) { this.classRealm = classRealm; } @Deprecated public void setClassRealm( final org.codehaus.classworlds.ClassRealm classRealm ) { if ( classRealm.getClassLoader() instanceof ClassRealm ) { setClassRealm( (ClassRealm) classRealm.getClassLoader() ); } else { setClassRealm( ClassRealmReverseAdapter.getInstance( classRealm ) ); } } public boolean canConvert( final Class type ) { // backwards compatibility for old ClassWorld fields return org.codehaus.classworlds.ClassRealm.class.isAssignableFrom( type ) || ClassRealm.class.isAssignableFrom( type ); } public Object fromConfiguration( final ConverterLookup converterLookup, final PlexusConfiguration configuration, final Class type, final Class baseType, final ClassLoader classLoader, final ExpressionEvaluator expressionEvaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { Object retValue = fromExpression( configuration, expressionEvaluator, type ); if ( retValue == null ) { retValue = classRealm; } // backwards compatibility for old ClassWorld fields if ( retValue instanceof ClassRealm && org.codehaus.classworlds.ClassRealm.class.isAssignableFrom( type ) ) { retValue = ClassRealmAdapter.getInstance( (ClassRealm) retValue ); } return retValue; } } 000077500000000000000000000000001167051330000430115ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/expressionDefaultExpressionEvaluator.java000066400000000000000000000024051167051330000512040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/expressionpackage org.codehaus.plexus.component.configurator.expression; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.io.File; /** * Evaluate an expression. * * @author Brett Porter * @version $Id: DefaultExpressionEvaluator.java 4779 2006-11-23 04:09:31Z jvanzyl $ */ public class DefaultExpressionEvaluator implements ExpressionEvaluator { /** * Evaluate an expression. * * @param expression the expression * @return the value of the expression */ public Object evaluate( final String expression ) { return expression; } public File alignToBaseDirectory( final File file ) { return file; } } ExpressionEvaluationException.java000066400000000000000000000015651167051330000517310ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/expression/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.configurator.expression; public final class ExpressionEvaluationException extends Exception { private static final long serialVersionUID = 1L; public ExpressionEvaluationException( final String message ) { super( message ); } public ExpressionEvaluationException( final String message, final Throwable detail ) { super( message, detail ); } } ExpressionEvaluator.java000066400000000000000000000026371167051330000477060ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/expressionpackage org.codehaus.plexus.component.configurator.expression; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.io.File; /** * Evaluate an expression. * * @author Brett Porter * @version $Id: ExpressionEvaluator.java 4779 2006-11-23 04:09:31Z jvanzyl $ */ public interface ExpressionEvaluator { String ROLE = ExpressionEvaluator.class.getName(); /** * Evaluate an expression. * * @param expression the expression * @return the value of the expression */ Object evaluate( String expression ) throws ExpressionEvaluationException; /** * Align a given path to the base directory that can be evaluated by this expression evaluator, if known. * * @param file the file * @return the aligned file */ File alignToBaseDirectory( File file ); } TypeAwareExpressionEvaluator.java000066400000000000000000000030021167051330000515130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/expressionpackage org.codehaus.plexus.component.configurator.expression; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * Evaluate an expression. * * @author Brett Porter * @version $Id: TypeAwareExpressionEvaluator.java 8347 2009-08-20 17:37:19Z bentmann $ */ public interface TypeAwareExpressionEvaluator extends ExpressionEvaluator { /** * Evaluate an expression. The optional type provided to this method is a hint (not a requirement) for the evaluator * to resolve the expression to a compatible value. The evaluator is not expected to perform any conversion but * rather filter out incompatible values from its result. * * @param expression the expression * @param type The expected type of expression result, may be {@code null}. * @return the value of the expression */ Object evaluate( String expression, Class type ) throws ExpressionEvaluationException; } 000077500000000000000000000000001167051330000375575ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/factoryAbstractComponentFactory.java000066400000000000000000000027021167051330000454010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/factory/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.factory; import org.codehaus.classworlds.ClassRealmAdapter; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.ComponentDescriptor; @SuppressWarnings( "rawtypes" ) public abstract class AbstractComponentFactory implements ComponentFactory { public Object newInstance( final ComponentDescriptor cd, final ClassRealm realm, final PlexusContainer container ) throws ComponentInstantiationException { return newInstance( cd, ClassRealmAdapter.getInstance( realm ), container ); } @SuppressWarnings( "unused" ) protected Object newInstance( final ComponentDescriptor cd, final org.codehaus.classworlds.ClassRealm realm, final PlexusContainer container ) throws ComponentInstantiationException { throw new IllegalStateException( getClass() + " does not implement component creation" ); } } ComponentFactory.java000066400000000000000000000016151167051330000437170ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/factory/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.factory; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.ComponentDescriptor; public interface ComponentFactory { String getId(); @SuppressWarnings( "rawtypes" ) Object newInstance( ComponentDescriptor cd, ClassRealm realm, PlexusContainer container ) throws ComponentInstantiationException; } ComponentInstantiationException.java000066400000000000000000000015511167051330000470120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/factory/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.factory; public final class ComponentInstantiationException extends Exception { private static final long serialVersionUID = 1L; public ComponentInstantiationException( final String message ) { super( message ); } public ComponentInstantiationException( final String message, final Throwable cause ) { super( message, cause ); } } 000077500000000000000000000000001167051330000403275ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/repositoryComponentDependency.java000066400000000000000000000035131167051330000451350ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/repository/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.repository; public final class ComponentDependency { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private String groupId; private String artifactId; private String version; private String type = "jar"; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void setGroupId( final String groupId ) { this.groupId = groupId; } public void setArtifactId( final String artifactId ) { this.artifactId = artifactId; } public void setVersion( final String version ) { this.version = version; } public void setType( final String type ) { this.type = type; } public String getGroupId() { return groupId; } public String getArtifactId() { return artifactId; } public String getVersion() { return version; } public String getType() { return type; } @Override public String toString() { return "groupId = " + groupId + ", artifactId = " + artifactId + ", version = " + version + ", type = " + type; } } ComponentDescriptor.java000066400000000000000000000221341167051330000451750ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/repository/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.repository; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.sonatype.guice.plexus.config.Hints; import org.sonatype.guice.plexus.config.Strategies; public class ComponentDescriptor { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private String role; private String hint = Hints.DEFAULT_HINT; private String description = ""; private String instantiationStrategy = Strategies.SINGLETON; private String implementation; private ClassRealm classRealm; private Class implementationClass; private String componentComposer; private String componentConfigurator; private String componentFactory; private List requirements = Collections.emptyList(); private PlexusConfiguration configuration; private String alias; private String version; private String componentType; private String componentProfile; private String lifecycleHandler; private boolean isolatedRealm; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public ComponentDescriptor() { // nothing to set } public ComponentDescriptor( final Class implementationClass, final ClassRealm classRealm ) { setImplementationClass( implementationClass ); this.classRealm = classRealm; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public final void setRole( final String role ) { this.role = role; } public final void setRoleClass( final Class roleClass ) { role = roleClass.getName(); } public final void setRoleHint( final String hint ) { this.hint = Hints.canonicalHint( hint ); } public final void setDescription( final String description ) { this.description = null != description ? description : ""; } public final void setInstantiationStrategy( final String instantiationStrategy ) { this.instantiationStrategy = instantiationStrategy; } public final void setImplementation( final String implementation ) { this.implementation = implementation; implementationClass = null; } public final void setRealm( final ClassRealm classRealm ) { this.classRealm = classRealm; implementationClass = null; } @SuppressWarnings( "rawtypes" ) public final void setImplementationClass( final Class implementationClass ) { this.implementationClass = implementationClass; implementation = implementationClass.getName(); } public final void setComponentComposer( final String componentComposer ) { this.componentComposer = componentComposer; } public final void setComponentConfigurator( final String componentConfigurator ) { this.componentConfigurator = componentConfigurator; } public final void setComponentFactory( final String componentFactory ) { this.componentFactory = componentFactory; } public final void addRequirement( final ComponentRequirement requirement ) { if ( requirements.isEmpty() ) { requirements = new ArrayList(); } requirements.add( requirement ); } public final void setConfiguration( final PlexusConfiguration configuration ) { this.configuration = configuration; } public final void setAlias( final String alias ) { this.alias = alias; } public final void setVersion( final String version ) { this.version = version; } public final void setComponentType( final String componentType ) { this.componentType = componentType; } public final void setComponentProfile( final String componentProfile ) { this.componentProfile = componentProfile; } public final void setLifecycleHandler( final String lifecycleHandler ) { this.lifecycleHandler = lifecycleHandler; } public final void setIsolatedRealm( final boolean isolatedRealm ) { this.isolatedRealm = isolatedRealm; } public String getRole() { return role; } @SuppressWarnings( "unchecked" ) public final Class getRoleClass() { try { return classRealm.loadClass( getRole() ); } catch ( final Exception e ) { throw new TypeNotPresentException( getRole(), e ); } catch ( final LinkageError e ) { throw new TypeNotPresentException( getRole(), e ); } } public String getRoleHint() { return hint; } public final String getDescription() { return description; } public final String getInstantiationStrategy() { return instantiationStrategy; } public final String getImplementation() { return implementation; } public final ClassRealm getRealm() { return classRealm; } @SuppressWarnings( "unchecked" ) public final Class getImplementationClass() { if ( null == implementationClass && null != classRealm ) { try { implementationClass = classRealm.loadClass( implementation ); } catch ( final Exception e ) { throw new TypeNotPresentException( implementation, e ); } catch ( final LinkageError e ) { throw new TypeNotPresentException( implementation, e ); } } return (Class) implementationClass; } public final String getComponentComposer() { return componentComposer; } public final String getComponentConfigurator() { return componentConfigurator; } public final String getComponentFactory() { return componentFactory; } public final List getRequirements() { return Collections.unmodifiableList( requirements ); } public final boolean hasConfiguration() { return configuration != null; } public final PlexusConfiguration getConfiguration() { return configuration; } public final String getAlias() { return alias; } public final String getVersion() { return version; } public String getComponentType() { return componentType; } public final String getComponentProfile() { return componentProfile; } public final String getLifecycleHandler() { return lifecycleHandler; } public final boolean isIsolatedRealm() { return isolatedRealm; } public final String getHumanReadableKey() { return "role: '" + getRole() + "', implementation: '" + implementation + "', role hint: '" + getRoleHint() + "'"; } @Override public final String toString() { return getClass().getName() + " [role: '" + getRole() + "', hint: '" + getRoleHint() + "', realm: " + classRealm + "]"; } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof ComponentDescriptor ) { final ComponentDescriptor rhsDescriptor = (ComponentDescriptor) rhs; return equals( getRole(), rhsDescriptor.getRole() ) && equals( getRoleHint(), rhsDescriptor.getRoleHint() ) && equals( classRealm, rhsDescriptor.classRealm ); } return false; } @Override public int hashCode() { return ( ( 17 * 31 + hash( getRole() ) ) * 31 + hash( getRoleHint() ) ) * 31 + hash( classRealm ); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private static final boolean equals( final T lhs, final T rhs ) { return null != lhs ? lhs.equals( rhs ) : null == rhs; } private static final int hash( final Object obj ) { return null != obj ? obj.hashCode() : 0; } } ComponentRequirement.java000066400000000000000000000052421167051330000453600ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/repository/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.repository; public class ComponentRequirement { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private String role; private String hint = ""; private String name; private boolean optional; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public final void setRole( final String role ) { this.role = role; } public final void setRoleHint( final String hint ) { // empty/null hint represents wildcard this.hint = null != hint ? hint : ""; } public final void setFieldName( final String name ) { this.name = name; } public final void setOptional( final boolean optional ) { this.optional = optional; } @SuppressWarnings( "unused" ) public final void setFieldMappingType( final String mappingType ) { // ignore } public final String getRole() { return role; } public final String getRoleHint() { return hint; } public final String getFieldName() { return name; } public final boolean isOptional() { return optional; } @Override public String toString() { return "ComponentRequirement{role='" + role + "', roleHint='" + hint + "', fieldName='" + name + "'}"; } @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof ComponentRequirement ) { return id().equals( ( (ComponentRequirement) rhs ).id() ); } return false; } @Override public int hashCode() { return id().hashCode(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private final String id() { return role + ':' + hint; } } ComponentRequirementList.java000066400000000000000000000022321167051330000462100ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/repository/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.repository; import java.util.List; public final class ComponentRequirementList extends ComponentRequirement { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private List hints; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void setRoleHints( final List hints ) { this.hints = hints; } public List getRoleHints() { return hints; } } ComponentSetDescriptor.java000066400000000000000000000055461167051330000456610ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/repository/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.repository; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ComponentSetDescriptor { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private boolean isolatedRealm; private List> components = Collections.emptyList(); private List dependencies = Collections.emptyList(); // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public final void setIsolatedRealm( final boolean isolatedRealm ) { this.isolatedRealm = isolatedRealm; } public final void addComponentDescriptor( final ComponentDescriptor component ) { if ( components.isEmpty() ) { components = new ArrayList>(); } components.add( component ); } public final void setComponents( final List> components ) { this.components = new ArrayList>( components ); } public final void addDependency( final ComponentDependency dependency ) { if ( dependencies.isEmpty() ) { dependencies = new ArrayList(); } dependencies.add( dependency ); } public final void setDependencies( final List dependencies ) { this.dependencies = new ArrayList( dependencies ); } public final boolean isIsolatedRealm() { return isolatedRealm; } public final List> getComponents() { return components; } public final List getDependencies() { return dependencies; } @Override public final String toString() { final StringBuffer buf = new StringBuffer( "Component Descriptor: " ); for ( final ComponentDescriptor cd : components ) { buf.append( cd.getHumanReadableKey() ).append( "\n" ); } return buf.append( "---" ).toString(); } @SuppressWarnings( "unused" ) public final void setId( final String id ) { // ignore } } 000077500000000000000000000000001167051330000423255ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/repository/exceptionComponentLifecycleException.java000066400000000000000000000015541167051330000506360ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/repository/exception/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.repository.exception; public final class ComponentLifecycleException extends Exception { private static final long serialVersionUID = 1L; public ComponentLifecycleException( final String message ) { super( message ); } public ComponentLifecycleException( final String message, final Throwable detail ) { super( message, detail ); } } ComponentLookupException.java000066400000000000000000000034661167051330000502140ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/repository/exception/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.repository.exception; public final class ComponentLookupException extends Exception { private static final long serialVersionUID = 1L; // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final String LS = System.getProperty( "line.separator" ); // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final String role; private final String hint; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public ComponentLookupException( final String message, final String role, final String hint ) { super( message ); this.role = role; this.hint = hint; } public ComponentLookupException( final Throwable cause, final String role, final String hint ) { super( cause ); this.role = role; this.hint = hint; } @Override public String getMessage() { return super.getMessage() + LS + " role: " + role + LS + " roleHint: " + hint; } } ComponentRepositoryException.java000066400000000000000000000015571167051330000511210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/repository/exception/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.component.repository.exception; public final class ComponentRepositoryException extends Exception { private static final long serialVersionUID = 1L; public ComponentRepositoryException( final String message ) { super( message ); } public ComponentRepositoryException( final String message, final Throwable detail ) { super( message, detail ); } } 000077500000000000000000000000001167051330000367555ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/configurationDefaultPlexusConfiguration.java000066400000000000000000000134701167051330000451420ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/configuration/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.configuration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class DefaultPlexusConfiguration implements PlexusConfiguration { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- private static final PlexusConfiguration[] NO_CHILDREN = new PlexusConfiguration[0]; // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final String name; private String value; private List childIndex = Collections.emptyList(); private Map> childMap = Collections.emptyMap(); private Map attributeMap = Collections.emptyMap(); // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public DefaultPlexusConfiguration( final String name ) { this( name, null ); } public DefaultPlexusConfiguration( final String name, final String value ) { this.name = name; this.value = value; } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public final String getName() { return name; } public final String getValue() { return value; } public final String getValue( final String defaultValue ) { return null != value ? value : defaultValue; } public final void setValue( final String value ) { this.value = value; } public final String[] getAttributeNames() { return attributeMap.keySet().toArray( new String[attributeMap.size()] ); } public final String getAttribute( final String attributeName ) { return attributeMap.get( attributeName ); } public final String getAttribute( final String attributeName, final String defaultValue ) { final String attributeValue = attributeMap.get( attributeName ); return null != attributeValue ? attributeValue : defaultValue; } public final void setAttribute( final String attributeName, final String attributeValue ) { if ( attributeMap.isEmpty() ) { attributeMap = new HashMap(); } attributeMap.put( attributeName, attributeValue ); } public final PlexusConfiguration getChild( final String childName ) { return getChild( childName, true ); } public final PlexusConfiguration getChild( final String childName, final boolean create ) { final List children = childMap.get( childName ); if ( null != children ) { return children.get( 0 ); } return create ? add( createChild( childName ) ) : null; } public final PlexusConfiguration[] getChildren() { return childIndex.toArray( new PlexusConfiguration[childIndex.size()] ); } public final PlexusConfiguration[] getChildren( final String childName ) { final List children = childMap.get( childName ); if ( null != children ) { return children.toArray( new PlexusConfiguration[children.size()] ); } return NO_CHILDREN; } public final int getChildCount() { return childIndex.size(); } public final PlexusConfiguration getChild( final int index ) { return childIndex.get( index ); } public final void addChild( final PlexusConfiguration child ) { add( child ); } public final PlexusConfiguration addChild( final String childName, final String childValue ) { add( createChild( childName ) ).setValue( childValue ); return this; } // ---------------------------------------------------------------------- // Customizable methods // ---------------------------------------------------------------------- protected PlexusConfiguration createChild( final String childName ) { return new DefaultPlexusConfiguration( childName ); } // ---------------------------------------------------------------------- // Shared methods // ---------------------------------------------------------------------- protected final PlexusConfiguration add( final PlexusConfiguration child ) { final String childName = child.getName(); List children = childMap.get( childName ); if ( null == children ) { children = new ArrayList(); if ( childMap.isEmpty() ) { // create mutable map and index at the same time childMap = new LinkedHashMap>(); childIndex = new ArrayList(); } childMap.put( childName, children ); } childIndex.add( child ); children.add( child ); return child; } } PlexusConfiguration.java000066400000000000000000000024111167051330000436260ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/configuration/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.configuration; public interface PlexusConfiguration { String getName(); String getValue(); String getValue( String defaultValue ); void setValue( String value ); String[] getAttributeNames(); String getAttribute( String attributeName ); String getAttribute( String attributeName, String defaultValue ); void setAttribute( String name, String value ); PlexusConfiguration getChild( String childName ); PlexusConfiguration getChild( String childName, boolean create ); PlexusConfiguration[] getChildren(); PlexusConfiguration[] getChildren( String childName ); int getChildCount(); PlexusConfiguration getChild( int index ); void addChild( PlexusConfiguration child ); PlexusConfiguration addChild( String name, String value ); } PlexusConfigurationException.java000066400000000000000000000015301167051330000455060ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/configuration/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.configuration; public class PlexusConfigurationException extends Exception { private static final long serialVersionUID = 1L; public PlexusConfigurationException( final String message ) { super( message ); } public PlexusConfigurationException( final String message, final Throwable detail ) { super( message, detail ); } } 000077500000000000000000000000001167051330000375555ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/configuration/xmlXmlPlexusConfiguration.java000066400000000000000000000051151167051330000451130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/configuration/xml/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.configuration.xml; import org.codehaus.plexus.configuration.DefaultPlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.util.xml.Xpp3Dom; public final class XmlPlexusConfiguration extends DefaultPlexusConfiguration { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public XmlPlexusConfiguration( final String name ) { super( name ); } public XmlPlexusConfiguration( final Xpp3Dom dom ) { super( dom.getName(), dom.getValue() ); for ( final String attribute : dom.getAttributeNames() ) { setAttribute( attribute, dom.getAttribute( attribute ) ); } for ( final Xpp3Dom child : dom.getChildren() ) { addChild( new XmlPlexusConfiguration( child ) ); } } @Override public String toString() { final StringBuilder buf = new StringBuilder().append( '<' ).append( getName() ); for ( final String a : getAttributeNames() ) { buf.append( ' ' ).append( a ).append( "=\"" ).append( getAttribute( a ) ).append( '"' ); } if ( getChildCount() > 0 ) { buf.append( '>' ); for ( final PlexusConfiguration c : getChildren() ) { buf.append( c ); } buf.append( "' ); } else if ( null != getValue() ) { buf.append( '>' ).append( getValue() ).append( "' ); } else { buf.append( "/>" ); } return buf.append( '\n' ).toString(); } // ---------------------------------------------------------------------- // Customizable methods // ---------------------------------------------------------------------- @Override protected PlexusConfiguration createChild( final String name ) { return new XmlPlexusConfiguration( name ); } } 000077500000000000000000000000001167051330000355725ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/contextContextMapAdapter.java000066400000000000000000000043161167051330000420240ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.context; import java.util.AbstractMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public final class ContextMapAdapter extends AbstractMap { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- final Map contextData; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public ContextMapAdapter( final Context context ) { contextData = context.getContextData(); } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public boolean containsKey( final Object key ) { return get( key ) != null; } @Override public Object get( final Object key ) { final Object value = contextData.get( key ); return value instanceof String ? value : null; } // ---------------------------------------------------------------------- // Implementation helpers // ---------------------------------------------------------------------- @Override public Set> entrySet() { final Set> tempSet = new HashSet>(); for ( final Entry entry : contextData.entrySet() ) { if ( entry.getValue() instanceof String ) { tempSet.add( entry ); } } return tempSet; } } DefaultContext.java000066400000000000000000000050461167051330000413730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.context; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; public class DefaultContext implements Context { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- protected final Map contextData = new ConcurrentHashMap(); // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public DefaultContext() { // nothing to store } public DefaultContext( final Map context ) { if ( null != context ) { for ( final Entry e : context.entrySet() ) { put( e.getKey(), e.getValue() ); } } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public boolean contains( final Object key ) { return contextData.containsKey( key ); } public void put( final Object key, final Object value ) { if ( null == key ) { throw new IllegalArgumentException( "Key is null" ); } if ( null != value ) { contextData.put( key, value ); } else { contextData.remove( key ); } } public Object get( final Object key ) throws ContextException { final Object data = contextData.get( key ); if ( data == null ) { throw new ContextException( "Unable to resolve context key: " + key ); } return data; } public Map getContextData() { return Collections.unmodifiableMap( contextData ); } @Override public String toString() { return contextData.toString(); } } 000077500000000000000000000000001167051330000355345ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/loggingAbstractLogEnabled.java000066400000000000000000000036351167051330000420660ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/logging/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.logging; public abstract class AbstractLogEnabled implements LogEnabled { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private Logger logger; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void enableLogging( final Logger theLogger ) { logger = theLogger; } // ---------------------------------------------------------------------- // Shared methods // ---------------------------------------------------------------------- protected Logger getLogger() { return logger; } protected final void setupLogger( final Object component ) { setupLogger( component, logger ); } protected final void setupLogger( final Object component, final String category ) { if ( category == null ) { throw new IllegalStateException( "Logging category must be defined." ); } setupLogger( component, logger.getChildLogger( category ) ); } protected final void setupLogger( final Object component, final Logger logger ) { if ( component instanceof LogEnabled ) { ( (LogEnabled) component ).enableLogging( logger ); } } } AbstractLoggerManager.java000066400000000000000000000017071167051330000426020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/logging/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.logging; import org.sonatype.guice.bean.reflect.IgnoreSetters; import org.sonatype.guice.plexus.config.Hints; @IgnoreSetters public abstract class AbstractLoggerManager implements LoggerManager { public final Logger getLoggerForComponent( final String role ) { return getLoggerForComponent( role, Hints.DEFAULT_HINT ); } public final void returnComponentLogger( final String role ) { returnComponentLogger( role, Hints.DEFAULT_HINT ); } } BaseLoggerManager.java000066400000000000000000000070721167051330000417120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/logging/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.logging; import java.util.Map; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.sonatype.guice.bean.reflect.Weak; import org.sonatype.guice.plexus.config.Roles; public abstract class BaseLoggerManager extends AbstractLoggerManager implements Initializable { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Map activeLoggers = Weak.values(); String threshold = "INFO"; private int currentThreshold; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public final void initialize() { currentThreshold = parseThreshold( threshold ); } public final synchronized Logger getLoggerForComponent( final String role, final String hint ) { final String name = Roles.canonicalRoleHint( role, hint ); Logger logger = activeLoggers.get( name ); if ( null == logger ) { logger = createLogger( name ); logger.setThreshold( currentThreshold ); activeLoggers.put( name, logger ); } return logger; } public final synchronized void returnComponentLogger( final String role, final String hint ) { activeLoggers.remove( Roles.canonicalRoleHint( role, hint ) ); } public final int getThreshold() { return currentThreshold; } public final void setThreshold( final int currentThreshold ) { this.currentThreshold = currentThreshold; } public final synchronized void setThresholds( final int currentThreshold ) { this.currentThreshold = currentThreshold; for ( final Logger logger : activeLoggers.values() ) { logger.setThreshold( currentThreshold ); } } public static final int parseThreshold( final String text ) { if ( "DEBUG".equalsIgnoreCase( text ) ) { return Logger.LEVEL_DEBUG; } else if ( "INFO".equalsIgnoreCase( text ) ) { return Logger.LEVEL_INFO; } else if ( "WARN".equalsIgnoreCase( text ) ) { return Logger.LEVEL_WARN; } else if ( "ERROR".equalsIgnoreCase( text ) ) { return Logger.LEVEL_ERROR; } else if ( "FATAL".equalsIgnoreCase( text ) ) { return Logger.LEVEL_FATAL; } else if ( "DISABLED".equalsIgnoreCase( text ) ) { return Logger.LEVEL_DISABLED; } return Logger.LEVEL_DEBUG; } public final synchronized int getActiveLoggerCount() { return activeLoggers.size(); } // ---------------------------------------------------------------------- // Customizable methods // ---------------------------------------------------------------------- protected abstract Logger createLogger( String name ); } 000077500000000000000000000000001167051330000371765ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/logging/consoleConsoleLoggerManager.java000066400000000000000000000036041167051330000441010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/logging/console/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.logging.console; import org.codehaus.plexus.logging.AbstractLoggerManager; import org.codehaus.plexus.logging.BaseLoggerManager; import org.codehaus.plexus.logging.Logger; public final class ConsoleLoggerManager extends AbstractLoggerManager { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final Logger logger = new ConsoleLogger(); // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void setThreshold( final String threshold ) { logger.setThreshold( BaseLoggerManager.parseThreshold( threshold ) ); } public Logger getLoggerForComponent( final String role, final String hint ) { return logger; } public void returnComponentLogger( final String role, final String hint ) { // nothing to do } public int getThreshold() { return logger.getThreshold(); } public void setThreshold( final int currentThreshold ) { logger.setThreshold( currentThreshold ); } public void setThresholds( final int currentThreshold ) { logger.setThreshold( currentThreshold ); } public int getActiveLoggerCount() { return 0; } } 000077500000000000000000000000001167051330000364575ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/personality000077500000000000000000000000001167051330000377775ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/personality/plexus000077500000000000000000000000001167051330000417365ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle000077500000000000000000000000001167051330000430365ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phaseConfigurable.java000066400000000000000000000014231167051330000463010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; public interface Configurable { void configure( PlexusConfiguration configuration ) throws PlexusConfigurationException; } PlexusContainerLocator.java000066400000000000000000000044571167051330000503620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; import java.util.List; import java.util.Map; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; public final class PlexusContainerLocator implements ServiceLocator { private final PlexusContainer container; public PlexusContainerLocator( final PlexusContainer container ) { this.container = container; } public Object lookup( final String role ) throws ComponentLookupException { return container.lookup( role ); } public Object lookup( final String role, final String hint ) throws ComponentLookupException { return container.lookup( role, hint ); } public Map lookupMap( final String role ) throws ComponentLookupException { return container.lookupMap( role ); } public List lookupList( final String role ) throws ComponentLookupException { return container.lookupList( role ); } public void release( final Object component ) throws ComponentLifecycleException { container.release( component ); } public void releaseAll( final Map components ) throws ComponentLifecycleException { container.releaseAll( components ); } public void releaseAll( final List components ) throws ComponentLifecycleException { container.releaseAll( components ); } public boolean hasComponent( final String role ) { return container.hasComponent( role ); } public boolean hasComponent( final String role, final String hint ) { return container.hasComponent( role, hint ); } } ServiceLocator.java000066400000000000000000000026761167051330000466400ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; import java.util.List; import java.util.Map; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; public interface ServiceLocator { Object lookup( String role ) throws ComponentLookupException; Object lookup( String role, String hint ) throws ComponentLookupException; Map lookupMap( String role ) throws ComponentLookupException; List lookupList( String role ) throws ComponentLookupException; void release( Object component ) throws ComponentLifecycleException; void releaseAll( Map components ) throws ComponentLifecycleException; void releaseAll( List components ) throws ComponentLifecycleException; boolean hasComponent( String role ); boolean hasComponent( String role, String hint ); } Serviceable.java000066400000000000000000000011231167051330000461220ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; public interface Serviceable { void service( ServiceLocator locator ); } Suspendable.java000066400000000000000000000011171167051330000461460ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/******************************************************************************* * Copyright (c) 2010-2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.codehaus.plexus.personality.plexus.lifecycle.phase; public interface Suspendable { void suspend(); void resume(); } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/sonatype/000077500000000000000000000000001167051330000327145ustar00rootroot00000000000000000077500000000000000000000000001167051330000337315ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/sonatype/guice000077500000000000000000000000001167051330000352515ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/sonatype/guice/plexus000077500000000000000000000000001167051330000362115ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/sonatype/guice/plexus/shimPlexusSpaceModule.java000066400000000000000000000062021167051330000424560ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/sonatype/guice/plexus/shim/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.shim; import java.util.Map; import javax.inject.Inject; import javax.inject.Provider; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextMapAdapter; import org.codehaus.plexus.context.DefaultContext; import org.codehaus.plexus.logging.LoggerManager; import org.sonatype.guice.bean.reflect.ClassSpace; import org.sonatype.guice.plexus.binders.PlexusBeanManager; import org.sonatype.guice.plexus.binders.PlexusBindingModule; import org.sonatype.guice.plexus.binders.PlexusXmlBeanModule; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import org.sonatype.guice.plexus.config.PlexusBeanLocator; import org.sonatype.guice.plexus.config.PlexusBeanModule; import org.sonatype.guice.plexus.converters.PlexusXmlBeanConverter; import org.sonatype.guice.plexus.lifecycles.PlexusLifecycleManager; import org.sonatype.guice.plexus.locators.DefaultPlexusBeanLocator; import org.sonatype.inject.Parameters; import com.google.inject.Binder; import com.google.inject.Module; public final class PlexusSpaceModule implements Module { private final ClassSpace space; public PlexusSpaceModule( final ClassSpace space ) { this.space = space; } public void configure( final Binder binder ) { final Context context = new ParameterizedContext(); binder.bind( Context.class ).toInstance( context ); final Provider slf4jLoggerFactoryProvider = space.deferLoadClass( "org.slf4j.ILoggerFactory" ).asProvider(); binder.requestInjection( slf4jLoggerFactoryProvider ); binder.bind( PlexusBeanConverter.class ).to( PlexusXmlBeanConverter.class ); binder.bind( PlexusBeanLocator.class ).to( DefaultPlexusBeanLocator.class ); binder.bind( PlexusContainer.class ).to( PseudoPlexusContainer.class ); final PlexusBeanManager manager = new PlexusLifecycleManager( binder.getProvider( Context.class ), // binder.getProvider( LoggerManager.class ), // slf4jLoggerFactoryProvider ); // SLF4J (optional) binder.bind( PlexusBeanManager.class ).toInstance( manager ); final PlexusBeanModule xmlModule = new PlexusXmlBeanModule( space, new ContextMapAdapter( context ) ); binder.install( new PlexusBindingModule( manager, xmlModule ) ); } static final class ParameterizedContext extends DefaultContext { @Inject protected void setParameters( @Parameters final Map parameters ) { contextData.putAll( parameters ); } } } PseudoPlexusContainer.java000066400000000000000000000225211167051330000433610ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/java/org/sonatype/guice/plexus/shim/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.sonatype.guice.plexus.shim; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.context.Context; import org.sonatype.guice.bean.locators.EntryListAdapter; import org.sonatype.guice.bean.locators.EntryMapAdapter; import org.sonatype.guice.plexus.binders.PlexusBeanManager; import org.sonatype.guice.plexus.config.Hints; import org.sonatype.guice.plexus.config.PlexusBean; import org.sonatype.guice.plexus.config.PlexusBeanLocator; import com.google.inject.TypeLiteral; @Singleton @SuppressWarnings( { "unchecked", "rawtypes" } ) final class PseudoPlexusContainer implements PlexusContainer { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- final PlexusBeanLocator locator; final PlexusBeanManager manager; final Context context; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- @Inject PseudoPlexusContainer( final PlexusBeanLocator locator, final PlexusBeanManager manager, final Context context ) { this.locator = locator; this.manager = manager; this.context = context; } // ---------------------------------------------------------------------- // Context methods // ---------------------------------------------------------------------- public Context getContext() { return context; } // ---------------------------------------------------------------------- // Lookup methods // ---------------------------------------------------------------------- public Object lookup( final String role ) throws ComponentLookupException { return lookup( role, "" ); } public Object lookup( final String role, final String hint ) throws ComponentLookupException { return lookup( null, role, hint ); } public T lookup( final Class role ) throws ComponentLookupException { return lookup( role, "" ); } public T lookup( final Class role, final String hint ) throws ComponentLookupException { return lookup( role, null, hint ); } public T lookup( final Class type, final String role, final String hint ) throws ComponentLookupException { try { return locate( role, type, hint ).iterator().next().getValue(); } catch ( final RuntimeException e ) { throw new ComponentLookupException( e, null != role ? role : type.getName(), hint ); } } public List lookupList( final String role ) throws ComponentLookupException { return new EntryListAdapter( locate( role, null ) ); } public List lookupList( final Class role ) throws ComponentLookupException { return new EntryListAdapter( locate( null, role ) ); } public Map lookupMap( final String role ) throws ComponentLookupException { return new EntryMapAdapter( locate( role, null ) ); } public Map lookupMap( final Class role ) throws ComponentLookupException { return new EntryMapAdapter( locate( null, role ) ); } // ---------------------------------------------------------------------- // Query methods // ---------------------------------------------------------------------- public boolean hasComponent( final String role ) { return hasComponent( role, "" ); } public boolean hasComponent( final String role, final String hint ) { return hasComponent( null, role, hint ); } public boolean hasComponent( final Class role ) { return hasComponent( role, "" ); } public boolean hasComponent( final Class role, final String hint ) { return hasComponent( role, null, hint ); } public boolean hasComponent( final Class type, final String role, final String hint ) { return hasPlexusBeans( locate( role, type, hint ) ); } // ---------------------------------------------------------------------- // Component descriptor methods // ---------------------------------------------------------------------- public void addComponent( final Object component, final String role ) { throw new UnsupportedOperationException(); } public void addComponent( final T component, final Class role, final String hint ) { throw new UnsupportedOperationException(); } public void addComponentDescriptor( final ComponentDescriptor descriptor ) { throw new UnsupportedOperationException(); } public ComponentDescriptor getComponentDescriptor( final String role, final String hint ) { throw new UnsupportedOperationException(); } public ComponentDescriptor getComponentDescriptor( final Class type, final String role, final String hint ) { throw new UnsupportedOperationException(); } public List getComponentDescriptorList( final String role ) { throw new UnsupportedOperationException(); } public List> getComponentDescriptorList( final Class type, final String role ) { throw new UnsupportedOperationException(); } public Map getComponentDescriptorMap( final String role ) { throw new UnsupportedOperationException(); } public Map> getComponentDescriptorMap( final Class type, final String role ) { throw new UnsupportedOperationException(); } public List> discoverComponents( final ClassRealm realm ) { throw new UnsupportedOperationException(); } // ---------------------------------------------------------------------- // Class realm methods // ---------------------------------------------------------------------- public ClassRealm getContainerRealm() { throw new UnsupportedOperationException(); } public ClassRealm setLookupRealm( final ClassRealm realm ) { throw new UnsupportedOperationException(); } public ClassRealm getLookupRealm() { throw new UnsupportedOperationException(); } public ClassRealm createChildRealm( final String id ) { throw new UnsupportedOperationException(); } // ---------------------------------------------------------------------- // Shutdown methods // ---------------------------------------------------------------------- public void release( final Object component ) { manager.unmanage( component ); } public void releaseAll( final Map components ) { for ( final Object o : components.values() ) { release( o ); } } public void releaseAll( final List components ) { for ( final Object o : components ) { release( o ); } } public void dispose() { manager.unmanage(); } // ---------------------------------------------------------------------- // Implementation methods // ---------------------------------------------------------------------- private Iterable> locate( final String role, final Class type, final String... hints ) { final String[] canonicalHints = Hints.canonicalHints( hints ); if ( null == role || null != type && type.getName().equals( role ) ) { return locator.locate( TypeLiteral.get( type ), canonicalHints ); } try { final Class clazz = Thread.currentThread().getContextClassLoader().loadClass( role ); final Iterable beans = locator.locate( TypeLiteral.get( clazz ), canonicalHints ); if ( hasPlexusBeans( beans ) ) { return beans; } } catch ( final Exception e ) { // drop through... } catch ( final LinkageError e ) { // drop through... } return Collections.EMPTY_SET; } private static boolean hasPlexusBeans( final Iterable> beans ) { final Iterator> i = beans.iterator(); return i.hasNext() && i.next().getImplementationClass() != null; } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/resources/000077500000000000000000000000001167051330000313545ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/resources/META-INF/000077500000000000000000000000001167051330000325145ustar00rootroot00000000000000000077500000000000000000000000001167051330000337555ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/resources/META-INF/plexuscomponents.xml000066400000000000000000000011271167051330000366650ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/main/resources/META-INF/plexus org.codehaus.plexus.component.configurator.BasicComponentConfigurator org.codehaus.plexus.component.configurator.ComponentConfigurator basic org.codehaus.plexus.component.configurator.MapOrientedComponentConfigurator org.codehaus.plexus.component.configurator.ComponentConfigurator map-oriented sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/000077500000000000000000000000001167051330000273755ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/000077500000000000000000000000001167051330000303165ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/000077500000000000000000000000001167051330000311055ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/000077500000000000000000000000001167051330000327005ustar00rootroot00000000000000000077500000000000000000000000001167051330000341415ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexusDefaultComponentLookupManagerTest.java000066400000000000000000000021311167051330000435750ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexuspackage org.codehaus.plexus; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.test.ComponentA; /** * @author Trygve Laugstøl * @version $Id: DefaultComponentLookupManagerTest.java 7828 2008-11-14 22:07:56Z dain $ */ public class DefaultComponentLookupManagerTest extends PlexusTestCase { public void testLookupsWithAndWithoutRoleHint() throws Exception { final String resource = getConfigurationName( "components.xml" ); System.out.println( "resource = " + resource ); assertNotNull( resource ); final ContainerConfiguration c = new DefaultContainerConfiguration().setName( "test" ).setContainerConfiguration( resource ); final DefaultPlexusContainer container = new DefaultPlexusContainer( c ); try { container.lookup( ComponentA.class ); fail( "Expected exception" ); } catch ( final ComponentLookupException e ) { // expected } } } DyanamicComponentKungFuTest.java000066400000000000000000000063541167051330000424040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexuspackage org.codehaus.plexus; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import junit.framework.TestCase; /** * This is the start of the sketch which outlines some of the things I would like to do with components during runtime. * * @author Jason van Zyl * @version $Id: DyanamicComponentKungFuTest.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DyanamicComponentKungFuTest extends TestCase { /** * Component additions during container operation. 1. Add a component at runtime -> Additions could be made by * specifying an URL which will be compatible with Wagon and specifically Maven's way of using Wagon. 2. Configure * the dynamically added component -> We need to be able to deal with different flavours of components but we can * focus on Plexus components to start with. But some components may have meta information and some may not like * pico components. But one of the first flavours I want to support is phoenix components because I specifically * need the FTP server. 3. Let the component perform its role 4. Suspend the component a) Define the criteria for * which we can suspend a component -> When there are no client connections? -> Even when there are no connections * and a client tries to obtain a connection what do we do? -> If we are in desperate need to suspend the component, * say for urgent security requirement, and clients simply won't bugger off what do we do? 5. Reconfigure the * component 6. Resume the component 7. Let the component perform its role 8. Release the component */ public void testAdditionOfComponentDuringContainerOperation() throws Exception { } /** * Component replacement during container operation. This will force the design of a mechanism where the components * communicate with one another via a connector. In order for components to be replaced dynamically the components * cannot be directly coupled to one another. How to decide if a component is a suitable replacement given the * versions of the specifications of the component and any required components if the component is a composite * component. Definitely need to simulate the connection (a MockConnection) during runtime to make sure that in the * event something goes wrong the container can just refuse to allow the component substitution. This shouldn't be * trial and error but until much field testing has occurred I'm sure there will be instances where miscalculations * happen simply due to lack of experience and usage with dynamic component replacement. */ public void testComponentReplacementDuringContainerOperation() throws Exception { } } PlexusTestCaseTest.java000066400000000000000000000061151167051330000405630ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexuspackage org.codehaus.plexus; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.io.File; import junit.framework.TestCase; import org.codehaus.plexus.component.discovery.DiscoveredComponent; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.test.DefaultLoadOnStartService; /** * @author Jason van Zyl * @version $Id: PlexusTestCaseTest.java 7828 2008-11-14 22:07:56Z dain $ */ public class PlexusTestCaseTest extends TestCase { private String basedir; @Override public void setUp() { basedir = System.getProperty( "basedir" ); if ( basedir == null ) { basedir = new File( "." ).getAbsolutePath(); } } public void testPlexusTestCase() throws Exception { final PlexusTestCase tc = new PlexusTestCase() { }; tc.setUp(); try { tc.lookup( DiscoveredComponent.class, "unknown" ); fail( "Expected ComponentLookupException." ); } catch ( final ComponentLookupException ex ) { assertTrue( true ); } // This component is discovered from src/test/META-INF/plexus/components.xml final DiscoveredComponent component = tc.lookup( DiscoveredComponent.class ); assertNotNull( component ); assertNotNull( tc.getClassLoader() ); tc.tearDown(); } public void testLoadOnStartComponents() throws Exception { final PlexusTestCase tc = new PlexusTestCase() { @Override protected String getCustomConfigurationName() { return PlexusTestCase.getTestConfiguration( getClass() ); } }; tc.setupContainer(); // Assert that the load on start component has started. assertTrue( "The load on start components haven't been started.", DefaultLoadOnStartService.isStarted ); tc.tearDown(); } public void testGetFile() { File file = PlexusTestCase.getTestFile( "pom.xml" ); assertTrue( file.exists() ); file = PlexusTestCase.getTestFile( basedir, "pom.xml" ); assertTrue( file.exists() ); } public void testGetPath() { File file = new File( PlexusTestCase.getTestPath( "pom.xml" ) ); assertTrue( file.exists() ); file = new File( PlexusTestCase.getTestPath( basedir, "pom.xml" ) ); assertTrue( file.exists() ); } } 000077500000000000000000000000001167051330000361435ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/componentPlexusTestCaseTest.java000066400000000000000000000014201167051330000425570ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/componentpackage org.codehaus.plexus.component; import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; public class PlexusTestCaseTest extends PlexusTestCase { private static final String CUSTOM_PROPERTY = "custom.property"; private static final String CUSTOM_VALUE = "custom.value"; @Override protected void customizeContext( final Context context ) { super.customizeContext( context ); context.put( CUSTOM_PROPERTY, CUSTOM_VALUE ); } public void testCustomizeContext() throws ContextException { final String value = (String) getContainer().getContext().get( CUSTOM_PROPERTY ); assertEquals( CUSTOM_VALUE, value ); } } TestMapOrientedComponent.java000066400000000000000000000025701167051330000437440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/componentpackage org.codehaus.plexus.component; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.util.Map; import java.util.TreeMap; import org.codehaus.plexus.component.repository.ComponentRequirement; public class TestMapOrientedComponent implements MapOrientedComponent { public static final String ROLE = TestMapOrientedComponent.class.getName(); private final Map context = new TreeMap(); public void addComponentRequirement( final ComponentRequirement requirementDescriptor, final Object requirementValue ) { context.put( requirementDescriptor.getFieldName(), requirementValue ); } public void setComponentConfiguration( final Map componentConfiguration ) { context.putAll( componentConfiguration ); } public Map getContext() { return context; } } 000077500000000000000000000000001167051330000405065ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionAbstractComponent.java000066400000000000000000000016611167051330000450030ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: AbstractComponent.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class AbstractComponent implements Component { private ComponentA componentA; public ComponentA getComponentA() { return componentA; } } Component.java000066400000000000000000000014331167051330000433140ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: Component.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface Component { } ComponentA.java000066400000000000000000000015541167051330000434210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ComponentA.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface ComponentA { String ROLE = ComponentA.class.getName(); ComponentB getComponentB(); } ComponentB.java000066400000000000000000000014761167051330000434250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ComponentB.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface ComponentB { ComponentC getComponentC(); } ComponentC.java000066400000000000000000000014351167051330000434210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ComponentC.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface ComponentC { } ComponentD.java000066400000000000000000000014351167051330000434220ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ComponentD.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface ComponentD { } ComponentE.java000066400000000000000000000014351167051330000434230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ComponentE.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface ComponentE { } ComponentF.java000066400000000000000000000036661167051330000434340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.util.List; import java.util.Map; /** * @author Michal Maczka * @version $Id: ComponentF.java 4779 2006-11-23 04:09:31Z jvanzyl $ */ public class ComponentF { private ComponentA componentA; private ComponentB componentB; private ComponentC[] componentC; private List componentD; private Map componentE; public ComponentA getComponentA() { return componentA; } public void setComponentA( final ComponentA componentA ) { this.componentA = componentA; } public ComponentB getComponentB() { return componentB; } public void setComponentB( final ComponentB componentB ) { this.componentB = componentB; } public ComponentC[] getComponentC() { return componentC; } public void setComponentC( final ComponentC[] componentC ) { this.componentC = componentC; } public List getComponentD() { return componentD; } public void setComponentD( final List componentD ) { this.componentD = componentD; } public Map getComponentE() { return componentE; } public void setComponentE( final Map componentE ) { this.componentE = componentE; } } ComponentRealmCompositionTest.java000066400000000000000000000142051167051330000473620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; import static org.codehaus.plexus.PlexusConstants.PLEXUS_DEFAULT_HINT; import java.io.File; import java.net.URL; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.classworlds.realm.ClassRealm; /** @author Jason van Zyl */ public class ComponentRealmCompositionTest extends PlexusTestCase { // // Component archives // private static final String PLUGIN_0_JAR = "src/test/test-components/plugin0-1.0-SNAPSHOT.jar"; private static final String PLUGIN_1_JAR = "src/test/test-components/plugin1-1.0-SNAPSHOT.jar"; private static final String COMPONENT_A_JAR = "src/test/test-components/component-a-1.0-SNAPSHOT.jar"; private static final String COMPONENT_B_JAR = "src/test/test-components/component-b-1.0-SNAPSHOT.jar"; private static final String COMPONENT_C_JAR = "src/test/test-components/component-c-1.0-SNAPSHOT.jar"; private static final String ARCHIVER_JAR = "src/test/test-components/plexus-archiver-1.0-alpha-8.jar"; // // Component roles // private static final String PLUGIN_0_ROLE = "org.codehaus.plexus.plugins.Plugin0"; private static final String PLUGIN_1_ROLE = "org.codehaus.plexus.plugins.Plugin1"; // // Component realms // private static final String PLUGIN_0_REALM = "plugin0Realm"; private static final String PLUGIN_1_REALM = "plugin1Realm"; @Override protected void setUp() throws Exception { super.setUp(); // Create ClassRealm plugin0 with plugin0 -> A, plugin0 -> B createClassRealm( PLUGIN_0_REALM, PLUGIN_0_JAR, COMPONENT_A_JAR, COMPONENT_B_JAR, ARCHIVER_JAR ); // Create ClassRealm plugin1 with plugin1 -> A, plugin1 -> C createClassRealm( PLUGIN_1_REALM, PLUGIN_1_JAR, COMPONENT_A_JAR, COMPONENT_C_JAR, ARCHIVER_JAR ); } /* * We are testing that when the same component implementation exists in more then one realm and components depend on * those implementations, that the right realm is used to wire up the components. An example of this in practice are * Maven plugins where each plugin is loaded into a separate realm and the plugin may have dependencies on other * components. We want to make sure that a requirement, say a JarArchiver, for a given component, say the * maven-jar-plugin, is wired up with a JarArchiver taken from the same realm as the maven-jar-plugin and not a * different realm. */ public void testCompositionWhereTheSameImplementationExistsInDifferentRealms() throws Exception { // Plugin0 getContainer().lookup( PLUGIN_0_ROLE ); // Plugin1 getContainer().lookup( PLUGIN_1_ROLE ); // Plugin0(alt) getContainer().lookup( PLUGIN_0_ROLE, "alt" ); // Plugin1(alt) getContainer().lookup( PLUGIN_1_ROLE, "alt" ); } public void testThatASingletonComponentIntheCoreRealmWhenLookedUpInComponentRealmsYieldsTheSameInstance() throws Exception { } public void testMultiRealmLookupMap() throws Exception { final Map plugin0Map = getContainer().lookupMap( PLUGIN_0_ROLE ); assertNotNull( "plugin0Map is null", plugin0Map ); assertNotNull( "plugin0Map does not contain a DefaultPlugin0", plugin0Map.get( PLEXUS_DEFAULT_HINT ) ); assertNotNull( "plugin0Map does not contain a AltPlugin0", plugin0Map.get( "alt" ) ); assertEquals( "Expected only 2 components in plugin0Map", 2, plugin0Map.size() ); final Map plugin1Map = getContainer().lookupMap( PLUGIN_1_ROLE ); assertNotNull( "plugin1Map is null", plugin1Map ); assertNotNull( "plugin1Map does not contain a DefaultPlugin1", plugin1Map.get( PLEXUS_DEFAULT_HINT ) ); assertNotNull( "plugin1Map does not contain a AltPlugin1", plugin1Map.get( "alt" ) ); assertEquals( "Expected only 2 components in plugin1Map", 2, plugin1Map.size() ); } public void testMultiRealmLookupList() throws Exception { final List plugin0List = getContainer().lookupList( PLUGIN_0_ROLE ); assertNotNull( "plugin0List is null", plugin0List ); final Map plugin0Map = mapByClassSimpleName( plugin0List ); assertNotNull( "plugin0List does not contain a DefaultPlugin0", plugin0Map.get( "DefaultPlugin0" ) ); assertNotNull( "plugin0List does not contain a AltPlugin0", plugin0Map.get( "AltPlugin0" ) ); assertEquals( "Expected only 2 components in plugin0Map", 2, plugin0Map.size() ); final List plugin1List = getContainer().lookupList( PLUGIN_1_ROLE ); assertNotNull( "plugin1List is null", plugin1List ); final Map plugin1Map = mapByClassSimpleName( plugin1List ); assertNotNull( "plugin1List does not contain a DefaultPlugin1", plugin1Map.get( "DefaultPlugin1" ) ); assertNotNull( "plugin1List does not contain a AltPlugin1", plugin1Map.get( "AltPlugin1" ) ); assertEquals( "Expected only 2 components in plugin0Map", 2, plugin1Map.size() ); } private ClassRealm createClassRealm( final String id, final String... jars ) throws Exception { // create the realm final ClassRealm classRealm = getContainer().createChildRealm( id ); // populate the realm for ( final String jar : jars ) { final File file = new File( jar ); assertTrue( jar + " is not a file", file.isFile() ); final URL url = file.toURI().toURL(); classRealm.addURL( url ); } // descover all component definitions in the realm and register them with the repository getContainer().discoverComponents( classRealm ); return classRealm; } private Map mapByClassSimpleName( final List objects ) { final Map map = new TreeMap(); for ( final Object object : objects ) { map.put( object.getClass().getSimpleName(), object ); } return map; } } ComponentWithSeveralFieldsOfTheSameType.java000066400000000000000000000020731167051330000512200ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Trygve Laugstøl * @version $Id: ComponentWithSeveralFieldsOfTheSameType.java 4779 2006-11-23 04:09:31Z jvanzyl $ */ public class ComponentWithSeveralFieldsOfTheSameType { private ComponentE one; private ComponentE two; public ComponentE getOne() { return one; } public ComponentE getTwo() { return two; } } DefaultComponent.java000066400000000000000000000015031167051330000446170ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: DefaultComponent.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultComponent extends AbstractComponent { } DefaultComponentA.java000066400000000000000000000017721167051330000447300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: DefaultComponentA.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultComponentA implements ComponentA { private ComponentB componentB; // Just so we can retrieve the value of componentB for testing. */ public ComponentB getComponentB() { return componentB; } } DefaultComponentB.java000066400000000000000000000021451167051330000447240ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: DefaultComponentB.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultComponentB implements ComponentB { private ComponentC componentC; public ComponentC getComponentC() { return componentC; } public void setComponentC( final ComponentC componentC ) { System.out.println( "Setting componentC:" + componentC ); this.componentC = componentC; } } DefaultComponentC.java000066400000000000000000000015011167051330000447200ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: DefaultComponentC.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultComponentC implements ComponentC { } DefaultComponentComposerManagerTest.java000066400000000000000000000027111167051330000504640ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/compositionpackage org.codehaus.plexus.component.composition; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.PlexusTestCase; /** * @author Michal Maczka * @version $Id: DefaultComponentComposerManagerTest.java 7828 2008-11-14 22:07:56Z dain $ */ public class DefaultComponentComposerManagerTest extends PlexusTestCase { @Override protected String getCustomConfigurationName() { return "org/codehaus/plexus/component/composition/components.xml"; } public void testComposition() throws Exception { final ComponentA componentA = lookup( ComponentA.class ); assertNotNull( componentA ); final ComponentB componentB = componentA.getComponentB(); assertNotNull( componentB ); final ComponentC componentC = componentB.getComponentC(); assertNotNull( componentC ); } } 000077500000000000000000000000001167051330000406455ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorAbstractComponent.java000066400000000000000000000026521167051330000451430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * @author Jason van Zyl * @version $Id: AbstractComponent.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class AbstractComponent implements Component { private String name; public String getName() { return name; } } AbstractComponentConfiguratorTest.java000066400000000000000000001135151167051330000503670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import static org.junit.Assert.assertArrayEquals; import java.io.File; import java.io.StringReader; import java.lang.annotation.ElementType; import java.net.URI; import java.net.URL; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Vector; import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.configurator.expression.DefaultExpressionEvaluator; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.io.PlexusTools; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; /** * @author Michal Maczka * @version $Id: AbstractComponentConfiguratorTest.java 8622 2010-01-30 18:56:56Z bentmann $ */ public abstract class AbstractComponentConfiguratorTest extends PlexusTestCase { protected void configureComponent( final Object component, final PlexusConfiguration configuration ) throws Exception { configureComponent( component, configuration, new DefaultExpressionEvaluator() ); } protected void configureComponent( final Object component, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator ) throws Exception { final ComponentDescriptor descriptor = new ComponentDescriptor(); descriptor.setRole( "role" ); descriptor.setImplementation( component.getClass().getName() ); descriptor.setConfiguration( configuration ); final ClassWorld classWorld = new ClassWorld(); final ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); configureComponent( component, descriptor, realm, expressionEvaluator ); } protected void configureComponent( final Object component, final ComponentDescriptor descriptor, final ClassRealm realm ) throws Exception { final ComponentConfigurator cc = getComponentConfigurator(); cc.configureComponent( component, descriptor.getConfiguration(), realm ); } protected void configureComponent( final Object component, final ComponentDescriptor descriptor, final ClassRealm realm, final ExpressionEvaluator expressionEvaluator ) throws Exception { final ComponentConfigurator cc = getComponentConfigurator(); cc.configureComponent( component, descriptor.getConfiguration(), expressionEvaluator, realm ); } protected abstract ComponentConfigurator getComponentConfigurator() throws Exception; public void testComponentConfigurator() throws Exception { final String xml = "" + " true" + " 64" + " -128" + " -1" + " 1" + " 2" + " 3" + " X" + " foo" + " test.txt" + " http://www.apache.org/" + " http://maven.apache.org/" + " " + " jason" + " tess" + " " + " " + " jason" + " " + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ConfigurableComponent component = new ConfigurableComponent(); configureComponent( component, configuration ); assertEquals( "check boolean value", true, component.getBooleanValue() ); assertEquals( "check byte value", 64, component.getByteValue() ); assertEquals( "check short value", -128, component.getShortValue() ); assertEquals( "check integer value", -1, component.getIntValue() ); assertEquals( "check float value", 1.0f, component.getFloatValue(), 0.001f ); assertEquals( "check long value", 2L, component.getLongValue() ); assertEquals( "check double value", 3.0, component.getDoubleValue(), 0.001 ); assertEquals( 'X', component.getCharValue() ); assertEquals( "foo", component.getStringValue() ); assertEquals( new File( "test.txt" ), component.getFileValue() ); assertEquals( new URI( "http://www.apache.org/" ), component.getUriValue() ); assertEquals( new URL( "http://maven.apache.org/" ), component.getUrlValue() ); final List list = component.getImportantThings(); assertEquals( 2, list.size() ); assertEquals( "jason", ( (ImportantThing) list.get( 0 ) ).getName() ); assertEquals( "tess", ( (ImportantThing) list.get( 1 ) ).getName() ); // Embedded Configuration final PlexusConfiguration c = component.getConfiguration(); assertEquals( "jason", c.getChild( "name" ).getValue() ); } public void testComponentConfiguratorWithAComponentThatProvidesSettersForConfiguration() throws Exception { final String xml = "" + " 0" + " 1" + " 2" + " 3" + " foo" + " " + " jason" + " tess" + " " + " " + " jason" + " " + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithSetters component = new ComponentWithSetters(); configureComponent( component, configuration ); assertEquals( "check integer value", 0, component.getIntValue() ); assertTrue( component.intValueSet ); assertEquals( "check float value", 1.0f, component.getFloatValue(), 0.001f ); assertTrue( component.floatValueSet ); assertEquals( "check long value", 2L, component.getLongValue() ); assertTrue( component.longValueSet ); assertEquals( "check double value", 3.0, component.getDoubleValue(), 0.001 ); assertTrue( component.doubleValueSet ); assertEquals( "foo", component.getStringValue() ); assertTrue( component.stringValueSet ); final List list = component.getImportantThings(); assertEquals( 2, list.size() ); assertEquals( "jason", ( (ImportantThing) list.get( 0 ) ).getName() ); assertEquals( "tess", ( (ImportantThing) list.get( 1 ) ).getName() ); assertTrue( component.importantThingsValueSet ); // Embedded Configuration final PlexusConfiguration c = component.getConfiguration(); assertEquals( "jason", c.getChild( "name" ).getValue() ); assertTrue( component.configurationValueSet ); } public void testComponentConfigurationWhereFieldsToConfigureResideInTheSuperclass() throws Exception { final String xml = "" + " jason" + "
bollywood
" + "
"; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final DefaultComponent component = new DefaultComponent(); configureComponent( component, configuration ); assertEquals( "jason", component.getName() ); assertEquals( "bollywood", component.getAddress() ); } public void testComponentConfigurationWhereFieldsAreCollections() throws Exception { final String xml = "" + " " + " " + " life" + " " + " " + " " + " " + " life" + " " + " " + " " + " " + " life" + " " + " " + " " + " abc" + " def" + " " + " abc" + " abc" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithCollectionFields component = new ComponentWithCollectionFields(); configureComponent( component, configuration ); final Vector vector = component.getVector(); assertEquals( "life", ( (ImportantThing) vector.get( 0 ) ).getName() ); assertEquals( 1, vector.size() ); Set set = component.getHashSet(); assertEquals( 1, set.size() ); final Object[] setContents = set.toArray(); assertEquals( "life", ( (ImportantThing) setContents[0] ).getName() ); final List list = component.getList(); assertEquals( list.getClass(), LinkedList.class ); assertEquals( "life", ( (ImportantThing) list.get( 0 ) ).getName() ); assertEquals( 1, list.size() ); final List stringList = component.getStringList(); assertEquals( "abc", (String) stringList.get( 0 ) ); assertEquals( "def", (String) stringList.get( 1 ) ); assertEquals( 2, stringList.size() ); set = component.getSet(); assertEquals( 1, set.size() ); set = component.getSortedSet(); assertEquals( 1, set.size() ); } public void testComponentConfigurationWhereFieldsAreGenericCollections() throws Exception { final String xml = "" + "" + " 12" + " 34" + "" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithCollectionFields component = new ComponentWithCollectionFields(); configureComponent( component, configuration ); final List intList = component.getIntList(); assertEquals( 2, intList.size() ); assertEquals( Integer.class, intList.get( 0 ).getClass() ); assertEquals( new Integer( 12 ), intList.get( 0 ) ); assertEquals( new Integer( 34 ), intList.get( 1 ) ); } public void testComponentConfigurationWhereFieldsAreArrays() throws Exception { final String xml = "" + " " + " value1" + " value2" + " " + " " + " 42" + " 69" + " " + " " + " Hello" + " World!" + " " + " " + " some string" + " something important" + " 303" + " " + " " + " http://foo.com/bar" + " file://localhost/c:/windows" + " " + " " + " c:/windows" + " /usr/local/bin/foo.sh" + " " + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithArrayFields component = new ComponentWithArrayFields(); configureComponent( component, configuration ); final String[] stringArray = component.getStringArray(); assertEquals( 2, stringArray.length ); assertEquals( "value1", stringArray[0] ); assertEquals( "value2", stringArray[1] ); final Integer[] integerArray = component.getIntegerArray(); assertEquals( 2, integerArray.length ); assertEquals( new Integer( 42 ), integerArray[0] ); assertEquals( new Integer( 69 ), integerArray[1] ); final ImportantThing[] importantThingArray = component.getImportantThingArray(); assertEquals( 2, importantThingArray.length ); assertEquals( "Hello", importantThingArray[0].getName() ); assertEquals( "World!", importantThingArray[1].getName() ); final Object[] objectArray = component.getObjectArray(); assertEquals( 3, objectArray.length ); assertEquals( "some string", objectArray[0] ); assertEquals( "something important", ( (ImportantThing) objectArray[1] ).getName() ); assertEquals( new Integer( 303 ), objectArray[2] ); final URL[] urls = component.getUrlArray(); assertEquals( new URL( "http://foo.com/bar" ), urls[0] ); assertEquals( new URL( "file://localhost/c:/windows" ), urls[1] ); final File[] files = component.getFileArray(); assertEquals( new File( "c:/windows" ), files[0] ); assertEquals( new File( "/usr/local/bin/foo.sh" ), files[1] ); } public void testComponentConfigurationWithCompositeFields() throws Exception { final String xml = "" + " " + " I am not abstract!" + " " + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithCompositeFields component = new ComponentWithCompositeFields(); configureComponent( component, configuration ); assertNotNull( component.getThing() ); assertEquals( "I am not abstract!", component.getThing().getName() ); } public void testInvalidComponentConfiguration() throws Exception { final String xml = "theName"; try { PlexusTools.buildConfiguration( "", new StringReader( xml ) ); fail( "Should have caused an error because of the invalid XML." ); } catch ( final PlexusConfigurationException e ) { // Error should be caught here. } catch ( final Exception e ) { fail( "Should have caught the invalid plexus configuration exception." ); } } public void testComponentConfigurationWithPropertiesFields() throws Exception { final String xml = "" + " " + " " + " firstname" + " michal" + " " + " " + " lastname" + " maczka" + " " + " " + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithPropertiesField component = new ComponentWithPropertiesField(); configureComponent( component, configuration ); final Properties properties = component.getSomeProperties(); assertNotNull( properties ); assertEquals( "michal", properties.get( "firstname" ) ); assertEquals( "maczka", properties.get( "lastname" ) ); } public void testComponentConfigurationWithPropertiesFieldsUsingMapStyleConfig() throws Exception { final String xml = "" + " " + "val1" + "val2" + " " + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithPropertiesField component = new ComponentWithPropertiesField(); configureComponent( component, configuration ); final Properties properties = component.getSomeProperties(); assertNotNull( properties ); assertEquals( "val1", properties.get( "key1" ) ); assertEquals( "val2", properties.get( "key2" ) ); } public void testComponentConfigurationWithPropertiesFieldsWithExpression() throws Exception { final String xml = "" + " ${injectedProperties} " + ""; final Properties propertiesInterpolated = new Properties(); propertiesInterpolated.put( "firstname", "olivier" ); propertiesInterpolated.put( "lastname", "lamy" ); final ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator() { public Object evaluate( final String expression ) { return propertiesInterpolated; } public File alignToBaseDirectory( final File file ) { return null; } }; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithPropertiesField component = new ComponentWithPropertiesField(); configureComponent( component, configuration, expressionEvaluator ); final Properties properties = component.getSomeProperties(); assertNotNull( properties ); assertEquals( "olivier", properties.get( "firstname" ) ); assertEquals( "lamy", properties.get( "lastname" ) ); } public void testComponentConfigurationWithPropertiesFieldsWithExpressions() throws Exception { final String xml = "" + "" // + "${theName}${theValue}" // + "empty" // + "" + ""; final Properties values = new Properties(); values.put( "${theName}", "test" ); values.put( "${theValue}", "PASSED" ); final ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator() { public Object evaluate( final String expression ) { return values.containsKey( expression ) ? values.get( expression ) : expression; } public File alignToBaseDirectory( final File file ) { return null; } }; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithPropertiesField component = new ComponentWithPropertiesField(); configureComponent( component, configuration, expressionEvaluator ); final Properties properties = component.getSomeProperties(); assertNotNull( properties ); assertEquals( "PASSED", properties.get( "test" ) ); assertEquals( "", properties.get( "empty" ) ); } public void testComponentConfigurationWithMapField() throws Exception { final String xml = "" + " " + " Kenney" + " Westerhof" + " " + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithMapField component = new ComponentWithMapField(); configureComponent( component, configuration ); final Map map = component.getMap(); assertNotNull( map ); assertEquals( "Kenney", map.get( "firstName" ) ); assertEquals( "Westerhof", map.get( "lastName" ) ); } public void testComponentConfigurationWithMapFieldUsingCustomImplClass() throws Exception { final String xml = "" + " " + "value" + " " + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithMapField component = new ComponentWithMapField(); configureComponent( component, configuration ); final Map map = component.getMap(); assertNotNull( map ); assertEquals( Properties.class, map.getClass() ); assertEquals( "value", map.get( "key" ) ); } public void testComponentConfigurationWhereFieldIsBadArray() throws Exception { final String xml = "" // + " string" // + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithArrayFields component = new ComponentWithArrayFields(); try { configureComponent( component, configuration ); fail( "Configuration did not fail" ); } catch ( final ComponentConfigurationException e ) { // expected e.printStackTrace(); } } public void testComponentConfigurationWhereFieldIsEnum() throws Exception { final String xml = "" // + " TYPE" // + " ONE" // + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithEnumFields component = new ComponentWithEnumFields(); configureComponent( component, configuration ); assertEquals( ElementType.TYPE, component.getSimpleEnum() ); assertEquals( ComponentWithEnumFields.NestedEnum.ONE, component.getNestedEnum() ); } public void testComponentConfigurationWithAmbiguousExpressionValue() throws Exception { final String xml = "" // + "
${address}
" // + "
"; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final DefaultComponent component = new DefaultComponent(); final ExpressionEvaluator expressionEvaluator = new TypeAwareExpressionEvaluator() { public Object evaluate( final String expression ) throws ExpressionEvaluationException { return evaluate( expression, null ); } public File alignToBaseDirectory( final File file ) { return null; } public Object evaluate( final String expression, final Class type ) throws ExpressionEvaluationException { if ( String.class == type ) { return "PASSED"; } else { return Boolean.FALSE; } } }; configureComponent( component, configuration, expressionEvaluator ); assertEquals( "PASSED", component.getAddress() ); } public void testComponentConfigurationWithPrimitiveValueConversion() throws Exception { final String xml = "" // + " ${primitive}" // + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ConfigurableComponent component = new ConfigurableComponent(); final ExpressionEvaluator expressionEvaluator = new TypeAwareExpressionEvaluator() { public Object evaluate( final String expression ) throws ExpressionEvaluationException { return evaluate( expression, null ); } public File alignToBaseDirectory( final File file ) { return null; } public Object evaluate( final String expression, final Class type ) throws ExpressionEvaluationException { // java.lang.Short -> short -> int return new Short( (short) 23 ); } }; configureComponent( component, configuration, expressionEvaluator ); assertEquals( 23, component.getIntValue() ); } public void testComponentConfigurationWithEmptyContentForBasicField() throws Exception { final String xml = "" // + "
" // + "
"; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final DefaultComponent component = new DefaultComponent(); configureComponent( component, configuration ); assertEquals( null, component.getAddress() ); } public void testComponentConfigurationWithEmptyContentForCompositeField() throws Exception { final String xml = "" // + " " // + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithCompositeFields component = new ComponentWithCompositeFields(); configureComponent( component, configuration ); assertNotNull( component.getBean() ); } public void testComponentConfigurationWithUnresolvedExpressionContentForCompositeFieldOfNonInstantiatableType() throws Exception { final String xml = "" // + " ${null-valued-expression}" // + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithCompositeFields component = new ComponentWithCompositeFields(); final ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator() { public Object evaluate( final String expression ) throws ExpressionEvaluationException { return null; } public File alignToBaseDirectory( final File file ) { return null; } }; configureComponent( component, configuration, expressionEvaluator ); assertEquals( null, component.getThing() ); } public void testComponentConfiguratorFileNormalizesSeparator() throws Exception { final String xml = "" + " dir/test.txt" + " dir\\test.txt" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithArrayFields component = new ComponentWithArrayFields(); configureComponent( component, configuration ); assertEquals( new File( "dir", "test.txt" ), component.getFileArray()[0] ); assertEquals( new File( "dir", "test.txt" ), component.getFileArray()[1] ); } public void testComponentConfiguratorDecodesHexNumbers() throws Exception { final String xml = "" + " 0x40" + " -0X10" + " #20" + " 0x200000000" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ConfigurableComponent component = new ConfigurableComponent(); configureComponent( component, configuration ); assertEquals( "check byte value", 64, component.getByteValue() ); assertEquals( "check short value", -16, component.getShortValue() ); assertEquals( "check integer value", 32, component.getIntValue() ); assertEquals( "check long value", 8589934592L, component.getLongValue() ); } public void testComponentConfiguratorDecodesOctalNumbers() throws Exception { final String xml = "" + " 040" + " -010" + " 020" + " 0100000000000" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ConfigurableComponent component = new ConfigurableComponent(); configureComponent( component, configuration ); assertEquals( "check byte value", 32, component.getByteValue() ); assertEquals( "check short value", -8, component.getShortValue() ); assertEquals( "check integer value", 16, component.getIntValue() ); assertEquals( "check long value", 8589934592L, component.getLongValue() ); } public void testComponentConfiguratorCollectionInlined() throws Exception { final String xml = "" + "a" + "1" + "b" + "true" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithInlinedCollection component = new ComponentWithInlinedCollection(); configureComponent( component, configuration ); assertEquals( Arrays. asList( "a", Integer.valueOf( 1 ), "b", Boolean.TRUE ), component.getItems() ); } public void testComponentConfigurationWhereCollectionIsConfiguredWithInterfaceImpl() throws Exception { final String xml = "" + "" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithCollectionFields component = new ComponentWithCollectionFields(); configureComponent( component, configuration ); assertNotNull( component.getList() ); assertEquals( 0, component.getList().size() ); } public void testComponentConfigurationWhereUserOnlySetsThePrimaryBeanProperty() throws Exception { final String xml = "" + "dir/test.txt" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithDefaultProperty component = new ComponentWithDefaultProperty(); configureComponent( component, configuration ); assertEquals( 1, component.beans.length ); assertEquals( new File( "dir", "test.txt" ), component.beans[0].getFile() ); } public void testComponentConfigurationWhereArrayIsConfiguredFromCollectionExpression() throws Exception { final String xml = "" + "${collection}" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithArrayFields component = new ComponentWithArrayFields(); final ExpressionEvaluator evaluator = new DefaultExpressionEvaluator() { public Object evaluate( final String expression ) { if ( "${collection}".equals( expression ) ) { return Arrays.asList( "0", "1", "2" ); } return super.evaluate( expression ); } }; configureComponent( component, configuration, evaluator ); assertNotNull( component.getStringArray() ); assertArrayEquals( new String[] { "0", "1", "2" }, component.getStringArray() ); } public void testComponentConfigurationWhereCollectionIsConfiguredFromArrayExpression() throws Exception { final String xml = "" + "${array}" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithCollectionFields component = new ComponentWithCollectionFields(); final ExpressionEvaluator evaluator = new DefaultExpressionEvaluator() { public Object evaluate( final String expression ) { if ( "${array}".equals( expression ) ) { return new String[] { "0", "1", "2" }; } return super.evaluate( expression ); } }; configureComponent( component, configuration, evaluator ); assertNotNull( component.getList() ); assertEquals( Arrays.asList( "0", "1", "2" ), component.getList() ); } public void testComponentConfigurationWhereArrayIsConfiguredFromCommaSeparatedStringExpression() throws Exception { final String xml = "" + "${arr0}" + "${arr1}" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithArrayFields component = new ComponentWithArrayFields(); final ExpressionEvaluator evaluator = new DefaultExpressionEvaluator() { public Object evaluate( final String expression ) { if ( "${arr0}".equals( expression ) ) { return " 1 ,,"; } else if ( "${arr1}".equals( expression ) ) { return ""; } return super.evaluate( expression ); } }; configureComponent( component, configuration, evaluator ); assertNotNull( component.getStringArray() ); assertArrayEquals( new String[] { " 1 ", null, null }, component.getStringArray() ); assertNotNull( component.getObjectArray() ); assertEquals( 0, component.getObjectArray().length ); } public void testComponentConfigurationWhereCollectionIsConfiguredFromCommaSeparatedStringExpression() throws Exception { final String xml = "" + "${list}" + "${set}" + ""; final PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); final ComponentWithCollectionFields component = new ComponentWithCollectionFields(); final ExpressionEvaluator evaluator = new DefaultExpressionEvaluator() { public Object evaluate( final String expression ) { if ( "${list}".equals( expression ) ) { return " 1 ,,"; } else if ( "${set}".equals( expression ) ) { return ""; } return super.evaluate( expression ); } }; configureComponent( component, configuration, evaluator ); assertNotNull( component.getList() ); assertEquals( Arrays.asList( " 1 ", null, null ), component.getList() ); assertNotNull( component.getSet() ); assertEquals( 0, component.getSet().size() ); } } AbstractThing.java000066400000000000000000000023221167051330000442440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public abstract class AbstractThing { } BasicComponentConfiguratorTest.java000066400000000000000000000026541167051330000476460ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class BasicComponentConfiguratorTest extends AbstractComponentConfiguratorTest { @Override protected ComponentConfigurator getComponentConfigurator() throws Exception { return new BasicComponentConfigurator(); } } Component.java000066400000000000000000000024561167051330000434610ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * @author Jason van Zyl * @version $Id: Component.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface Component { } ComponentWithArrayFields.java000066400000000000000000000043421167051330000464370ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.io.File; import java.net.URL; /** * @author Kenney Westerhof * @version $Id: ComponentWithArrayFields.java 5127 2006-12-12 03:49:50Z jvanzyl $ */ public class ComponentWithArrayFields { private String[] stringArray; private Integer[] integerArray; private ImportantThing[] importantThingArray; private Object[] objectArray; private AbstractThing[] abstractArray; private URL[] urlArray; private File[] fileArray; public String[] getStringArray() { return stringArray; } public Integer[] getIntegerArray() { return integerArray; } public ImportantThing[] getImportantThingArray() { return importantThingArray; } public Object[] getObjectArray() { return objectArray; } public AbstractThing[] getAbstractThingArray() { return abstractArray; } public URL[] getUrlArray() { return urlArray; } public File[] getFileArray() { return fileArray; } } ComponentWithCollectionFields.java000066400000000000000000000042371167051330000474570ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.Vector; /** * @author Michal Maczka * @version $Id: ComponentWithCollectionFields.java 8004 2009-01-04 18:39:40Z bentmann $ */ public class ComponentWithCollectionFields { private Vector vector; private HashSet hashSet; private List list; private List stringList; private List intList; private Set set; private SortedSet sortedSet; public Vector getVector() { return vector; } public HashSet getHashSet() { return hashSet; } public List getList() { return list; } public List getStringList() { return stringList; } public Set getSet() { return set; } public SortedSet getSortedSet() { return sortedSet; } public List getIntList() { return intList; } } ComponentWithCompositeFields.java000066400000000000000000000031211167051330000473150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * @author Michal Maczka * @version $Id: ComponentWithCompositeFields.java 8512 2009-10-21 23:15:04Z bentmann $ */ public class ComponentWithCompositeFields { private ThingInterface thing; private DefaultComponent bean; public ThingInterface getThing() { return thing; } public DefaultComponent getBean() { return bean; } } ComponentWithDefaultProperty.java000066400000000000000000000030021167051330000473530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.io.File; /** */ public class ComponentWithDefaultProperty { public Bean[] beans; public static class Bean { private File file; public void set( final File file ) { this.file = file; } public File getFile() { return file; } } } ComponentWithEnumFields.java000066400000000000000000000031141167051330000462610ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.lang.annotation.ElementType; /** * @author Benjamin Bentmann */ public class ComponentWithEnumFields { public enum NestedEnum { ONE, TWO, THREE, } private NestedEnum nestedEnum; private ElementType simpleEnum; public NestedEnum getNestedEnum() { return nestedEnum; } public ElementType getSimpleEnum() { return simpleEnum; } } ComponentWithInlinedCollection.java000066400000000000000000000033401167051330000476250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.util.ArrayList; import java.util.List; /** */ public class ComponentWithInlinedCollection { private final List items = new ArrayList(); public List getItems() { return items; } public void addString( final String string ) { items.add( string ); } public ComponentWithInlinedCollection addInteger( final Integer integer ) { items.add( integer ); return this; } public void addBoolean( final Boolean bool ) { items.add( bool ); } } ComponentWithMapField.java000066400000000000000000000027201167051330000457110ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.util.Map; /** * @author Michal Maczka * @version $Id: ComponentWithMapField.java 5127 2006-12-12 03:49:50Z jvanzyl $ */ public class ComponentWithMapField { private Map map; public Map getMap() { return map; } } ComponentWithPropertiesField.java000066400000000000000000000030241167051330000473260ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.util.Properties; /** * @author Michal Maczka * @version $Id: ComponentWithPropertiesField.java 5127 2006-12-12 03:49:50Z jvanzyl $ */ public class ComponentWithPropertiesField { private Properties someProperties; public Properties getSomeProperties() { return someProperties; } } ComponentWithSetters.java000066400000000000000000000072401167051330000456630ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.util.List; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Jason van Zyl * @version $Id: ComponentWithSetters.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ComponentWithSetters { private int intValueVariable; private float floatValueVariable; private long longValueVariable; private double doubleValueVariable; private String stringValueVariable; private List importantThingsVariable; private PlexusConfiguration configurationVariable; public int getIntValue() { return intValueVariable; } public float getFloatValue() { return floatValueVariable; } public long getLongValue() { return longValueVariable; } public double getDoubleValue() { return doubleValueVariable; } public String getStringValue() { return stringValueVariable; } public List getImportantThings() { return importantThingsVariable; } public PlexusConfiguration getConfiguration() { return configurationVariable; } // ---------------------------------------------------------------------- // setters // ---------------------------------------------------------------------- boolean intValueSet; boolean floatValueSet; boolean longValueSet; boolean doubleValueSet; boolean stringValueSet; boolean importantThingsValueSet; boolean configurationValueSet; public void setIntValue( final int intValue ) { intValueVariable = intValue; intValueSet = true; } public void setFloatValue( final float floatValue ) { floatValueVariable = floatValue; floatValueSet = true; } public void setLongValue( final long longValue ) { longValueVariable = longValue; longValueSet = true; } public void setDoubleValue( final double doubleValue ) { doubleValueVariable = doubleValue; doubleValueSet = true; } public void setStringValue( final String stringValue ) { stringValueVariable = stringValue; stringValueSet = true; } public void setImportantThings( final List importantThings ) { importantThingsVariable = importantThings; importantThingsValueSet = true; } public void setConfiguration( final PlexusConfiguration configuration ) { configurationVariable = configuration; configurationValueSet = true; } } ConfigurableComponent.java000066400000000000000000000056311167051330000460000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import java.io.File; import java.net.URI; import java.net.URL; import java.util.List; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Jason van Zyl * @version $Id: ConfigurableComponent.java 7783 2008-10-13 21:56:51Z bentmann $ */ public class ConfigurableComponent { private boolean booleanValue; private byte byteValue; private short shortValue; private int intValue; private float floatValue; private long longValue; private double doubleValue; private char charValue; private String stringValue; private File fileValue; private URI uriValue; private URL urlValue; private List importantThings; private PlexusConfiguration configuration; public boolean getBooleanValue() { return booleanValue; } public int getByteValue() { return byteValue; } public int getShortValue() { return shortValue; } public int getIntValue() { return intValue; } public float getFloatValue() { return floatValue; } public long getLongValue() { return longValue; } public double getDoubleValue() { return doubleValue; } public char getCharValue() { return charValue; } public String getStringValue() { return stringValue; } public File getFileValue() { return fileValue; } public URI getUriValue() { return uriValue; } public URL getUrlValue() { return urlValue; } public List getImportantThings() { return importantThings; } public PlexusConfiguration getConfiguration() { return configuration; } } DefaultComponent.java000066400000000000000000000026661167051330000447710ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * @author Jason van Zyl * @version $Id: DefaultComponent.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultComponent extends AbstractComponent { private String address; public String getAddress() { return address; } } ImportantThing.java000066400000000000000000000027031167051330000444610ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * @author Jason van Zyl * @version $Id: ImportantThing.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ImportantThing extends AbstractThing implements ThingInterface { private String name; public String getName() { return name; } } LegacyComponentConfiguratorTest.java000066400000000000000000000051341167051330000500250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import junit.framework.TestCase; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Benjamin Bentmann */ public class LegacyComponentConfiguratorTest extends TestCase { /** * A component configurator implementing the legacy Classworlds API. */ static class LegacyComponentConfigurator extends AbstractComponentConfigurator { int called; public void configureComponent( final Object component, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final org.codehaus.classworlds.ClassRealm containerRealm, final ConfigurationListener listener ) { called++; } } public void testLegacySupport() throws Exception { final ClassWorld classWorld = new ClassWorld(); final ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); final LegacyComponentConfigurator configurator = new LegacyComponentConfigurator(); configurator.configureComponent( new Object(), null, realm ); assertEquals( 1, configurator.called ); } } ThingInterface.java000066400000000000000000000023441167051330000444050ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/configuratorpackage org.codehaus.plexus.component.configurator; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public interface ThingInterface { String getName(); } 000077500000000000000000000000001167051330000401525ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/discoveryDefaultDiscoveredComponent.java000066400000000000000000000015321167051330000462750ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/discoverypackage org.codehaus.plexus.component.discovery; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: DefaultDiscoveredComponent.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultDiscoveredComponent implements DiscoveredComponent { } DiscoveredComponent.java000066400000000000000000000015441167051330000447730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/discoverypackage org.codehaus.plexus.component.discovery; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: DiscoveredComponent.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface DiscoveredComponent { String ROLE = DiscoveredComponent.class.getName(); } 000077500000000000000000000000001167051330000376125ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factoryComponent.java000066400000000000000000000014701167051330000424210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factorypackage org.codehaus.plexus.component.factory; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Michal Maczka * @version $Id: Component.java 4778 2006-11-23 03:54:18Z jvanzyl $ */ public interface Component { } ComponentImplA.java000066400000000000000000000014661167051330000433510ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factorypackage org.codehaus.plexus.component.factory; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ComponentImplA.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ComponentImplA implements Component { } ComponentImplB.java000066400000000000000000000015061167051330000433450ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factorypackage org.codehaus.plexus.component.factory; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Michal Maczka * @version $Id: ComponentImplB.java 4779 2006-11-23 04:09:31Z jvanzyl $ */ public class ComponentImplB { } ComponentImplC.java000066400000000000000000000015171167051330000433500ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factorypackage org.codehaus.plexus.component.factory; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Michal Maczka * @version $Id: ComponentImplC.java 4779 2006-11-23 04:09:31Z jvanzyl $ */ public abstract class ComponentImplC { } TestComponentFactory1.java000066400000000000000000000023561167051330000446760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factorypackage org.codehaus.plexus.component.factory; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.ComponentDescriptor; public class TestComponentFactory1 implements ComponentFactory { public String getId() { return "testFactory1"; } public Object newInstance( final ComponentDescriptor componentDescriptor, final ClassRealm classRealm, final PlexusContainer container ) throws ComponentInstantiationException { return new TestFactoryResultComponent( getId() ); } } TestComponentFactory2.java000066400000000000000000000023561167051330000446770ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factorypackage org.codehaus.plexus.component.factory; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.ComponentDescriptor; public class TestComponentFactory2 implements ComponentFactory { public String getId() { return "testFactory2"; } public Object newInstance( final ComponentDescriptor componentDescriptor, final ClassRealm classRealm, final PlexusContainer container ) throws ComponentInstantiationException { return new TestFactoryResultComponent( getId() ); } } TestFactoryResultComponent.java000066400000000000000000000016361167051330000460140ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factorypackage org.codehaus.plexus.component.factory; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public class TestFactoryResultComponent { private final String factoryId; public TestFactoryResultComponent( final String factoryId ) { this.factoryId = factoryId; } public String getFactoryId() { return factoryId; } } 000077500000000000000000000000001167051330000412465ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factory/nonjavaNonJavaComponentFactory.java000066400000000000000000000014321167051330000466600ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factory/nonjavapackage org.codehaus.plexus.component.factory.nonjava; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.factory.ComponentFactory; import org.codehaus.plexus.component.factory.ComponentInstantiationException; import org.codehaus.plexus.component.repository.ComponentDescriptor; /** @author Jason van Zyl */ public class NonJavaComponentFactory implements ComponentFactory { public String getId() { return "nonjava"; } public Object newInstance( final ComponentDescriptor componentDescriptor, final ClassRealm classRealm, final PlexusContainer container ) throws ComponentInstantiationException { return "component"; } } NonJavaComponentFactoryTest.java000066400000000000000000000007241167051330000475230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/factory/nonjavapackage org.codehaus.plexus.component.factory.nonjava; import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.component.factory.ComponentFactory; /** @author Jason van Zyl */ public class NonJavaComponentFactoryTest extends PlexusTestCase { public void testNonJavaComponentFactory() throws Exception { final ComponentFactory factory = lookup( ComponentFactory.class, "nonjava" ); assertNotNull( factory ); } } 000077500000000000000000000000001167051330000375555ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/managerClassicSingletonComponentManagerTest.java000066400000000000000000000013061167051330000477020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/managerpackage org.codehaus.plexus.component.manager; import org.codehaus.plexus.PlexusTestCase; /** * @author Ben Walding * @version $Id: ClassicSingletonComponentManagerTest.java 7828 2008-11-14 22:07:56Z dain $ */ public class ClassicSingletonComponentManagerTest extends PlexusTestCase { public void testSequentialLookupsReturnTheSameInstance() throws Exception { final Component a = lookup( Component.class ); final Component b = lookup( Component.class ); final Component c = lookup( Component.class ); final Component d = lookup( Component.class ); assertTrue( a == b ); assertTrue( a == c ); assertTrue( a == d ); } } Component.java000066400000000000000000000002311167051330000423560ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/managerpackage org.codehaus.plexus.component.manager; /** @author Jason van Zyl */ public interface Component { String ROLE = Component.class.getName(); } DefaultComponent.java000066400000000000000000000002101167051330000436600ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/managerpackage org.codehaus.plexus.component.manager; /** @author Jason van Zyl */ public class DefaultComponent implements Component { } SlowComponent.java000066400000000000000000000025621167051330000432340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/managerpackage org.codehaus.plexus.component.manager; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; /** * A slow starting component that checks that sleeps during its Start phase. Configuration: delay - number of * milliseconds to sleep during start() * * @author Ben Walding * @version $Id: SlowComponent.java 5451 2007-01-17 02:36:27Z jvanzyl $ */ public class SlowComponent implements Startable { public static final String ROLE = SlowComponent.class.getName(); /* Number of ms to sleep during start() */ private long delay; public void start() { try { Thread.sleep( delay ); } catch ( final InterruptedException e ) { } } public void stop() { } } SlowComponentClassicSingletonComponentManagerTest.java000066400000000000000000000064641167051330000524440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/managerpackage org.codehaus.plexus.component.manager; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.PlexusTestCase; /** * @author Ben Walding * @version $Id: SlowComponentClassicSingletonComponentManagerTest.java 7876 2008-11-23 14:39:51Z bentmann $ */ public class SlowComponentClassicSingletonComponentManagerTest extends PlexusTestCase { public void testThreads1() throws Exception { test( 1 ); } /** * Tests that multiple concurrent threads don't acquire different components. */ public void testThreads1000() throws Exception { test( 1000 ); } private void test( final int count ) throws Exception { final ComponentLookupThread components[] = new ComponentLookupThread[count]; // Create them for ( int i = 0; i < count; i++ ) { components[i] = new ComponentLookupThread( getContainer() ); } // Start them for ( int i = 0; i < count; i++ ) { components[i].start(); } // Wait for them to finish for ( int i = 0; i < count; i++ ) { components[i].join( 10000 ); } // Get master component final SlowComponent masterComponent = lookup( SlowComponent.class ); // Verify them for ( int i = 0; i < count; i++ ) { assertSame( i + ":" + components[i].getComponent() + " == " + masterComponent, masterComponent, components[i].getComponent() ); } } class ComponentLookupThread extends Thread { final PlexusContainer container; private SlowComponent component; public ComponentLookupThread( final PlexusContainer container ) { /* * NOTE: A high priority seems to increase the likelihood of exhibiting missing synchronization. */ setPriority( MAX_PRIORITY ); this.container = container; } @Override public void run() { try { // DefaultPlexusContainer.setLookupRealm( lookupRealm ); final SlowComponent tmpComponent = container.lookup( SlowComponent.class ); synchronized ( this ) { component = tmpComponent; } } catch ( final Exception e ) { container.getLookupRealm().display(); e.printStackTrace(); } } public SlowComponent getComponent() { synchronized ( this ) { return component; } } } } 000077500000000000000000000000001167051330000400135ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/registryDefaultComponentRegistryTest.java000066400000000000000000000056451167051330000465300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/registrypackage org.codehaus.plexus.component.registry; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import junit.framework.TestCase; import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.components.A; public class DefaultComponentRegistryTest extends TestCase { public void testConcurrentDisposeAndLookup() throws Exception { final PlexusContainer plexus = new DefaultPlexusContainer(); final ComponentDescriptor descriptor = new ComponentDescriptor( TestSynchronizedComponent.class, plexus.getContainerRealm() ); descriptor.setRole( TestSynchronizedComponent.class.getCanonicalName() ); descriptor.setImplementation( TestSynchronizedComponent.class.getCanonicalName() ); plexus.addComponentDescriptor( descriptor ); final TestSynchronizedComponent component = plexus.lookup( TestSynchronizedComponent.class ); class LookupThread extends Thread { private TestSynchronizedComponent component; @Override public synchronized void run() { try { component = plexus.lookup( TestSynchronizedComponent.class ); } catch ( final ComponentLookupException e ) { // expected } } public synchronized TestSynchronizedComponent getComponent() { return component; } } final LookupThread lookupThread = new LookupThread(); component.setLookupThread( lookupThread ); plexus.dispose(); assertNull( lookupThread.getComponent() ); } public void testImplementationClassNotFromRealm() throws Exception { final File aJar = new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ); final ClassLoader customLoader = URLClassLoader.newInstance( new URL[] { aJar.toURL() }, getClass().getClassLoader() ); final Class componentA = customLoader.loadClass( "org.codehaus.plexus.components.DefaultA" ); final PlexusContainer plexus = new DefaultPlexusContainer(); final ComponentDescriptor descriptor = new ComponentDescriptor(); descriptor.setRole( A.class.getName() ); descriptor.setRealm( plexus.getContainerRealm() ); descriptor.setImplementationClass( componentA ); plexus.addComponentDescriptor( descriptor ); assertSame( componentA, plexus.lookup( A.class ).getClass() ); plexus.dispose(); } } TestSynchronizedComponent.java000066400000000000000000000016251167051330000460640ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/registrypackage org.codehaus.plexus.component.registry; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException; public class TestSynchronizedComponent implements Startable { private Thread lookupThread; public synchronized void start() throws StartingException { } public synchronized void stop() throws StoppingException { lookupThread.start(); try { lookupThread.join(); } catch ( final InterruptedException e ) { throw new StoppingException( "Can't stop lookupThread", e ); } } public synchronized void setLookupThread( final Thread lookupThread ) { this.lookupThread = lookupThread; } } 000077500000000000000000000000001167051330000403625ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/repositoryComponentDescriptorTest.java000066400000000000000000000061071167051330000460720ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/repositorypackage org.codehaus.plexus.component.repository; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.util.List; import junit.framework.TestCase; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.io.PlexusTools; /** * @author Jason van Zyl * @version $Id: ComponentDescriptorTest.java 8155 2009-04-26 01:22:53Z jvanzyl $ */ public class ComponentDescriptorTest extends TestCase { public void testSimpleComponentResolution() throws Exception { final String cc1 = "" + " java.lang.String" + " c1" + " role-hint" + " component-profile" + " " + " " + " c2" + " " + " " + " c3" + " " + " " + ""; final ClassWorld classWorld = new ClassWorld( "test", Thread.currentThread().getContextClassLoader() ); final ClassRealm realm = classWorld.getRealm( "test" ); final ComponentDescriptor c1 = PlexusTools.buildComponentDescriptor( cc1, realm ); assertEquals( "c1", c1.getRole() ); assertEquals( "role-hint", c1.getRoleHint() ); assertEquals( "component-profile", c1.getComponentProfile() ); final List requirements = c1.getRequirements(); assertEquals( 2, requirements.size() ); boolean containsC2 = false; boolean containsC3 = false; for ( final ComponentRequirement requirement : requirements ) { if ( requirement.getRole().equals( "c2" ) ) { containsC2 = true; } else if ( requirement.getRole().equals( "c3" ) ) { containsC3 = true; } } assertTrue( containsC2 ); assertTrue( containsC3 ); } public void testShouldNotBeEqualWhenRolesAreSameButHintsAreDifferent() { final ComponentDescriptor desc = new ComponentDescriptor(); desc.setRole( "one" ); desc.setRoleHint( "one" ); final ComponentDescriptor desc2 = new ComponentDescriptor(); desc2.setRole( "one" ); desc2.setRoleHint( "two" ); assertFalse( desc.equals( desc2 ) ); } } ComponentRequirementTest.java000066400000000000000000000023411167051330000462500ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/repositorypackage org.codehaus.plexus.component.repository; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import junit.framework.TestCase; /** * @author Michal Maczka * @version $Id: ComponentRequirementTest.java 4779 2006-11-23 04:09:31Z jvanzyl $ */ public class ComponentRequirementTest extends TestCase { public void testComponentRequirement() { final ComponentRequirement requirement = new ComponentRequirement(); requirement.setFieldName( "field" ); requirement.setRole( "role" ); assertEquals( "field", requirement.getFieldName() ); assertEquals( "role", requirement.getRole() ); } } ComponentSetTest.java000066400000000000000000000065321167051330000445110ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/repositorypackage org.codehaus.plexus.component.repository; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.util.List; import junit.framework.TestCase; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.io.PlexusTools; /** * @author Jason van Zyl * @version $Id: ComponentSetTest.java 8155 2009-04-26 01:22:53Z jvanzyl $ */ public class ComponentSetTest extends TestCase { public void testSimpleComponentResolution() throws Exception { final String xml = "" + " " + " " + " java.lang.String" + " c1" + " role-hint" + " component-profile" + " " + " " + " c2" + " " + " " + " c3" + " " + " " + " " + " " + " " + " " + " plexus" + " wedgy" + " 1.0" + " " + " " + ""; final ClassWorld classWorld = new ClassWorld( "test", Thread.currentThread().getContextClassLoader() ); final ClassRealm realm = classWorld.getRealm( "test" ); final ComponentSetDescriptor cs = PlexusTools.buildComponentSet( PlexusTools.buildConfiguration( xml ), realm ); final ComponentDescriptor c1 = cs.getComponents().get( 0 ); assertEquals( "c1", c1.getRole() ); assertEquals( "role-hint", c1.getRoleHint() ); assertEquals( "component-profile", c1.getComponentProfile() ); final List requirements = c1.getRequirements(); assertEquals( 2, requirements.size() ); boolean containsC2 = false; boolean containsC3 = false; for ( final ComponentRequirement requirement : requirements ) { if ( requirement.getRole().equals( "c2" ) ) { containsC2 = true; } else if ( requirement.getRole().equals( "c3" ) ) { containsC3 = true; } } assertTrue( containsC2 ); assertTrue( containsC3 ); final ComponentDependency d1 = cs.getDependencies().get( 0 ); assertEquals( "plexus", d1.getGroupId() ); assertEquals( "wedgy", d1.getArtifactId() ); assertEquals( "1.0", d1.getVersion() ); } } DefaultComponentRepositoryTest.java000066400000000000000000000016641167051330000474430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/repositorypackage org.codehaus.plexus.component.repository; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import junit.framework.TestCase; /** * @author Jason van Zyl * @version $Id: DefaultComponentRepositoryTest.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultComponentRepositoryTest extends TestCase { public void testDefaultComponentRepository() { } } 000077500000000000000000000000001167051330000407715ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/repository/ioPlexusTools.java000066400000000000000000000254721167051330000441470ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/component/repository/iopackage org.codehaus.plexus.component.repository.io; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.io.IOException; import java.io.PrintStream; import java.io.Reader; import java.io.StringReader; import java.util.LinkedList; import java.util.List; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.ComponentDependency; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.ComponentRequirement; import org.codehaus.plexus.component.repository.ComponentRequirementList; import org.codehaus.plexus.component.repository.ComponentSetDescriptor; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.configuration.io.XmlPlexusConfigurationReader; /** * @author Jason van Zyl */ public class PlexusTools { public static PlexusConfiguration buildConfiguration( final String resourceName, final Reader configuration ) throws PlexusConfigurationException { try { final XmlPlexusConfigurationReader reader = new XmlPlexusConfigurationReader(); final PlexusConfiguration result = reader.read( configuration ); return result; } catch ( final PlexusConfigurationException e ) { throw new PlexusConfigurationException( "PlexusConfigurationException building configuration from: " + resourceName, e ); } catch ( final IOException e ) { throw new PlexusConfigurationException( "IO error building configuration from: " + resourceName, e ); } } public static PlexusConfiguration buildConfiguration( final String configuration ) throws PlexusConfigurationException { return buildConfiguration( "", new StringReader( configuration ) ); } public static ComponentDescriptor buildComponentDescriptor( final String configuration, final ClassRealm realm ) throws PlexusConfigurationException { return buildComponentDescriptor( buildConfiguration( configuration ), realm ); } public static ComponentDescriptor buildComponentDescriptor( final PlexusConfiguration configuration ) throws PlexusConfigurationException { return buildComponentDescriptorImpl( configuration, null ); } public static ComponentDescriptor buildComponentDescriptor( final PlexusConfiguration configuration, final ClassRealm realm ) throws PlexusConfigurationException { if ( realm == null ) { throw new NullPointerException( "realm is null" ); } return buildComponentDescriptorImpl( configuration, realm ); } private static ComponentDescriptor buildComponentDescriptorImpl( final PlexusConfiguration configuration, final ClassRealm realm ) throws PlexusConfigurationException { final String implementation = configuration.getChild( "implementation" ).getValue(); if ( implementation == null ) { throw new PlexusConfigurationException( "implementation is null" ); } ComponentDescriptor cd; try { if ( realm != null ) { final Class implementationClass = realm.loadClass( implementation ); cd = new ComponentDescriptor( implementationClass, realm ); } else { cd = new ComponentDescriptor(); cd.setImplementation( implementation ); } } catch ( final Exception e ) { throw new PlexusConfigurationException( "Can not load implementation class " + implementation + " from realm " + realm, e ); } cd.setRole( configuration.getChild( "role" ).getValue() ); cd.setRoleHint( configuration.getChild( "role-hint" ).getValue() ); cd.setVersion( configuration.getChild( "version" ).getValue() ); cd.setComponentType( configuration.getChild( "component-type" ).getValue() ); cd.setInstantiationStrategy( configuration.getChild( "instantiation-strategy" ).getValue() ); cd.setLifecycleHandler( configuration.getChild( "lifecycle-handler" ).getValue() ); cd.setComponentProfile( configuration.getChild( "component-profile" ).getValue() ); cd.setComponentComposer( configuration.getChild( "component-composer" ).getValue() ); cd.setComponentConfigurator( configuration.getChild( "component-configurator" ).getValue() ); cd.setComponentFactory( configuration.getChild( "component-factory" ).getValue() ); cd.setDescription( configuration.getChild( "description" ).getValue() ); cd.setAlias( configuration.getChild( "alias" ).getValue() ); final String s = configuration.getChild( "isolated-realm" ).getValue(); if ( s != null ) { cd.setIsolatedRealm( s.equals( "true" ) ? true : false ); } // ---------------------------------------------------------------------- // Here we want to look for directives for inlining external // configurations. we probably want to take them from files or URLs. // ---------------------------------------------------------------------- cd.setConfiguration( configuration.getChild( "configuration" ) ); // ---------------------------------------------------------------------- // Requirements // ---------------------------------------------------------------------- final PlexusConfiguration[] requirements = configuration.getChild( "requirements" ).getChildren( "requirement" ); for ( final PlexusConfiguration requirement : requirements ) { ComponentRequirement cr; final PlexusConfiguration[] hints = requirement.getChild( "role-hints" ).getChildren( "role-hint" ); if ( hints != null && hints.length > 0 ) { cr = new ComponentRequirementList(); final List hintList = new LinkedList(); for ( final PlexusConfiguration hint : hints ) { hintList.add( hint.getValue() ); } ( (ComponentRequirementList) cr ).setRoleHints( hintList ); } else { cr = new ComponentRequirement(); cr.setRoleHint( requirement.getChild( "role-hint" ).getValue() ); } cr.setRole( requirement.getChild( "role" ).getValue() ); cr.setOptional( Boolean.parseBoolean( requirement.getChild( "optional" ).getValue() ) ); cr.setFieldName( requirement.getChild( "field-name" ).getValue() ); cd.addRequirement( cr ); } return cd; } public static ComponentSetDescriptor buildComponentSet( final PlexusConfiguration c ) throws PlexusConfigurationException { return buildComponentSet( c, null ); } public static ComponentSetDescriptor buildComponentSet( final PlexusConfiguration c, final ClassRealm realm ) throws PlexusConfigurationException { final ComponentSetDescriptor csd = new ComponentSetDescriptor(); // ---------------------------------------------------------------------- // Components // ---------------------------------------------------------------------- final PlexusConfiguration[] components = c.getChild( "components" ).getChildren( "component" ); for ( final PlexusConfiguration component : components ) { csd.addComponentDescriptor( buildComponentDescriptorImpl( component, realm ) ); } // ---------------------------------------------------------------------- // Dependencies // ---------------------------------------------------------------------- final PlexusConfiguration[] dependencies = c.getChild( "dependencies" ).getChildren( "dependency" ); for ( final PlexusConfiguration d : dependencies ) { final ComponentDependency cd = new ComponentDependency(); cd.setArtifactId( d.getChild( "artifact-id" ).getValue() ); cd.setGroupId( d.getChild( "group-id" ).getValue() ); final String type = d.getChild( "type" ).getValue(); if ( type != null ) { cd.setType( type ); } cd.setVersion( d.getChild( "version" ).getValue() ); csd.addDependency( cd ); } return csd; } public static void writeConfiguration( final PrintStream out, final PlexusConfiguration configuration ) throws PlexusConfigurationException { writeConfiguration( out, configuration, "" ); } private static void writeConfiguration( final PrintStream out, final PlexusConfiguration configuration, final String indent ) throws PlexusConfigurationException { out.print( indent + "<" + configuration.getName() ); final String[] atts = configuration.getAttributeNames(); if ( atts.length > 0 ) { for ( final String att : atts ) { out.print( "\n" + indent + " " + att + "='" + configuration.getAttribute( att ) + "'" ); } } final PlexusConfiguration[] pc = configuration.getChildren(); if ( configuration.getValue() != null && configuration.getValue().trim().length() > 0 || pc.length > 0 ) { out.print( ">" + ( configuration.getValue() == null ? "" : configuration.getValue().trim() ) ); if ( pc.length > 0 ) { out.println(); for ( final PlexusConfiguration element : pc ) { writeConfiguration( out, element, indent + " " ); } out.print( indent ); } out.println( "" ); } else { out.println( "/>" ); } } } 000077500000000000000000000000001167051330000363265ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/componentsA.java000066400000000000000000000001221167051330000373440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/componentspackage org.codehaus.plexus.components; public interface A { void hello(); } 000077500000000000000000000000001167051330000370105ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/configurationConfigurationTestHelper.java000066400000000000000000000053641167051330000444720ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/configurationpackage org.codehaus.plexus.configuration; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.io.StringReader; import junit.framework.TestCase; import org.codehaus.plexus.component.repository.io.PlexusTools; /** * @author Jason van Zyl * @version $Id: ConfigurationTestHelper.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public abstract class ConfigurationTestHelper extends TestCase { public static PlexusConfiguration getTestConfiguration() throws Exception { return PlexusTools.buildConfiguration( "", new StringReader( ConfigurationTestHelper.getXmlConfiguration() ) ); } public static String getXmlConfiguration() { return "" + "" + "" + "string" + "0" + "not-a-number" + "true" + "false" + "not-a-boolean" + ""; } public static void testConfiguration( final PlexusConfiguration c ) throws Exception { // Exercise all value/attribute retrieval methods. // Values // TODO: uncomment once maven can test the latest plexus-utils // assertNull( c.getChild( "singleton" ).getValue( null ) ); // String assertEquals( "string", c.getValue( "string" ) ); assertEquals( "string", c.getChild( "string" ).getValue() ); assertEquals( "string", c.getChild( "ne-string" ).getValue( "string" ) ); assertNull( c.getChild( "not-existing" ).getValue( null ) ); assertEquals( "''", "'" + c.getChild( "empty-element" ).getValue() + "'" ); assertEquals( "", c.getChild( "empty-element" ).getValue( null ) ); // Attributes assertEquals( "string", c.getChild( "string" ).getAttribute( "string" ) ); assertEquals( "attribute", c.getChild( "singleton" ).getAttribute( "attribute" ) ); } } DefaultPlexusConfigurationTest.java000066400000000000000000000106361167051330000460360ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/configurationpackage org.codehaus.plexus.configuration; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import junit.framework.TestCase; /** * @author Ran Tene * @version $Id: DefaultPlexusConfigurationTest.java 7854 2008-11-18 22:33:53Z bentmann $ */ public final class DefaultPlexusConfigurationTest extends TestCase { private DefaultPlexusConfiguration configuration; @Override public void setUp() { configuration = new DefaultPlexusConfiguration( "a" ); } public void testWithHelper() throws Exception { final PlexusConfiguration c = ConfigurationTestHelper.getTestConfiguration(); ConfigurationTestHelper.testConfiguration( c ); } public void testGetValue() throws Exception { final String orgValue = "Original String"; configuration.setValue( orgValue ); assertEquals( orgValue, configuration.getValue() ); } public void testGetAttribute() throws Exception { final String key = "key"; final String value = "original value"; final String defaultStr = "default"; configuration.setAttribute( key, value ); assertEquals( value, configuration.getAttribute( key, defaultStr ) ); assertEquals( defaultStr, configuration.getAttribute( "newKey", defaultStr ) ); } public void testGetChild() throws Exception { DefaultPlexusConfiguration child = (DefaultPlexusConfiguration) configuration.getChild( "child" ); assertNotNull( child ); child.setValue( "child value" ); assertEquals( 1, configuration.getChildCount() ); child = (DefaultPlexusConfiguration) configuration.getChild( "child" ); assertNotNull( child ); assertEquals( "child value", child.getValue() ); assertEquals( 1, configuration.getChildCount() ); } public void testToString() throws Exception { // TODO: this currently works since getTestConfiguration() invokes PlexusTools.buildConfiguration() // and it returns XmlPlexusConfiguration actually. final PlexusConfiguration c = ConfigurationTestHelper.getTestConfiguration(); assertEquals( "string\n", c.getChild( "string" ).toString() ); // TODO: uncomment once maven can test the latest plexus-utils assertEquals( "\n", c.getChild( "singleton" ).toString() ); } public void testProgrammaticConfigurationCreation() throws Exception { final String viewRoot = "/path/to/viewRoot"; final PlexusConfiguration c = new DefaultPlexusConfiguration( "configuration" ).addChild( "viewRoot", viewRoot ); assertEquals( viewRoot, c.getChild( "viewRoot" ).getValue() ); } public void testChildOrdering() throws Exception { final PlexusConfiguration child0 = new DefaultPlexusConfiguration( "child" ); final PlexusConfiguration child1 = new DefaultPlexusConfiguration( "child" ); final PlexusConfiguration child2 = new DefaultPlexusConfiguration( "special-child" ); final PlexusConfiguration child3 = new DefaultPlexusConfiguration( "child" ); final PlexusConfiguration child4 = new DefaultPlexusConfiguration( "child" ); configuration.addChild( child0 ); configuration.addChild( child1 ); configuration.addChild( child2 ); configuration.addChild( child3 ); configuration.addChild( child4 ); assertEquals( 5, configuration.getChildCount() ); assertSame( child0, configuration.getChild( 0 ) ); assertSame( child1, configuration.getChild( 1 ) ); assertSame( child2, configuration.getChild( 2 ) ); assertSame( child3, configuration.getChild( 3 ) ); assertSame( child4, configuration.getChild( 4 ) ); } } 000077500000000000000000000000001167051330000374175ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/configuration/ioPlexusConfigurationReader.java000066400000000000000000000010351167051330000454140ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/configuration/iopackage org.codehaus.plexus.configuration.io; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; public interface PlexusConfigurationReader { public PlexusConfiguration read( Reader reader ) throws IOException, PlexusConfigurationException; public PlexusConfiguration read( InputStream inputStream ) throws IOException, PlexusConfigurationException; } XmlPlexusConfigurationReader.java000066400000000000000000000024561167051330000461050ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/configuration/iopackage org.codehaus.plexus.configuration.io; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; public class XmlPlexusConfigurationReader implements PlexusConfigurationReader { public PlexusConfiguration read( final InputStream inputStream ) throws IOException, PlexusConfigurationException { return read( new InputStreamReader( inputStream ) ); } public PlexusConfiguration read( final Reader reader ) throws IOException, PlexusConfigurationException { try { final Xpp3Dom dom = Xpp3DomBuilder.build( reader ); return new XmlPlexusConfiguration( dom ); } catch ( final XmlPullParserException e ) { throw new PlexusConfigurationException( "Failed to parse configuration resource!\nError was: \'" + e.getLocalizedMessage() + "\'", e ); } } } XmlPlexusConfigurationReaderTest.java000066400000000000000000000012471167051330000467420ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/configuration/iopackage org.codehaus.plexus.configuration.io; import java.io.StringReader; import junit.framework.TestCase; import org.codehaus.plexus.configuration.ConfigurationTestHelper; import org.codehaus.plexus.configuration.PlexusConfiguration; public class XmlPlexusConfigurationReaderTest extends TestCase { public void testRead() throws Exception { final StringReader sr = new StringReader( ConfigurationTestHelper.getXmlConfiguration() ); final XmlPlexusConfigurationReader reader = new XmlPlexusConfigurationReader(); final PlexusConfiguration c = reader.read( sr ); ConfigurationTestHelper.testConfiguration( c ); } } 000077500000000000000000000000001167051330000376105ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/configuration/xmlXmlPlexusConfigurationTest.java000066400000000000000000000063631167051330000460140ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/configuration/xmlpackage org.codehaus.plexus.configuration.xml; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import junit.framework.TestCase; import org.codehaus.plexus.configuration.ConfigurationTestHelper; import org.codehaus.plexus.configuration.PlexusConfiguration; /** * @author Ran Tene * @version $Id: XmlPlexusConfigurationTest.java 7187 2008-01-26 20:55:42Z cstamas $ */ public final class XmlPlexusConfigurationTest extends TestCase { private XmlPlexusConfiguration configuration; @Override public void setUp() { configuration = new XmlPlexusConfiguration( "a" ); } public void testWithHelper() throws Exception { final PlexusConfiguration c = ConfigurationTestHelper.getTestConfiguration(); ConfigurationTestHelper.testConfiguration( c ); } public void testGetValue() throws Exception { final String orgValue = "Original String"; configuration.setValue( orgValue ); assertEquals( orgValue, configuration.getValue() ); } public void testGetAttribute() throws Exception { final String key = "key"; final String value = "original value"; final String defaultStr = "default"; configuration.setAttribute( key, value ); assertEquals( value, configuration.getAttribute( key, defaultStr ) ); assertEquals( defaultStr, configuration.getAttribute( "newKey", defaultStr ) ); } public void testGetChild() throws Exception { PlexusConfiguration child = configuration.getChild( "child" ); assertNotNull( child ); child.setValue( "child value" ); assertEquals( 1, configuration.getChildCount() ); child = configuration.getChild( "child" ); assertNotNull( child ); assertEquals( "child value", child.getValue() ); assertEquals( 1, configuration.getChildCount() ); } public void testToString() throws Exception { final PlexusConfiguration c = ConfigurationTestHelper.getTestConfiguration(); assertEquals( "string\n", c.getChild( "string" ).toString() ); // TODO: uncomment once maven can test the latest plexus-utils // assertEquals( "\n", c.getChild( "singleton" ).toString() ); } public void testProgrammaticConfigurationCreation() throws Exception { final String viewRoot = "/path/to/viewRoot"; final PlexusConfiguration c = new XmlPlexusConfiguration( "configuration" ).addChild( "viewRoot", viewRoot ); assertEquals( viewRoot, c.getChild( "viewRoot" ).getValue() ); } } 000077500000000000000000000000001167051330000356255ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/contextContextMapAdapterTest.java000066400000000000000000000045071167051330000427210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/contextpackage org.codehaus.plexus.context; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.io.StringReader; import java.io.StringWriter; import junit.framework.TestCase; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.InterpolationFilterReader; /** * Generated by JUnitDoclet, a tool provided by ObjectFab GmbH under LGPL. Please see www.junitdoclet.org, www.gnu.org * and www.objectfab.de for informations about the tool, the licence and the authors. */ public class ContextMapAdapterTest extends TestCase { public ContextMapAdapterTest( final String name ) { super( name ); } public void testInterpolation() throws Exception { final DefaultContext context = new DefaultContext(); context.put( "name", "jason" ); context.put( "occupation", "exotic dancer" ); final ContextMapAdapter adapter = new ContextMapAdapter( context ); assertEquals( "jason", (String) adapter.get( "name" ) ); assertEquals( "exotic dancer", (String) adapter.get( "occupation" ) ); assertNull( adapter.get( "foo" ) ); } public void testInterpolationWithContext() throws Exception { final DefaultContext context = new DefaultContext(); context.put( "name", "jason" ); context.put( "noun", "asshole" ); final String foo = "${name} is an ${noun}. ${not.interpolated}"; final InterpolationFilterReader reader = new InterpolationFilterReader( new StringReader( foo ), new ContextMapAdapter( context ) ); final StringWriter writer = new StringWriter(); IOUtil.copy( reader, writer ); final String bar = writer.toString(); assertEquals( "jason is an asshole. ${not.interpolated}", bar ); } } DefaultContextTest.java000066400000000000000000000040131167051330000422570ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/contextpackage org.codehaus.plexus.context; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * TestCase for Context. * * @author Berin Loritsch * @author Leo Sutic */ public class DefaultContextTest extends TestCase { public DefaultContextTest( final String name ) { super( name ); } public void testContextCreationWithMap() throws Exception { final Map map = new HashMap(); map.put( "name", "jason" ); final DefaultContext context = new DefaultContext( map ); assertEquals( "jason", (String) context.get( "name" ) ); assertEquals( map, context.getContextData() ); // Test removal context.put( "name", null ); // There is no data and no parent containerContext. try { context.get( "name" ); } catch ( final ContextException e ) { // do nothing } } public void testAddContext() throws Exception { final DefaultContext context = new DefaultContext(); context.put( "key1", "value1" ); assertTrue( "value1".equals( context.get( "key1" ) ) ); context.put( "key1", "" ); assertTrue( "".equals( context.get( "key1" ) ) ); context.put( "key1", "value1" ); } } 000077500000000000000000000000001167051330000361175ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/hierarchyPlexusHierarchyTest.java000066400000000000000000000000001167051330000427270ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/hierarchyPlexusTestService.java000066400000000000000000000000001167051330000424110ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/hierarchyTestServiceImpl.java000066400000000000000000000000001167051330000420320ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/hierarchy000077500000000000000000000000001167051330000355675ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/loggingAbstractLoggerManagerTest.java000066400000000000000000000162741167051330000435020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/loggingpackage org.codehaus.plexus.logging; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.PlexusTestCase; /** * Abtract base class for testing implementations of the {@link LoggerManager} and {@link Logger} interfaces. * * @author Mark H. Wilkinson * @author Trygve Laugstøl * @version $Revision: 4778 $ */ public abstract class AbstractLoggerManagerTest extends PlexusTestCase { protected abstract LoggerManager createLoggerManager() throws Exception; public void testSetThreshold() throws Exception { LoggerManager manager; Logger logger1, logger2; manager = createLoggerManager(); manager.setThreshold( Logger.LEVEL_FATAL ); logger1 = manager.getLoggerForComponent( "role1", "roleHint1" ); assertEquals( Logger.LEVEL_FATAL, logger1.getThreshold() ); manager.setThreshold( Logger.LEVEL_DEBUG ); logger2 = manager.getLoggerForComponent( "role2", "roleHint2" ); assertEquals( Logger.LEVEL_FATAL, logger1.getThreshold() ); assertEquals( Logger.LEVEL_DEBUG, logger2.getThreshold() ); } /** * There is only one logger instance pr component even if looked up more that once. */ public void testActiveLoggerCount() throws Exception { LoggerManager manager; Logger b, c1_1, c1_2, c2; manager = getManager( Logger.LEVEL_FATAL ); assertEquals( 0, manager.getActiveLoggerCount() ); b = manager.getLoggerForComponent( "b" ); assertNotNull( b ); assertEquals( 1, manager.getActiveLoggerCount() ); c1_1 = manager.getLoggerForComponent( "c", "1" ); c1_2 = manager.getLoggerForComponent( "c", "1" ); assertNotNull( c1_1 ); assertNotNull( c1_2 ); assertSame( c1_1, c1_2 ); assertEquals( 2, manager.getActiveLoggerCount() ); c2 = manager.getLoggerForComponent( "c", "2" ); assertNotNull( c2 ); assertEquals( 3, manager.getActiveLoggerCount() ); manager.returnComponentLogger( "c", "1" ); assertEquals( 2, manager.getActiveLoggerCount() ); manager.returnComponentLogger( "c", "2" ); manager.returnComponentLogger( "c", "2" ); manager.returnComponentLogger( "c", "1" ); assertEquals( 1, manager.getActiveLoggerCount() ); manager.returnComponentLogger( "b" ); assertEquals( 0, manager.getActiveLoggerCount() ); } public void testDebugLevelConfiguration() throws Exception { final LoggerManager manager = getManager( Logger.LEVEL_DEBUG ); Logger logger = extractLogger( manager ); checkDebugLevel( logger ); logger = extractLogger( manager ); checkDebugLevel( logger ); } public void testInfoLevelConfiguration() throws Exception { final LoggerManager manager = getManager( Logger.LEVEL_INFO ); Logger logger = extractLogger( manager ); checkInfoLevel( logger ); logger = extractLogger( manager ); checkInfoLevel( logger ); } public void testWarnLevelConfiguration() throws Exception { final LoggerManager manager = getManager( Logger.LEVEL_WARN ); Logger logger = extractLogger( manager ); checkWarnLevel( logger ); logger = extractLogger( manager ); checkWarnLevel( logger ); } public void testErrorLevelConfiguration() throws Exception { final LoggerManager manager = getManager( Logger.LEVEL_ERROR ); Logger logger = extractLogger( manager ); checkErrorLevel( logger ); logger = extractLogger( manager ); checkErrorLevel( logger ); } public void testFatalLevelConfiguration() throws Exception { final LoggerManager manager = getManager( Logger.LEVEL_FATAL ); Logger logger = extractLogger( manager ); checkFatalLevel( logger ); logger = extractLogger( manager ); checkFatalLevel( logger ); } private LoggerManager getManager( final int threshold ) throws Exception { final LoggerManager manager = createLoggerManager(); manager.setThreshold( threshold ); assertNotNull( manager ); return manager; } /* * private Logger extractRootLogger( LoggerManager manager ) { Logger logger = manager.getRootLogger(); * assertNotNull( logger ); return logger; } */ private Logger extractLogger( final LoggerManager manager ) { final Logger logger = manager.getLoggerForComponent( "foo" ); assertNotNull( logger ); // assertEquals( "foo", logger.getName() ); return logger; } private void checkDebugLevel( final Logger logger ) { assertTrue( "debug enabled", logger.isDebugEnabled() ); assertTrue( "info enabled", logger.isInfoEnabled() ); assertTrue( "warn enabled", logger.isWarnEnabled() ); assertTrue( "error enabled", logger.isErrorEnabled() ); assertTrue( "fatal enabled", logger.isFatalErrorEnabled() ); } private void checkInfoLevel( final Logger logger ) { assertFalse( "debug disabled", logger.isDebugEnabled() ); assertTrue( "info enabled", logger.isInfoEnabled() ); assertTrue( "warn enabled", logger.isWarnEnabled() ); assertTrue( "error enabled", logger.isErrorEnabled() ); assertTrue( "fatal enabled", logger.isFatalErrorEnabled() ); } private void checkWarnLevel( final Logger logger ) { assertFalse( "debug disabled", logger.isDebugEnabled() ); assertFalse( "info disabled", logger.isInfoEnabled() ); assertTrue( "warn enabled", logger.isWarnEnabled() ); assertTrue( "error enabled", logger.isErrorEnabled() ); assertTrue( "fatal enabled", logger.isFatalErrorEnabled() ); } private void checkErrorLevel( final Logger logger ) { assertFalse( "debug disabled", logger.isDebugEnabled() ); assertFalse( "info disabled", logger.isInfoEnabled() ); assertFalse( "warn disabled", logger.isWarnEnabled() ); assertTrue( "error enabled", logger.isErrorEnabled() ); assertTrue( "fatal enabled", logger.isFatalErrorEnabled() ); } private void checkFatalLevel( final Logger logger ) { assertFalse( "debug disabled", logger.isDebugEnabled() ); assertFalse( "info disabled", logger.isInfoEnabled() ); assertFalse( "warn disabled", logger.isWarnEnabled() ); assertFalse( "error disabled", logger.isErrorEnabled() ); assertTrue( "fatal enabled", logger.isFatalErrorEnabled() ); } } CustomLoggerFactoryTest.java000066400000000000000000000013241167051330000432340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/loggingpackage org.codehaus.plexus.logging; import javax.inject.Inject; import org.codehaus.plexus.PlexusTestCase; public class CustomLoggerFactoryTest extends PlexusTestCase { static class ComponentWithSLF4J { @Inject org.slf4j.Logger loggerDependency; org.slf4j.Logger loggerRequirement; } public void testCustomLoggerName() throws Exception { final String customName = "::" + ComponentWithSLF4J.class.getName() + "::"; final ComponentWithSLF4J component = lookup( ComponentWithSLF4J.class ); assertEquals( customName, component.loggerDependency.getName() ); assertEquals( customName, component.loggerRequirement.getName() ); } } CustomLoggerManagerTest.java000066400000000000000000000023451167051330000432030ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/loggingpackage org.codehaus.plexus.logging; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.PlexusTestCase; //TODO: this test will get nuked, this needs to be done programmatically /** * @author Trygve Laugstøl * @version $Id: CustomLoggerManagerTest.java 7828 2008-11-14 22:07:56Z dain $ */ public class CustomLoggerManagerTest extends PlexusTestCase { public void testBasic() throws Exception { final LoggerManager manager = lookup( LoggerManager.class ); assertNotNull( manager ); assertEquals( MockLoggerManager.class.getName(), manager.getClass().getName() ); } } LogEnabledTest.java000066400000000000000000000062521167051330000412730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/loggingpackage org.codehaus.plexus.logging; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import junit.framework.TestCase; /** * @author Peter Donald * @version $Revision: 4779 $ $Date: 2006-11-23 12:09:31 +0800 (Thu, 23 Nov 2006) $ */ public class LogEnabledTest extends TestCase { public void testGetLogger() throws Exception { final MockLogEnabled logEnabled = new MockLogEnabled(); final MockLogger logger = new MockLogger( "base" ); logEnabled.enableLogging( logger ); assertEquals( "logger", logger, logEnabled.getLogger() ); } public void testSetupLoggerOnLogEnabled() throws Exception { final MockLogEnabled logEnabled = new MockLogEnabled(); final MockLogEnabled childLogEnabled = new MockLogEnabled(); final MockLogger logger = new MockLogger( "base" ); logEnabled.enableLogging( logger ); logEnabled.setupLogger( childLogEnabled ); assertEquals( "logEnabled.logger", logger, logEnabled.getLogger() ); assertEquals( "childLogEnabled.logger", logger, childLogEnabled.getLogger() ); } public void testSetupLoggerOnNonLogEnabled() throws Exception { final MockLogEnabled logEnabled = new MockLogEnabled(); final MockLogger logger = new MockLogger( "base" ); logEnabled.enableLogging( logger ); logEnabled.setupLogger( new Object() ); } public void testSetupLoggerWithNameOnLogEnabled() throws Exception { final MockLogEnabled logEnabled = new MockLogEnabled(); final MockLogEnabled childLogEnabled = new MockLogEnabled(); final MockLogger logger = new MockLogger( "base" ); logEnabled.enableLogging( logger ); logEnabled.setupLogger( childLogEnabled, "child" ); assertEquals( "logEnabled.logger", logger, logEnabled.getLogger() ); assertEquals( "childLogEnabled.logger.name", "base.child", ( (MockLogger) childLogEnabled.getLogger() ).getName() ); } public void testSetupLoggerWithNullName() throws Exception { final MockLogEnabled logEnabled = new MockLogEnabled(); final MockLogEnabled childLogEnabled = new MockLogEnabled(); final MockLogger logger = new MockLogger( "base" ); logEnabled.enableLogging( logger ); try { logEnabled.setupLogger( childLogEnabled, (String) null ); } catch ( final IllegalStateException npe ) { return; } fail( "Expected to fail setting up child logger with null name" ); } } MockLogEnabled.java000066400000000000000000000015441167051330000412440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/loggingpackage org.codehaus.plexus.logging; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Peter Donald * @version $Revision: 4779 $ $Date: 2006-11-23 12:09:31 +0800 (Thu, 23 Nov 2006) $ */ class MockLogEnabled extends AbstractLogEnabled { } MockLogger.java000066400000000000000000000044731167051330000404730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/loggingpackage org.codehaus.plexus.logging; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Peter Donald * @version $Revision: 4779 $ $Date: 2006-11-23 12:09:31 +0800 (Thu, 23 Nov 2006) $ */ class MockLogger implements Logger { private final String m_name; MockLogger( final String name ) { m_name = name; } public String getName() { return m_name; } public Logger getChildLogger( final String name ) { return new MockLogger( getName() + "." + name ); } public void debug( final String message ) { } public void debug( final String message, final Throwable throwable ) { } public boolean isDebugEnabled() { return false; } public void info( final String message ) { } public void info( final String message, final Throwable throwable ) { } public boolean isInfoEnabled() { return false; } public void warn( final String message ) { } public void warn( final String message, final Throwable throwable ) { } public boolean isWarnEnabled() { return false; } public boolean isFatalErrorEnabled() { return false; } public void fatalError( final String message ) { } public void fatalError( final String message, final Throwable throwable ) { } public void error( final String message ) { } public void error( final String message, final Throwable throwable ) { } public boolean isErrorEnabled() { return false; } public int getThreshold() { return 0; } public void setThreshold( final int threshold ) { } } MockLoggerFactory.java000066400000000000000000000004751167051330000420210ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/loggingpackage org.codehaus.plexus.logging; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MockLoggerFactory implements ILoggerFactory { public Logger getLogger( final String name ) { return LoggerFactory.getLogger( "::" + name + "::" ); } } MockLoggerManager.java000066400000000000000000000036661167051330000417710ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/loggingpackage org.codehaus.plexus.logging; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Trygve Laugstøl * @version $Id: MockLoggerManager.java 4778 2006-11-23 03:54:18Z jvanzyl $ */ public class MockLoggerManager implements LoggerManager { public void setThreshold( final int threshold ) { } public void setThresholds( final int threshold ) { } public int getThreshold() { return 0; } public void setThreshold( final String role, final int threshold ) { } public void setThreshold( final String role, final String roleHint, final int threshold ) { } public int getThreshold( final String role ) { return 0; } public int getThreshold( final String role, final String roleHint ) { return 0; } public Logger getLoggerForComponent( final String role ) { return new MockLogger( role.getClass().getName() ); } public Logger getLoggerForComponent( final String role, final String roleHint ) { return new MockLogger( role.getClass().getName() + ":" + roleHint ); } public void returnComponentLogger( final String role ) { } public void returnComponentLogger( final String role, final String hint ) { } public int getActiveLoggerCount() { return 0; } } 000077500000000000000000000000001167051330000372315ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/logging/consoleConsoleLoggerManagerTest.java000066400000000000000000000035371167051330000450010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/logging/consolepackage org.codehaus.plexus.logging.console; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.logging.AbstractLoggerManagerTest; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.LoggerManager; /** * Test for {@link org.codehaus.plexus.logging.console.ConsoleLoggerManager} and * {@link org.codehaus.plexus.logging.console.ConsoleLogger}. * * @author Mark H. Wilkinson * @version $Revision: 7828 $ */ public final class ConsoleLoggerManagerTest extends AbstractLoggerManagerTest { @Override protected LoggerManager createLoggerManager() throws Exception { return lookup( LoggerManager.class ); } @Override public void testSetThreshold() { // disable test } @Override public void testActiveLoggerCount() { // disable test } public void testSetAllThresholds() throws Exception { final LoggerManager manager = createLoggerManager(); manager.setThreshold( Logger.LEVEL_ERROR ); final Logger logger = manager.getLoggerForComponent( "test" ); assertEquals( logger.getThreshold(), Logger.LEVEL_ERROR ); manager.setThresholds( Logger.LEVEL_DEBUG ); assertEquals( logger.getThreshold(), Logger.LEVEL_DEBUG ); } } ConsoleLoggerTest.java000066400000000000000000000071151167051330000435020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/logging/consolepackage org.codehaus.plexus.logging.console; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.io.ByteArrayOutputStream; import java.io.PrintStream; import junit.framework.TestCase; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.util.StringUtils; /** * @author Jason van Zyl * @version $Id: ConsoleLoggerTest.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ConsoleLoggerTest extends TestCase { public void testConsoleLogger() { final ConsoleLogger logger = new ConsoleLogger( Logger.LEVEL_DEBUG, "test" ); assertTrue( logger.isDebugEnabled() ); assertTrue( logger.isInfoEnabled() ); assertTrue( logger.isWarnEnabled() ); assertTrue( logger.isErrorEnabled() ); assertTrue( logger.isFatalErrorEnabled() ); // Save the original print stream. final PrintStream original = System.out; final Throwable t = new Throwable( "throwable" ); ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintStream consoleStream = new PrintStream( os ); System.setOut( consoleStream ); logger.debug( "debug" ); assertEquals( "[DEBUG] debug", getMessage( consoleStream, os ) ); logger.debug( "debug", t ); assertEquals( "[DEBUG] debug", getMessage( consoleStream, os ) ); os = new ByteArrayOutputStream(); consoleStream = new PrintStream( os ); System.setOut( consoleStream ); logger.info( "info" ); assertEquals( "[INFO] info", getMessage( consoleStream, os ) ); logger.info( "info", t ); assertEquals( "[INFO] info", getMessage( consoleStream, os ) ); os = new ByteArrayOutputStream(); consoleStream = new PrintStream( os ); System.setOut( consoleStream ); logger.warn( "warn" ); assertEquals( "[WARNING] warn", getMessage( consoleStream, os ) ); logger.warn( "warn", t ); assertEquals( "[WARNING] warn", getMessage( consoleStream, os ) ); os = new ByteArrayOutputStream(); consoleStream = new PrintStream( os ); System.setOut( consoleStream ); logger.error( "error" ); assertEquals( "[ERROR] error", getMessage( consoleStream, os ) ); logger.error( "error", t ); assertEquals( "[ERROR] error", getMessage( consoleStream, os ) ); os = new ByteArrayOutputStream(); consoleStream = new PrintStream( os ); System.setOut( consoleStream ); logger.fatalError( "error" ); assertEquals( "[FATAL ERROR] error", getMessage( consoleStream, os ) ); logger.fatalError( "error", t ); assertEquals( "[FATAL ERROR] error", getMessage( consoleStream, os ) ); // Set the original print stream. System.setOut( original ); } private String getMessage( final PrintStream consoleStream, final ByteArrayOutputStream os ) { consoleStream.flush(); consoleStream.close(); return StringUtils.chopNewline( os.toString() ); } } 000077500000000000000000000000001167051330000351205ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testAbstractStartableComponent.java000066400000000000000000000040461167051330000432570ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; import static junit.framework.Assert.assertTrue; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException; public class AbstractStartableComponent implements StartableComponent, Startable { public int startOrder; public int stopOrder; public AbstractStartableComponent component1; public AbstractStartableComponent component2; public void start() throws StartingException { startOrder = startGenerator.getAndIncrement(); } public void stop() throws StoppingException { stopOrder = stopGenerator.getAndIncrement(); } public void assertStartOrderCorrect() { if ( component1 != null ) { assertTrue( "This component started before injected component1", startOrder > component1.startOrder ); } if ( component2 != null ) { assertTrue( "This component started before injected component2", startOrder > component2.startOrder ); } // assert children are correct if ( component1 != null ) { component1.assertStartOrderCorrect(); } if ( component2 != null ) { component2.assertStartOrderCorrect(); } } public void assertStopOrderCorrect() { if ( component1 != null ) { assertTrue( "This component stopped after injected component1", stopOrder < component1.stopOrder ); } if ( component2 != null ) { assertTrue( "This component stopped after injected component2", stopOrder < component2.stopOrder ); } // assert children are correct if ( component1 != null ) { component1.assertStopOrderCorrect(); } if ( component2 != null ) { component2.assertStopOrderCorrect(); } } } Action.java000066400000000000000000000014041167051330000371770ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: Action.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface Action { } AddUserAction.java000066400000000000000000000014441167051330000404530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: AddUserAction.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class AddUserAction implements Action { } CircularComponent.java000066400000000000000000000002061167051330000414100ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; public interface CircularComponent { static String ROLE = CircularComponent.class.getName(); } Component.java000066400000000000000000000016651167051330000377350ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.test.map.Activity; /** * @author Jason van Zyl * @version $Id: Component.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface Component { static String ROLE = Component.class.getName(); String getHost(); int getPort(); Activity getActivity(); } ComponentA.java000066400000000000000000000015101167051330000400230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface ComponentA { static String ROLE = ComponentA.class.getName(); ComponentB getComponentB(); ComponentC getComponentC(); String getHost(); int getPort(); } ComponentB.java000066400000000000000000000013331167051330000400270ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface ComponentB { static String ROLE = ComponentB.class.getName(); } ComponentC.java000066400000000000000000000013741167051330000400350ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface ComponentC { static String ROLE = ComponentC.class.getName(); ComponentD getComponentD(); } ComponentD.java000066400000000000000000000013621167051330000400330ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface ComponentD { static String ROLE = ComponentD.class.getName(); String getName(); } ComponentManager.java000066400000000000000000000014211167051330000412160ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.util.List; import java.util.Map; public interface ComponentManager { List getList(); Map getMap(); } ComponentWithRoleDefault.java000066400000000000000000000012611167051330000427100ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public class ComponentWithRoleDefault { } ConcreteThing.java000066400000000000000000000012731167051330000405220ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public class ConcreteThing implements Thing { } CountInstancesComponent.java000066400000000000000000000021741167051330000426120ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * Component counts number of created instances of it. * * @author Piotr Tabor */ public class CountInstancesComponent { public static String ROLE = CountInstancesComponent.class.getName(); private static int instances = 0; public CountInstancesComponent() { instances++; } public static void reset() { instances = 0; } public static int getInstancesCount() { return instances; } } DefaultCircularComponent.java000066400000000000000000000015621167051330000427230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException; public class DefaultCircularComponent implements CircularComponent, Startable { private PlexusContainer container; private String lookup; public void start() throws StartingException { try { if ( lookup != null ) { container.lookup( CircularComponent.class, lookup ); } } catch ( final Exception e ) { throw new StartingException( "failed", e ); } } public void stop() throws StoppingException { } } DefaultComponent.java000066400000000000000000000020011167051330000412230ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.test.map.Activity; public class DefaultComponent implements Component { private String host; private int port; private Activity activity; public Activity getActivity() { return activity; } public String getHost() { return host; } public int getPort() { return port; } } DefaultComponentA.java000066400000000000000000000025351167051330000413400ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @component.role org.codehaus.plexus.test.ComponentA * @component.requirement org.codehaus.plexus.test.ComponentB * @component.requirement org.codehaus.plexus.test.ComponentC * @component.version 1.0 */ public class DefaultComponentA implements ComponentA { private ComponentB componentB; private ComponentC componentC; /** @default localhost */ private String host; /** @default 10000 */ private int port; public ComponentB getComponentB() { return componentB; } public ComponentC getComponentC() { return componentC; } public String getHost() { return host; } public int getPort() { return port; } } DefaultComponentB.java000066400000000000000000000013451167051330000413370ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @component.version 2.0 */ public class DefaultComponentB implements ComponentB { } DefaultComponentC.java000066400000000000000000000014641167051330000413420ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public class DefaultComponentC implements ComponentC { private ComponentD componentD; public ComponentD getComponentD() { return componentD; } } DefaultComponentD.java000066400000000000000000000014321167051330000413360ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public class DefaultComponentD implements ComponentD { private String name; public String getName() { return name; } } DefaultComponentManager.java000066400000000000000000000016751167051330000425360ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.util.List; import java.util.Map; public class DefaultComponentManager implements ComponentManager { private List list; private Map map; public List getList() { return list; } public Map getMap() { return map; } } DefaultComponentWithOptionalRequirement.java000066400000000000000000000014031167051330000460130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public class DefaultComponentWithOptionalRequirement extends DefaultComponent { public Object optionalComponent; } DefaultLoadOnStartService.java000066400000000000000000000020551167051330000430050ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; /** * @author Jason van Zyl * @version $Id: DefaultLoadOnStartService.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultLoadOnStartService implements LoadOnStartService, Startable { public static boolean isStarted = false; public void start() { isStarted = true; } public void stop() { } } DefaultLoadOnStartServiceWithRoleHint.java000066400000000000000000000015401167051330000453040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: DefaultLoadOnStartServiceWithRoleHint.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultLoadOnStartServiceWithRoleHint implements LoadOnStartService { } DefaultServiceB.java000066400000000000000000000034441167051330000407770ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; /** * A simple native plexus component. */ public class DefaultServiceB extends AbstractLogEnabled implements ServiceB, Contextualizable, Initializable, Startable { public boolean enableLogging; public boolean contextualize; public boolean initialize; public boolean start; public boolean stop; @Override public void enableLogging( final Logger logger ) { enableLogging = true; } public void contextualize( final Context context ) throws ContextException { contextualize = true; } public void initialize() { initialize = true; } public void start() { start = true; } public void stop() { stop = true; } } DefaultServiceC.java000066400000000000000000000017261167051330000410010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; public class DefaultServiceC implements ServiceC, Startable { public boolean started = false; public boolean stopped = false; public void start() { started = true; } public void stop() { stopped = true; } } DefaultServiceD.java000066400000000000000000000012771167051330000410030ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public class DefaultServiceD implements ServiceD { } DefaultServiceE.java000066400000000000000000000036161167051330000410030ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; /** * A simple native plexus component implementing the manual configuration phase. */ public class DefaultServiceE extends AbstractLogEnabled implements ServiceE, Contextualizable, Initializable, Startable { public boolean enableLogging; public boolean configured; public boolean contextualize; public boolean initialize; public boolean start; public boolean stop; public boolean serviced; @Override public void enableLogging( final Logger logger ) { enableLogging = true; } public void contextualize( final Context context ) throws ContextException { contextualize = true; } public void initialize() { initialize = true; } public void start() { start = true; } public void stop() { stop = true; } } DefaultStartableComponentA.java000066400000000000000000000001661167051330000432000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; public class DefaultStartableComponentA extends AbstractStartableComponent { } DefaultStartableComponentB.java000066400000000000000000000001661167051330000432010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; public class DefaultStartableComponentB extends AbstractStartableComponent { } DefaultStartableComponentC.java000066400000000000000000000001661167051330000432020ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; public class DefaultStartableComponentC extends AbstractStartableComponent { } DefaultStartableComponentD.java000066400000000000000000000001661167051330000432030ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; public class DefaultStartableComponentD extends AbstractStartableComponent { } DefaultStartableComponentE.java000066400000000000000000000001661167051330000432040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; public class DefaultStartableComponentE extends AbstractStartableComponent { } DefaultThingUser.java000066400000000000000000000013331167051330000412000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public class DefaultThingUser implements ThingUser { public Thing thing; } LiveComponent.java000066400000000000000000000012461167051330000405500ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public class LiveComponent { } LoadOnStartService.java000066400000000000000000000015221167051330000414760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: LoadOnStartService.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface LoadOnStartService { String ROLE = LoadOnStartService.class.getName(); } LoadOnStartServiceWithRoleHint.java000066400000000000000000000015661167051330000440070ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: LoadOnStartServiceWithRoleHint.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface LoadOnStartServiceWithRoleHint { String ROLE = LoadOnStartServiceWithRoleHint.class.getName(); } PlexusContainerTest.java000066400000000000000000000715201167051330000417530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Inject; import junit.framework.TestCase; import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.DefaultContainerConfiguration; import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.discovery.DiscoveredComponent; import org.codehaus.plexus.test.list.Pipeline; import org.codehaus.plexus.test.list.Valve; import org.codehaus.plexus.test.list.ValveFour; import org.codehaus.plexus.test.list.ValveOne; import org.codehaus.plexus.test.list.ValveThree; import org.codehaus.plexus.test.list.ValveTwo; import org.codehaus.plexus.test.map.Activity; import org.codehaus.plexus.test.map.ActivityManager; import org.sonatype.guice.plexus.config.PlexusBeanConverter; import org.sonatype.guice.plexus.converters.PlexusXmlBeanConverter; import com.google.inject.AbstractModule; import com.google.inject.TypeLiteral; public class PlexusContainerTest extends TestCase { private String basedir; private ClassLoader classLoader; private String configuration; private DefaultPlexusContainer container; public PlexusContainerTest( final String name ) { super( name ); } @Override public void setUp() throws Exception { basedir = System.getProperty( "basedir" ); classLoader = getClass().getClassLoader(); configuration = "/" + getClass().getName().replace( '.', '/' ) + ".xml"; assertNotNull( classLoader ); // ---------------------------------------------------------------------------- // Context // ---------------------------------------------------------------------------- final Map context = new HashMap(); context.put( "basedir", basedir ); context.put( "plexus.home", basedir + "/target/plexus-home" ); final ContainerConfiguration containerConfiguration = new DefaultContainerConfiguration().setName( "test" ).setContext( context ).setContainerConfiguration( configuration ); container = new DefaultPlexusContainer( containerConfiguration ); } @Override public void tearDown() throws Exception { container.dispose(); container = null; } // ---------------------------------------------------------------------- // Test the native plexus lifecycle. Note that the configuration for // this TestCase supplies its own lifecycle, so this test verifies that // the native lifecycle is available after configuration merging. // ---------------------------------------------------------------------- public void testNativeLifecyclePassage() throws Exception { final DefaultServiceB serviceB = (DefaultServiceB) container.lookup( ServiceB.class ); // Make sure the component is alive. assertNotNull( serviceB ); // Make sure the component went through all the lifecycle phases assertEquals( true, serviceB.enableLogging ); assertEquals( true, serviceB.contextualize ); assertEquals( true, serviceB.initialize ); assertEquals( true, serviceB.start ); assertEquals( false, serviceB.stop ); container.release( serviceB ); assertEquals( true, serviceB.stop ); } public void testConfigurableLifecyclePassage() throws Exception { final DefaultServiceE serviceE = (DefaultServiceE) container.lookup( ServiceE.class ); // Make sure the component is alive. assertNotNull( serviceE ); // Make sure the component went through all the lifecycle phases assertEquals( true, serviceE.enableLogging ); assertEquals( true, serviceE.contextualize ); assertEquals( true, serviceE.initialize ); assertEquals( true, serviceE.start ); assertEquals( false, serviceE.stop ); container.release( serviceE ); assertEquals( true, serviceE.stop ); } /* * Check that we can get references to a single component with a role hint. */ public void testSingleComponentLookupWithRoleHint() throws Exception { // Retrieve an instance of component c. final DefaultServiceC serviceC1 = (DefaultServiceC) container.lookup( ServiceC.class, "first-instance" ); // Make sure the component is alive. assertNotNull( serviceC1 ); assertTrue( serviceC1.started ); assertFalse( serviceC1.stopped ); // Retrieve a second reference to the same component. final DefaultServiceC serviceC2 = (DefaultServiceC) container.lookup( ServiceC.class, "first-instance" ); // Make sure component is alive. assertNotNull( serviceC2 ); assertTrue( serviceC2.started ); assertFalse( serviceC2.stopped ); // Let's make sure it gave us back the same component. assertSame( serviceC1, serviceC2 ); container.release( serviceC1 ); // The component should still be alive. assertTrue( serviceC2.started ); assertTrue( serviceC2.stopped ); container.release( serviceC2 ); // The component should now have been stopped. assertTrue( serviceC2.started ); assertTrue( serviceC2.stopped ); } /* * Check that distinct components with the same implementation are managed correctly. */ public void testMultipleSingletonComponentInstances() throws Exception { // Retrieve an instance of component c. final DefaultServiceC serviceC1 = (DefaultServiceC) container.lookup( ServiceC.class, "first-instance" ); // Make sure the component is alive. assertNotNull( serviceC1 ); assertTrue( serviceC1.started ); assertFalse( serviceC1.stopped ); // Retrieve an instance of component c, with a different role hint. // This should give us a different component instance. final DefaultServiceC serviceC2 = (DefaultServiceC) container.lookup( ServiceC.class, "second-instance" ); // Make sure component is alive. assertNotNull( serviceC2 ); assertTrue( serviceC2.started ); assertFalse( serviceC2.stopped ); // The components should be distinct. assertNotSame( serviceC1, serviceC2 ); container.release( serviceC1 ); // The first component should now have been stopped, the second // one should still be alive. assertTrue( serviceC1.started ); assertTrue( serviceC1.stopped ); assertTrue( serviceC2.started ); assertFalse( serviceC2.stopped ); container.release( serviceC2 ); // The second component should now have been stopped. assertTrue( serviceC2.started ); assertTrue( serviceC2.stopped ); } public void testLookupAll() throws Exception { final Map components = container.lookupMap( ServiceC.class ); assertNotNull( components ); assertEquals( 2, components.size() ); ServiceC component = components.get( "first-instance" ); assertNotNull( component ); component = components.get( "second-instance" ); assertNotNull( component ); container.releaseAll( components ); } public void testAutomatedComponentConfigurationUsingXStreamPoweredComponentConfigurator() throws Exception { final Component component = container.lookup( Component.class ); assertNotNull( component ); assertNotNull( component.getActivity() ); assertEquals( "localhost", component.getHost() ); assertEquals( 10000, component.getPort() ); } public void testAutomatedComponentComposition() throws Exception { final ComponentA componentA = container.lookup( ComponentA.class ); assertNotNull( componentA ); assertEquals( "localhost", componentA.getHost() ); assertEquals( 10000, componentA.getPort() ); final ComponentB componentB = componentA.getComponentB(); assertNotNull( componentB ); final ComponentC componentC = componentA.getComponentC(); assertNotNull( componentC ); final ComponentD componentD = componentC.getComponentD(); assertNotNull( componentD ); assertEquals( "jason", componentD.getName() ); } public void testComponentCompositionWhereTargetFieldIsAMap() throws Exception { final ActivityManager am = container.lookup( ActivityManager.class ); final Activity one = am.getActivity( "one" ); assertNotNull( one ); // repeated retrieval from map should not cause re-lookup even if instantiation strategy is per-lookup assertSame( one, am.getActivity( "one" ) ); assertFalse( one.getState() ); am.execute( "one" ); assertTrue( one.getState() ); final Activity two = am.getActivity( "two" ); assertNotNull( two ); assertFalse( two.getState() ); am.execute( "two" ); assertTrue( two.getState() ); } public void testComponentCompositionWhereTargetFieldIsAPartialMap() throws Exception { final ActivityManager am = container.lookup( ActivityManager.class, "slim" ); assertEquals( 1, am.getActivityCount() ); final Activity one = am.getActivity( "one" ); assertNotNull( one ); assertFalse( one.getState() ); am.execute( "one" ); assertTrue( one.getState() ); } public void testComponentCompositionWhereTargetFieldIsAList() throws Exception { final Pipeline pipeline = container.lookup( Pipeline.class ); final List valves = pipeline.getValves(); for ( int i = 0; i < valves.size(); i++ ) { // repeated retrieval from list should not cause re-lookup even if instantiation strategy is per-lookup assertSame( valves.get( i ), valves.get( i ) ); } assertFalse( ( (Valve) valves.get( 0 ) ).getState() ); assertFalse( ( (Valve) valves.get( 1 ) ).getState() ); pipeline.execute(); assertTrue( ( (Valve) valves.get( 0 ) ).getState() ); assertTrue( ( (Valve) valves.get( 1 ) ).getState() ); } public void testComponentCompositionWhereTargetFieldIsAPartialList() throws Exception { final Pipeline pipeline = container.lookup( Pipeline.class, "slim" ); final List valves = pipeline.getValves(); assertEquals( valves.size(), 1 ); assertFalse( ( (Valve) valves.get( 0 ) ).getState() ); pipeline.execute(); assertTrue( ( (Valve) valves.get( 0 ) ).getState() ); } public void testComponentCompositionWhereTargetFieldAMapThatMustRetainTheOrderOfComponentsGivenASetOfRoleHints() throws Exception { final Pipeline pipeline = container.lookup( Pipeline.class, "chubby" ); final Map valveMap = pipeline.getValveMap(); final List valves = new ArrayList( valveMap.values() ); assertEquals( "Expecting three valves.", 4, valves.size() ); assertTrue( "Expecting valve one.", valves.get( 0 ) instanceof ValveOne ); assertTrue( "Expecting valve two.", valves.get( 1 ) instanceof ValveTwo ); assertTrue( "Expecting valve three.", valves.get( 2 ) instanceof ValveThree ); assertTrue( "Expecting valve four.", valves.get( 3 ) instanceof ValveFour ); } public void testLookupOfComponentThatShouldBeDiscovered() throws Exception { final DiscoveredComponent discoveredComponent = container.lookup( DiscoveredComponent.class ); assertNotNull( discoveredComponent ); } public void testStartableComponentSnake() throws Exception { final StartableComponent ca = container.lookup( StartableComponent.class, "A-snake" ); assertNotNull( ca ); ca.assertStartOrderCorrect(); container.dispose(); ca.assertStopOrderCorrect(); } public void testStartableComponentTree() throws Exception { final StartableComponent ca = container.lookup( StartableComponent.class, "A-tree" ); assertNotNull( ca ); ca.assertStartOrderCorrect(); container.dispose(); ca.assertStopOrderCorrect(); } public void testAddComponent() throws Exception { final LiveComponent live = new LiveComponent(); container.addComponent( live, LiveComponent.class.getName() ); final LiveComponent c = container.lookup( LiveComponent.class ); assertSame( live, c ); } public void testComponentOverride() throws Exception { assertNotNull( container.lookup( Component.class ) ); final Component live = new Component() { public Activity getActivity() { return null; } public String getHost() { return null; } public int getPort() { return 0; } }; container.addComponent( live, Component.class, null ); assertSame( live, container.lookup( Component.class ) ); } public void testUpdateOfActiveComponentCollectionUponChangeOfThreadContextClassLoader() throws Exception { final ComponentManager manager = container.lookup( ComponentManager.class ); Map map = manager.getMap(); assertNotNull( map ); assertEquals( 0, map.size() ); List list = manager.getList(); assertNotNull( list ); assertEquals( 0, list.size() ); /* * Below we're creating two realms which basically contain the same components, only their bytecode/version * differs. When we switch the thread's context class loader, the active component collections in the component * manager must accurately reflect the components from the current realm (and not from a previous realm). */ final ClassRealm realmA = container.createChildRealm( "realm-a" ); realmA.addURL( new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ).toURI().toURL() ); container.discoverComponents( realmA ); final ClassRealm realmB = container.createChildRealm( "realm-b" ); realmB.addURL( new File( "src/test/test-components/component-a-2.0-SNAPSHOT.jar" ).toURI().toURL() ); container.discoverComponents( realmB ); final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( realmA ); map = manager.getMap(); assertNotNull( map ); assertEquals( 1, map.size() ); assertSame( realmA, map.values().iterator().next().getClass().getClassLoader() ); list = manager.getList(); assertNotNull( list ); assertEquals( 1, list.size() ); assertSame( realmA, list.iterator().next().getClass().getClassLoader() ); Thread.currentThread().setContextClassLoader( realmB ); map = manager.getMap(); assertNotNull( map ); assertEquals( 1, map.size() ); assertSame( realmB, map.values().iterator().next().getClass().getClassLoader() ); list = manager.getList(); assertNotNull( list ); assertEquals( 1, list.size() ); assertSame( realmB, list.iterator().next().getClass().getClassLoader() ); } finally { Thread.currentThread().setContextClassLoader( oldClassLoader ); } } public void testUpdateOfActiveComponentCollectionUponChangeOfThreadContextClassLoaderFromParentToChildRealm() throws Exception { final ComponentManager manager = container.lookup( ComponentManager.class ); Map map = manager.getMap(); assertNotNull( map ); assertEquals( 0, map.size() ); List list = manager.getList(); assertNotNull( list ); assertEquals( 0, list.size() ); /* * Below we're creating two realms which basically contain the same components, only their bytecode/version * differs. The realms form a parent-child relationship where the child imports the component role from the * parent. When we first load from the parent and then switch the thread's context class loader to the child, * the active component collections in the component manager must accurately reflect the components from the * current realm (and not from a previous realm). */ final ClassRealm realmA = container.createChildRealm( "realm-a" ); realmA.addURL( new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ).toURI().toURL() ); container.discoverComponents( realmA ); final ClassRealm realmB = realmA.createChildRealm( "realm-b" ); realmB.importFrom( realmA, "org.codehaus.plexus.components.A" ); realmB.importFromParent( "nothing" ); realmB.addURL( new File( "src/test/test-components/component-a-2.0-SNAPSHOT.jar" ).toURI().toURL() ); container.discoverComponents( realmB ); final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( realmA ); map = manager.getMap(); assertNotNull( map ); assertEquals( 1, map.size() ); assertSame( realmA, map.values().iterator().next().getClass().getClassLoader() ); list = manager.getList(); assertNotNull( list ); assertEquals( 1, list.size() ); assertSame( realmA, list.iterator().next().getClass().getClassLoader() ); Thread.currentThread().setContextClassLoader( realmB ); map = manager.getMap(); assertNotNull( map ); assertEquals( 2, map.size() ); assertSame( realmB, map.values().iterator().next().getClass().getClassLoader() ); list = manager.getList(); assertNotNull( list ); assertEquals( 2, list.size() ); assertSame( realmB, list.iterator().next().getClass().getClassLoader() ); } finally { Thread.currentThread().setContextClassLoader( oldClassLoader ); } } public void testComponentLookupFromParentRealmOfImportedRealms() throws Exception { final ComponentManager manager = container.lookup( ComponentManager.class ); Map map = manager.getMap(); assertNotNull( map ); assertEquals( 0, map.size() ); List list = manager.getList(); assertNotNull( list ); assertEquals( 0, list.size() ); final URL componentUrl = new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ).toURI().toURL(); final ClassRealm realmP = container.createChildRealm( "parent-of-imported-realm" ); realmP.addURL( componentUrl ); container.discoverComponents( realmP ); final ClassRealm realmI = realmP.createChildRealm( "imported-realm" ); final ClassRealm realmL = container.createChildRealm( "lookup-realm" ); realmL.importFrom( realmI, "org.something" ); final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( realmL ); map = manager.getMap(); assertNotNull( map ); assertEquals( 1, map.size() ); assertSame( realmP, map.values().iterator().next().getClass().getClassLoader() ); list = manager.getList(); assertNotNull( list ); assertEquals( 1, list.size() ); assertSame( realmP, list.iterator().next().getClass().getClassLoader() ); } finally { Thread.currentThread().setContextClassLoader( oldClassLoader ); } } public void testOptionalComponentRequirement() throws Exception { final DefaultComponentWithOptionalRequirement ca = (DefaultComponentWithOptionalRequirement) container.lookup( Component.class, "with-optional" ); assertNotNull( ca ); assertNotNull( ca.getActivity() ); assertNull( ca.optionalComponent ); } public void testLookupOfComponentThatHasARequirementWithoutRoleHintAndTheOneAndOnlyImplHasNoDefaultHint() throws Exception { final DefaultThingUser component = (DefaultThingUser) container.lookup( ThingUser.class ); assertNotNull( component.thing ); } public void testSingleLookupWithAndWithoutRoleHint() throws Exception { final ComponentWithRoleDefault withRoleHint = container.lookup( ComponentWithRoleDefault.class, "default" ); final ComponentWithRoleDefault withoutRoleHint = container.lookup( ComponentWithRoleDefault.class ); assertSame( withRoleHint, withoutRoleHint ); } public void testLookupUponChangeOfThreadContextClassLoaderFromParentToChildRealm() throws Exception { /* * Below we're creating two realms which basically contain the same components, only their bytecode/version * differs. The realms form a parent-child relationship where the child imports the component role from the * parent. When we first lookup from the parent and then switch the thread's context class loader to the child, * the second lookup must accurately reflect the components from the current realm (and not from a previous * realm). */ final ClassRealm realmA = container.createChildRealm( "realm-a" ); realmA.addURL( new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ).toURI().toURL() ); container.discoverComponents( realmA ); final ClassRealm realmB = realmA.createChildRealm( "realm-b" ); realmB.importFrom( realmA, "org.codehaus.plexus.components.A" ); realmB.importFromParent( "nothing" ); realmB.addURL( new File( "src/test/test-components/component-a-2.0-SNAPSHOT.jar" ).toURI().toURL() ); container.discoverComponents( realmB ); final Class role = realmA.loadClass( "org.codehaus.plexus.components.A" ); final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( realmA ); final Object comp1 = container.lookup( role, "default" ); Thread.currentThread().setContextClassLoader( realmB ); final Object comp2 = container.lookup( role, "default" ); assertNotNull( comp1 ); assertNotNull( comp2 ); assertNotSame( comp1, comp2 ); assertSame( realmA, comp1.getClass().getClassLoader() ); assertSame( realmB, comp2.getClass().getClassLoader() ); } finally { Thread.currentThread().setContextClassLoader( oldClassLoader ); } } public void testSafeConcurrentAccessToActiveComponentCollection() throws Exception { final ComponentManager manager = container.lookup( ComponentManager.class ); final Map map = manager.getMap(); assertNotNull( map ); assertEquals( 0, map.size() ); final List list = manager.getList(); assertNotNull( list ); assertEquals( 0, list.size() ); final AtomicBoolean go = new AtomicBoolean( false ); final List exceptions = new CopyOnWriteArrayList(); final Thread[] threads = new Thread[64]; final CountDownLatch latch = new CountDownLatch( threads.length ); for ( int i = 0; i < threads.length; i++ ) { threads[i] = new Thread() { @Override public void run() { try { final ClassRealm realm = container.createChildRealm( "realm-" + UUID.randomUUID().toString() ); realm.addURL( new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ).toURI().toURL() ); container.discoverComponents( realm ); Thread.currentThread().setContextClassLoader( realm ); while ( !go.get() ) { // just wait } for ( int j = 0; j < 1000; j++ ) { // this just must not die with some exception for ( final Object value : map.values() ) { value.toString(); } for ( final Object value : list ) { value.toString(); } } } catch ( final Exception e ) { e.printStackTrace(); exceptions.add( e ); } finally { latch.countDown(); } } }; threads[i].start(); } go.set( true ); latch.await(); assertTrue( exceptions.toString(), exceptions.isEmpty() ); } public void testComponentConfigurationEvaluation() throws Exception { /** *
         * Inject component configuration provided via user-editable text file, similar in nature to pom.xml
         * Immediately need to support two cases
         * 
         * 1. Injecting well-known "external" objects, like org.apache.maven.settings.Settings instance
         * 2. Inject string constants, like repository URLs or credentials.
         * 
         * There is probably more than one way to implement this, but I will attempt logic similar to ${parameter}
         * Maven plugin parameter substitution, with actual substitution logic provided by the client.
         * 
         * IMPLEMENTATION QUESTION: instead of passing PlexusBeanConverter as explicit parameter, is there a way to
         * push Provider instance as thread/request scoped bean?
         * 
*/ final ClassRealm realmA = container.createChildRealm( "realm-with-configuration" ); realmA.addURL( new File( "src/test/test-components/component-with-configuration-1.0-SNAPSHOT.jar" ).toURI().toURL() ); final String stringValue = "string value"; final Object objectValue = new Object(); final PlexusBeanConverter converter = new PlexusBeanConverter() { @Inject private PlexusXmlBeanConverter xmlConverter; @SuppressWarnings( { "unchecked", "rawtypes" } ) public Object convert( final TypeLiteral role, final String value ) { if ( "${stringValue}".equals( value ) ) { return stringValue; } if ( "${objectValue}".equals( value ) ) { return objectValue; } return xmlConverter.convert( role, value ); } }; container.discoverComponents( realmA, new AbstractModule() { @Override protected void configure() { bind( PlexusBeanConverter.class ).toInstance( converter ); } } ); final Object c = container.lookup( "org.codehaus.plexus.components.withconfiguration.C" ); assertEquals( stringValue, c.getClass().getField( "stringValue" ).get( c ) ); assertSame( objectValue, c.getClass().getField( "objectValue" ).get( c ) ); assertEquals( "default value", c.getClass().getField( "defaultValue" ).get( c ) ); } } ServiceB.java000066400000000000000000000013271167051330000374700ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface ServiceB { static String ROLE = ServiceB.class.getName(); } ServiceC.java000066400000000000000000000013271167051330000374710ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface ServiceC { static String ROLE = ServiceC.class.getName(); } ServiceD.java000066400000000000000000000013271167051330000374720ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface ServiceD { static String ROLE = ServiceD.class.getName(); } ServiceE.java000066400000000000000000000013271167051330000374730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface ServiceE { static String ROLE = ServiceE.class.getName(); } ServiceH.java000066400000000000000000000013271167051330000374760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface ServiceH { static String ROLE = ServiceH.class.getName(); } StartableComponent.java000066400000000000000000000005731167051330000415740ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; import java.util.concurrent.atomic.AtomicInteger; public interface StartableComponent { static String ROLE = StartableComponent.class.getName(); AtomicInteger startGenerator = new AtomicInteger( 1 ); AtomicInteger stopGenerator = new AtomicInteger( 1 ); void assertStartOrderCorrect(); void assertStopOrderCorrect(); } Thing.java000066400000000000000000000012421167051330000370330ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface Thing { } ThingUser.java000066400000000000000000000012461167051330000376760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/testpackage org.codehaus.plexus.test; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ public interface ThingUser { } 000077500000000000000000000000001167051330000362175ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cycleCircularComponentTest.java000066400000000000000000000004221167051330000433470ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cyclepackage org.codehaus.plexus.test.cycle; import org.codehaus.plexus.PlexusTestCase; public class CircularComponentTest extends PlexusTestCase { public void testCircularComponents() throws Exception { lookup( CycleComponent.class, "A" ); } } CycleComponent.java000066400000000000000000000001501167051330000420000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cyclepackage org.codehaus.plexus.test.cycle; public interface CycleComponent { CycleComponent next(); } DefaultCycleComponentA.java000066400000000000000000000003051167051330000434100ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cyclepackage org.codehaus.plexus.test.cycle; public class DefaultCycleComponentA implements CycleComponent { CycleComponent b; public CycleComponent next() { return b; } } DefaultCycleComponentB.java000066400000000000000000000003051167051330000434110ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cyclepackage org.codehaus.plexus.test.cycle; public class DefaultCycleComponentB implements CycleComponent { CycleComponent c; public CycleComponent next() { return c; } } DefaultCycleComponentC.java000066400000000000000000000006421167051330000434160ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cyclepackage org.codehaus.plexus.test.cycle; import junit.framework.Assert; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; public class DefaultCycleComponentC implements CycleComponent, Initializable { CycleComponent d; public CycleComponent next() { return d; } public void initialize() { Assert.assertNotNull( next().next().next() ); } } DefaultCycleComponentD.java000066400000000000000000000003051167051330000434130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cyclepackage org.codehaus.plexus.test.cycle; public class DefaultCycleComponentD implements CycleComponent { CycleComponent a; public CycleComponent next() { return a; } } EagerComponent.java000066400000000000000000000017171167051330000417760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cyclepackage org.codehaus.plexus.test.cycle; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException; public class EagerComponent implements Startable { LockComponent lockComponent; Thread lockThread; public void start() throws StartingException { lockThread = new Thread( new Runnable() { public void run() { lockComponent.update(); } } ); lockThread.start(); try { Thread.sleep( 200 ); } catch ( final InterruptedException e ) { // ignore } lockComponent.update(); } public void stop() { try { lockThread.join(); } catch ( final InterruptedException e ) { throw new RuntimeException(); } } } LazyComponent.java000066400000000000000000000001101167051330000416540ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cyclepackage org.codehaus.plexus.test.cycle; public class LazyComponent { } LockComponent.java000066400000000000000000000014751167051330000416440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cyclepackage org.codehaus.plexus.test.cycle; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; public class LockComponent { ReadWriteLock lock = new ReentrantReadWriteLock(); PlexusContainer container; public void update() { final Lock writeLock = lock.writeLock(); writeLock.lock(); try { container.lookup( LazyComponent.class ); } catch ( final ComponentLookupException e ) { throw new RuntimeException( e.toString() ); } finally { writeLock.unlock(); } } } LockComponentTest.java000066400000000000000000000004041167051330000424730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/cyclepackage org.codehaus.plexus.test.cycle; import org.codehaus.plexus.PlexusTestCase; public class LockComponentTest extends PlexusTestCase { public void testLockComponent() throws Exception { lookup( EagerComponent.class ); } } 000077500000000000000000000000001167051330000360735ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/listAbstractValve.java000066400000000000000000000017121167051330000415000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/listpackage org.codehaus.plexus.test.list; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: AbstractValve.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public abstract class AbstractValve implements Valve { private boolean state; public boolean getState() { return state; } public void execute() { state = true; } } DefaultPipeline.java000066400000000000000000000023311167051330000420070ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/listpackage org.codehaus.plexus.test.list; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.util.Iterator; import java.util.List; import java.util.Map; /** * @author Jason van Zyl * @version $Id: DefaultPipeline.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultPipeline implements Pipeline { private List valves; private Map valveMap; public void execute() { for ( final Iterator i = valves.iterator(); i.hasNext(); ) { ( (Valve) i.next() ).execute(); } } public List getValves() { return valves; } public Map getValveMap() { return valveMap; } } Pipeline.java000066400000000000000000000016621167051330000405100ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/listpackage org.codehaus.plexus.test.list; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.util.List; import java.util.Map; /** * @author Jason van Zyl * @version $Id: Pipeline.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface Pipeline { static String ROLE = Pipeline.class.getName(); void execute(); List getValves(); Map getValveMap(); } Valve.java000066400000000000000000000015451167051330000400200ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/listpackage org.codehaus.plexus.test.list; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: Valve.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface Valve { static String ROLE = Valve.class.getName(); void execute(); boolean getState(); } ValveFour.java000066400000000000000000000014451167051330000406530ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/listpackage org.codehaus.plexus.test.list; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ValveFour.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ValveFour extends AbstractValve { } ValveOne.java000066400000000000000000000014431167051330000404570ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/listpackage org.codehaus.plexus.test.list; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ValveOne.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ValveOne extends AbstractValve { } ValveThree.java000066400000000000000000000014471167051330000410110ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/listpackage org.codehaus.plexus.test.list; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ValveThree.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ValveThree extends AbstractValve { } ValveTwo.java000066400000000000000000000014431167051330000405070ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/listpackage org.codehaus.plexus.test.list; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ValveTwo.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ValveTwo extends AbstractValve { } 000077500000000000000000000000001167051330000356755ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/mapAbstractActivity.java000066400000000000000000000017221167051330000420220ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/mappackage org.codehaus.plexus.test.map; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: AbstractActivity.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public abstract class AbstractActivity implements Activity { private boolean state; public boolean getState() { return state; } public void execute() { state = true; } } Activity.java000066400000000000000000000015551167051330000403420ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/mappackage org.codehaus.plexus.test.map; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: Activity.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface Activity { static String ROLE = Activity.class.getName(); void execute(); boolean getState(); } ActivityManager.java000066400000000000000000000016711167051330000416340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/mappackage org.codehaus.plexus.test.map; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ActivityManager.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public interface ActivityManager { static String ROLE = ActivityManager.class.getName(); void execute( String id ); Activity getActivity( String id ); int getActivityCount(); } ActivityOne.java000066400000000000000000000014531167051330000410010ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/mappackage org.codehaus.plexus.test.map; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ActivityOne.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ActivityOne extends AbstractActivity { } ActivityTwo.java000066400000000000000000000014531167051330000410310ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/mappackage org.codehaus.plexus.test.map; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ /** * @author Jason van Zyl * @version $Id: ActivityTwo.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class ActivityTwo extends AbstractActivity { } DefaultActivityManager.java000066400000000000000000000022241167051330000431340ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/mappackage org.codehaus.plexus.test.map; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import java.util.Map; /** * @author Jason van Zyl * @version $Id: DefaultActivityManager.java 7089 2007-11-25 15:19:06Z jvanzyl $ */ public class DefaultActivityManager implements ActivityManager { private Map activities; public void execute( final String id ) { getActivity( id ).execute(); } public Activity getActivity( final String id ) { return (Activity) activities.get( id ); } public int getActivityCount() { return activities.size(); } } NoComponentsMapTest.java000066400000000000000000000021461167051330000424630ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/java/org/codehaus/plexus/test/mappackage org.codehaus.plexus.test.map; /* * Copyright 2001-2006 Codehaus Foundation. * * 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. */ import org.codehaus.plexus.PlexusTestCase; /** * @author Trygve Laugstøl * @version $Id: NoComponentsMapTest.java 7828 2008-11-14 22:07:56Z dain $ */ public class NoComponentsMapTest extends PlexusTestCase { public void testNoComponents() throws Exception { ActivityManager manager; manager = lookup( ActivityManager.class ); assertEquals( 0, manager.getActivityCount() ); } } sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/000077500000000000000000000000001167051330000314075ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/META-INF/000077500000000000000000000000001167051330000325475ustar00rootroot00000000000000000077500000000000000000000000001167051330000340105ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/META-INF/plexuscomponents.xml000066400000000000000000000012761167051330000367250ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/META-INF/plexus org.codehaus.plexus.component.discovery.DiscoveredComponent org.codehaus.plexus.component.discovery.DefaultDiscoveredComponent org.codehaus.plexus.component.factory.ComponentFactory testFactory2 org.codehaus.plexus.component.factory.TestComponentFactory2 plexus monkey 1.0 plexus.xml000066400000000000000000000007451167051330000360600ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/META-INF/plexus org.codehaus.plexus.component.factory.ComponentFactory testFactory1 org.codehaus.plexus.component.factory.TestComponentFactory1 org.codehaus.plexus.test.CountInstancesComponent org.codehaus.plexus.test.CountInstancesComponent sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/application/000077500000000000000000000000001167051330000337125ustar00rootroot00000000000000components.xml000066400000000000000000000023141167051330000365420ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/application server two three four one two three configuration-mapping.xml000066400000000000000000000023371167051330000406620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/application 8080 localhost Santa Claus santa@northpole.com email Email irc Irc one one one sentinel.xml000066400000000000000000000010371167051330000361770ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/application 8080 localhost Santa Claus santa@northpole.com email Email irc Irc one one one inline-configuration.properties000066400000000000000000000000441167051330000375670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resourcesfirst-name=andrew last-name=williamsinline-configuration.xml000066400000000000000000000001241167051330000361720ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources jason van zyl sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/000077500000000000000000000000001167051330000321765ustar00rootroot00000000000000000077500000000000000000000000001167051330000337125ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus000077500000000000000000000000001167051330000352325ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexusPlexusTestCaseTest.xml000066400000000000000000000005621167051330000415330ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus org.codehaus.plexus.test.LoadOnStartService org.codehaus.plexus.test.LoadOnStartService org.codehaus.plexus.test.DefaultLoadOnStartService 000077500000000000000000000000001167051330000372345ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component000077500000000000000000000000001167051330000415775ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/composition000077500000000000000000000000001167051330000434365ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/composition/autowireAutowireCompositionTest.xml000066400000000000000000000007211167051330000510430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/composition/autowire org.codehaus.plexus.component.composition.autowire.One org.codehaus.plexus.component.composition.autowire.DefaultOne org.codehaus.plexus.component.composition.autowire.Two org.codehaus.plexus.component.composition.autowire.DefaultTwo components.xml000066400000000000000000000042361167051330000445130ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/composition org.codehaus.plexus.component.composition.ComponentA org.codehaus.plexus.component.composition.DefaultComponentA field org.codehaus.plexus.component.composition.ComponentB localhost 10000 org.codehaus.plexus.component.composition.ComponentB org.codehaus.plexus.component.composition.DefaultComponentB setter org.codehaus.plexus.component.composition.ComponentC org.codehaus.plexus.component.composition.ComponentC org.codehaus.plexus.component.composition.DefaultComponentC 000077500000000000000000000000001167051330000431055ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/composition/setterSetterCompositionTest.xml000066400000000000000000000017621167051330000501670ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/composition/setter org.codehaus.plexus.component.composition.setter.Component org.codehaus.plexus.component.composition.setter.ChildComponent setter org.codehaus.plexus.component.composition.ComponentA org.codehaus.plexus.component.composition.ComponentB org.codehaus.plexus.component.composition.ComponentA org.codehaus.plexus.component.composition.DefaultComponentA org.codehaus.plexus.component.composition.ComponentB org.codehaus.plexus.component.composition.DefaultComponentB 000077500000000000000000000000001167051330000407035ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/factory000077500000000000000000000000001167051330000423375ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/factory/nonjavaNonJavaComponentFactoryTest.xml000066400000000000000000000004561167051330000504750ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/factory/nonjava org.codehaus.plexus.component.factory.ComponentFactory nonjava org.codehaus.plexus.component.factory.nonjava.NonJavaComponentFactory 000077500000000000000000000000001167051330000406465ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/managerClassicSingletonComponentManagerTest.xml000066400000000000000000000004011167051330000506450ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/manager org.codehaus.plexus.component.manager.Component org.codehaus.plexus.component.manager.DefaultComponent SlowComponentClassicSingletonComponentManagerTest.xml000066400000000000000000000005121167051330000534000ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/component/manager org.codehaus.plexus.component.manager.SlowComponent org.codehaus.plexus.component.manager.SlowComponent 300 components.xml000066400000000000000000000007261167051330000401460ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus org.codehaus.plexus.test.ComponentA one org.codehaus.plexus.test.DefaultComponentA org.codehaus.plexus.test.ComponentA two org.codehaus.plexus.test.DefaultComponentA 000077500000000000000000000000001167051330000401015ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/configurationavalon.xml000066400000000000000000000142051167051330000421050ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/configuration ${foo.home}/jars ${my.home}/resources user-conf-dir logging-implementation INFO org.codehaus.plexus.personality.avalon.AvalonComponentRepository frankie custom custom avalon avalon Avalon Lifecycle Handler org.codehaus.plexus.ServiceA org.codehaus.plexus.DefaultServiceA org.codehaus.plexus.ServiceB org.codehaus.plexus.DefaultServiceB org.codehaus.plexus.ServiceC first-instance org.codehaus.plexus.DefaultServiceC org.codehaus.plexus.ServiceC second-instance org.codehaus.plexus.DefaultServiceC org.codehaus.plexus.ServiceE org.codehaus.plexus.DefaultServiceE per-lookup org.codehaus.plexus.ServiceG org.codehaus.plexus.DefaultServiceG singleton org.codehaus.plexus.ServiceH org.codehaus.plexus.DefaultServiceH arbitrary org.codehaus.plexus.LoadOnStartService org.codehaus.plexus.DefaultLoadOnStartService org.codehaus.plexus.LoadOnStartServiceWithRoleHint role-hint org.codehaus.plexus.DefaultLoadOnStartServiceWithRoleHint org.codehaus.plexus.ConfigureService org.codehaus.plexus.DefaultConfigureService singleton 1 2 000077500000000000000000000000001167051330000414015ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/configuration/sourceExtendingConfigurationSourceTest.xml000066400000000000000000000013751167051330000506270ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/configuration/source org.codehaus.plexus.configuration.source.ConfigurationSource dummy org.codehaus.plexus.configuration.source.ADummyConfigurationSource org.codehaus.plexus.configuration.source.ConfigurationSource anotherDummy org.codehaus.plexus.configuration.source.AnotherDummyConfigurationSource org.codehaus.plexus.configuration.source.ConfigurationSource dummy OverridingConfigurationSourceTest.xml000066400000000000000000000004611167051330000510050ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/configuration/source org.codehaus.plexus.configuration.source.ConfigurationSource default org.codehaus.plexus.configuration.source.ADummyConfigurationSource 000077500000000000000000000000001167051330000363065ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/embedEmbedderTest.xml000066400000000000000000000010341167051330000413750ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/embed ${basedir}/test-input org.codehaus.plexus.embed.MockComponent default org.codehaus.plexus.embed.MockComponent org.codehaus.plexus.embed.MockComponent foo org.codehaus.plexus.embed.MockComponent 000077500000000000000000000000001167051330000372105ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/hierarchyChildPlexusOne.xml000066400000000000000000000023201167051330000426150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/hierarchy org.codehaus.plexus.logging.console.ConsoleLoggerManager ERROR org.codehaus.plexus.hierarchy.PlexusTestService default org.codehaus.plexus.hierarchy.TestServiceImpl three blind mice org.codehaus.plexus.hierarchy.PlexusTestService hinted org.codehaus.plexus.hierarchy.TestServiceImpl plexus one overriding hinted service org.codehaus.plexus.hierarchy.PlexusTestService local org.codehaus.plexus.hierarchy.TestServiceImpl plexus one local service ChildPlexusTwo.xml000066400000000000000000000015751167051330000426600ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/hierarchy org.codehaus.plexus.logging.console.ConsoleLoggerManager ERROR org.codehaus.plexus.hierarchy.PlexusTestService default org.codehaus.plexus.hierarchy.TestServiceImpl see how they run org.codehaus.plexus.hierarchy.PlexusTestService local org.codehaus.plexus.hierarchy.TestServiceImpl plexus two local service PlexusHierarchyTest.xml000066400000000000000000000043431167051330000437150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/hierarchy org.codehaus.plexus.logging.console.ConsoleLoggerManager ERROR org.codehaus.plexus.PlexusContainerManager default org.codehaus.plexus.SimplePlexusContainerManager org/codehaus/plexus/hierarchy/ChildPlexusOne.xml plexus-name ChildPlexusOne org.codehaus.plexus.PlexusContainerManager two org.codehaus.plexus.SimplePlexusContainerManager org/codehaus/plexus/hierarchy/ChildPlexusTwo.xml plexus-name ChildPlexusTwo org.codehaus.plexus.hierarchy.PlexusTestService default org.codehaus.plexus.hierarchy.TestServiceImpl cheesy default service org.codehaus.plexus.hierarchy.PlexusTestService hinted org.codehaus.plexus.hierarchy.TestServiceImpl hinted default service org.codehaus.plexus.hierarchy.PlexusTestService global org.codehaus.plexus.hierarchy.TestServiceImpl globally visible service 000077500000000000000000000000001167051330000366605ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/loggingCustomLoggerFactoryTest.xml000066400000000000000000000012701167051330000442040ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/logging org.codehaus.plexus.logging.CustomLoggerFactoryTest$ComponentWithSLF4J org.codehaus.plexus.logging.CustomLoggerFactoryTest$ComponentWithSLF4J org.slf4j.Logger loggerRequirement org.slf4j.ILoggerFactory org.codehaus.plexus.logging.MockLoggerFactory CustomLoggerManagerTest.xml000066400000000000000000000003451167051330000441510ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/logging org.codehaus.plexus.logging.LoggerManager org.codehaus.plexus.logging.MockLoggerManager 000077500000000000000000000000001167051330000403225ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/logging/consoleConsoleLoggerManagerTest.xml000066400000000000000000000011101167051330000457320ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/logging/console org.codehaus.plexus.logging.LoggerManager org.codehaus.plexus.logging.console.ConsoleLoggerManager basic per-lookup fatal 000077500000000000000000000000001167051330000362115ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/testPlexusContainerTest.xml000066400000000000000000000401041167051330000427150ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/test ${basedir}/src/test-input/configurations-directory org.codehaus.plexus.test.ServiceB org.codehaus.plexus.test.DefaultServiceB org.codehaus.plexus.test.ServiceC first-instance org.codehaus.plexus.test.DefaultServiceC org.codehaus.plexus.test.ServiceC second-instance org.codehaus.plexus.test.DefaultServiceC org.codehaus.plexus.test.ServiceD org.codehaus.plexus.test.DefaultServiceD org.codehaus.plexus.test.ServiceE org.codehaus.plexus.test.DefaultServiceE plexus-configurable org.codehaus.plexus.test.ServiceH org.codehaus.plexus.test.DefaultServiceH arbitrary org.codehaus.plexus.test.LoadOnStartService org.codehaus.plexus.test.DefaultLoadOnStartService org.codehaus.plexus.test.LoadOnStartServiceWithRoleHint role-hint org.codehaus.plexus.test.DefaultLoadOnStartServiceWithRoleHint org.codehaus.plexus.logging.LoggerManager org.codehaus.plexus.logging.console.ConsoleLoggerManager basic fatal org.codehaus.plexus.test.Component org.codehaus.plexus.test.DefaultComponent org.codehaus.plexus.test.map.Activity one localhost 10000 org.codehaus.plexus.test.Component org.codehaus.plexus.test.DefaultComponentWithOptionalRequirement with-optional org.codehaus.plexus.test.map.Activity one activity org.codehaus.plexus.test.NonAvailableComponent missing optionalComponent true org.codehaus.plexus.test.ComponentA org.codehaus.plexus.test.DefaultComponentA org.codehaus.plexus.test.ComponentB org.codehaus.plexus.test.ComponentC localhost 10000 org.codehaus.plexus.test.ComponentB org.codehaus.plexus.test.DefaultComponentB org.codehaus.plexus.test.ComponentC org.codehaus.plexus.test.DefaultComponentC org.codehaus.plexus.test.ComponentD org.codehaus.plexus.test.ComponentD org.codehaus.plexus.test.DefaultComponentD jason org.codehaus.plexus.test.map.ActivityManager org.codehaus.plexus.test.map.DefaultActivityManager org.codehaus.plexus.test.map.Activity activities org.codehaus.plexus.test.map.ActivityManager slim org.codehaus.plexus.test.map.DefaultActivityManager org.codehaus.plexus.test.map.Activity activities one org.codehaus.plexus.test.map.Activity one org.codehaus.plexus.test.map.ActivityOne per-lookup org.codehaus.plexus.test.map.Activity two org.codehaus.plexus.test.map.ActivityTwo org.codehaus.plexus.test.list.Pipeline default org.codehaus.plexus.test.list.DefaultPipeline org.codehaus.plexus.test.list.Valve valves org.codehaus.plexus.test.list.Pipeline slim org.codehaus.plexus.test.list.DefaultPipeline org.codehaus.plexus.test.list.Valve valves one org.codehaus.plexus.test.list.Pipeline chubby org.codehaus.plexus.test.list.DefaultPipeline org.codehaus.plexus.test.list.Valve valveMap one two three four org.codehaus.plexus.test.list.Valve four org.codehaus.plexus.test.list.ValveFour org.codehaus.plexus.test.list.Valve three org.codehaus.plexus.test.list.ValveThree org.codehaus.plexus.test.list.Valve two org.codehaus.plexus.test.list.ValveTwo org.codehaus.plexus.test.list.Valve one org.codehaus.plexus.test.list.ValveOne per-lookup org.codehaus.plexus.test.ComponentManager org.codehaus.plexus.test.DefaultComponentManager org.codehaus.plexus.components.A list org.codehaus.plexus.components.A map org.codehaus.plexus.logging.LoggerManager org.codehaus.plexus.logging.console.ConsoleLoggerManager basic fatal org.codehaus.plexus.test.Component ComponentMissingRequirements org.codehaus.plexus.test.DefaultComponent NonExistingComponent org.codehaus.plexus.test.StartableComponent A-snake org.codehaus.plexus.test.DefaultStartableComponentA org.codehaus.plexus.test.StartableComponent B-snake component1 org.codehaus.plexus.test.StartableComponent B-snake org.codehaus.plexus.test.DefaultStartableComponentB org.codehaus.plexus.test.StartableComponent C-snake component1 org.codehaus.plexus.test.StartableComponent C-snake org.codehaus.plexus.test.DefaultStartableComponentC org.codehaus.plexus.test.StartableComponent D-snake component1 org.codehaus.plexus.test.StartableComponent D-snake org.codehaus.plexus.test.DefaultStartableComponentD org.codehaus.plexus.test.StartableComponent E-snake component1 org.codehaus.plexus.test.StartableComponent E-snake org.codehaus.plexus.test.DefaultStartableComponentE org.codehaus.plexus.test.StartableComponent A-tree org.codehaus.plexus.test.DefaultStartableComponentA org.codehaus.plexus.test.StartableComponent B-tree component1 org.codehaus.plexus.test.StartableComponent C-tree component2 org.codehaus.plexus.test.StartableComponent B-tree org.codehaus.plexus.test.DefaultStartableComponentB org.codehaus.plexus.test.StartableComponent D-tree component1 org.codehaus.plexus.test.StartableComponent E-tree component2 org.codehaus.plexus.test.StartableComponent C-tree org.codehaus.plexus.test.DefaultStartableComponentC org.codehaus.plexus.test.StartableComponent D-tree org.codehaus.plexus.test.DefaultStartableComponentD org.codehaus.plexus.test.StartableComponent E-tree org.codehaus.plexus.test.DefaultStartableComponentE org.codehaus.plexus.test.CircularComponent A org.codehaus.plexus.test.DefaultCircularComponent org.codehaus.plexus.test.CircularComponent B requirement org.codehaus.plexus.test.CircularComponent B org.codehaus.plexus.test.DefaultCircularComponent org.codehaus.plexus.PlexusContainer container A org.codehaus.plexus.test.Thing concrete org.codehaus.plexus.test.ConcreteThing org.codehaus.plexus.test.ThingUser org.codehaus.plexus.test.DefaultThingUser org.codehaus.plexus.test.Thing thing org.codehaus.plexus.test.ComponentWithRoleDefault org.codehaus.plexus.test.ComponentWithRoleDefault default 000077500000000000000000000000001167051330000373105ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/test/cycleCircularComponentTest.xml000077500000000000000000000034761167051330000443360ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/test/cycle org.codehaus.plexus.test.cycle.CycleComponent A org.codehaus.plexus.test.cycle.DefaultCycleComponentA org.codehaus.plexus.test.cycle.CycleComponent B b org.codehaus.plexus.test.cycle.CycleComponent B org.codehaus.plexus.test.cycle.DefaultCycleComponentB org.codehaus.plexus.test.cycle.CycleComponent C c org.codehaus.plexus.test.cycle.CycleComponent C org.codehaus.plexus.test.cycle.DefaultCycleComponentC org.codehaus.plexus.test.cycle.CycleComponent D d org.codehaus.plexus.test.cycle.CycleComponent D org.codehaus.plexus.test.cycle.DefaultCycleComponentD org.codehaus.plexus.test.cycle.CycleComponent A a LockComponentTest.xml000077500000000000000000000013011167051330000434430ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/test/cycle org.codehaus.plexus.test.cycle.EagerComponent org.codehaus.plexus.test.cycle.LockComponent org.codehaus.plexus.test.cycle.LockComponent org.codehaus.plexus.PlexusContainer org.codehaus.plexus.test.cycle.LazyComponent 000077500000000000000000000000001167051330000367665ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/test/mapNoComponentsMapTest.xml000066400000000000000000000020061167051330000434260ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/org/codehaus/plexus/test/map org.codehaus.plexus.logging.console.ConsoleLoggerManager INFO org.codehaus.plexus.test.map.ActivityManager org.codehaus.plexus.test.map.DefaultActivityManager org.codehaus.plexus.test.map.Activity activities sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/resources/test.txt000066400000000000000000000000161167051330000331240ustar00rootroot00000000000000This is a testsisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/000077500000000000000000000000001167051330000336345ustar00rootroot00000000000000000077500000000000000000000000001167051330000357755ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-apom.xml000066400000000000000000000055771167051330000373300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-a 4.0.0 org.codehaus.plexus.components component-a 1.0-SNAPSHOT component-a org.codehaus.plexus plexus-maven-plugin 1.3.3 descriptor 000077500000000000000000000000001167051330000365645ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-a/src000077500000000000000000000000001167051330000375105ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-a/src/main000077500000000000000000000000001167051330000404315ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-a/src/main/java000077500000000000000000000000001167051330000412205ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-a/src/main/java/org000077500000000000000000000000001167051330000430135ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-a/src/main/java/org/codehaus000077500000000000000000000000001167051330000443335ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-a/src/main/java/org/codehaus/plexuscomponents/000077500000000000000000000000001167051330000465205ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-a/src/main/java/org/codehaus/plexuscomponents/A.java000066400000000000000000000001301167051330000475350ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-a/src/main/java/org/codehaus/plexuspackage org.codehaus.plexus.components; public interface A { public void hello(); } components/DefaultA.java000066400000000000000000000003031167051330000510440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-a/src/main/java/org/codehaus/plexuspackage org.codehaus.plexus.components; /** * @plexus.component */ public class DefaultA implements A { public void hello() { System.out.println( "Hello World!" ); } } 000077500000000000000000000000001167051330000357765ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-bpom.xml000066400000000000000000000055771167051330000373310ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-b 4.0.0 org.codehaus.plexus.components component-b 1.0-SNAPSHOT component-b org.codehaus.plexus plexus-maven-plugin 1.3.3 descriptor 000077500000000000000000000000001167051330000365655ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-b/src000077500000000000000000000000001167051330000375115ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-b/src/main000077500000000000000000000000001167051330000404325ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-b/src/main/java000077500000000000000000000000001167051330000412215ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-b/src/main/java/org000077500000000000000000000000001167051330000430145ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-b/src/main/java/org/codehaus000077500000000000000000000000001167051330000443345ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-b/src/main/java/org/codehaus/plexuscomponents/000077500000000000000000000000001167051330000465215ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-b/src/main/java/org/codehaus/plexuscomponents/B.java000066400000000000000000000001301167051330000475370ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-b/src/main/java/org/codehaus/plexuspackage org.codehaus.plexus.components; public interface B { public void hello(); } components/DefaultB.java000066400000000000000000000003031167051330000510460ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-b/src/main/java/org/codehaus/plexuspackage org.codehaus.plexus.components; /** * @plexus.component */ public class DefaultB implements B { public void hello() { System.out.println( "Hello World!" ); } } 000077500000000000000000000000001167051330000357775ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-cpom.xml000066400000000000000000000055771167051330000373320ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-c 4.0.0 org.codehaus.plexus.components component-c 1.0-SNAPSHOT component-c org.codehaus.plexus plexus-maven-plugin 1.3.3 descriptor 000077500000000000000000000000001167051330000365665ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-c/src000077500000000000000000000000001167051330000375125ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-c/src/main000077500000000000000000000000001167051330000404335ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-c/src/main/java000077500000000000000000000000001167051330000412225ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-c/src/main/java/org000077500000000000000000000000001167051330000430155ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-c/src/main/java/org/codehaus000077500000000000000000000000001167051330000443355ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-c/src/main/java/org/codehaus/plexuscomponents/000077500000000000000000000000001167051330000465225ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-c/src/main/java/org/codehaus/plexuscomponents/C.java000066400000000000000000000001301167051330000475410ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-c/src/main/java/org/codehaus/plexuspackage org.codehaus.plexus.components; public interface C { public void hello(); } components/DefaultC.java000066400000000000000000000003031167051330000510500ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-c/src/main/java/org/codehaus/plexuspackage org.codehaus.plexus.components; /** * @plexus.component */ public class DefaultC implements C { public void hello() { System.out.println( "Hello World!" ); } } 000077500000000000000000000000001167051330000413755ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-with-configurationpom.xml000066400000000000000000000014461167051330000427170ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/component-with-configuration 4.0.0 org.codehaus.plexus.components component-with-configuration 1.0-SNAPSHOT component-ext-a org.codehaus.plexus plexus-maven-plugin 1.3.3 descriptor 000077500000000000000000000000001167051330000351335ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0pom.xml000066400000000000000000000041231167051330000364500ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0 4.0.0 org.codehaus.plexus.components plugin0 1.0-SNAPSHOT org.codehaus.plexus.components component-a 1.0-SNAPSHOT org.codehaus.plexus.components component-b 1.0-SNAPSHOT org.codehaus.plexus plexus-archiver 1.0-alpha-7 org.codehaus.plexus plexus-container-default 1.0-beta-2-SNAPSHOT org.codehaus.plexus plexus-maven-plugin 1.3.3 descriptor 000077500000000000000000000000001167051330000357225ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0/src000077500000000000000000000000001167051330000366465ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0/src/main000077500000000000000000000000001167051330000375675ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0/src/main/java000077500000000000000000000000001167051330000403565ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0/src/main/java/org000077500000000000000000000000001167051330000421515ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0/src/main/java/org/codehaus000077500000000000000000000000001167051330000434715ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0/src/main/java/org/codehaus/plexus000077500000000000000000000000001167051330000451525ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0/src/main/java/org/codehaus/plexus/pluginsAltPlugin0.java000066400000000000000000000030601167051330000477730ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0/src/main/java/org/codehaus/plexus/pluginspackage org.codehaus.plexus.plugins; import org.codehaus.plexus.components.A; import org.codehaus.plexus.components.B; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.archiver.manager.ArchiverManager; /** * @plexus.component role-hint="alt" */ public class AltPlugin0 implements Plugin0, Contextualizable { /** @plexus.requirement */ private A a; /** @plexus.requirement */ private B b; /** @plexus.requirement */ private ArchiverManager archiverManager; public void hello() { System.out.println( "Hello World!" ); } // ---------------------------------------------------------------------------- // Lifecycle // ---------------------------------------------------------------------------- public void contextualize( Context context ) throws ContextException { PlexusContainer container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); try { archiverManager = (ArchiverManager) container.lookup( ArchiverManager.ROLE ); } catch ( ComponentLookupException e ) { throw new ContextException( "Error retrieving ArchiverManager instance: " + e.getMessage(), e ); } } } DefaultPlugin0.java000066400000000000000000000030441167051330000506410ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0/src/main/java/org/codehaus/plexus/pluginspackage org.codehaus.plexus.plugins; import org.codehaus.plexus.components.A; import org.codehaus.plexus.components.B; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.archiver.manager.ArchiverManager; /** * @plexus.component */ public class DefaultPlugin0 implements Plugin0, Contextualizable { /** @plexus.requirement */ private A a; /** @plexus.requirement */ private B b; /** @plexus.requirement */ private ArchiverManager archiverManager; public void hello() { System.out.println( "Hello World!" ); } // ---------------------------------------------------------------------------- // Lifecycle // ---------------------------------------------------------------------------- public void contextualize( Context context ) throws ContextException { PlexusContainer container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); try { archiverManager = (ArchiverManager) container.lookup( ArchiverManager.ROLE ); } catch ( ComponentLookupException e ) { throw new ContextException( "Error retrieving ArchiverManager instance: " + e.getMessage(), e ); } } } Plugin0.java000066400000000000000000000001331167051330000473300ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin0/src/main/java/org/codehaus/plexus/pluginspackage org.codehaus.plexus.plugins; public interface Plugin0 { public void hello(); } 000077500000000000000000000000001167051330000351345ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1pom.xml000066400000000000000000000063371167051330000364620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1 4.0.0 org.codehaus.plexus.components plugin1 1.0-SNAPSHOT org.codehaus.plexus.components component-a 1.0-SNAPSHOT org.codehaus.plexus.components component-c 1.0-SNAPSHOT org.codehaus.plexus plexus-maven-plugin 1.3.3 descriptor 000077500000000000000000000000001167051330000357235ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1/src000077500000000000000000000000001167051330000366475ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1/src/main000077500000000000000000000000001167051330000375705ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1/src/main/java000077500000000000000000000000001167051330000403575ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1/src/main/java/org000077500000000000000000000000001167051330000421525ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1/src/main/java/org/codehaus000077500000000000000000000000001167051330000434725ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1/src/main/java/org/codehaus/plexus000077500000000000000000000000001167051330000451535ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1/src/main/java/org/codehaus/plexus/pluginsAltPlugin1.java000066400000000000000000000006311167051330000477760ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1/src/main/java/org/codehaus/plexus/pluginspackage org.codehaus.plexus.plugins; import org.codehaus.plexus.components.A; import org.codehaus.plexus.components.C; /** * @plexus.component role-hint="alt" */ public class AltPlugin1 implements Plugin1 { /** @plexus.requirement */ private A a; /** @plexus.requirement */ private C c; public void hello() { System.out.println( "Hello World!" ); } } DefaultPlugin1.java000066400000000000000000000006151167051330000506440ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1/src/main/java/org/codehaus/plexus/pluginspackage org.codehaus.plexus.plugins; import org.codehaus.plexus.components.A; import org.codehaus.plexus.components.C; /** * @plexus.component */ public class DefaultPlugin1 implements Plugin1 { /** @plexus.requirement */ private A a; /** @plexus.requirement */ private C c; public void hello() { System.out.println( "Hello World!" ); } } Plugin1.java000066400000000000000000000001331167051330000473320ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds/plugin1/src/main/java/org/codehaus/plexus/pluginspackage org.codehaus.plexus.plugins; public interface Plugin1 { public void hello(); } pom.xml000066400000000000000000000012231167051330000350700ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/guice-plexus-shim/src/test/test-component-builds 4.0.0 org.codehaus.plexus.components component-parent 1.0-SNAPSHOT pom component-a component-b component-c plugin0 plugin1 component-with-configuration sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/pom.xml000066400000000000000000000073311167051330000236000ustar00rootroot00000000000000 4.0.0 ../guice-bean org.sonatype.sisu.inject guice-bean 2.3.0 pom guice-plexus Sisu-Inject : Containers : Plexus guice-plexus-metadata guice-plexus-scanners guice-plexus-converters guice-plexus-locators guice-plexus-binders guice-plexus-lifecycles guice-plexus-shim sisu-inject-plexus Eclipse Public License, Version 1.0 http://www.eclipse.org/legal/epl-v10.html repo org.codehaus.plexus plexus-component-annotations 1.5.5 org.codehaus.plexus plexus-classworlds 2.4 org.codehaus.plexus plexus-utils 2.1 org.sonatype.sisu.inject guice-plexus-metadata ${project.version} org.sonatype.sisu.inject guice-plexus-scanners ${project.version} org.sonatype.sisu.inject guice-plexus-converters ${project.version} org.sonatype.sisu.inject guice-plexus-locators ${project.version} org.sonatype.sisu.inject guice-plexus-binders ${project.version} org.sonatype.sisu.inject guice-plexus-lifecycles ${project.version} org.sonatype.sisu.inject guice-plexus-shim ${project.version} org.sonatype.sisu.inject guice-plexus-tck ${project.version} org.sonatype.sisu sisu-inject-plexus ${project.version} sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/sisu-inject-plexus/000077500000000000000000000000001167051330000260325ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/containers/guice-plexus/sisu-inject-plexus/pom.xml000066400000000000000000000137771167051330000273660ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject guice-plexus 2.3.0 bundle org.sonatype.sisu sisu-inject-plexus Sisu-Inject-Plexus : Aggregate OSGi bundle org.codehaus.plexus plexus-component-annotations org.codehaus.plexus plexus-classworlds org.codehaus.plexus plexus-utils org.sonatype.sisu sisu-inject-bean org.sonatype.sisu.inject guice-plexus-shim true org.slf4j slf4j-api true junit junit true org.apache.felix maven-bundle-plugin true *;groupId=org.codehaus.plexus org.sonatype.inject.plexus;singleton:=true org.slf4j org.codehaus.plexus.*;-split-package:=merge-first, org.sonatype.guice.plexus.*;x-internal:=true;version=${project.version} org.sonatype.sisu.guava, org.sonatype.sisu.guice, org.sonatype.inject org.codehaus.*, !com.google.*,!org.sonatype.*, *;resolution:=optional META-INF.plexus release aggregate-sources maven-dependency-plugin aggregate-sources prepare-package unpack-dependencies sources false ${project.build.directory}/aggregate-sources org.codehaus.plexus org/codehaus/plexus/**,org/sonatype/guice/plexus/** maven-jar-plugin attach-sources prepare-package jar sources ${project.build.directory}/aggregate-sources maven-javadoc-plugin ${project.build.directory}/aggregate-sources m2e m2e.version org.sonatype.sisu.inject guice-plexus-shim false sisu-ioc-2.3.0/sisu-inject/containers/pom.xml000066400000000000000000000022571167051330000211700ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu sisu-inject 2.3.0 pom org.sonatype.sisu.inject containers Sisu-Inject : Containers guice-bean guice-plexus sisu-ioc-2.3.0/sisu-inject/lib/000077500000000000000000000000001167051330000162465ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/lib/osgi.xml000066400000000000000000002406341167051330000177420ustar00rootroot00000000000000 sisu-ioc-2.3.0/sisu-inject/pom.xml000066400000000000000000000062441167051330000170230ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu sisu-parent 2.3.0 pom sisu-inject Sisu-Inject containers registries 3.1.0 org.sonatype.sisu sisu-guice ${sisu.guice.version} org.sonatype.sisu sisu-guice ${sisu.guice.version} no_aop maven-javadoc-plugin com.google.doclava.Doclava ${project.basedir}/../../lib/doclava.jar: ${project.basedir}/../../../lib/doclava.jar ${sun.boot.class.path} *.internal -quiet -federate JDK http://download.oracle.com/javase/6/docs/api/index.html? -federationxml JDK http://doclava.googlecode.com/svn/static/api/openjdk-6.xml -federate Guice http://google-guice.googlecode.com/svn/trunk/javadoc/ -federate OSGi http://osgi.org/javadoc/r4v42/index.html? -federationxml OSGi https://raw.github.com/sonatype/sisu/master/sisu-inject/lib/osgi.xml -hdf project.name "${project.name}" -d ${project.build.directory}/apidocs false -J-Xmx1024m sisu-ioc-2.3.0/sisu-inject/registries/000077500000000000000000000000001167051330000176605ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/pom.xml000066400000000000000000000035101167051330000211740ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu sisu-inject 2.3.0 pom org.sonatype.sisu.inject registries Sisu-Inject : Registries sisu-osgi-registry sisu-eclipse-registry sisu-spi-registry org.sonatype.sisu sisu-inject-bean ${project.version} release maven-javadoc-plugin true sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/000077500000000000000000000000001167051330000241335ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/pom.xml000066400000000000000000000043331167051330000254530ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject registries 2.3.0 bundle org.sonatype.sisu sisu-eclipse-registry Sisu-Eclipse-Registry : Extension bindings org.eclipse.equinox org.eclipse.equinox.registry 3.5.0.v20100503 org.apache.felix maven-bundle-plugin true org.sonatype.inject.eclipse org.sonatype.inject org.eclipse.equinox.registry org.sonatype.guice.eclipse.* !com.google.*|org.sonatype.*|org.eclipse.*,* sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/src/000077500000000000000000000000001167051330000247225ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/src/main/000077500000000000000000000000001167051330000256465ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/src/main/java/000077500000000000000000000000001167051330000265675ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/src/main/java/org/000077500000000000000000000000001167051330000273565ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/src/main/java/org/sonatype/000077500000000000000000000000001167051330000312205ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/src/main/java/org/sonatype/guice/000077500000000000000000000000001167051330000323145ustar00rootroot00000000000000000077500000000000000000000000001167051330000336615ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/src/main/java/org/sonatype/guice/eclipseExtensionBindings.java000066400000000000000000000135051167051330000401620ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/src/main/java/org/sonatype/guice/eclipse/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ package org.sonatype.guice.eclipse; import java.security.ProviderException; import java.util.Collections; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import org.eclipse.core.runtime.ContributorFactoryOSGi; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.RegistryFactory; import org.osgi.framework.Bundle; import org.sonatype.guice.bean.locators.MutableBeanLocator; import org.sonatype.guice.bean.locators.spi.BindingPublisher; import org.sonatype.guice.bean.locators.spi.BindingSubscriber; import org.sonatype.inject.EagerSingleton; import com.google.inject.Binder; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.spi.BindingScopingVisitor; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.Dependency; import com.google.inject.spi.ElementVisitor; import com.google.inject.spi.InjectionPoint; import com.google.inject.spi.ProviderInstanceBinding; /** * {@link BindingPublisher} that queries the Eclipse {@link IExtensionRegistry}. */ @Named @EagerSingleton final class ExtensionBindings implements BindingPublisher { private final IExtensionRegistry registry; @Inject ExtensionBindings( final MutableBeanLocator locator ) { registry = RegistryFactory.getRegistry(); locator.add( this, -1 ); } public void subscribe( final BindingSubscriber subscriber ) { final TypeLiteral type = subscriber.type(); final Class clazz = type.getRawType(); final String pointId = clazz.getPackage().getName(); // FIXME for ( final IConfigurationElement config : registry.getConfigurationElementsFor( pointId ) ) { try { final String name = config.getAttribute( "class" ); if ( null != name ) { if ( type.getRawType().isAssignableFrom( loadExtensionClass( config, name ) ) ) { subscriber.add( new ExtensionBinding( type, config ), 0 ); } } } catch ( final Exception e ) // NOPMD { // check next element } catch ( final LinkageError e ) // NOPMD { // check next element } } } public void unsubscribe( final BindingSubscriber subscriber ) { for ( final Binding binding : subscriber.bindings() ) { if ( binding instanceof ExtensionBinding ) { subscriber.remove( binding ); } } } private static final class ExtensionBinding implements ProviderInstanceBinding { private final TypeLiteral type; final IConfigurationElement config; ExtensionBinding( final TypeLiteral type, final IConfigurationElement config ) { this.type = type; this.config = config; } public Key getKey() { return Key.get( type ); } @SuppressWarnings( "unchecked" ) public Provider getProvider() { return new Provider() { public T get() { try { return (T) config.createExecutableExtension( "class" ); } catch ( final CoreException e ) { throw new ProviderException( e ); } } }; } public Object getSource() { return config; } public Set> getDependencies() { return Collections.emptySet(); } public Set getInjectionPoints() { return Collections.emptySet(); } public Provider getProviderInstance() { return getProvider(); } public void applyTo( final Binder binder ) { binder.bind( getKey() ).toProvider( getProvider() ); } public S acceptVisitor( final ElementVisitor visitor ) { return visitor.visit( this ); } public V acceptScopingVisitor( final BindingScopingVisitor visitor ) { return visitor.visitNoScoping(); } public V acceptTargetVisitor( final BindingTargetVisitor visitor ) { return visitor.visit( this ); } } static Class loadExtensionClass( final IConfigurationElement config, final String clazzName ) throws ClassNotFoundException { final Bundle bundle = ContributorFactoryOSGi.resolve( config.getContributor() ); final String value = clazzName; final int n = value.indexOf( ':' ); return bundle.loadClass( n < 0 ? value : value.substring( 0, n ) ); } } package-info.java000066400000000000000000000014221167051330000370470ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-eclipse-registry/src/main/java/org/sonatype/guice/eclipse/******************************************************************************* * Copyright (c) 2011 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Apache License v2.0 is available at * http://www.apache.org/licenses/LICENSE-2.0.html * You may elect to redistribute this code under either of these licenses. *******************************************************************************/ /** * Eclipse {@link org.eclipse.core.runtime.IExtensionRegistry} support. */ package org.sonatype.guice.eclipse; sisu-ioc-2.3.0/sisu-inject/registries/sisu-osgi-registry/000077500000000000000000000000001167051330000234505ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-osgi-registry/pom.xml000066400000000000000000000021111167051330000247600ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject registries 2.3.0 org.sonatype.sisu sisu-osgi-registry Sisu-OSGi-Registry : Service bindings sisu-ioc-2.3.0/sisu-inject/registries/sisu-spi-registry/000077500000000000000000000000001167051330000233025ustar00rootroot00000000000000sisu-ioc-2.3.0/sisu-inject/registries/sisu-spi-registry/pom.xml000066400000000000000000000021071167051330000246170ustar00rootroot00000000000000 4.0.0 org.sonatype.sisu.inject registries 2.3.0 org.sonatype.sisu sisu-spi-registry Sisu-SPI-Registry : Service bindings