ivy-2.3.0.orig/0000755000175000017500000000000012126443423012027 5ustar tonytonyivy-2.3.0.orig/build.xml0000644000175000017500000007763211740504234013666 0ustar tonytony ivy-2.3.0.orig/ivy.xml0000644000175000017500000001004212073541462013360 0ustar tonytony Apache Ivy is a tool for managing (recording, tracking, resolving and reporting) project dependencies. ivy-2.3.0.orig/NOTICE0000644000175000017500000000114112070644750012734 0ustar tonytonyApache Ivy (TM) Copyright 2007-2013 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). Portions of Ivy were originally developed by Jayasoft SARL (http://www.jayasoft.fr/) and are licensed to the Apache Software Foundation under the "Software Grant License Agreement" SSH and SFTP support is provided by the JCraft JSch package, which is open source software, available under the terms of a BSD style license. The original software and related information is available at http://www.jcraft.com/jsch/. ivy-2.3.0.orig/RELEASE_NOTES0000644000175000017500000002422212073537642014014 0ustar tonytony Apache Ivy (TM) 2.3.0 Release Notes ----------------------------------------------------------------------- CONTENTS 1. What is Apache Ivy? 2. How to Get Involved 3. How to Report Issues 4. Committers and Contributors for this release 5. List of Changes in this Release 1. What is Apache Ivy? Apache Ivy is a tool for managing (recording, tracking, resolving and reporting) project dependencies. It is characterized by the following: 1. flexibility and configurability Apache Ivy is essentially process agnostic and is not tied to any methodology or structure. Instead it provides the necessary flexibility and configurability to be adapted to a broad range of dependency management and build processes. 2. tight integration with Apache Ant while available as a standalone tool, Apache Ivy works particularly well with Apache Ant providing a number of powerful Ant tasks ranging from dependency resolution to dependency reporting and publication. 2. How to Get Involved The Apache Ivy project really needs and appreciates any contributions, including documentation help, source code and feedback. If you are interested in contributing, please visit http://ant.apache.org/ivy/get-involved.html. 3. How to Report Issues The Apache Ivy project uses JIRA for issue tracking. Please report any issues you find at http://issues.apache.org/jira/browse/IVY 4. Committers and Contributors for this Release Here is the list of people who have contributed source code and documentation to this release. Many thanks to all of them, and also to the whole Ivy community contributing ideas and feedback, and promoting the use of Ivy. The list would be too long, but Ivy couldn't be what it is without you! Committers Matt Benson Jean-Louis Boudart Maarten Coene Xavier Hanin Nicolas Lalevee Jon Schneider Gilles Scokart Contributors Arnold Blaasmo Ed Burcher Joseph Boyd Wei Chen Robin Fernandes Wolfgang Frank Mitch Gitman Payam Hekmat Stepan Koltsov Thomas Kurpick Ales Nosek Douglas Palmer Carl Quinn Torkild U. Resheim Jens Rohloff Ben Schmidt Nihal Sinha Sven Zethelius For the list of people who have contributed since Ivy inception, see CHANGES.txt file. 5. List of Changes in this Release For a full release history of Ivy see the file CHANGES.txt For details about the following changes, check our JIRA install at http://issues.apache.org/jira/browse/ivy List of changes since Ivy 2.2.0: - DOCUMENTATION: Bad example in Project dependencies Tutorial (IVY-1263) - DOCUMENTATION: remove deprecated defaultCache setting from examples (IVY-1273) (thanks to Joseph Boyd) - DOCUMENTATION: link to FAQ is incorrect in distribution files (IVY-793) (thanks to Joseph Boyd) - DOCUMENTATION: The tag version-matchers is missing attribute in documentation (IVY-1292) (thanks to Per Arnold Blaasmo) - DOCUMENTATION: wrong default resolver documented on the 'How does it work' page (IVY-1265) - DOCUMENTATION: Correct outdated links to configuration pages (IVY-1266) - DOCUMENTATION: Documentation and Implementation mismatch of makepom (IVY-1383) (thanks to Thomas Kurpick) - DOCUMENTATION: added link to extra beginners guide (IVY-1381) - NEW: [orgPath] can now be used as token in ivy/artifact patterns - NEW: New Ant datatype ivy:resources, an Ant resource collection like ivy:cachepath or ivy:cachefileset (IVY-334) - NEW: ivy:resolve and post resole task can now have inlined dependencies declaration. - NEW: Import Bushel into Ivy core (IVY-1241) - NEW: An new resolver 'mirroredurl' which can handle a list of mirrored URL repositories (IVY-468) - NEW: Support for a jar resolver (IVY-1312) - IMPROVEMENT: ivy:install task does not allow specification of conf (IVY-1313) (thanks to Nihal Sinha) - IMPROVEMENT: ivy:makepom ignores the artifact type in generated dependencies (IVY-1229) (thanks to Douglas Palmer) - IMPROVEMENT: ivy:makepom now honors exclusion of artifacts in generated pom files (IVY-1294) (thanks to Jens Rohloff) - IMPROVEMENT: Added support for dynamic revisions in tag (IVY-1281) - IMPROVEMENT: ivy:makepom child element dependency should support the type and classifier attributes (IVY-1262) - IMPROVEMENT: ivy:retrieve can now create a path or fileset containing the retrieved artifacts (IVY-1235) - IMPROVEMENT: Improve diagnostics in ssh resolver (IVY-1267) (thanks to Stepan Koltsov) - IMPROVEMENT: ivy:retrieve now accepts a nested mapper type. - FIX: Ivy generates wrong revision in URL for Maven snapshots (IVY-1396) - FIX: Maven2: resolve failure when parent has with dependency in 'import' scope (IVY-1376) - FIX: IvyPublish fails when using extend tags with no explicit location attribute (IVY-1391) - FIX: *.lck files created by "artifact-lock" lock strategy are not cleaned up if ivy quits abruptly (IVY-1388) (thanks to Wei Chen) - FIX: Ivy default cache path with non-ASCII character lets it crash (IVY-1378) - FIX: latest.integration isn't resolved against a Maven snapshot repository (when uniqueVersion = true) (IVY-1036) - FIX: Resolve does not deliver all dependent artifacts (IVY-1366) (thanks to Wolfgang Frank) - FIX: Ivy descriptors are merged incorrectly when there is an element (IVY-1356) - FIX: SimpleDateFormat is not thread safe (IVY-1373) - FIX: Maven 'hk2-jar' packaging is now supported (IVY-1357) - FIX: Maven 'orbit' and 'pear' packaging is now supported (IVY-899) - FIX: Memory leak and infinite loop in ModuleId.java (IVY-1362) - FIX: Unnecessary warning when parent ivy.xml is not found (IVY-1346) - FIX: StackOverflowError when using and ../ivy.xml is not the parent ivy.xml (IVY-1437) - FIX: NullPointerExeption in AbstractOSGiResolver (IVY-1343) (thanks to Thomas Kurpick) - FIX: Delivered ivy descriptor inconsistent with resolve report / retrieve and other post-resolve actions (IVY-1300) (thanks to Ed Burcher) - FIX: The Updatesite resolver is downloading Eclipse features instead of Eclipse bundle/plugin - FIX: ivy:buildlist task confused by extends feature using two parents (IVY-1363) (thanks to Mitch Gitman and Jean-Louis Boudart) - FIX: ivy.xml extends feature complains about Windows filesystem path (IVY-1359) (thanks to Mitch Gitman and Jean-Louis Boudart) - FIX: buildlist task chokes on absolute path to parent Ivy module (IVY-1364) (thanks to Mitch Gitman and Jean-Louis Boudart) - FIX: The ignore circular dependency strategy is clobbering the warn strategy (IVY-1353) (Thanks to Carl Quinn) - FIX: Buildnumber and IvyFindRevision Ant tasks should honour defaultBranch setting (IVY-1344) (Thanks to Ales Nosek) - FIX: ApacheURLLister.retrieveListing() fails if the encoding of the URL list is different from the default encoding (IVY-1060) (Thanks to Robin Fernandes) - FIX: global exclude rules is not applying to root ivy files - FIX: Exclude doesn't work when there is some circular dependencies (IVY-1309) - FIX: Impossible to get artifacts when data has not been loaded for multiple dynamic revisions (IVY-1333) - FIX: Ivy didn't properly handle some file: URLs (IVY-1340) - FIX: fallback mechanism didn't work properly for private configurations - FIX: /localivy target does not work when building Ivy jar (IVY-1338) (thanks to Ben Schmidt) - FIX: The showprogress=false attribute of ivy:resolve doesn't do what it should (IVY-1052) (thanks to Joseph Boyd) - FIX: extends ignores defaultconfmapping/defaultconf/confmappingoverride attributes from parent's configurations and dependencies tags (IVY-1213) - FIX: NullPointerException when providing empty password to (IVY-1335) - FIX: [originalname] not expanded for source and javadoc types during publish in ivy:install (IVY-1324) - FIX: cannot resolve from repositories that return HTTP 204 in response to an HTTP HEAD request (IVY-1328) - FIX: extra attributes lost from info when ivy file is merged with parent (IVY-1206) - FIX: ivy:report ant task intermittently "cannot compile stylesheet" (IVY-1325) - FIX: Maven 'eclipse-plugin', 'jbi-component' and 'jbi-shared-library' packaging is now mapped to 'jar' extension (IVY-899) - FIX: Infinite loop in latest-compatible conflict manager (IVY-1233) (thanks to Payam Hekmat and Sven Zethelius) - FIX: extends section of ivy.xml info does not replace variable in location tag (IVY-1287) - FIX: Valid Path does not work for Filesystem Resolver (IVY-1268) - FIX: quiet="true" does not surpress download 'dots' on packager resolver (IVY-1269) - FIX: Dynamic version resolution result can be incorrect when ivy metadata contains extra attributes (IVY-1236) - FIX: NullPointerException in FileUtil#forceDelete. - FIX: XmlModuleDescriptorUpdater is a mess that produces broken xmls in many cases (IVY-1010) - FIX: ivy.xml that contains UTF-8 encoded umlauts cannot be bigger than 10000 bytes (IVY-1253) - FIX: Can not use a v[revision] in an artifact pattern of a filesystem resolver (IVY-1238) - FIX: Cached ivy.xml is invalid if the description contains the ampersand entity (&) (IVY-1237) - FIX: Couldn't authenticate against sites having the same address as the proxy server (IVY-1234) - FIX: OutOfMemoryError when uploading large files using commons-httpclient (IVY-1197) (thanks to Torkild U. Resheim) - FIX: Only the last dependency descriptor is taken into account on the same module (IVY-1240) - FIX: UseCacheOnly doesn't respect the cache configuration in the ivysettings (IVY-1227) - FIX: UseCacheOnly is influenced by the TTL on cached metadata (IVY-1243) - FIX: ConcurrentModificationException on ivy settings loading (IVY-1250) - FIX: Module inheritance sometimes fails to locate parent descriptor in deliver process (IVY-1248) - FIX: on an empty configuration produces a very slow-to-evaluate fileset (IVY-1272) - FIX: Ivy does not apply overridden properties to m2 parent dependency versions specified using properties (IVY-1299) - FIX: Ivy does not apply overridden properties to m2 parent dependency versions specified using dependencyManagement properties (IVY-1301) ivy-2.3.0.orig/META-INF/0000755000175000017500000000000012126443423013167 5ustar tonytonyivy-2.3.0.orig/META-INF/MANIFEST.MF0000644000175000017500000001132612013010742014611 0ustar tonytonyManifest-Version: 1.0 Main-Class: org.apache.ivy.Main Bundle-Version: 2.3.0 Bundle-Name: Ivy Bundle-ManifestVersion: 2 Bundle-SymbolicName: org.apache.ivy Bundle-Vendor: Apache Software Foundation Bundle-DocURL: http://ant.apache.org/ivy/ Import-Package: com.jcraft.jsch;resolution:=optional, javax.crypto, javax.swing;resolution:=optional, javax.swing.event;resolution:=optional, javax.xml.parsers, javax.xml.transform, javax.xml.transform.sax, javax.xml.transform.stream, org.apache.commons.httpclient;resolution:=optional, org.apache.commons.httpclient.methods;resolution:=optional, org.apache.commons.httpclient.params;resolution:=optional, org.apache.commons.httpclient.protocol;resolution:=optional, org.apache.commons.net.ftp;resolution:=optional, org.apache.commons.vfs;resolution:=optional, org.apache.commons.vfs.impl;resolution:=optional, org.apache.commons.vfs.provider;resolution:=optional, org.apache.commons.vfs.provider.ftp;resolution:=optional, org.apache.commons.vfs.provider.local;resolution:=optional, org.apache.commons.vfs.provider.sftp;resolution:=optional, org.apache.commons.vfs.provider.url;resolution:=optional, org.apache.oro.text;resolution:=optional, org.apache.oro.text.regex;resolution:=optional, org.apache.tools.ant;resolution:=optional, org.apache.tools.ant.filters;resolution:=optional, org.apache.tools.ant.taskdefs;resolution:=optional, org.apache.tools.ant.types;resolution:=optional, org.apache.tools.ant.util;resolution:=optional, org.apache.webdav;resolution:=optional, org.xml.sax, org.xml.sax.ext, org.xml.sax.helpers Export-Package: org.apache.ivy;version="2.0.0", org.apache.ivy.ant;version="2.0.0", org.apache.ivy.core;version="2.0.0", org.apache.ivy.core.cache;version="2.0.0", org.apache.ivy.core.check;version="2.0.0", org.apache.ivy.core.deliver;version="2.0.0", org.apache.ivy.core.event;version="2.0.0", org.apache.ivy.core.event.download;version="2.0.0", org.apache.ivy.core.event.publish;version="2.0.0", org.apache.ivy.core.event.resolve;version="2.0.0", org.apache.ivy.core.event.retrieve;version="2.0.0", org.apache.ivy.core.install;version="2.0.0", org.apache.ivy.core.module.descriptor;version="2.0.0", org.apache.ivy.core.module.id;version="2.0.0", org.apache.ivy.core.module.status;version="2.0.0", org.apache.ivy.core.publish;version="2.0.0", org.apache.ivy.core.report;version="2.0.0", org.apache.ivy.core.repository;version="2.0.0", org.apache.ivy.core.resolve;version="2.0.0", org.apache.ivy.core.retrieve;version="2.0.0", org.apache.ivy.core.search;version="2.0.0", org.apache.ivy.core.settings;version="2.0.0", org.apache.ivy.core.sort;version="2.0.0", org.apache.ivy.osgi.core;version="2.3.0", org.apache.ivy.osgi.obr;version="2.3.0", org.apache.ivy.osgi.obr.filter;version="2.3.0", org.apache.ivy.osgi.obr.xml;version="2.3.0", org.apache.ivy.osgi.p2;version="2.3.0", org.apache.ivy.osgi.repo;version="2.3.0", org.apache.ivy.osgi.updatesite;version="2.3.0", org.apache.ivy.osgi.updatesite.xml;version="2.3.0", org.apache.ivy.osgi.util;version="2.3.0", org.apache.ivy.plugins;version="2.0.0", org.apache.ivy.plugins.circular;version="2.0.0", org.apache.ivy.plugins.conflict;version="2.0.0", org.apache.ivy.plugins.latest;version="2.0.0", org.apache.ivy.plugins.lock;version="2.0.0", org.apache.ivy.plugins.matcher;version="2.0.0", org.apache.ivy.plugins.namespace;version="2.0.0", org.apache.ivy.plugins.parser;version="2.0.0", org.apache.ivy.plugins.parser.m2;version="2.0.0", org.apache.ivy.plugins.parser.xml;version="2.0.0", org.apache.ivy.plugins.report;version="2.0.0", org.apache.ivy.plugins.repository;version="2.0.0", org.apache.ivy.plugins.repository.file;version="2.0.0", org.apache.ivy.plugins.repository.jar;version="2.3.0", org.apache.ivy.plugins.repository.sftp;version="2.0.0", org.apache.ivy.plugins.repository.ssh;version="2.0.0", org.apache.ivy.plugins.repository.url;version="2.0.0", org.apache.ivy.plugins.repository.vfs;version="2.0.0", org.apache.ivy.plugins.repository.vsftp;version="2.0.0", org.apache.ivy.plugins.resolver;version="2.0.0", org.apache.ivy.plugins.resolver.packager;version="2.0.0", org.apache.ivy.plugins.resolver.util;version="2.0.0", org.apache.ivy.plugins.signer;version="2.2.0", org.apache.ivy.plugins.signer.bouncycastle;version="2.2.0", org.apache.ivy.plugins.trigger;version="2.0.0", org.apache.ivy.plugins.version;version="2.0.0", org.apache.ivy.tools.analyser;version="2.0.0", org.apache.ivy.util;version="2.0.0", org.apache.ivy.util.cli;version="2.0.0", org.apache.ivy.util.extendable;version="2.0.0", org.apache.ivy.util.filter;version="2.0.0", org.apache.ivy.util.url;version="2.0.0" Bundle-ClassPath: . ivy-2.3.0.orig/README0000644000175000017500000000434312043037434012712 0ustar tonytony Apache Ivy (TM) 2.3.0-rc2 --------------------------- Supported Platforms -------------------- Apache Ivy requires Java level 1.4; it has been tested with Sun Java SDK v1.4.2 Even if not mandatory, Apache Ivy is most of the times used with Apache Ant, for which version 1.6.0 or greater is required. Installation ------------- Please read doc/install.html for installation instructions. Getting Started ---------------- For an introduction to Apache Ivy and how to use it, please read the documentation located in the doc subdirectory. A good place to start is the index.html Licensing --------- This software is licensed under the terms you may find in the file named "LICENSE" in this directory. Crypto Notice ------------- This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. See for more information. The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS), has classified this software as Export Commodity Control Number (ECCN) 5D002.C.1, which includes information security software using or performing cryptographic functions with asymmetric algorithms. The form and manner of this Apache Software Foundation distribution makes it eligible for export under the License Exception ENC Technology Software Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Section 740.13) for both object code and source code. The following provides more details on the included cryptographic software: The Ivy ssh resolver requires the JSch library . The sftp and https resolvers requires the Java Cryptography extensions . The PGP signature generator requires the BouncyCastle Java cryptography APIs . ivy-2.3.0.orig/ivy.xsd0000644000175000017500000003473411736412736013402 0ustar tonytony ivy-2.3.0.orig/LICENSE0000644000175000017500000003432011411730724013035 0ustar tonytony 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. ------------------------------------------------------------------------------ License for JCraft JSch package ------------------------------------------------------------------------------ Copyright (c) 2002,2003,2004,2005,2006,2007 Atsuhiko Yamanaka, JCraft,Inc. 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. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. ------------------------------------------------------------------------------ License for jQuery ------------------------------------------------------------------------------ Copyright (c) 2007 John Resig, http://jquery.com/ 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. ivy-2.3.0.orig/src/0000755000175000017500000000000012126443423012616 5ustar tonytonyivy-2.3.0.orig/src/java/0000755000175000017500000000000012126443423013537 5ustar tonytonyivy-2.3.0.orig/src/java/org/0000755000175000017500000000000012126443423014326 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/0000755000175000017500000000000012126443423015547 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/0000755000175000017500000000000012126443423016356 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/logo.png0000644000175000017500000002157511411730672020037 0ustar tonytonyPNG  IHDRdbKGD pHYsaa?itIME&h IDATxyeOUulL& C @dԯ^鍑&T4"ſƝǁ'`*»&LjwUZm_?[4mSQEa`3pʲPqT NPة*Suܠ&>E $x_'n|K83, NsΞYE(39AlGZ&)(XZ.GC!v_G^@>u]G@x} (,R⿩drCxo.Y*%:X}j~Ns; 0(1hZl9ЁA^ -Qtw{09i\旛>g(LD&ISEߊFDĉTb ܔ= _!(f)KieN7HL;;r&06aJYBQ:r&O+F| y?,P~U_N 8$^(V [)yFU kPsb.XQuDa',AnlTs<(H%}:'Kø+YC`|zaSvO^zyS;\HQ^twpyK@pow۳KKcFUQ*>CxF=FJ(X\`k;dڒ߫&l4 by$5u:Pf>cxA}um(YSZ?rU͖Y5h Q.p f5ӿ[W󴎅7$8Rq6tȊYe b`k.pJ۱%aR6_n NS,Ӹs+^犠Ps6hzxsᵻF3((d5Ě]Wt&v@u]B_=I9hO$"7^=,-X@3-ǒ@/Ș+l D \' gUcoUǵ1 U>jtIhG19,ʩO^>x,J;Y=@hz%f%hN3"Ia aPA")éKNg~,Cip-o2Y8 YZa.#=*-MS50vcd|ˌ bl6E̬:P^VZ^>(p Uǵ8u9=ՙ:cOX4t>8/2LV(,+pkj!St0BZr?¿7GUӍ =n>0$KƛpkM;|MkcC\u#ct0bnݭ%T^QD 1|g٠O+<-cC`,` y+e3 _P>&]E2^TA /7%|Ϸ_m"ҮqEx}FÖp hkȶlڱs9 ĭ񬓾gތܺgpWGzδXEQ=ffEˌ=oܮҙ*"G1(oEHYuZIy vSVP`$h+^|bz14ٰudCKKiܓJ[tU81zHeFdRmaRAVu11e݇t;s~gYXrΩ !X,.=aDqµ_*dEUUxad-`~/V7NC^щ%ˌo2|89Z:in n%.sҷ7l{͆avd3\%/TH&ZjmucCSc顮]/J^!a{u9NAN#Y89sBJҐ׊~"r-г虥=R>QnD.L}Od90O)29fM_D,y!&b $Zu \uv3϶jNv]73m'81+03FR!b`YSٶĘ1P.B4 [V:Z&qe?vV ϦEUF@Yg "KRk Ê OgG iZFR:o>N1yzsN)`QT&%yv&(W9Fo=9%%2 0X/8uQu"DLL=U.5Dz!VS{ Hz=0<&!-:Oc<>n$MT%O }1.NGQY!eMNfj{y;3cM8Nlv\nN!yPyHD0  cey"ʡ8&kpdK (S]_\X墴U!{ .zpZ rq"c[}߱؎N)M-۸cժ?T @iBYgMʅXd %ba~E PÁo{R:a_ <`eieQ`o;9TaumM9uӌebJ$*_͑ՋCey x -mڭl U,&nùrI57ZpPn2zEY<`>bg/i̘g9{ɼ3%~L2;wv;8]8q킜KHT4a k}(k, zU{fmv1Bĵ(zRH'_cUׁe< Prx*;oʕ~ngZf*3}_sv$-O<ܯ6ugǡO͞~1XBM !ke4F .V8 p[ ,wImX-ϔc@_[59ZYrty{鷔4 *!, ׍aSR-%"c12ϽxƊGW'c/a /)R:>0O oOxGov8xϝ"D_",V"G?i@#k%ijh}ܓY #"`iy3Y!B<րS f/KgMiӰ~FJV(SwT%o^shQ~~~׵v[b`A+d 2ST;2n( ܀rgc%Ppױc9cv~IiH4Gwc,2w}[xzd*Nim&sIL)b<BgT(_/L&U*+L- Eg B]zz"QY]zWGW ;:GN"|TP{OEQkg.x?tN}Fcrjn̥4c z7>x1{GvDaS[g0Iǵ75l$:n7 o}%^^8 h*- /\JRᆈ0p#ݚDT8u}_t [*Cc @`_}:?܂wD9rh!auͭhz2{ڒ/ϙqe?<w]מeSmô/ώunm};NjJmѱk-nK j4L+o%f": 8ÀSŚId1z+'"MWJe[-Sՙ䓷%'3Q̲XR C2 iMA x/W V[sW5~Ƭ=[Nܽ)sN:DcƲLRcXV׵>ܖGC:mKSǕ-yb[ϺTz[6轊rM,ba+4bhgJ nefF _CZ~Nh,(t£[RDN!YUYάrP)\ۂ(+ `q$ j}=^e@.& i76񎂈LI_\r€po@4~XT_ePƫcQ`|JF5`gG{iĺZ2Ln=q\w!&^<}eKӴv㝠cɁ,GCnmkfݑΤ.O$~"-|vGL#AϬhX!3(ݾ~ $0Zo9U7x54"n{@o#M׀cx{mtZj(֒S:T;Uqll;C:zIf$GΠ459پr,3̶]\e8mb̎ElK:;J:"5>k;E ؊&jzt=˭z=Rom; Z)'gOpouޢx_r/e+oF-ʇ|.3=ID.^Wd*4&MmyǑEt\{(K/q]T16wdtfA|œܰu7sYDfw-ksc;M4L,zsȸO,ޒXCa$Ylkg[9x}-BX\evʝx-)/)Fjᰰ JH:V=PgJjmۯ8} O:M2ь=wwS{Vb 23VM/}lXi;9 UHw/E*•uE(' i51(ODܶ_ϛҐH M|ue8 ዬwBq)Pۂ +άHUoHe/ 꺈 mwqD`p]#dz#順dcv lጎC֒l_ťlt{IU?< d`r{C x%*) ׎D~IDD>W>Zi^,i&pR1ޠX:ꥐa/˞+ sUFA>WR*2M1> r!k/:{C̊9a58}Xq !OZ–K,O݊pȿLk y\eF%ULL?ޅ07|b8NQ `[wx~c 21 㥕UbOC)VjRU{NuM&;:ϙ3㨞Dzaxt׎gFqrSª!Fڈ5d  wʒn%MHg!(F+"EƓսkP~py]o3^㡴u0CD O l7ߍDVZj1  jHbuVWzE9H'Zk\-/oJ ]t{|C%53ױ] ;Wn~UD9ӏ+ OuΦyNٵ5loDEOH&Ӛ$_f?zbRq>BMD1OzEA8y~"=EdN=:*A^`VE=&灦BBWX,mJNy0~DZ:61 DZ 5>=0Xe>%m*GJTjr@xGX~ ܃Q-%꺔w~vt⥸f(P%7p950IlULě=ۓcC-#x-^M,YpnAtζ'T0 ܢ*o,/*Zє"Isp*8u[?$#1\~G%fv멱QvZ1+1Ҕң"[^gՐh4-Ggxt#=Rfv?;2hRq5_Rs~2(UbiZv{)y%^vzτS֢a"Zk OպGVMd㍻'Due~kgsN`cÆmE<Ǯ ӳN:jOӐ#sr<ݑ%#eEXh9"?:$$mMhZ}$kk~M%3 pa4bLpxx7xk6<4ciH0wR0'f=U }~25|;A.ڷsr3`z:(ȯq*W>K>}l2{ehpU"F2f5iX<{74 Ӵ,ҘhM|W\'s<$x<@ok3Kvd !]C,Q"8hq"U yD w$B;5QibƬxUӈ1i~nVsxi-y}p)盌C= Zb[௼^ET8 T+_p |Eؘ&Nu"V=N|XL ʋWvgM#|/\D-BJ/"TjqJ Tz(Z@2̄m1SU=gkRn &UJ_EV]VV?Z2SӜn8n~omDa$,P:yx}K^mm R\pQUZZY'8yO|Xl.P/:ڍ:-qcCC,l_nKM8x&;U'넫sG  zPRɚEmo4avyjGt~~WMuK=ϟ)߫%82RZ.~2=/+µY];CBU[FD~]%s/tjսU ^9:()?,W'ɤ=xugP|ϡI4<*JU4Ky(^lu$!\Z\;_X3;FQd8er߫SzztSR!+}Xf?R|G(3a56</{y% F4C(E tu U+!d a3('BH%GIENDB`ivy-2.3.0.orig/src/java/org/apache/ivy/tools/0000755000175000017500000000000012126443423017516 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/tools/analyser/0000755000175000017500000000000012126443423021334 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/tools/analyser/DependencyAnalyser.java0000644000175000017500000000202511736412720025755 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.tools.analyser; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; public interface DependencyAnalyser { public ModuleDescriptor[] analyze(JarModule[] modules); } ivy-2.3.0.orig/src/java/org/apache/ivy/tools/analyser/JarModule.java0000644000175000017500000000253511736412720024070 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.tools.analyser; import java.io.File; import org.apache.ivy.core.module.id.ModuleRevisionId; public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } ivy-2.3.0.orig/src/java/org/apache/ivy/tools/analyser/JarJarDependencyAnalyser.java0000644000175000017500000001025011736412720027046 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.tools.analyser; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.util.Message; public class JarJarDependencyAnalyser implements DependencyAnalyser { private File jarjarjarLocation; public JarJarDependencyAnalyser(File jarjarjarLocation) { this.jarjarjarLocation = jarjarjarLocation; } public ModuleDescriptor[] analyze(JarModule[] modules) { StringBuffer jarjarCmd = new StringBuffer("java -jar \"").append( jarjarjarLocation.getAbsolutePath()).append("\" --find --level=jar "); Map jarModulesMap = new HashMap(); Map mds = new HashMap(); for (int i = 0; i < modules.length; i++) { jarModulesMap.put(modules[i].getJar().getAbsolutePath(), modules[i]); DefaultModuleDescriptor md = DefaultModuleDescriptor.newBasicInstance(modules[i] .getMrid(), new Date(modules[i].getJar().lastModified())); mds.put(modules[i].getMrid(), md); jarjarCmd.append("\"").append(modules[i].getJar().getAbsolutePath()).append("\""); if (i + 1 < modules.length) { jarjarCmd.append(File.pathSeparator); } } Message.verbose("jarjar command: " + jarjarCmd); try { Process p = Runtime.getRuntime().exec(jarjarCmd.toString()); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = r.readLine()) != null) { String[] deps = line.split(" -> "); JarModule module = (JarModule) jarModulesMap.get(deps[0]); JarModule dependency = (JarModule) jarModulesMap.get(deps[1]); if (module.getMrid().getModuleId().equals(dependency.getMrid().getModuleId())) { continue; } Message.verbose(module.getMrid() + " depends on " + dependency.getMrid()); DefaultModuleDescriptor md = (DefaultModuleDescriptor) mds.get(module.getMrid()); DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, dependency .getMrid(), false, false, true); dd.addDependencyConfiguration(ModuleDescriptor.DEFAULT_CONFIGURATION, ModuleDescriptor.DEFAULT_CONFIGURATION); md.addDependency(dd); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return (ModuleDescriptor[]) mds.values().toArray(new ModuleDescriptor[mds.values().size()]); } public static void main(String[] args) { JarJarDependencyAnalyser a = new JarJarDependencyAnalyser(new File( "D:/temp/test2/jarjar-0.7.jar")); a.analyze(new JarModuleFinder( "D:/temp/test2/ivyrep/[organisation]/[module]/[revision]/[artifact].[ext]") .findJarModules()); } } ivy-2.3.0.orig/src/java/org/apache/ivy/tools/analyser/JarModuleFinder.java0000644000175000017500000000640411736412720025217 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.tools.analyser; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.ivy.core.IvyPatternHelper; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.plugins.resolver.util.FileURLLister; import org.apache.ivy.plugins.resolver.util.ResolverHelper; import org.apache.ivy.plugins.resolver.util.URLLister; public class JarModuleFinder { private String pattern; private String filePattern; public JarModuleFinder(String pattern) { this.pattern = "file:///" + pattern; this.filePattern = pattern; } public JarModule[] findJarModules() { List ret = new ArrayList(); URLLister lister = new FileURLLister(); try { String[] orgs = ResolverHelper.listTokenValues(lister, pattern, "organisation"); for (int i = 0; i < orgs.length; i++) { String orgPattern = IvyPatternHelper.substituteToken(pattern, IvyPatternHelper.ORGANISATION_KEY, orgs[i]); String[] modules = ResolverHelper.listTokenValues(lister, orgPattern, "module"); for (int j = 0; j < modules.length; j++) { String modPattern = IvyPatternHelper.substituteToken(orgPattern, IvyPatternHelper.MODULE_KEY, modules[j]); String[] revs = ResolverHelper.listTokenValues(lister, modPattern, "revision"); for (int k = 0; k < revs.length; k++) { File jar = new File(IvyPatternHelper.substitute(filePattern, orgs[i], modules[j], revs[k], modules[j], "jar", "jar")); if (jar.exists()) { ret.add(new JarModule(ModuleRevisionId.newInstance(orgs[i], modules[j], revs[k]), jar)); } } } } } catch (Exception e) { // TODO: handle exception } return (JarModule[]) ret.toArray(new JarModule[ret.size()]); } public static void main(String[] args) { JarModule[] mods = new JarModuleFinder( "D:/temp/test2/ivyrep/[organisation]/[module]/[revision]/[artifact].[ext]") .findJarModules(); for (int i = 0; i < mods.length; i++) { System.out.println(mods[i]); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/tools/analyser/RepositoryAnalyser.java0000644000175000017500000000475311736412720026070 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.tools.analyser; import java.io.File; import java.io.IOException; import org.apache.ivy.core.IvyPatternHelper; import org.apache.ivy.core.module.descriptor.DefaultArtifact; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.plugins.parser.xml.XmlModuleDescriptorWriter; import org.apache.ivy.util.Message; public class RepositoryAnalyser { public void analyse(String pattern, DependencyAnalyser depAnalyser) { JarModuleFinder finder = new JarModuleFinder(pattern); ModuleDescriptor[] mds = depAnalyser.analyze(finder.findJarModules()); Message.info("found " + mds.length + " modules"); for (int i = 0; i < mds.length; i++) { File ivyFile = new File(IvyPatternHelper.substitute(pattern, DefaultArtifact .newIvyArtifact(mds[i].getModuleRevisionId(), mds[i].getPublicationDate()))); try { Message.info("generating " + ivyFile); XmlModuleDescriptorWriter.write(mds[i], ivyFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { if (args.length != 2) { System.out.println( "usage: ivyanalyser path/to/jarjar.jar absolute-ivy-repository-pattern"); return; } String jarjarLocation = args[0]; String pattern = args[1]; JarJarDependencyAnalyser a = new JarJarDependencyAnalyser(new File(jarjarLocation)); new RepositoryAnalyser().analyse(pattern, a); } } ivy-2.3.0.orig/src/java/org/apache/ivy/Main.java0000644000175000017500000006310211736412766020123 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.StringTokenizer; import org.apache.ivy.core.cache.ResolutionCacheManager; import org.apache.ivy.core.deliver.DeliverOptions; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.core.publish.PublishOptions; import org.apache.ivy.core.report.ArtifactDownloadReport; import org.apache.ivy.core.report.ResolveReport; import org.apache.ivy.core.resolve.ResolveOptions; import org.apache.ivy.core.retrieve.RetrieveOptions; import org.apache.ivy.core.settings.IvySettings; import org.apache.ivy.plugins.parser.xml.XmlModuleDescriptorWriter; import org.apache.ivy.plugins.report.XmlReportParser; import org.apache.ivy.util.DefaultMessageLogger; import org.apache.ivy.util.Message; import org.apache.ivy.util.cli.CommandLine; import org.apache.ivy.util.cli.CommandLineParser; import org.apache.ivy.util.cli.OptionBuilder; import org.apache.ivy.util.cli.ParseException; import org.apache.ivy.util.filter.FilterHelper; import org.apache.ivy.util.url.CredentialsStore; import org.apache.ivy.util.url.URLHandler; import org.apache.ivy.util.url.URLHandlerDispatcher; import org.apache.ivy.util.url.URLHandlerRegistry; /** * Class used to launch ivy as a standalone tool. *

* Valid arguments can be obtained with the -? argument. */ public final class Main { private static final int HELP_WIDTH = 80; static CommandLineParser getParser() { return new CommandLineParser() .addCategory("settings options") .addOption(new OptionBuilder("settings").arg("settingsfile") .description("use given file for settings").create()) .addOption(new OptionBuilder("cache").arg("cachedir") .description("use given directory for cache").create()) .addOption(new OptionBuilder("novalidate") .description("do not validate ivy files against xsd").create()) .addOption(new OptionBuilder("m2compatible") .description("use maven2 compatibility").create()) .addOption(new OptionBuilder("conf").arg("settingsfile").deprecated() .description("use given file for settings").create()) .addOption(new OptionBuilder("useOrigin").deprecated() .description("use original artifact location " + "with local resolvers instead of copying to the cache").create()) .addCategory("resolve options") .addOption(new OptionBuilder("ivy").arg("ivyfile") .description("use given file as ivy file").create()) .addOption(new OptionBuilder("refresh") .description("refresh dynamic resolved revisions").create()) .addOption(new OptionBuilder("dependency") .arg("organisation").arg("module").arg("revision") .description("use this instead of ivy file to do the rest " + "of the work with this as a dependency.").create()) .addOption(new OptionBuilder("confs").arg("configurations").countArgs(false) .description("resolve given configurations").create()) .addOption(new OptionBuilder("types").arg("types").countArgs(false) .description("comma separated list of accepted artifact types").create()) .addOption(new OptionBuilder("mode").arg("resolvemode") .description("the resolve mode to use").create()) .addOption(new OptionBuilder("notransitive") .description("do not resolve dependencies transitively").create()) .addCategory("retrieve options") .addOption(new OptionBuilder("retrieve").arg("retrievepattern") .description("use given pattern as retrieve pattern").create()) .addOption(new OptionBuilder("ivypattern").arg("pattern") .description("use given pattern to copy the ivy files").create()) .addOption(new OptionBuilder("sync") .description("use sync mode for retrieve").create()) .addOption(new OptionBuilder("symlink") .description("create symbolic links").create()) .addCategory("cache path options") .addOption(new OptionBuilder("cachepath").arg("cachepathfile") .description("outputs a classpath consisting of all dependencies in cache " + "(including transitive ones) " + "of the given ivy file to the given cachepathfile").create()) .addCategory("deliver options") .addOption(new OptionBuilder("deliverto").arg("ivypattern") .description("use given pattern as resolved ivy file pattern").create()) .addCategory("publish options") .addOption(new OptionBuilder("publish").arg("resolvername") .description("use given resolver to publish to").create()) .addOption(new OptionBuilder("publishpattern").arg("artpattern") .description("use given pattern to find artifacts to publish").create()) .addOption(new OptionBuilder("revision").arg("revision") .description("use given revision to publish the module").create()) .addOption(new OptionBuilder("status").arg("status") .description("use given status to publish the module").create()) .addOption(new OptionBuilder("overwrite") .description("overwrite files in the repository if they exist").create()) .addCategory("http auth options") .addOption(new OptionBuilder("realm").arg("realm") .description("use given realm for HTTP AUTH").create()) .addOption(new OptionBuilder("host").arg("host") .description("use given host for HTTP AUTH").create()) .addOption(new OptionBuilder("username").arg("username") .description("use given username for HTTP AUTH").create()) .addOption(new OptionBuilder("passwd").arg("passwd") .description("use given password for HTTP AUTH").create()) .addCategory("launcher options") .addOption(new OptionBuilder("main").arg("main") .description("the FQCN of the main class to launch").create()) .addOption(new OptionBuilder("args").arg("args").countArgs(false) .description("the arguments to give to the launched process").create()) .addOption(new OptionBuilder("cp").arg("cp") .description("extra classpath to use when launching process").create()) .addCategory("message options") .addOption(new OptionBuilder("debug") .description("set message level to debug").create()) .addOption(new OptionBuilder("verbose") .description("set message level to verbose").create()) .addOption(new OptionBuilder("warn") .description("set message level to warn").create()) .addOption(new OptionBuilder("error") .description("set message level to error").create()) .addCategory("help options") .addOption(new OptionBuilder("?") .description("display this help").create()) .addOption(new OptionBuilder("deprecated") .description("show deprecated options").create()) .addOption(new OptionBuilder("version") .description("displays version information").create()); } public static void main(String[] args) throws Exception { CommandLineParser parser = getParser(); try { run(parser, args); System.exit(0); } catch (ParseException ex) { System.err.println(ex.getMessage()); usage(parser, false); System.exit(1); } } static void run(CommandLineParser parser, String[] args) throws Exception { // parse the command line arguments CommandLine line = parser.parse(args); if (line.hasOption("?")) { usage(parser, line.hasOption("deprecated")); return; } if (line.hasOption("version")) { System.out.println("Apache Ivy " + Ivy.getIvyVersion() + " - " + Ivy.getIvyDate() + " :: " + Ivy.getIvyHomeURL()); return; } boolean validate = line.hasOption("novalidate") ? false : true; Ivy ivy = Ivy.newInstance(); initMessage(line, ivy); IvySettings settings = initSettings(line, ivy); ivy.pushContext(); File cache = new File(settings.substitute(line.getOptionValue("cache", settings .getDefaultCache().getAbsolutePath()))); if (line.hasOption("cache")) { //override default cache path with user supplied cache path settings.setDefaultCache(cache); } if (!cache.exists()) { cache.mkdirs(); } else if (!cache.isDirectory()) { error(cache + " is not a directory"); } String[] confs; if (line.hasOption("confs")) { confs = line.getOptionValues("confs"); } else { confs = new String[] {"*"}; } File ivyfile; if (line.hasOption("dependency")) { String[] dep = line.getOptionValues("dependency"); ivyfile = File.createTempFile("ivy", ".xml"); ivyfile.deleteOnExit(); DefaultModuleDescriptor md = DefaultModuleDescriptor .newDefaultInstance(ModuleRevisionId.newInstance(dep[0], dep[1] + "-caller", "working")); DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, ModuleRevisionId.newInstance(dep[0], dep[1], dep[2]), false, false, true); for (int i = 0; i < confs.length; i++) { dd.addDependencyConfiguration("default", confs[i]); } md.addDependency(dd); XmlModuleDescriptorWriter.write(md, ivyfile); confs = new String[] {"default"}; } else { ivyfile = new File(settings.substitute(line.getOptionValue("ivy", "ivy.xml"))); if (!ivyfile.exists()) { error("ivy file not found: " + ivyfile); } else if (ivyfile.isDirectory()) { error("ivy file is not a file: " + ivyfile); } } if (line.hasOption("useOrigin")) { ivy.getSettings().useDeprecatedUseOrigin(); } ResolveOptions resolveOptions = new ResolveOptions().setConfs(confs) .setValidate(validate) .setResolveMode(line.getOptionValue("mode")) .setArtifactFilter(FilterHelper.getArtifactTypeFilter(line.getOptionValues("types"))); if (line.hasOption("notransitive")) { resolveOptions.setTransitive(false); } if (line.hasOption("refresh")) { resolveOptions.setRefresh(true); } ResolveReport report = ivy.resolve(ivyfile.toURI().toURL(), resolveOptions); if (report.hasError()) { System.exit(1); } ModuleDescriptor md = report.getModuleDescriptor(); if (confs.length == 1 && "*".equals(confs[0])) { confs = md.getConfigurationsNames(); } if (line.hasOption("retrieve")) { String retrievePattern = settings.substitute(line.getOptionValue("retrieve")); if (retrievePattern.indexOf("[") == -1) { retrievePattern = retrievePattern + "/lib/[conf]/[artifact].[ext]"; } String ivyPattern = settings.substitute(line.getOptionValue("ivypattern")); ivy.retrieve(md.getModuleRevisionId(), retrievePattern, new RetrieveOptions() .setConfs(confs).setSync(line.hasOption("sync")) .setUseOrigin(line.hasOption("useOrigin")) .setDestIvyPattern(ivyPattern) .setArtifactFilter(FilterHelper.getArtifactTypeFilter(line.getOptionValues("types"))) .setMakeSymlinks(line.hasOption("symlink"))); } if (line.hasOption("cachepath")) { outputCachePath(ivy, cache, md, confs, line.getOptionValue("cachepath", "ivycachepath.txt")); } if (line.hasOption("revision")) { ivy.deliver(md.getResolvedModuleRevisionId(), settings.substitute(line .getOptionValue("revision")), settings.substitute(line.getOptionValue( "deliverto", "ivy-[revision].xml")), DeliverOptions.newInstance(settings) .setStatus(settings.substitute(line.getOptionValue("status", "release"))) .setValidate(validate)); if (line.hasOption("publish")) { ivy.publish(md.getResolvedModuleRevisionId(), Collections.singleton(settings .substitute(line.getOptionValue("publishpattern", "distrib/[type]s/[artifact]-[revision].[ext]"))), line .getOptionValue("publish"), new PublishOptions() .setPubrevision(settings.substitute(line.getOptionValue("revision"))) .setValidate(validate).setSrcIvyPattern( settings.substitute(line.getOptionValue("deliverto", "ivy-[revision].xml"))).setOverwrite(line.hasOption("overwrite"))); } } if (line.hasOption("main")) { // check if the option cp has been set List fileList = getExtraClasspathFileList(line); // merge -args and left over args String[] fargs = line.getOptionValues("args"); if (fargs == null) { fargs = new String[0]; } String[] extra = line.getLeftOverArgs(); if (extra == null) { extra = new String[0]; } String[] params = new String[fargs.length + extra.length]; System.arraycopy(fargs, 0, params, 0, fargs.length); System.arraycopy(extra, 0, params, fargs.length, extra.length); // invoke with given main class and merged params invoke(ivy, cache, md, confs, fileList, line.getOptionValue("main"), params); } ivy.getLoggerEngine().popLogger(); ivy.popContext(); } /** * Parses the cp option from the command line, and returns a list of {@link File}. *

* All the files contained in the returned List exist, non existing files are simply skipped * with a warning. *

* * @param line * the command line in which the cp option shold be parsed * @return a List of files to include as extra classpath entries, or null if no * cp option was provided. */ private static List/**/ getExtraClasspathFileList(CommandLine line) { List fileList = null; if (line.hasOption("cp")) { fileList = new ArrayList/**/(); String[] cpArray = line.getOptionValues("cp"); for (int index = 0; index < cpArray.length; index++) { StringTokenizer tokenizer = new StringTokenizer(cpArray[index], System.getProperty("path.separator")); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); File file = new File(token); if (file.exists()) { fileList.add(file); } else { Message.warn( "Skipping extra classpath '" + file + "' as it does not exist."); } } } } return fileList; } private static IvySettings initSettings(CommandLine line, Ivy ivy) throws java.text.ParseException, IOException, ParseException { IvySettings settings = ivy.getSettings(); settings.addAllVariables(System.getProperties()); if (line.hasOption("m2compatible")) { settings.setVariable("ivy.default.configuration.m2compatible", "true"); } configureURLHandler(line.getOptionValue("realm", null), line.getOptionValue("host", null), line.getOptionValue("username", null), line.getOptionValue("passwd", null)); String settingsPath = line.getOptionValue("settings", ""); if ("".equals(settingsPath)) { settingsPath = line.getOptionValue("conf", ""); if (!"".equals(settingsPath)) { Message.deprecated("-conf is deprecated, use -settings instead"); } } if ("".equals(settingsPath)) { ivy.configureDefault(); } else { File conffile = new File(settingsPath); if (!conffile.exists()) { error("ivy configuration file not found: " + conffile); } else if (conffile.isDirectory()) { error("ivy configuration file is not a file: " + conffile); } ivy.configure(conffile); } return settings; } private static void initMessage(CommandLine line, Ivy ivy) { if (line.hasOption("debug")) { ivy.getLoggerEngine().pushLogger(new DefaultMessageLogger(Message.MSG_DEBUG)); } else if (line.hasOption("verbose")) { ivy.getLoggerEngine().pushLogger(new DefaultMessageLogger(Message.MSG_VERBOSE)); } else if (line.hasOption("warn")) { ivy.getLoggerEngine().pushLogger(new DefaultMessageLogger(Message.MSG_WARN)); } else if (line.hasOption("error")) { ivy.getLoggerEngine().pushLogger(new DefaultMessageLogger(Message.MSG_ERR)); } else { ivy.getLoggerEngine().pushLogger(new DefaultMessageLogger(Message.MSG_INFO)); } } private static void outputCachePath(Ivy ivy, File cache, ModuleDescriptor md, String[] confs, String outFile) { try { String pathSeparator = System.getProperty("path.separator"); StringBuffer buf = new StringBuffer(); Collection all = new LinkedHashSet(); ResolutionCacheManager cacheMgr = ivy.getResolutionCacheManager(); XmlReportParser parser = new XmlReportParser(); for (int i = 0; i < confs.length; i++) { String resolveId = ResolveOptions.getDefaultResolveId(md); File report = cacheMgr.getConfigurationResolveReportInCache(resolveId, confs[i]); parser.parse(report); all.addAll(Arrays.asList(parser.getArtifactReports())); } for (Iterator iter = all.iterator(); iter.hasNext();) { ArtifactDownloadReport artifact = (ArtifactDownloadReport) iter.next(); if (artifact.getLocalFile() != null) { buf.append(artifact.getLocalFile().getCanonicalPath()); buf.append(pathSeparator); } } PrintWriter writer = new PrintWriter(new FileOutputStream(outFile)); if (buf.length() > 0) { writer.println(buf.substring(0, buf.length() - pathSeparator.length())); } writer.close(); System.out.println("cachepath output to " + outFile); } catch (Exception ex) { throw new RuntimeException( "impossible to build ivy cache path: " + ex.getMessage(), ex); } } private static void invoke(Ivy ivy, File cache, ModuleDescriptor md, String[] confs, List fileList, String mainclass, String[] args) { List urls = new ArrayList(); // Add option cp (extra classpath) urls if (fileList != null && fileList.size() > 0) { for (Iterator iter = fileList.iterator(); iter.hasNext();) { File file = (File) iter.next(); try { urls.add(file.toURI().toURL()); } catch (MalformedURLException e) { // Should not happen, just ignore. } } } try { Collection all = new LinkedHashSet(); ResolutionCacheManager cacheMgr = ivy.getResolutionCacheManager(); XmlReportParser parser = new XmlReportParser(); for (int i = 0; i < confs.length; i++) { String resolveId = ResolveOptions.getDefaultResolveId(md); File report = cacheMgr.getConfigurationResolveReportInCache(resolveId, confs[i]); parser.parse(report); all.addAll(Arrays.asList(parser.getArtifactReports())); } for (Iterator iter = all.iterator(); iter.hasNext();) { ArtifactDownloadReport artifact = (ArtifactDownloadReport) iter.next(); if (artifact.getLocalFile() != null) { urls.add(artifact.getLocalFile().toURI().toURL()); } } } catch (Exception ex) { throw new RuntimeException( "impossible to build ivy cache path: " + ex.getMessage(), ex); } URLClassLoader classLoader = new URLClassLoader((URL[]) urls.toArray(new URL[urls.size()]), Main.class.getClassLoader()); try { Class c = classLoader.loadClass(mainclass); Method mainMethod = c.getMethod("main", new Class[] {String[].class}); Thread.currentThread().setContextClassLoader(classLoader); mainMethod.invoke(null, new Object[] {(args == null ? new String[0] : args)}); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("Could not find class: " + mainclass, cnfe); } catch (SecurityException e) { throw new RuntimeException("Could not find main method: " + mainclass, e); } catch (NoSuchMethodException e) { throw new RuntimeException("Could not find main method: " + mainclass, e); } catch (IllegalAccessException e) { throw new RuntimeException("No permissions to invoke main method: " + mainclass, e); } catch (InvocationTargetException e) { throw new RuntimeException( "Unexpected exception invoking main method: " + mainclass, e); } } private static void configureURLHandler(String realm, String host, String username, String passwd) { CredentialsStore.INSTANCE.addCredentials(realm, host, username, passwd); URLHandlerDispatcher dispatcher = new URLHandlerDispatcher(); URLHandler httpHandler = URLHandlerRegistry.getHttp(); dispatcher.setDownloader("http", httpHandler); dispatcher.setDownloader("https", httpHandler); URLHandlerRegistry.setDefault(dispatcher); } private static void error(String msg) throws ParseException { throw new ParseException(msg); } private static void usage(CommandLineParser parser, boolean showDeprecated) { // automatically generate the help statement PrintWriter pw = new PrintWriter(System.out); parser.printHelp(pw, HELP_WIDTH, "ivy", showDeprecated); pw.flush(); } private Main() { } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/0000755000175000017500000000000012126443423017317 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/0000755000175000017500000000000012126443423021466 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteDescriptor.java0000644000175000017500000000331211736412722026442 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite; import java.net.URI; import java.util.Iterator; import org.apache.ivy.osgi.core.ExecutionEnvironmentProfileProvider; import org.apache.ivy.osgi.repo.RepoDescriptor; import org.apache.ivy.osgi.updatesite.xml.EclipseFeature; import org.apache.ivy.osgi.updatesite.xml.EclipsePlugin; public class UpdateSiteDescriptor extends RepoDescriptor { public UpdateSiteDescriptor(URI baseUri, ExecutionEnvironmentProfileProvider profileProvider) { super(baseUri, profileProvider); } public void addFeature(EclipseFeature feature) { addBundle(PluginAdapter.featureAsBundle(getBaseUri(), feature)); Iterator itPlugins = feature.getPlugins().iterator(); while (itPlugins.hasNext()) { addBundle(PluginAdapter.pluginAsBundle(getBaseUri(), (EclipsePlugin) itPlugins.next())); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/PluginAdapter.java0000644000175000017500000000635211736412722025102 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite; import java.net.URI; import java.util.Iterator; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.BundleRequirement; import org.apache.ivy.osgi.updatesite.xml.EclipseFeature; import org.apache.ivy.osgi.updatesite.xml.EclipsePlugin; import org.apache.ivy.osgi.updatesite.xml.Require; import org.apache.ivy.osgi.util.VersionRange; public class PluginAdapter { public static BundleInfo featureAsBundle(URI baseUri, EclipseFeature feature) { BundleInfo b = new BundleInfo(feature.getId(), feature.getVersion()); if (feature.getUrl() == null) { b.setUri(baseUri.resolve("features/" + feature.getId() + '_' + feature.getVersion() + ".jar")); } else { b.setUri(baseUri.resolve(feature.getUrl())); } b.setDescription(feature.getDescription()); b.setLicense(feature.getLicense()); Iterator itPlugins = feature.getPlugins().iterator(); while (itPlugins.hasNext()) { EclipsePlugin plugin = (EclipsePlugin) itPlugins.next(); BundleRequirement r = new BundleRequirement(BundleInfo.BUNDLE_TYPE, plugin.getId(), new VersionRange(plugin.getVersion()), null); b.addRequirement(r); } Iterator itRequires = feature.getRequires().iterator(); while (itRequires.hasNext()) { Require require = (Require) itRequires.next(); String id; if (require.getPlugin() != null) { id = require.getPlugin(); } else { id = require.getFeature(); } VersionRange range; if (require.getMatch().equals("greaterOrEqual")) { range = new VersionRange(require.getVersion()); } else { throw new IllegalStateException("unsupported match " + require.getMatch()); } BundleRequirement r = new BundleRequirement(BundleInfo.BUNDLE_TYPE, id, range, null); b.addRequirement(r); } return b; } public static BundleInfo pluginAsBundle(URI baseUri, EclipsePlugin plugin) { BundleInfo b = new BundleInfo(plugin.getId(), plugin.getVersion()); b.setUri(baseUri.resolve("plugins/" + plugin.getId() + '_' + plugin.getVersion() + ".jar")); return b; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/xml/0000755000175000017500000000000012126443423022266 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/xml/Archive.java0000644000175000017500000000214611736412722024521 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite.xml; public class Archive { public void setPath(String path) { // TODO Auto-generated method stub } public void setURL(String url) { // TODO Auto-generated method stub } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/xml/UpdateSite.java0000644000175000017500000000360511736412722025210 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite.xml; import java.net.URI; import java.util.ArrayList; import java.util.List; public class UpdateSite { private URI uri; private String mirrorsURL; private boolean pack200; private URI digestUri; private List/* */features = new ArrayList(); public void setUri(URI uri) { this.uri = uri; } public URI getUri() { return uri; } public void setMirrorsURL(String mirrorsURL) { this.mirrorsURL = mirrorsURL; } public void setPack200(boolean pack200) { this.pack200 = pack200; } public void setDigestUri(URI digestUri) { this.digestUri = digestUri; } public URI getDigestUri() { return digestUri; } public void addFeature(EclipseFeature feature) { features.add(feature); } public List getFeatures() { return features; } public void setAssociateSitesURL(String associateSitesURL) { // TODO what's that ? } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/xml/EclipsePlugin.java0000644000175000017500000000310111736412722025673 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite.xml; import org.apache.ivy.osgi.util.Version; public class EclipsePlugin { private String id; private Version version; public void setId(String id) { this.id = id; } public String getId() { return id; } public void setVersion(Version version) { this.version = version; } public Version getVersion() { return version; } public void setUnpack(boolean valueOf) { // TODO Auto-generated method stub } public void setFragment(String value) { // TODO Auto-generated method stub } public void setFilter(String value) { // TODO Auto-generated method stub } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/xml/FeatureParser.java0000644000175000017500000003142611742633062025712 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite.xml; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.apache.ivy.osgi.util.DelegetingHandler; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.util.XMLHelper; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class FeatureParser { public static EclipseFeature parse(InputStream in) throws ParseException, IOException, SAXException { FeatureHandler handler = new FeatureHandler(); try { XMLHelper.parse(in, null, handler, null); } catch (ParserConfigurationException e) { throw new SAXException(e); } return handler.feature; } static class FeatureHandler extends DelegetingHandler { private static final String FEATURE = "feature"; private static final String COLOCATION_AFFINITY = "colocation-affinity"; private static final String PRIMARY = "primary"; private static final String EXCLUSIVE = "exclusive"; private static final String PLUGIN = "plugin"; private static final String APPLICATION = "application"; private static final String ARCH = "arch"; private static final String NL = "nl"; private static final String WS = "ws"; private static final String OS = "os"; private static final String VERSION = "version"; private static final String ID = "id"; private static final String PROVIDER_NAME = "provider-name"; private static final String LABEL = "label"; private static final String IMAGE = "image"; EclipseFeature feature; public FeatureHandler() { super(FEATURE); addChild(new DescriptionHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { feature.setDescription(child.getBufferedChars().trim()); } }); addChild(new LicenseHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { feature.setLicense(child.getBufferedChars().trim()); } }); addChild(new CopyrightHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { feature.setCopyright(child.getBufferedChars().trim()); } }); addChild(new PluginHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { feature.addPlugin(((PluginHandler) child).plugin); } }); addChild(new RequiresHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { Iterator itRequire = ((RequiresHandler) child).requires.iterator(); while (itRequire.hasNext()) { feature.addRequire((Require) itRequire.next()); } } }); addChild(new UrlHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); } protected void handleAttributes(Attributes atts) throws SAXException { String id = atts.getValue(ID); String version = atts.getValue(VERSION); try { feature = new EclipseFeature(id, new Version(version)); } catch (ParseException e) { throw new SAXException("Incorrect version on feature '" + id + "': " + version + " (" + e.getMessage() + ")"); } feature.setOS(atts.getValue(OS)); feature.setWS(atts.getValue(WS)); feature.setNL(atts.getValue(NL)); feature.setArch(atts.getValue(ARCH)); feature.setApplication(atts.getValue(APPLICATION)); feature.setPlugin(atts.getValue(PLUGIN)); feature.setExclusive(Boolean.valueOf(atts.getValue(EXCLUSIVE)).booleanValue()); feature.setPrimary(Boolean.valueOf(atts.getValue(PRIMARY)).booleanValue()); feature.setColocationAffinity(atts.getValue(COLOCATION_AFFINITY)); feature.setProviderName(atts.getValue(PROVIDER_NAME)); feature.setLabel(atts.getValue(LABEL)); feature.setImage(atts.getValue(IMAGE)); } } static class PluginHandler extends DelegetingHandler { private static final String PLUGIN = "plugin"; private static final String FILTER = "filter"; private static final String FRAGMENT = "fragment"; private static final String UNPACK = "unpack"; private static final String VERSION = "version"; private static final String ID = "id"; private EclipsePlugin plugin; public PluginHandler() { super(PLUGIN); } protected void handleAttributes(Attributes atts) throws SAXException { plugin = new EclipsePlugin(); String id = atts.getValue(ID); String version = atts.getValue(VERSION); plugin.setId(id); try { plugin.setVersion(new Version(version)); } catch (ParseException e) { throw new SAXException("Incorrect version on feature's plugin '" + id + "': " + version + " (" + e.getMessage() + ")"); } plugin.setUnpack(Boolean.valueOf(atts.getValue(UNPACK)).booleanValue()); plugin.setFragment(atts.getValue(FRAGMENT)); plugin.setFilter(atts.getValue(FILTER)); } } static class DescriptionHandler extends DelegetingHandler { private static final String DESCRIPTION = "description"; private static final String URL = "url"; public DescriptionHandler() { super(DESCRIPTION); setBufferingChar(true); } protected void handleAttributes(Attributes atts) throws SAXException { String url = atts.getValue(URL); } } static class LicenseHandler extends DelegetingHandler { private static final String LICENSE = "license"; private static final String URL = "url"; public LicenseHandler() { super(LICENSE); setBufferingChar(true); } protected void handleAttributes(Attributes atts) throws SAXException { String url = atts.getValue(URL); } } static class CopyrightHandler extends DelegetingHandler { private static final String COPYRIGHT = "copyright"; private static final String URL = "url"; public CopyrightHandler() { super(COPYRIGHT); setBufferingChar(true); } protected void handleAttributes(Attributes atts) throws SAXException { String url = atts.getValue(URL); } } static class RequiresHandler extends DelegetingHandler { private static final String REQUIRES = "requires"; List requires = new ArrayList(); public RequiresHandler() { super(REQUIRES); addChild(new ImportHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { requires.add(((ImportHandler) child).require); } }); } } static class ImportHandler extends DelegetingHandler { Require require; private static final String IMPORT = "import"; private static final String FILTER = "filter"; private static final String MATCH = "match"; private static final String VERSION = "version"; private static final String PLUGIN = "plugin"; private static final String FEATURE = "feature"; public ImportHandler() { super(IMPORT); } protected void handleAttributes(Attributes atts) throws SAXException { require = new Require(); String version = atts.getValue(VERSION); require.setFeature(atts.getValue(FEATURE)); require.setPlugin(atts.getValue(PLUGIN)); try { require.setVersion(new Version(version)); } catch (ParseException e) { throw new SAXException("Incorrect version on feature's import: " + version + " (" + e.getMessage() + ")"); } require.setMatch(atts.getValue(MATCH)); require.setFilter(atts.getValue(FILTER)); } } static class IncludesHandler extends DelegetingHandler { private static final String INCLUDES = "includes"; private static final String FILTER = "filter"; private static final String OPTIONAL = "optional"; private static final String VERSION = "version"; private static final String ID = "id"; public IncludesHandler() { super(INCLUDES); } protected void handleAttributes(Attributes atts) throws SAXException { String id = atts.getValue(ID); String version = atts.getValue(VERSION); String optional = atts.getValue(OPTIONAL); String filter = atts.getValue(FILTER); } } static class InstallHandlerHandler extends DelegetingHandler { private static final String INSTALL_HANDLER = "install-handler"; private static final String URL = "url"; private static final String LIBRARY = "library"; private static final String HANDLER = "handler"; public InstallHandlerHandler() { super(INSTALL_HANDLER); } protected void handleAttributes(Attributes atts) throws SAXException { String handler = atts.getValue(HANDLER); String library = atts.getValue(LIBRARY); String url = atts.getValue(URL); } } static class UrlHandler extends DelegetingHandler { private static final String URL = "url"; public UrlHandler() { super(URL); addChild(new UpdateHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); addChild(new DiscoveryHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); } } static class UpdateHandler extends DelegetingHandler { private static final String UPDATE = "update"; private static final String LABEL = "label"; private static final String URL = "url"; public UpdateHandler() { super(UPDATE); } protected void handleAttributes(Attributes atts) throws SAXException { String label = atts.getValue(LABEL); String url = atts.getValue(URL); } } static class DiscoveryHandler extends DelegetingHandler { private static final String DISCOVERY = "discovery"; private static final String URL = "url"; private static final String LABEL = "label"; private static final String TYPE = "type"; public DiscoveryHandler() { super(DISCOVERY); } protected void handleAttributes(Attributes atts) throws SAXException { String type = atts.getValue(TYPE); String label = atts.getValue(LABEL); String url = atts.getValue(URL); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/xml/Require.java0000644000175000017500000000350611736412722024555 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite.xml; import org.apache.ivy.osgi.util.Version; public class Require { private String plugin; private String feature; private Version version; private String match; private String filter; public void setFeature(String feature) { this.feature = feature; } public String getFeature() { return feature; } public void setPlugin(String plugin) { this.plugin = plugin; } public String getPlugin() { return plugin; } public void setVersion(Version version) { this.version = version; } public Version getVersion() { return version; } public void setMatch(String match) { this.match = match; } public String getMatch() { return match; } public void setFilter(String filter) { this.filter = filter; } public String getFilter() { return filter; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/xml/EclipseUpdateSiteParser.java0000644000175000017500000002217711742633064027700 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite.xml; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.text.ParseException; import javax.xml.parsers.ParserConfigurationException; import org.apache.ivy.osgi.util.DelegetingHandler; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.util.XMLHelper; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class EclipseUpdateSiteParser { public static UpdateSite parse(InputStream in) throws ParseException, IOException, SAXException { SiteHandler handler = new SiteHandler(); try { XMLHelper.parse(in, null, handler, null); } catch (ParserConfigurationException e) { throw new SAXException(e); } return handler.updatesite; } static class SiteHandler extends DelegetingHandler { private static final String SITE = "site"; private static final String URL = "url"; private static final String PACK200 = "pack200"; private static final String MIRRORS_URL = "mirrorsURL"; private static final String ASSOCIATE_SITES_URL = "associateSitesURL"; private static final String DIGEST_URL = "digestURL"; UpdateSite updatesite; public SiteHandler() { super(SITE); // addChild(new DescriptionHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // updateSite.setDescription(child.getBufferedChars().trim()); // } // }); addChild(new FeatureHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { updatesite.addFeature(((FeatureHandler) child).feature); } }); // addChild(new ArchiveHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // updateSite.addArchive(((ArchiveHandler) child).archive); // } // }); // addChild(new CategoryDefHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // updateSite.addCategoryDef(((CategoryDefHandler) child).categoryDef); // } // }); } protected void handleAttributes(Attributes atts) { updatesite = new UpdateSite(); String url = atts.getValue(URL); if (url != null && !("".equals(url.trim()))) { if (!url.endsWith("/") && !url.endsWith(File.separator)) { url += "/"; } try { updatesite.setUri(new URI(url)); } catch (URISyntaxException e) { throw new RuntimeException("illegal url", e); } } String mirrorsURL = atts.getValue(MIRRORS_URL); if (mirrorsURL != null && mirrorsURL.trim().length() > 0) { updatesite.setMirrorsURL(mirrorsURL); } String pack200 = atts.getValue(PACK200); if (pack200 != null && new Boolean(pack200).booleanValue()) { updatesite.setPack200(true); } String digestURL = atts.getValue(DIGEST_URL); if (digestURL != null) { try { updatesite.setDigestUri(new URI(digestURL)); } catch (URISyntaxException e) { throw new RuntimeException("illegal url", e); } } String associateSitesURL = atts.getValue(ASSOCIATE_SITES_URL); if (associateSitesURL != null) { updatesite.setAssociateSitesURL(associateSitesURL); } } } static class DescriptionHandler extends DelegetingHandler { private static final String DESCRIPTION = "description"; private static final String URL = "url"; public DescriptionHandler() { super(DESCRIPTION); setBufferingChar(true); } protected void handleAttributes(Attributes atts) { String url = atts.getValue(URL); } } static class FeatureHandler extends DelegetingHandler { private static final String FEATURE = "feature"; private static final String VERSION = "version"; private static final String ID = "id"; private static final String URL = "url"; private static final String PATCH = "patch"; private static final String ARCH = "arch"; private static final String NL = "nl"; private static final String WS = "ws"; private static final String OS = "os"; private static final String LABEL = "label"; private static final String TYPE = "type"; private EclipseFeature feature; public FeatureHandler() { super(FEATURE); addChild(new CategoryHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { feature.addCategory(((CategoryHandler) child).name); } }); } protected void handleAttributes(Attributes atts) throws SAXException { String id = atts.getValue(ID); String version = atts.getValue(VERSION); try { feature = new EclipseFeature(id, new Version(version)); } catch (ParseException e) { throw new SAXException("Incorrect version on the feature '" + id + "': " + version + " (" + e.getMessage() + ")"); } String url = atts.getValue(URL); if (url != null) { feature.setURL(url); } feature.setType(atts.getValue(TYPE)); feature.setLabel(atts.getValue(LABEL)); feature.setOS(atts.getValue(OS)); feature.setWS(atts.getValue(WS)); feature.setNL(atts.getValue(NL)); feature.setArch(atts.getValue(ARCH)); feature.setPatch(atts.getValue(PATCH)); } } static class CategoryHandler extends DelegetingHandler { private static final String CATEGORY = "category"; private static final String NAME = "name"; String name; public CategoryHandler() { super(CATEGORY); } protected void handleAttributes(Attributes atts) throws SAXException { name = atts.getValue(NAME); } } static class ArchiveHandler extends DelegetingHandler { private static final String ARCHIVE = "archive"; private static final String URL = "url"; private static final String PATH = "path"; private Archive archive; public ArchiveHandler() { super(ARCHIVE); } protected void handleAttributes(Attributes atts) throws SAXException { archive = new Archive(); String path = atts.getValue(PATH); archive.setPath(path); String url = atts.getValue(URL); archive.setURL(url); } } static class CategoryDefHandler extends DelegetingHandler { private static final String CATEGORY_DEF = "category-def"; private static final String NAME = "name"; private static final String LABEL = "label"; private CategoryDef categoryDef; public CategoryDefHandler() { super(CATEGORY_DEF); addChild(new DescriptionHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { categoryDef.setDescription(child.getBufferedChars().trim()); } }); } protected void handleAttributes(Attributes atts) throws SAXException { categoryDef = new CategoryDef(); String name = atts.getValue(NAME); categoryDef.setName(name); String label = atts.getValue(LABEL); categoryDef.setLabel(label); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/xml/UpdateSiteDigestParser.java0000644000175000017500000000471211736412722027525 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite.xml; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import javax.xml.parsers.ParserConfigurationException; import org.apache.ivy.osgi.core.ExecutionEnvironmentProfileProvider; import org.apache.ivy.osgi.updatesite.UpdateSiteDescriptor; import org.apache.ivy.osgi.updatesite.xml.FeatureParser.FeatureHandler; import org.apache.ivy.osgi.util.DelegetingHandler; import org.apache.ivy.util.XMLHelper; import org.xml.sax.SAXException; public class UpdateSiteDigestParser { public static UpdateSiteDescriptor parse(InputStream in, UpdateSite site) throws ParseException, IOException, SAXException { DigestHandler handler = new DigestHandler(site); try { XMLHelper.parse(in, null, handler, null); } catch (ParserConfigurationException e) { throw new SAXException(e); } return handler.repoDescriptor; } static class DigestHandler extends DelegetingHandler { private static final String DIGEST = "digest"; UpdateSiteDescriptor repoDescriptor; public DigestHandler(final UpdateSite site) { super(DIGEST); repoDescriptor = new UpdateSiteDescriptor(site.getUri(), ExecutionEnvironmentProfileProvider.getInstance()); addChild(new FeatureHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { repoDescriptor.addFeature(((FeatureHandler) child).feature); } }); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/xml/EclipseFeature.java0000644000175000017500000000766611736412722026054 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite.xml; import java.util.ArrayList; import java.util.List; import org.apache.ivy.osgi.util.Version; public class EclipseFeature { private String id; private Version version; private List/* */plugins = new ArrayList(); private List/* */requires = new ArrayList(); private String url; private String description; private String license; public EclipseFeature(String id, Version version) { this.id = id; this.version = version; this.url = "features/" + id + '_' + version + ".jar"; } public void setURL(String url) { this.url = url; } public String getUrl() { return url; } public void setType(String type) { // TODO Auto-generated method stub } public String getId() { return id; } public Version getVersion() { return version; } public void setLabel(String label) { // TODO Auto-generated method stub } public void setOS(String os) { // TODO Auto-generated method stub } public void setWS(String ws) { // TODO Auto-generated method stub } public void setNL(String nl) { // TODO Auto-generated method stub } public void setArch(String arch) { // TODO Auto-generated method stub } public void setPatch(String patch) { // TODO Auto-generated method stub } public void addCategory(String name) { // TODO Auto-generated method stub } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setCopyright(String trim) { // not useful } public void setLicense(String license) { this.license = license; } public String getLicense() { return license; } public void addPlugin(EclipsePlugin plugin) { plugins.add(plugin); } public List getPlugins() { return plugins; } public void addRequire(Require require) { requires.add(require); } public List getRequires() { return requires; } public void setApplication(String value) { // TODO Auto-generated method stub } public void setPlugin(String value) { // TODO Auto-generated method stub } public void setExclusive(boolean booleanValue) { // TODO Auto-generated method stub } public void setPrimary(boolean booleanValue) { // TODO Auto-generated method stub } public void setColocationAffinity(String value) { // TODO Auto-generated method stub } public void setProviderName(String value) { // TODO Auto-generated method stub } public void setImage(String value) { // TODO Auto-generated method stub } public String toString() { return id + "#" + version; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/xml/CategoryDef.java0000644000175000017500000000232011736412722025326 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite.xml; public class CategoryDef { public void setLabel(String label) { // TODO Auto-generated method stub } public void setName(String name) { // TODO Auto-generated method stub } public void setDescription(String trim) { // TODO Auto-generated method stub } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java0000644000175000017500000002777711736412722025557 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.text.ParseException; import java.util.Iterator; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.ivy.core.cache.CacheResourceOptions; import org.apache.ivy.core.cache.RepositoryCacheManager; import org.apache.ivy.core.event.EventManager; import org.apache.ivy.core.report.ArtifactDownloadReport; import org.apache.ivy.core.report.DownloadStatus; import org.apache.ivy.osgi.core.ExecutionEnvironmentProfileProvider; import org.apache.ivy.osgi.p2.P2ArtifactParser; import org.apache.ivy.osgi.p2.P2CompositeParser; import org.apache.ivy.osgi.p2.P2Descriptor; import org.apache.ivy.osgi.p2.P2MetadataParser; import org.apache.ivy.osgi.p2.XMLInputParser; import org.apache.ivy.osgi.repo.RepoDescriptor; import org.apache.ivy.osgi.updatesite.xml.EclipseFeature; import org.apache.ivy.osgi.updatesite.xml.EclipseUpdateSiteParser; import org.apache.ivy.osgi.updatesite.xml.FeatureParser; import org.apache.ivy.osgi.updatesite.xml.UpdateSite; import org.apache.ivy.osgi.updatesite.xml.UpdateSiteDigestParser; import org.apache.ivy.plugins.repository.url.URLRepository; import org.apache.ivy.plugins.repository.url.URLResource; import org.apache.ivy.util.Message; import org.xml.sax.SAXException; public class UpdateSiteLoader { private final RepositoryCacheManager repositoryCacheManager; private final URLRepository urlRepository = new URLRepository(); private final CacheResourceOptions options; public UpdateSiteLoader(RepositoryCacheManager repositoryCacheManager, EventManager eventManager, CacheResourceOptions options) { this.repositoryCacheManager = repositoryCacheManager; this.options = options; if (eventManager != null) { urlRepository.addTransferListener(eventManager); } } public RepoDescriptor load(URI repoUri) throws IOException, ParseException, SAXException { if (!repoUri.toString().endsWith("/")) { try { repoUri = new URI(repoUri.toString() + "/"); } catch (URISyntaxException e) { throw new RuntimeException("Cannot make an uri for the repo"); } } Message.verbose("Loading the update site " + repoUri); // first look for a p2 repository RepoDescriptor repo = loadP2(repoUri); if (repo != null) { return repo; } Message.verbose("\tNo P2 artifacts, falling back on the old fashioned updatesite"); // then try the old update site UpdateSite site = loadSite(repoUri); if (site == null) { return null; } repo = loadFromDigest(site); if (repo != null) { return repo; } return loadFromSite(site); } private P2Descriptor loadP2(URI repoUri) throws IOException, ParseException, SAXException { P2Descriptor p2Descriptor = new P2Descriptor(repoUri, ExecutionEnvironmentProfileProvider.getInstance()); if (!populateP2Descriptor(repoUri, p2Descriptor)) { return null; } return p2Descriptor; } private boolean populateP2Descriptor(URI repoUri, P2Descriptor p2Descriptor) throws IOException, ParseException, SAXException { Message.verbose("Loading P2 repository " + repoUri); boolean artifactExists = readComposite(repoUri, "compositeArtifacts", p2Descriptor); if (!artifactExists) { artifactExists = readJarOrXml(repoUri, "artifacts", new P2ArtifactParser(p2Descriptor, repoUri.toURL().toExternalForm())); } boolean contentExists = readComposite(repoUri, "compositeContent", p2Descriptor); if (!contentExists) { contentExists = readJarOrXml(repoUri, "content", new P2MetadataParser(p2Descriptor)); } return artifactExists || contentExists; } private boolean readComposite(URI repoUri, String name, P2Descriptor p2Descriptor) throws IOException, ParseException, SAXException { P2CompositeParser p2CompositeParser = new P2CompositeParser(); boolean exist = readJarOrXml(repoUri, name, p2CompositeParser); if (exist) { Iterator itChildLocation = p2CompositeParser.getChildLocations().iterator(); while (itChildLocation.hasNext()) { String childLocation = (String) itChildLocation.next(); if (!childLocation.endsWith("/")) { childLocation += "/"; } URI childUri = repoUri.resolve(childLocation); populateP2Descriptor(childUri, p2Descriptor); } } return exist; } private boolean readJarOrXml(URI repoUri, String baseName, XMLInputParser reader) throws IOException, ParseException, SAXException { InputStream readIn = null; // the input stream from which the xml should be read URL contentUrl = repoUri.resolve(baseName + ".jar").toURL(); URLResource res = new URLResource(contentUrl); ArtifactDownloadReport report = repositoryCacheManager.downloadRepositoryResource(res, baseName, baseName, "jar", options, urlRepository); if (report.getDownloadStatus() == DownloadStatus.FAILED) { // no jar file, try the xml one contentUrl = repoUri.resolve(baseName + ".xml").toURL(); res = new URLResource(contentUrl); report = repositoryCacheManager.downloadRepositoryResource(res, baseName, baseName, "xml", options, urlRepository); if (report.getDownloadStatus() == DownloadStatus.FAILED) { // no xml either return false; } readIn = new FileInputStream(report.getLocalFile()); } else { InputStream in = new FileInputStream(report.getLocalFile()); try { // compressed, let's get the pointer on the actual xml readIn = findEntry(in, baseName + ".xml"); if (readIn == null) { in.close(); return false; } } catch (IOException e) { in.close(); throw e; } } try { reader.parse(readIn); } finally { readIn.close(); } return true; } private UpdateSite loadSite(URI repoUri) throws IOException, ParseException, SAXException { URI siteUri = normalizeSiteUri(repoUri, null); URL u = siteUri.resolve("site.xml").toURL(); URLResource res = new URLResource(u); ArtifactDownloadReport report = repositoryCacheManager.downloadRepositoryResource(res, "site", "updatesite", "xml", options, urlRepository); if (report.getDownloadStatus() == DownloadStatus.FAILED) { return null; } InputStream in = new FileInputStream(report.getLocalFile()); try { UpdateSite site = EclipseUpdateSiteParser.parse(in); site.setUri(normalizeSiteUri(site.getUri(), siteUri)); return site; } finally { in.close(); } } private URI normalizeSiteUri(URI uri, URI defaultValue) { if (uri == null) { return defaultValue; } String uriString = uri.toString(); if (uriString.endsWith("site.xml")) { try { return new URI(uriString.substring(0, uriString.length() - 8)); } catch (URISyntaxException e) { throw new RuntimeException("Illegal uri", e); } } if (!uriString.endsWith("/")) { try { return new URI(uriString + "/"); } catch (URISyntaxException e) { throw new RuntimeException("Illegal uri", e); } } return uri; } private UpdateSiteDescriptor loadFromDigest(UpdateSite site) throws IOException, ParseException, SAXException { URI digestBaseUri = site.getDigestUri(); if (digestBaseUri == null) { digestBaseUri = site.getUri(); } else if (!digestBaseUri.isAbsolute()) { digestBaseUri = site.getUri().resolve(digestBaseUri); } URL digest = digestBaseUri.resolve("digest.zip").toURL(); Message.verbose("\tReading " + digest); URLResource res = new URLResource(digest); ArtifactDownloadReport report = repositoryCacheManager.downloadRepositoryResource(res, "digest", "digest", "zip", options, urlRepository); if (report.getDownloadStatus() == DownloadStatus.FAILED) { return null; } InputStream in = new FileInputStream(report.getLocalFile()); try { ZipInputStream zipped = findEntry(in, "digest.xml"); if (zipped == null) { return null; } return UpdateSiteDigestParser.parse(zipped, site); } finally { in.close(); } } private UpdateSiteDescriptor loadFromSite(UpdateSite site) throws IOException, ParseException, SAXException { UpdateSiteDescriptor repoDescriptor = new UpdateSiteDescriptor(site.getUri(), ExecutionEnvironmentProfileProvider.getInstance()); Iterator itFeatures = site.getFeatures().iterator(); while (itFeatures.hasNext()) { EclipseFeature feature = (EclipseFeature) itFeatures.next(); URL url = site.getUri().resolve(feature.getUrl()).toURL(); URLResource res = new URLResource(url); ArtifactDownloadReport report = repositoryCacheManager.downloadRepositoryResource(res, feature.getId(), "feature", "jar", options, urlRepository); if (report.getDownloadStatus() == DownloadStatus.FAILED) { return null; } InputStream in = new FileInputStream(report.getLocalFile()); try { ZipInputStream zipped = findEntry(in, "feature.xml"); if (zipped == null) { return null; } EclipseFeature f = FeatureParser.parse(zipped); f.setURL(feature.getUrl()); repoDescriptor.addFeature(f); } finally { in.close(); } } return repoDescriptor; } private ZipInputStream findEntry(InputStream in, String entryName) throws IOException { ZipInputStream zipped = new ZipInputStream(in); ZipEntry zipEntry = zipped.getNextEntry(); while (zipEntry != null && !zipEntry.getName().equals(entryName)) { zipEntry = zipped.getNextEntry(); } if (zipEntry == null) { return null; } return zipped; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteResolver.java0000644000175000017500000000541611742633064026135 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.updatesite; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.text.ParseException; import org.apache.ivy.core.cache.CacheResourceOptions; import org.apache.ivy.osgi.repo.AbstractOSGiResolver; import org.xml.sax.SAXException; public class UpdateSiteResolver extends AbstractOSGiResolver { private String url; private Long metadataTtl; private Boolean forceMetadataUpdate; public void setUrl(String url) { this.url = url; } public void setMetadataTtl(Long metadataTtl) { this.metadataTtl = metadataTtl; } public void setForceMetadataUpdate(Boolean forceMetadataUpdate) { this.forceMetadataUpdate = forceMetadataUpdate; } protected void init() { if (url == null) { throw new RuntimeException("Missing url"); } CacheResourceOptions options = new CacheResourceOptions(); if (metadataTtl != null) { options.setTtl(metadataTtl.longValue()); } if (forceMetadataUpdate != null) { options.setForce(forceMetadataUpdate.booleanValue()); } UpdateSiteLoader loader = new UpdateSiteLoader(getRepositoryCacheManager(), getEventManager(), options); try { setRepoDescriptor(loader.load(new URI(url))); } catch (IOException e) { throw new RuntimeException("IO issue while trying to read the update site (" + e.getMessage() + ")"); } catch (ParseException e) { throw new RuntimeException("Failed to parse the updatesite (" + e.getMessage() + ")"); } catch (SAXException e) { throw new RuntimeException("Illformed updatesite (" + e.getMessage() + ")"); } catch (URISyntaxException e) { throw new RuntimeException("Illformed url (" + e.getMessage() + ")"); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/0000755000175000017500000000000012126443423020264 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/RepositoryManifestIterable.java0000644000175000017500000000522511736412722026455 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.ivy.plugins.repository.Repository; import org.apache.ivy.plugins.repository.Resource; import org.apache.ivy.plugins.resolver.util.ResolverHelper; public class RepositoryManifestIterable extends AbstractFSManifestIterable/* */{ private final Repository repo; /** * Default constructor * * @param root * the root directory of the file system to lookup */ public RepositoryManifestIterable(Repository repo) { super(""); this.repo = repo; } protected URI buildBundleURI(Object/* String */location) throws IOException { Resource resource = repo.getResource((String) location); // We have a resource to transform into an URI, let's use some heuristics try { return new URI(resource.getName()); } catch (URISyntaxException e) { return new File(resource.getName()).toURI(); } } protected InputStream getInputStream(Object/* String */f) throws IOException { return repo.getResource((String) f).openStream(); } protected List/* */listBundleFiles(Object/* String */dir) throws IOException { return asList(ResolverHelper.listAll(repo, (String) dir)); } protected List/* */listDirs(Object/* String */dir) throws IOException { return asList(ResolverHelper.listAll(repo, (String) dir)); } private List/* */asList(String[] array) { return array == null ? Collections.EMPTY_LIST : Arrays./* */asList(array); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/RepoDescriptor.java0000644000175000017500000001201111742633060024067 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import java.net.URI; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.osgi.core.BundleCapability; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.BundleInfoAdapter; import org.apache.ivy.osgi.core.ExecutionEnvironmentProfileProvider; import org.apache.ivy.osgi.core.OSGiManifestParser; import org.apache.ivy.util.Message; public class RepoDescriptor { private final Map/* >> */moduleByCapbilities = new HashMap(); private final Set/* */modules = new HashSet(); private final ExecutionEnvironmentProfileProvider profileProvider; private final URI baseUri; public RepoDescriptor(URI baseUri, ExecutionEnvironmentProfileProvider profileProvider) { this.baseUri = baseUri; this.profileProvider = profileProvider; } public URI getBaseUri() { return baseUri; } public Set/* */getModules() { return modules; } public Map/* >> */getModuleByCapbilities() { return moduleByCapbilities; } public Set/* */findModule(String requirement, String value) { Map/* > */modules = (Map) moduleByCapbilities .get(requirement); if (modules == null) { return null; } return (Set) modules.get(value); } public Set/* */getCapabilityValues(String capabilityName) { Map/* > */modules = (Map) moduleByCapbilities .get(capabilityName); if (modules == null) { return null; } return (Set) modules.keySet(); } public void add(String type, String value, ModuleDescriptor md) { modules.add(md); Map/* > */map = (Map) moduleByCapbilities.get(type); if (map == null) { map = new HashMap/* > */(); moduleByCapbilities.put(type, map); } Set/* */bundleReferences = (Set) map.get(value); if (bundleReferences == null) { bundleReferences = new HashSet/* */(); map.put(value, bundleReferences); } if (!bundleReferences.add(md)) { Message.debug("Duplicate module in the repo " + baseUri + " for " + type + " " + value + ": " + md.getModuleRevisionId()); } } public void addBundle(BundleInfo bundleInfo) { DefaultModuleDescriptor md = BundleInfoAdapter.toModuleDescriptor( OSGiManifestParser.getInstance(), baseUri, bundleInfo, profileProvider); add(BundleInfo.BUNDLE_TYPE, bundleInfo.getSymbolicName(), md); Iterator itCapability = bundleInfo.getCapabilities().iterator(); while (itCapability.hasNext()) { BundleCapability capability = (BundleCapability) itCapability.next(); add(capability.getType(), capability.getName(), md); } } public String toString() { return modules.toString(); } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((modules == null) ? 0 : modules.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } RepoDescriptor other = (RepoDescriptor) obj; if (modules == null) { if (other.modules != null) { return false; } } else if (!modules.equals(other.modules)) { return false; } return true; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/ResolverManifestIterable.java0000644000175000017500000001733011736412722026077 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import java.io.IOException; import java.net.URI; import java.text.ParseException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import org.apache.ivy.core.event.EventManager; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.core.resolve.ResolveData; import org.apache.ivy.core.resolve.ResolveEngine; import org.apache.ivy.core.resolve.ResolveOptions; import org.apache.ivy.core.resolve.ResolvedModuleRevision; import org.apache.ivy.core.search.ModuleEntry; import org.apache.ivy.core.search.OrganisationEntry; import org.apache.ivy.core.search.RevisionEntry; import org.apache.ivy.core.settings.IvySettings; import org.apache.ivy.core.sort.SortEngine; import org.apache.ivy.osgi.core.BundleInfoAdapter; import org.apache.ivy.plugins.resolver.BasicResolver; import org.apache.ivy.plugins.resolver.util.ResolvedResource; import org.apache.ivy.util.Message; public class ResolverManifestIterable { //implements Iterable/* */{ // We should support the interface DependencyResolver, but the API is not convenient to get // references to artifact private final BasicResolver resolver; public ResolverManifestIterable(BasicResolver resolver) { this.resolver = resolver; } public Iterator/* */iterator() { return new ResolverManifestIterator(); } class ResolverManifestIterator implements Iterator/* */{ private OrganisationEntry[] organisations; private int indexOrganisation = 0; private OrganisationEntry organisation; private ModuleEntry[] modules; private int indexModule = -1; private ModuleEntry module; private ManifestAndLocation next = null; private RevisionEntry[] revisions; private int indexRevision; private RevisionEntry revision; private Artifact[] artifacts; private int indexArtifact; private Artifact artifact; private ModuleRevisionId mrid; private ResolveData data; public ResolverManifestIterator() { organisations = resolver.listOrganisations(); IvySettings settings = new IvySettings(); ResolveEngine engine = new ResolveEngine(settings, new EventManager(), new SortEngine( settings)); data = new ResolveData(engine, new ResolveOptions()); } public boolean hasNext() { while (next == null) { if (organisation == null) { if (indexOrganisation >= organisations.length) { return false; } organisation = organisations[indexOrganisation++]; modules = resolver.listModules(organisation); indexModule = 0; module = null; } if (module == null) { if (indexModule >= modules.length) { organisation = null; continue; } module = modules[indexModule++]; revisions = resolver.listRevisions(module); indexRevision = 0; revision = null; } if (revision == null) { if (indexRevision >= revisions.length) { module = null; continue; } revision = revisions[indexRevision++]; mrid = ModuleRevisionId.newInstance(organisation.getOrganisation(), module.getModule(), revision.getRevision()); DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(mrid, false); ResolvedModuleRevision dependency; try { dependency = resolver.getDependency(dd, data); } catch (ParseException e) { Message.error("Error while resolving " + mrid + " : " + e.getMessage()); revision = null; continue; } if (dependency == null) { revision = null; continue; } ModuleDescriptor md = dependency.getDescriptor(); mrid = md.getModuleRevisionId(); artifacts = md.getAllArtifacts(); indexArtifact = 0; artifact = null; } if (artifact == null) { if (indexArtifact >= artifacts.length) { revision = null; continue; } artifact = artifacts[indexArtifact++]; } ResolvedResource resource = resolver.doFindArtifactRef(artifact, null); if (resource == null) { artifact = null; continue; } JarInputStream in; try { in = new JarInputStream(resource.getResource().openStream()); } catch (IOException e) { Message.warn("Unreadable jar " + resource.getResource().getName() + " (" + e.getMessage() + ")"); artifact = null; continue; } Manifest manifest; try { manifest = in.getManifest(); } finally { try { in.close(); } catch (IOException e) { // don't care } } if (manifest == null) { Message.debug("No manifest on " + artifact); } else { URI uri = BundleInfoAdapter.buildIvyURI(artifact); next = new ManifestAndLocation(manifest, uri); } artifact = null; } return true; } public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } ManifestAndLocation manifest = next; next = null; return manifest; } public void remove() { throw new UnsupportedOperationException(); } } }ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/BundleCapabilityAndLocation.java0000644000175000017500000000322411736412722026463 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.util.Version; public class BundleCapabilityAndLocation { private final String name; private final Version version; private final BundleInfo bundleInfo; private final String type; public BundleCapabilityAndLocation(String type, String name, Version version, BundleInfo bundleInfo) { this.type = type; this.name = name; this.version = version; this.bundleInfo = bundleInfo; } public BundleInfo getBundleInfo() { return bundleInfo; } public String getName() { return name; } public String getType() { return type; } public Version getVersion() { return version; } }ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/AbstractOSGiResolver.java0000644000175000017500000006640712013010722025136 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import java.io.File; import java.io.IOException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.ivy.core.IvyPatternHelper; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.Configuration; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.descriptor.DependencyDescriptor; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.core.report.DownloadStatus; import org.apache.ivy.core.report.MetadataArtifactDownloadReport; import org.apache.ivy.core.resolve.IvyNode; import org.apache.ivy.core.resolve.ResolveData; import org.apache.ivy.core.resolve.ResolvedModuleRevision; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.BundleInfoAdapter; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.plugins.repository.Resource; import org.apache.ivy.plugins.repository.url.URLRepository; import org.apache.ivy.plugins.repository.url.URLResource; import org.apache.ivy.plugins.resolver.BasicResolver; import org.apache.ivy.plugins.resolver.util.MDResolvedResource; import org.apache.ivy.plugins.resolver.util.ResolvedResource; import org.apache.ivy.plugins.resolver.util.ResourceMDParser; import org.apache.ivy.util.Message; public abstract class AbstractOSGiResolver extends BasicResolver { private static final String CAPABILITY_EXTRA_ATTR = "osgi_bundle"; private RepoDescriptor repoDescriptor = null; private URLRepository repository = new URLRepository(); public static class RequirementStrategy { // take the first matching public static RequirementStrategy first = new RequirementStrategy(); // if there are any ambiguity, fail to resolve public static RequirementStrategy noambiguity = new RequirementStrategy(); public static RequirementStrategy valueOf(String strategy) { if (strategy.equals("first")) { return first; } if (strategy.equals("noambiguity")) { return noambiguity; } throw new IllegalStateException(); } } private RequirementStrategy requirementStrategy = RequirementStrategy.noambiguity; public void setRequirementStrategy(RequirementStrategy importPackageStrategy) { this.requirementStrategy = importPackageStrategy; } public void setRequirementStrategy(String strategy) { setRequirementStrategy(RequirementStrategy.valueOf(strategy)); } protected void setRepoDescriptor(RepoDescriptor repoDescriptor) { this.repoDescriptor = repoDescriptor; } public URLRepository getRepository() { return repository; } protected void ensureInit() { if (repoDescriptor == null) { init(); } } abstract protected void init(); private RepoDescriptor getRepoDescriptor() { ensureInit(); return repoDescriptor; } public boolean isAllownomd() { // this a repo based resolver, we always have md return false; } public ResolvedResource findIvyFileRef(DependencyDescriptor dd, ResolveData data) { ModuleRevisionId mrid = dd.getDependencyRevisionId(); String osgiType = mrid.getOrganisation(); if (osgiType == null) { throw new RuntimeException("Unsupported OSGi module Id: " + mrid.getModuleId()); } String id = mrid.getName(); Set/* */mds = getRepoDescriptor().findModule(osgiType, id); if (mds == null || mds.isEmpty()) { Message.verbose("\t " + id + " not found."); return null; } ResolvedResource[] ret; if (BundleInfo.BUNDLE_TYPE.equals(osgiType)) { ret = findBundle(dd, data, mds); } else { ret = findCapability(dd, data, mds); } ResolvedResource found = findResource(ret, getDefaultRMDParser(dd.getDependencyId()), mrid, data.getDate()); if (found == null) { Message.debug("\t" + getName() + ": no resource found for " + mrid); } return found; } public ResolvedResource[] findBundle(DependencyDescriptor dd, ResolveData data, Set/* * < * ModuleDescriptor * > */mds) { ResolvedResource[] ret = new ResolvedResource[mds.size()]; int i = 0; Iterator itMd = mds.iterator(); while (itMd.hasNext()) { ModuleDescriptor md = (ModuleDescriptor) itMd.next(); MetadataArtifactDownloadReport report = new MetadataArtifactDownloadReport(null); report.setDownloadStatus(DownloadStatus.NO); report.setSearched(true); ResolvedModuleRevision rmr = new ResolvedModuleRevision(this, this, md, report); MDResolvedResource mdrr = new MDResolvedResource(null, md.getRevision(), rmr); ret[i++] = mdrr; } return ret; } public ResolvedResource[] findCapability(DependencyDescriptor dd, ResolveData data, Set/* * < * ModuleDescriptor * > */mds) { ResolvedResource[] ret = new ResolvedResource[mds.size()]; int i = 0; Iterator itMd = mds.iterator(); while (itMd.hasNext()) { ModuleDescriptor md = (ModuleDescriptor) itMd.next(); IvyNode node = data.getNode(md.getModuleRevisionId()); if (node != null && node.getDescriptor() != null) { // already resolved import, no need to go further return new ResolvedResource[] {buildResolvedCapabilityMd(dd, node.getDescriptor())}; } ret[i++] = buildResolvedCapabilityMd(dd, md); } return ret; } private MDResolvedResource buildResolvedCapabilityMd(DependencyDescriptor dd, ModuleDescriptor md) { String org = dd.getDependencyRevisionId().getOrganisation(); String name = dd.getDependencyRevisionId().getName(); String rev = (String) md.getExtraInfo().get( BundleInfoAdapter.EXTRA_INFO_EXPORT_PREFIX + name); ModuleRevisionId capabilityRev = ModuleRevisionId.newInstance(org, name, rev, Collections.singletonMap(CAPABILITY_EXTRA_ATTR, md.getModuleRevisionId().toString())); DefaultModuleDescriptor capabilityMd = new DefaultModuleDescriptor(capabilityRev, "release", new Date()); String useConf = BundleInfoAdapter.CONF_USE_PREFIX + dd.getDependencyRevisionId().getName(); capabilityMd.addConfiguration(BundleInfoAdapter.CONF_DEFAULT); capabilityMd.addConfiguration(BundleInfoAdapter.CONF_OPTIONAL); capabilityMd.addConfiguration(BundleInfoAdapter.CONF_TRANSITIVE_OPTIONAL); capabilityMd.addConfiguration(new Configuration(useConf)); DefaultDependencyDescriptor capabilityDD = new DefaultDependencyDescriptor( md.getModuleRevisionId(), false); capabilityDD.addDependencyConfiguration(BundleInfoAdapter.CONF_NAME_DEFAULT, BundleInfoAdapter.CONF_NAME_DEFAULT); capabilityDD.addDependencyConfiguration(BundleInfoAdapter.CONF_NAME_OPTIONAL, BundleInfoAdapter.CONF_NAME_OPTIONAL); capabilityDD.addDependencyConfiguration(BundleInfoAdapter.CONF_NAME_TRANSITIVE_OPTIONAL, BundleInfoAdapter.CONF_NAME_TRANSITIVE_OPTIONAL); capabilityDD.addDependencyConfiguration(useConf, useConf); capabilityMd.addDependency(capabilityDD); MetadataArtifactDownloadReport report = new MetadataArtifactDownloadReport(null); report.setDownloadStatus(DownloadStatus.NO); report.setSearched(true); ResolvedModuleRevision rmr = new ResolvedModuleRevision(this, this, capabilityMd, report); return new MDResolvedResource(null, capabilityMd.getRevision(), rmr); } public ResolvedResource findResource(ResolvedResource[] rress, ResourceMDParser rmdparser, ModuleRevisionId mrid, Date date) { ResolvedResource found = super.findResource(rress, rmdparser, mrid, date); String osgiType = mrid.getOrganisation(); // for non bundle requirement : log the selected bundle if (!BundleInfo.BUNDLE_TYPE.equals(osgiType)) { // several candidates with different symbolic name : make an warning about the ambiguity if (rress.length != 1) { // several candidates with different symbolic name ? Map/* > */matching = new HashMap(); for (int i = 0; i < rress.length; i++) { String name = ((MDResolvedResource) rress[i]).getResolvedModuleRevision() .getDescriptor().getExtraAttribute(CAPABILITY_EXTRA_ATTR); List/* */list = (List) matching.get(name); if (list == null) { list = new ArrayList/* */(); matching.put(name, list); } list.add(rress[i]); } if (matching.keySet().size() != 1) { if (requirementStrategy == RequirementStrategy.first) { Message.warn("Ambiguity for the '" + osgiType + "' requirement " + mrid.getName() + ";version=" + mrid.getRevision()); Iterator itMatching = matching.entrySet().iterator(); while (itMatching.hasNext()) { Entry/* > */entry = (Entry) itMatching .next(); Message.warn("\t" + entry.getKey()); Iterator itB = ((List) entry.getValue()).iterator(); while (itB.hasNext()) { MDResolvedResource c = (MDResolvedResource) itB.next(); Message.warn("\t\t" + c.getRevision() + (found == c ? " (selected)" : "")); } } } else if (requirementStrategy == RequirementStrategy.noambiguity) { Message.error("Ambiguity for the '" + osgiType + "' requirement " + mrid.getName() + ";version=" + mrid.getRevision()); Iterator itMatching = matching.entrySet().iterator(); while (itMatching.hasNext()) { Entry/* > */entry = (Entry) itMatching .next(); Message.error("\t" + entry.getKey()); Iterator itB = ((List) entry.getValue()).iterator(); while (itB.hasNext()) { MDResolvedResource c = (MDResolvedResource) itB.next(); Message.error("\t\t" + c.getRevision() + (found == c ? " (best match)" : "")); } } return null; } } } Message.info("'" + osgiType + "' requirement " + mrid.getName() + ";version=" + mrid.getRevision() + " satisfied by " + ((MDResolvedResource) found).getResolvedModuleRevision().getId().getName() + ";" + found.getRevision()); } return found; } public ResolvedResource findArtifactRef(Artifact artifact, Date date) { URL url = artifact.getUrl(); if (url == null) { // not an artifact resolved by this resolver return null; } Message.verbose("\tusing url for " + artifact + ": " + url); logArtifactAttempt(artifact, url.toExternalForm()); Resource resource = new URLResource(url); return new ResolvedResource(resource, artifact.getModuleRevisionId().getRevision()); } protected void checkModuleDescriptorRevision(ModuleDescriptor systemMd, ModuleRevisionId systemMrid) { String osgiType = systemMrid.getOrganisation(); // only check revision if we're searching for a bundle (package and bundle have different // version if (osgiType == null || osgiType.equals(BundleInfo.BUNDLE_TYPE)) { super.checkModuleDescriptorRevision(systemMd, systemMrid); } } protected Collection/* */filterNames(Collection/* */names) { getSettings().filterIgnore(names); return names; } protected Collection findNames(Map tokenValues, String token) { if (IvyPatternHelper.ORGANISATION_KEY.equals(token)) { return getRepoDescriptor().getModuleByCapbilities().keySet(); } String osgiType = (String) tokenValues.get(IvyPatternHelper.ORGANISATION_KEY); if (osgiType == null || osgiType.length() == 0) { return Collections.EMPTY_LIST; } String rev = (String) tokenValues.get(IvyPatternHelper.REVISION_KEY); if (IvyPatternHelper.MODULE_KEY.equals(token)) { Map/* >> */moduleByCapbilities = getRepoDescriptor() .getModuleByCapbilities(); if (osgiType != null) { Map/* > */moduleByCapabilityValue = (Map) moduleByCapbilities .get(osgiType); if (moduleByCapabilityValue == null) { return Collections.EMPTY_LIST; } Set/* */capabilityValues = new HashSet(); return moduleByCapabilityValue.keySet(); } else { Set/* */capabilityValues = new HashSet(); Iterator/* >> */it = ((Collection) moduleByCapbilities .values()).iterator(); while (it.hasNext()) { Map/* > */moduleByCapbilityValue = (Map) it .next(); filterCapabilityValues(capabilityValues, moduleByCapbilityValue, tokenValues, rev); } return capabilityValues; } } if (IvyPatternHelper.REVISION_KEY.equals(token)) { String name = (String) tokenValues.get(IvyPatternHelper.MODULE_KEY); List/* */versions = new ArrayList/* */(); Set/* */mds = getRepoDescriptor().findModule(osgiType, name); if (mds != null) { Iterator itMd = mds.iterator(); while (itMd.hasNext()) { ModuleDescriptor md = (ModuleDescriptor) itMd.next(); versions.add(md.getRevision()); } } return versions; } if (IvyPatternHelper.CONF_KEY.equals(token)) { String name = (String) tokenValues.get(IvyPatternHelper.MODULE_KEY); if (name == null) { return Collections.EMPTY_LIST; } if (osgiType.equals(BundleInfo.PACKAGE_TYPE)) { return Collections.singletonList(BundleInfoAdapter.CONF_USE_PREFIX + name); } Set/* */bundleCapabilities = getRepoDescriptor() .findModule(osgiType, name); if (bundleCapabilities == null) { return Collections.EMPTY_LIST; } String version = (String) tokenValues.get(IvyPatternHelper.REVISION_KEY); if (version == null) { return Collections.EMPTY_LIST; } Version v; try { v = new Version(version); } catch (ParseException e) { return Collections.EMPTY_LIST; } BundleCapabilityAndLocation found = null; Iterator itBundle = bundleCapabilities.iterator(); while (itBundle.hasNext()) { BundleCapabilityAndLocation bundleCapability = (BundleCapabilityAndLocation) itBundle .next(); if (bundleCapability.getVersion().equals(v)) { found = bundleCapability; } } if (found == null) { return Collections.EMPTY_LIST; } List/* */confs = BundleInfoAdapter.getConfigurations(found.getBundleInfo()); return confs; } return Collections.EMPTY_LIST; } /** * Populate capabilityValues with capability values for which at least one module match the * expected revision */ private void filterCapabilityValues(Set/* */capabilityValues, Map/* > */moduleByCapbilityValue, Map/* >> */it = moduleByCapbilityValue .entrySet().iterator(); while (it.hasNext()) { Entry/* > */entry = (Entry) it.next(); Iterator/* */itModules = ((Set) entry.getValue()).iterator(); boolean moduleMatchRev = false; while (!moduleMatchRev && itModules.hasNext()) { ModuleDescriptor md = (ModuleDescriptor) itModules.next(); moduleMatchRev = rev.equals(md.getRevision()); } if (moduleMatchRev) { // at least one module matched, the capability value is ok to add capabilityValues.add(entry.getKey()); } } } } public Map[] listTokenValues(String[] tokens, Map criteria) { Set/* */tokenSet = new HashSet/* */(Arrays.asList(tokens)); Set/* > */listTokenValues = listTokenValues(tokenSet, criteria); return (Map[]) listTokenValues.toArray(new Map[listTokenValues.size()]); } private Set/* > */listTokenValues(Set/* */tokens, Map/* * */criteria) { if (tokens.isEmpty()) { return Collections./* > */singleton(criteria); } Set/* */tokenSet = new HashSet/* */(tokens); Map/* */values = new HashMap/* */(); tokenSet.remove(IvyPatternHelper.ORGANISATION_KEY); String osgiType = (String) criteria.get(IvyPatternHelper.ORGANISATION_KEY); if (osgiType == null || osgiType.length() == 0) { return Collections.EMPTY_SET; } values.put(IvyPatternHelper.ORGANISATION_KEY, osgiType); if (osgiType == null) { Set/* > */tokenValues = new HashSet/* > */(); Map/* */newCriteria = new HashMap/* */(criteria); newCriteria.put(IvyPatternHelper.ORGANISATION_KEY, BundleInfo.BUNDLE_TYPE); tokenValues.addAll(listTokenValues(tokenSet, newCriteria)); newCriteria = new HashMap/* */(criteria); newCriteria.put(IvyPatternHelper.ORGANISATION_KEY, BundleInfo.PACKAGE_TYPE); tokenValues.addAll(listTokenValues(tokenSet, newCriteria)); newCriteria = new HashMap/* */(criteria); newCriteria.put(IvyPatternHelper.ORGANISATION_KEY, BundleInfo.SERVICE_TYPE); tokenValues.addAll(listTokenValues(tokenSet, newCriteria)); return tokenValues; } Set/* */capabilities = getRepoDescriptor().getCapabilityValues(osgiType); if (capabilities == null || capabilities.isEmpty()) { return Collections.EMPTY_SET; } tokenSet.remove(IvyPatternHelper.MODULE_KEY); String module = (String) criteria.get(IvyPatternHelper.MODULE_KEY); if (module == null) { Set/* > */tokenValues = new HashSet/* > */(); Iterator itNames = capabilities.iterator(); while (itNames.hasNext()) { String name = (String) itNames.next(); Map/* */newCriteria = new HashMap/* */(criteria); newCriteria.put(IvyPatternHelper.MODULE_KEY, name); tokenValues.addAll(listTokenValues(tokenSet, newCriteria)); } return tokenValues; } values.put(IvyPatternHelper.MODULE_KEY, module); tokenSet.remove(IvyPatternHelper.REVISION_KEY); String rev = (String) criteria.get(IvyPatternHelper.REVISION_KEY); if (rev == null) { Set/* */bundleCapabilities = getRepoDescriptor() .findModule(osgiType, module); if (bundleCapabilities == null) { return Collections.EMPTY_SET; } Set/* > */tokenValues = new HashSet/* > */(); Iterator itBundle = bundleCapabilities.iterator(); while (itBundle.hasNext()) { BundleCapabilityAndLocation capability = (BundleCapabilityAndLocation) itBundle .next(); Map/* */newCriteria = new HashMap/* */(criteria); newCriteria.put(IvyPatternHelper.REVISION_KEY, capability.getVersion().toString()); tokenValues.addAll(listTokenValues(tokenSet, newCriteria)); } return tokenValues; } values.put(IvyPatternHelper.REVISION_KEY, rev); tokenSet.remove(IvyPatternHelper.CONF_KEY); String conf = (String) criteria.get(IvyPatternHelper.CONF_KEY); if (conf == null) { if (osgiType.equals(BundleInfo.PACKAGE_TYPE)) { values.put(IvyPatternHelper.CONF_KEY, BundleInfoAdapter.CONF_USE_PREFIX + module); return Collections./* > */singleton(values); } Set/* */bundleCapabilities = getRepoDescriptor() .findModule(osgiType, module); if (bundleCapabilities == null) { return Collections.EMPTY_SET; } Version v; try { v = new Version(rev); } catch (ParseException e) { return Collections.EMPTY_SET; } BundleCapabilityAndLocation found = null; Iterator itBundle = bundleCapabilities.iterator(); while (itBundle.hasNext()) { BundleCapabilityAndLocation bundleCapability = (BundleCapabilityAndLocation) itBundle .next(); if (bundleCapability.getVersion().equals(v)) { found = bundleCapability; } } if (found == null) { return Collections.EMPTY_SET; } Set/* > */tokenValues = new HashSet/* > */(); List/* */configurations = BundleInfoAdapter.getConfigurations(found .getBundleInfo()); for (int i = 0; i < configurations.size(); i++) { Map/* */newCriteria = new HashMap/* */(criteria); newCriteria.put(IvyPatternHelper.CONF_KEY, configurations.get(i)); tokenValues.add(newCriteria); } return tokenValues; } values.put(IvyPatternHelper.CONF_KEY, conf); return Collections./* > */singleton(values); } protected long get(Resource resource, File dest) throws IOException { Message.verbose("\t" + getName() + ": downloading " + resource.getName()); Message.debug("\t\tto " + dest); if (dest.getParentFile() != null) { dest.getParentFile().mkdirs(); } getRepository().get(resource.getName(), dest); return dest.length(); } protected Resource getResource(String source) throws IOException { return getRepository().getResource(source); } public void publish(Artifact artifact, File src, boolean overwrite) throws IOException { throw new UnsupportedOperationException(); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/RelativeURLRepository.java0000644000175000017500000000470111736412722025373 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.ivy.plugins.repository.Resource; import org.apache.ivy.plugins.repository.url.URLRepository; import org.apache.ivy.plugins.repository.url.URLResource; public class RelativeURLRepository extends URLRepository { private final URL baseUrl; public RelativeURLRepository() { super(); baseUrl = null; } public RelativeURLRepository(URL baseUrl) { super(); this.baseUrl = baseUrl; } private Map/* */resourcesCache = new HashMap/* */(); public Resource getResource(String source) throws IOException { source = encode(source); Resource res = (Resource) resourcesCache.get(source); if (res == null) { URI uri; try { uri = new URI(source); } catch (URISyntaxException e) { // very wierd URL, let's assume it is absolute uri = null; } if (uri == null || uri.isAbsolute()) { res = new URLResource(new URL(source)); } else { res = new URLResource(new URL(baseUrl + source)); } resourcesCache.put(source, res); } return res; } private static String encode(String source) { // TODO: add some more URL encodings here return source.trim().replaceAll(" ", "%20"); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/FSManifestIterable.java0000644000175000017500000001047711736412722024613 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class FSManifestIterable extends AbstractFSManifestIterable/* */{ /** * List of directory name that usually contains jars but are not bundles */ public static final Set/* */NON_BUNDLE_DIRS = new HashSet/* */( Arrays.asList(new String[] {"source", "sources", "javadoc", "javadocs", "doc", "docs"})); /** * Default directory filter that doesn't select .svn directories, neither the directories that * match {@link #NON_BUNDLE_DIRS}. */ public static final FilenameFilter DEFAULT_DIR_FILTER = new FilenameFilter() { public boolean accept(File dir, String name) { return !name.equals(".svn") && !NON_BUNDLE_DIRS.contains(name); } }; /** * Default bundle filter that select only .jar files */ public static final FilenameFilter DEFAULT_BUNLDE_FILTER = new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jar"); } }; private FilenameFilter dirFilter = DEFAULT_DIR_FILTER; private FilenameFilter bundleFilter = DEFAULT_BUNLDE_FILTER; /** * Default constructor * * @param root * the root directory of the file system to lookup */ public FSManifestIterable(File root) { super(root); } public FilenameFilter getDirFilter() { return dirFilter; } public void setDirFilter(FilenameFilter dirFilter) { this.dirFilter = dirFilter; } public FilenameFilter getBundleFilter() { return bundleFilter; } public void setBundleFilter(FilenameFilter bundleFilter) { this.bundleFilter = bundleFilter; } protected URI buildBundleURI(Object/* File */location) { try { return new URI(((File) location).toURL().toExternalForm()); } catch (MalformedURLException e) { throw new RuntimeException("Unexpected file to url conversion error", e); } catch (URISyntaxException e) { throw new RuntimeException("Unexpected url to uri conversion error", e); } } protected InputStream getInputStream(Object/* File */f) throws FileNotFoundException { return new FileInputStream((File) f); } protected List/* */listBundleFiles(Object/* File */dir) { return Arrays.asList(((File) dir).listFiles(new FileFilter() { public boolean accept(File f) { if (!f.isFile()) { return false; } return bundleFilter.accept(f.getParentFile(), f.getName()); } })); } protected List/* */listDirs(Object/* File */dir) { return Arrays.asList(((File) dir).listFiles(new FileFilter() { public boolean accept(File f) { if (!f.isDirectory()) { return false; } return dirFilter == null || dirFilter.accept(f.getParentFile(), f.getName()); } })); } }ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/BundleRepoDescriptor.java0000644000175000017500000000451411736412722025235 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import java.net.URI; import java.text.ParseException; import java.util.Iterator; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.ExecutionEnvironmentProfileProvider; import org.apache.ivy.osgi.core.ManifestParser; import org.apache.ivy.util.Message; public class BundleRepoDescriptor extends RepoDescriptor { private String name; private Long lastModified; public BundleRepoDescriptor(URI baseUri, ExecutionEnvironmentProfileProvider profileProvider) { super(baseUri, profileProvider); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setLastModified(Long lastModified) { this.lastModified = lastModified; } public Long getLastModified() { return lastModified; } public void populate(Iterator/* */it) { while (it.hasNext()) { ManifestAndLocation manifestAndLocation = (ManifestAndLocation) it.next(); try { BundleInfo bundleInfo = ManifestParser.parseManifest(manifestAndLocation .getManifest()); bundleInfo.setUri(manifestAndLocation.getUri()); addBundle(bundleInfo); } catch (ParseException e) { Message.error("Rejected " + manifestAndLocation.getUri() + ": " + e.getMessage()); } } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/AbstractFSManifestIterable.java0000644000175000017500000001430611736412722026272 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Stack; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import org.apache.ivy.util.Message; // T is the type of the resource "path" public abstract class AbstractFSManifestIterable /* implements Iterable/* */{ private final Object/* T */root; public AbstractFSManifestIterable(Object /* T */root) { this.root = root; } public Iterator/* */iterator() { return new FSManifestIterator(root); } abstract protected List/* */listBundleFiles(Object/* T */dir) throws IOException; abstract protected List/* */listDirs(Object/* T */dir) throws IOException; abstract protected InputStream getInputStream(Object/* T */f) throws IOException; abstract protected URI buildBundleURI(Object/* T */location) throws IOException; class FSManifestIterator implements Iterator/* */{ private ManifestAndLocation next = null; /** * Stack of list of directories. An iterator in the stack represents the current directory * being lookup. The first element in the stack is the root directory. The next element in * the stack is an iterator on the children on the root. The last iterator in the stack * points to {@link #currentDir}. */ private Stack/* > */dirs = new Stack/* > */(); /** * The bundles files being lookup. */ private Iterator/* */bundleCandidates = null; private Object/* T */currentDir = null; FSManifestIterator(Object /* T */root) { dirs.add(Collections.singleton(root).iterator()); } /** * Deep first tree lookup for the directories and the bundles are searched on each found * directory. */ public boolean hasNext() { while (next == null) { // no current directory if (currentDir == null) { // so get the next one if (((Iterator) dirs.peek()).hasNext()) { currentDir = ((Iterator) dirs.peek()).next(); try { bundleCandidates = listBundleFiles(currentDir).iterator(); } catch (IOException e) { Message.warn("Unlistable dir: " + currentDir + " (" + e + ")"); currentDir = null; } } else if (dirs.size() <= 1) { // no next directory, but we are at the root: finished return false; } else { // remove the top of the stack and continue with a sibling. dirs.pop(); } } else if (bundleCandidates.hasNext()) { Object/* T */bundleCandidate = bundleCandidates.next(); JarInputStream in = null; try { in = new JarInputStream(getInputStream(bundleCandidate)); Manifest manifest = in.getManifest(); if (manifest != null) { next = new ManifestAndLocation(manifest, buildBundleURI(bundleCandidate)); } else { Message.debug("No manifest in jar: " + bundleCandidate); } } catch (FileNotFoundException e) { Message.debug("Jar file just removed: " + bundleCandidate + " (" + e + ")"); } catch (IOException e) { Message.warn("Unreadable jar: " + bundleCandidate + " (" + e + ")"); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // Don't care } } } } else { // no more candidate on the current directory // so lookup in the children directories try { dirs.add(listDirs(currentDir).iterator()); } catch (IOException e) { Message.warn("Unlistable dir: " + currentDir + " (" + e + ")"); dirs.add(Collections.EMPTY_LIST.iterator()); } currentDir = null; } } return true; } public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } ManifestAndLocation manifest = next; next = null; return manifest; } public void remove() { throw new UnsupportedOperationException(); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/repo/ManifestAndLocation.java0000644000175000017500000000250011736412722025012 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import java.net.URI; import java.util.jar.Manifest; public class ManifestAndLocation { private final Manifest manifest; /** * location of the jar */ private final URI uri; public ManifestAndLocation(Manifest manifest, URI uri) { this.manifest = manifest; this.uri = uri; } public URI getUri() { return uri; } public Manifest getManifest() { return manifest; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/p2/0000755000175000017500000000000012126443423017640 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/osgi/p2/PropertiesParser.java0000644000175000017500000000444511736412722024027 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.p2; import java.util.HashMap; import java.util.Map; import org.apache.ivy.osgi.util.DelegetingHandler; import org.xml.sax.Attributes; public class PropertiesParser { static class PropertiesHandler extends DelegetingHandler { private static final String PROPERTIES = "properties"; private static final String SIZE = "size"; Map properties; public PropertiesHandler() { super(PROPERTIES); addChild(new PropertyHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { properties.put(((PropertyHandler) child).name, ((PropertyHandler) child).value); } }); } protected void handleAttributes(Attributes atts) { int size = Integer.parseInt(atts.getValue(SIZE)); properties = new HashMap(size); } } static class PropertyHandler extends DelegetingHandler { private static final String PROPERTY = "property"; private static final String NAME = "name"; private static final String VALUE = "value"; String name; String value; public PropertyHandler() { super(PROPERTY); } protected void handleAttributes(Attributes atts) { name = atts.getValue(NAME); value = atts.getValue(VALUE); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/p2/P2ArtifactParser.java0000644000175000017500000001720012013010720023600 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.p2; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.xml.parsers.ParserConfigurationException; import org.apache.ivy.osgi.p2.PropertiesParser.PropertiesHandler; import org.apache.ivy.osgi.util.DelegetingHandler; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.util.XMLHelper; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class P2ArtifactParser implements XMLInputParser { private final P2Descriptor p2Descriptor; private final String repoUrl; public P2ArtifactParser(P2Descriptor p2Descriptor, String repoUrl) { this.p2Descriptor = p2Descriptor; this.repoUrl = repoUrl; } public void parse(InputStream in) throws ParseException, IOException, SAXException { RepositoryHandler handler = new RepositoryHandler(p2Descriptor, repoUrl); try { XMLHelper.parse(in, null, handler, null); } catch (ParserConfigurationException e) { throw new SAXException(e); } } static class RepositoryHandler extends DelegetingHandler { private static final String REPOSITORY = "repository"; // private static final String NAME = "name"; // // private static final String TYPE = "type"; // // private static final String VERSION = "version"; private Map/* */patternsByClassifier = new HashMap(); public RepositoryHandler(final P2Descriptor p2Descriptor, String repoUrl) { super(REPOSITORY); // addChild(new PropertiesHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // } // }); addChild(new MappingsHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { Iterator it = ((MappingsHandler) child).outputByFilter.entrySet().iterator(); while (it.hasNext()) { Entry entry = (Entry) it.next(); String filter = (String) entry.getKey(); if (filter.startsWith("(& (classifier=") && filter.endsWith("")) { String classifier = filter.substring(15, filter.length() - 2); patternsByClassifier.put(classifier, entry.getValue()); } else { throw new IllegalStateException(); } } } }); addChild(new ArtifactsHandler(p2Descriptor, patternsByClassifier, repoUrl), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { // nothing to do } }); } // protected void handleAttributes(Attributes atts) { // String name = atts.getValue(NAME); // String type = atts.getValue(TYPE); // String version = atts.getValue(VERSION); // } } static class MappingsHandler extends DelegetingHandler { private static final String MAPPINGS = "mappings"; private static final String SIZE = "size"; Map/* */outputByFilter; public MappingsHandler() { super(MAPPINGS); addChild(new RuleHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { outputByFilter.put(((RuleHandler) child).filter, ((RuleHandler) child).output); } }); } protected void handleAttributes(Attributes atts) { int size = Integer.parseInt(atts.getValue(SIZE)); outputByFilter = new HashMap(size); } } static class RuleHandler extends DelegetingHandler { private static final String RULE = "rule"; private static final String FILTER = "filter"; private static final String OUTPUT = "output"; private String filter; private String output; public RuleHandler() { super(RULE); } protected void handleAttributes(Attributes atts) { filter = atts.getValue(FILTER); output = atts.getValue(OUTPUT); } } static class ArtifactsHandler extends DelegetingHandler { private static final String ARTIFACTS = "artifacts"; // private static final String SIZE = "size"; public ArtifactsHandler(final P2Descriptor p2Descriptor, final Map/* */patternsByClassifier, final String repoUrl) { super(ARTIFACTS); addChild(new ArtifactHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { P2Artifact a = ((ArtifactHandler) child).p2Artifact; String url = (String) patternsByClassifier.get(a.getClassifier()); url = url.replaceAll("\\$\\{repoUrl\\}", repoUrl); p2Descriptor.addArtifactUrl(a.getClassifier(), a.getId(), a.getVersion(), url); } }); } // protected void handleAttributes(Attributes atts) { // int size = Integer.parseInt(atts.getValue(SIZE)); // artifacts = new ArrayList(size); // } } static class ArtifactHandler extends DelegetingHandler { private static final String ARTIFACT = "artifact"; private static final String CLASSIFIER = "classifier"; private static final String ID = "id"; private static final String VERSION = "version"; P2Artifact p2Artifact; public ArtifactHandler() { super(ARTIFACT); addChild(new PropertiesHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); } protected void handleAttributes(Attributes atts) throws SAXException { String id = atts.getValue(ID); Version version; try { version = new Version(atts.getValue(VERSION)); } catch (ParseException e) { throw new SAXException("Incorrect version attribute on artifact '" + id + "': " + atts.getValue(VERSION) + " (" + e.getMessage() + ")"); } String classifier = atts.getValue(CLASSIFIER); p2Artifact = new P2Artifact(id, version, classifier); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/p2/P2Descriptor.java0000644000175000017500000000657012013010720023014 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.p2; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.ExecutionEnvironmentProfileProvider; import org.apache.ivy.osgi.repo.RepoDescriptor; import org.apache.ivy.osgi.util.Version; public class P2Descriptor extends RepoDescriptor { private long timestamp; private Map/* > */artifactUrlPatterns = new HashMap(); private String repoUrl; public P2Descriptor(URI repoUri, ExecutionEnvironmentProfileProvider profileProvider) { super(repoUri, profileProvider); try { repoUrl = repoUri.toURL().toExternalForm(); } catch (MalformedURLException e) { throw new RuntimeException("Illegal repo uri", e); } } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public void addBundle(BundleInfo bundleInfo) { // before transforming it and adding it into the repo, let's add the artifacts // and if no artifact, then no bundle Map/* */urlPatternsByVersion = (Map) artifactUrlPatterns.get(bundleInfo .getSymbolicName()); if (urlPatternsByVersion != null) { String urlPattern = (String) urlPatternsByVersion.get(bundleInfo.getVersion()); if (urlPattern != null) { String url = urlPattern.replaceAll("\\$\\{id\\}", bundleInfo.getSymbolicName()); url = url.replaceAll("\\$\\{version\\}", bundleInfo.getVersion().toString()); try { bundleInfo.setUri(new URI(url)); } catch (URISyntaxException e) { throw new RuntimeException("Unable to build the artifact uri of " + bundleInfo, e); } super.addBundle(bundleInfo); } } } public void addArtifactUrl(String classifier, String id, Version version, String url) { if (!classifier.equals("osgi.bundle")) { // we only support OSGi bundle, no Eclipse feature or anything else return; } Map/* */byVersion = (Map) artifactUrlPatterns.get(id); if (byVersion == null) { byVersion = new HashMap(); artifactUrlPatterns.put(id, byVersion); } byVersion.put(version, url); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/p2/P2CompositeParser.java0000644000175000017500000000763711736412722024045 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.p2; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import org.apache.ivy.osgi.util.DelegetingHandler; import org.apache.ivy.util.XMLHelper; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class P2CompositeParser implements XMLInputParser { private Set/* */childLocations = new LinkedHashSet(); public Set getChildLocations() { return childLocations; } public void parse(InputStream in) throws ParseException, IOException, SAXException { RepositoryHandler handler = new RepositoryHandler(); try { XMLHelper.parse(in, null, handler, null); } catch (ParserConfigurationException e) { throw new SAXException(e); } childLocations.addAll(handler.childLocations); } static class RepositoryHandler extends DelegetingHandler { private static final String REPOSITORY = "repository"; // private static final String NAME = "name"; // // private static final String TYPE = "type"; // // private static final String VERSION = "version"; List/* */childLocations; public RepositoryHandler() { super(REPOSITORY); addChild(new ChildrenHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { childLocations = ((ChildrenHandler) child).childLocations; } }); } // protected void handleAttributes(Attributes atts) { // String name = atts.getValue(NAME); // String type = atts.getValue(TYPE); // String version = atts.getValue(VERSION); // } } static class ChildrenHandler extends DelegetingHandler { private static final String CHILDREN = "children"; private static final String SIZE = "size"; List/* */childLocations; public ChildrenHandler() { super(CHILDREN); addChild(new ChildHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { childLocations.add(((ChildHandler) child).location); } }); } protected void handleAttributes(Attributes atts) { int size = Integer.parseInt(atts.getValue(SIZE)); childLocations = new ArrayList(size); } } static class ChildHandler extends DelegetingHandler { private static final String CHILD = "child"; private static final String LOCATION = "location"; String location; public ChildHandler() { super(CHILD); } protected void handleAttributes(Attributes atts) { location = atts.getValue(LOCATION); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/p2/P2MetadataParser.java0000644000175000017500000006311212013010720023566 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.p2; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.apache.ivy.osgi.core.BundleCapability; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.BundleRequirement; import org.apache.ivy.osgi.core.ExportPackage; import org.apache.ivy.osgi.p2.PropertiesParser.PropertiesHandler; import org.apache.ivy.osgi.util.DelegetingHandler; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.osgi.util.VersionRange; import org.apache.ivy.util.Message; import org.apache.ivy.util.XMLHelper; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class P2MetadataParser implements XMLInputParser { private final P2Descriptor p2Descriptor; public P2MetadataParser(P2Descriptor p2Descriptor) { this.p2Descriptor = p2Descriptor; } public void parse(InputStream in) throws ParseException, IOException, SAXException { RepositoryHandler handler = new RepositoryHandler(p2Descriptor); try { XMLHelper.parse(in, null, handler, null); } catch (ParserConfigurationException e) { throw new SAXException(e); } } static class RepositoryHandler extends DelegetingHandler { private static final String REPOSITORY = "repository"; // private static final String NAME = "name"; // // private static final String TYPE = "type"; // // private static final String VERSION = "version"; // // private static final String DESCRIPTION = "description"; // // private static final String PROVIDER = "provider"; public RepositoryHandler(final P2Descriptor p2Descriptor) { super(REPOSITORY); addChild(new PropertiesHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { Map properties = ((PropertiesHandler) child).properties; String timestamp = (String) properties.get("p2.timestamp"); if (timestamp != null) { p2Descriptor.setTimestamp(Long.parseLong(timestamp)); } } }); addChild(new UnitsHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { Iterator it = ((UnitsHandler) child).bundles.iterator(); while (it.hasNext()) { p2Descriptor.addBundle((BundleInfo) it.next()); } } }); addChild(new ReferencesHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); } // protected void handleAttributes(Attributes atts) { // String name = atts.getValue(NAME); // String type = atts.getValue(TYPE); // String version = atts.getValue(VERSION); // String description = atts.getValue(DESCRIPTION); // String provider = atts.getValue(PROVIDER); // } } static class ReferencesHandler extends DelegetingHandler { private static final String REFERENCES = "references"; private static final String SIZE = "size"; List/* */repositoryUris; public ReferencesHandler() { super(REFERENCES); addChild(new RepositoryReferenceHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { repositoryUris.add(((RepositoryReferenceHandler) child).uri); } }); } protected void handleAttributes(Attributes atts) throws SAXException { int size = Integer.parseInt(atts.getValue(SIZE)); repositoryUris = new ArrayList(size); } } static class RepositoryReferenceHandler extends DelegetingHandler { private static final String REPOSITORY = "repository"; private static final String TYPE = "type"; private static final String OPTIONS = "options"; private static final String NAME = "name"; private static final String URI = "uri"; private static final String URL = "url"; public RepositoryReferenceHandler() { super(REPOSITORY); } int type; int options; String name; URI uri; protected void handleAttributes(Attributes atts) throws SAXException { type = Integer.parseInt(atts.getValue(TYPE)); options = Integer.parseInt(atts.getValue(OPTIONS)); name = atts.getValue(NAME); try { String uriAtt = atts.getValue(URI); String url = atts.getValue(URL); if (uri != null) { uri = new URI(uriAtt); } else if (url != null) { uri = new URI(url); } } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } static class UnitsHandler extends DelegetingHandler { private static final String UNITS = "units"; private static final String SIZE = "size"; List bundles; public UnitsHandler() { super(UNITS); addChild(new UnitHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { BundleInfo bundleInfo = ((UnitHandler) child).bundleInfo; if (!bundleInfo.getCapabilities().isEmpty()) { bundles.add(((UnitHandler) child).bundleInfo); } } }); } protected void handleAttributes(Attributes atts) { int size = Integer.parseInt(atts.getValue(SIZE)); bundles = new ArrayList(size); } } static class UnitHandler extends DelegetingHandler { private static final String UNIT = "unit"; private static final String ID = "id"; private static final String VERSION = "version"; // private static final String SINGLETON = "singleton"; BundleInfo bundleInfo; public UnitHandler() { super(UNIT); // addChild(new UpdateHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // } // }); addChild(new PropertiesHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { Map properties = ((PropertiesHandler) child).properties; String category = (String) properties .get("org.eclipse.equinox.p2.type.category"); if (category != null && Boolean.valueOf(category).booleanValue()) { // this is a category definition, this is useless, skip this unit child.getParent().skip(); } } }); addChild(new ProvidesHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { Iterator it = ((ProvidesHandler) child).capabilities.iterator(); while (it.hasNext()) { bundleInfo.addCapability((BundleCapability) it.next()); } } }); addChild(new FilterHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); addChild(new RequiresHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { Iterator it = ((RequiresHandler) child).requirements.iterator(); while (it.hasNext()) { bundleInfo.addRequirement((BundleRequirement) it.next()); } } }); addChild(new HostRequirementsHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); addChild(new MetaRequirementsHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); addChild(new ArtifactsHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); // addChild(new TouchpointHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // } // }); // addChild(new TouchpointDataHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // } // }); // addChild(new LicensesHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // } // }); // addChild(new CopyrightHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // } // }); addChild(new ChangesHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); } protected void handleAttributes(Attributes atts) throws SAXException { String id = atts.getValue(ID); String version = atts.getValue(VERSION); // Boolean singleton = Boolean.valueOf(atts.getValue(SINGLETON)); try { bundleInfo = new BundleInfo(id, new Version(version)); } catch (ParseException e) { throw new SAXException("Incorrect version on bundle '" + id + "': " + version + " (" + e.getMessage() + ")"); } } } // static class UpdateHandler extends DelegetingHandler { // // private static final String UPDATE = "update"; // // private static final String ID = "id"; // // private static final String RANGE = "range"; // // private static final String SEVERITY = "severity"; // // public UpdateHandler() { // super(UPDATE); // } // // protected void handleAttributes(Attributes atts) { // String id = atts.getValue(ID); // String range = atts.getValue(RANGE); // String severity = atts.getValue(SEVERITY); // } // // } static class FilterHandler extends DelegetingHandler { private static final String FILTER = "filter"; public FilterHandler() { super(FILTER); setBufferingChar(true); } } private static String namespace2Type(String namespace) { if (namespace.equals("java.package")) { return BundleInfo.PACKAGE_TYPE; } if (namespace.equals("osgi.bundle")) { return BundleInfo.BUNDLE_TYPE; } return null; } static class ProvidesHandler extends DelegetingHandler { private static final String PROVIDES = "provides"; private static final String SIZE = "size"; List capabilities; public ProvidesHandler() { super(PROVIDES); addChild(new ProvidedHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { String name = ((ProvidedHandler) child).name; Version version = ((ProvidedHandler) child).version; String type = namespace2Type(((ProvidedHandler) child).namespace); if (type == null) { Message.debug("Unsupported provided capability " + ((ProvidedHandler) child).namespace + " " + name + " " + version); return; } BundleCapability capability; if (type == BundleInfo.PACKAGE_TYPE) { capability = new ExportPackage(name, version); } else { capability = new BundleCapability(type, name, version); } capabilities.add(capability); } }); } protected void handleAttributes(Attributes atts) { int size = Integer.parseInt(atts.getValue(SIZE)); capabilities = new ArrayList(size); } } static class ProvidedHandler extends DelegetingHandler { private static final String PROVIDED = "provided"; private static final String NAMESPACE = "namespace"; private static final String NAME = "name"; private static final String VERSION = "version"; String namespace; String name; Version version; public ProvidedHandler() { super(PROVIDED); } protected void handleAttributes(Attributes atts) throws SAXException { namespace = atts.getValue(NAMESPACE); name = atts.getValue(NAME); try { version = new Version(atts.getValue(VERSION)); } catch (ParseException e) { throw new SAXException("Incorrect version on provided capability: " + version + " (" + e.getMessage() + ")"); } } } static abstract class AbstractRequirementHandler extends DelegetingHandler { private static final String SIZE = "size"; List requirements; public AbstractRequirementHandler(String name) { super(name); addChild(new RequiredHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { String name = ((RequiredHandler) child).name; VersionRange range = ((RequiredHandler) child).range; String type = namespace2Type(((RequiredHandler) child).namespace); if (type == null) { Message.debug("Unsupported required capability " + ((RequiredHandler) child).namespace + " " + name + " " + range); } else { requirements.add(new BundleRequirement(type, name, range, null)); } } }); } protected void handleAttributes(Attributes atts) { int size = Integer.parseInt(atts.getValue(SIZE)); requirements = new ArrayList(size); } } static class RequiresHandler extends AbstractRequirementHandler { private static final String REQUIRES = "requires"; public RequiresHandler() { super(REQUIRES); } } static class RequiredHandler extends DelegetingHandler { private static final String REQUIRED = "required"; private static final String NAMESPACE = "namespace"; private static final String NAME = "name"; private static final String RANGE = "range"; String namespace; String name; VersionRange range; String filter; public RequiredHandler() { super(REQUIRED); addChild(new FilterHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { filter = child.getBufferedChars().trim(); } }); } protected void handleAttributes(Attributes atts) { namespace = atts.getValue(NAMESPACE); name = atts.getValue(NAME); try { range = new VersionRange(atts.getValue(RANGE)); } catch (ParseException e) { throw new RuntimeException(e); } } } static class HostRequirementsHandler extends AbstractRequirementHandler { private static final String HOST_REQUIREMENTS = "hostRequirements"; public HostRequirementsHandler() { super(HOST_REQUIREMENTS); } } static class MetaRequirementsHandler extends AbstractRequirementHandler { private static final String META_REQUIREMENTS = "metaRequirements"; public MetaRequirementsHandler() { super(META_REQUIREMENTS); } } static class ArtifactsHandler extends DelegetingHandler { private static final String ARTIFACTS = "artifacts"; private static final String SIZE = "size"; List artifacts; public ArtifactsHandler() { super(ARTIFACTS); addChild(new ArtifactHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { artifacts.add(((ArtifactHandler) child).artifact); } }); } protected void handleAttributes(Attributes atts) { int size = Integer.parseInt(atts.getValue(SIZE)); artifacts = new ArrayList(size); } } static class ArtifactHandler extends DelegetingHandler/* */{ private static final String ARTIFACT = "artifact"; private static final String ID = "id"; private static final String VERSION = "version"; private static final String CLASSIFIER = "classifier"; P2Artifact artifact; public ArtifactHandler() { super(ARTIFACT); } protected void handleAttributes(Attributes atts) throws SAXException { String id = atts.getValue(ID); String version = atts.getValue(VERSION); String classifier = atts.getValue(CLASSIFIER); try { artifact = new P2Artifact(id, new Version(version), classifier); } catch (ParseException e) { throw new SAXException("Incorrect version on artifact '" + id + "': " + version + " (" + e.getMessage() + ")"); } } } // // static class TouchpointHandler extends DelegetingHandler { // // private static final String TOUCHPOINT = "touchpoint"; // // private static final String ID = "id"; // // private static final String VERSION = "version"; // // public TouchpointHandler() { // super(TOUCHPOINT); // } // // protected void handleAttributes(Attributes atts) { // String id = atts.getValue(ID); // String version = atts.getValue(VERSION); // } // // } // // static class TouchpointDataHandler extends DelegetingHandler { // // private static final String TOUCHPOINTDATA = "touchpointData"; // // private static final String SIZE = "size"; // // public TouchpointDataHandler() { // super(TOUCHPOINTDATA); // addChild(new InstructionsHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // } // }); // } // // protected void handleAttributes(Attributes atts) { // String size = atts.getValue(SIZE); // } // // } // // static class InstructionsHandler extends DelegetingHandler { // // private static final String INSTRUCTIONS = "instructions"; // // private static final String SIZE = "size"; // // public InstructionsHandler() { // super(INSTRUCTIONS); // addChild(new InstructionHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // } // }); // } // // protected void handleAttributes(Attributes atts) { // String size = atts.getValue(SIZE); // } // // } // // static class InstructionHandler extends DelegetingHandler { // // private static final String INSTRUCTION = "instruction"; // // private static final String KEY = "key"; // // public InstructionHandler() { // super(INSTRUCTION); // setBufferingChar(true); // } // // protected void handleAttributes(Attributes atts) { // String size = atts.getValue(KEY); // } // // } // // static class LicensesHandler extends DelegetingHandler { // // private static final String LICENSES = "licenses"; // // private static final String SIZE = "size"; // // public LicensesHandler() { // super(LICENSES); // addChild(new LicenseHandler(), new ChildElementHandler() { // public void childHanlded(DelegetingHandler child) { // } // }); // } // // protected void handleAttributes(Attributes atts) { // String size = atts.getValue(SIZE); // } // // } // // static class LicenseHandler extends DelegetingHandler { // // private static final String LICENSE = "license"; // // private static final String URI = "uri"; // // private static final String URL = "url"; // // public LicenseHandler() { // super(LICENSE); // setBufferingChar(true); // } // // protected void handleAttributes(Attributes atts) { // String uri = atts.getValue(URI); // String url = atts.getValue(URL); // } // // } // // static class CopyrightHandler extends DelegetingHandler { // // private static final String COPYRIGHT = "copyright"; // // private static final String URI = "uri"; // // private static final String URL = "url"; // // public CopyrightHandler() { // super(COPYRIGHT); // } // // protected void handleAttributes(Attributes atts) { // String uri = atts.getValue(URI); // String url = atts.getValue(URL); // } // // } static class ChangesHandler extends DelegetingHandler { private static final String CHANGES = "changes"; // private static final String SIZE = "size"; public ChangesHandler() { super(CHANGES); addChild(new ChangeHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); } protected void handleAttributes(Attributes atts) { // int size = Integer.parseInt(atts.getValue(SIZE)); } } static class ChangeHandler extends DelegetingHandler { private static final String CHANGE = "change"; public ChangeHandler() { super(CHANGE); } } static class FromHandler extends AbstractRequirementHandler { private static final String FROM = "from"; public FromHandler() { super(FROM); } } static class ToHandler extends AbstractRequirementHandler { private static final String TO = "to"; public ToHandler() { super(TO); } } static class PatchScopeHandler extends DelegetingHandler { private static final String PATCH_SCOPE = "patchScope"; // private static final String SIZE = "size"; public PatchScopeHandler() { super(PATCH_SCOPE); addChild(new PatchScopeHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); } protected void handleAttributes(Attributes atts) { // int size = Integer.parseInt(atts.getValue(SIZE)); } } static class ScopeHandler extends DelegetingHandler { private static final String SCOPE = "scope"; public ScopeHandler() { super(SCOPE); addChild(new RequiresHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { } }); } } static class LifeCycleHandler extends AbstractRequirementHandler { private static final String LIFE_CYCLE = "lifeCycle"; public LifeCycleHandler() { super(LIFE_CYCLE); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/p2/XMLInputParser.java0000644000175000017500000000215211736412722023344 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.p2; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import org.xml.sax.SAXException; public interface XMLInputParser { public void parse(InputStream in) throws ParseException, IOException, SAXException; } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/p2/P2Artifact.java0000644000175000017500000000260411736412720022446 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.p2; import org.apache.ivy.osgi.util.Version; public class P2Artifact { private String id; private Version version; private String classifier; public P2Artifact(String id, Version version, String classifier) { this.id = id; this.version = version; this.classifier = classifier; } public String getClassifier() { return classifier; } public String getId() { return id; } public Version getVersion() { return version; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/0000755000175000017500000000000012126443423020101 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/OBRResolver.java0000644000175000017500000001357211742633052023122 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.text.ParseException; import org.apache.ivy.core.cache.CacheResourceOptions; import org.apache.ivy.core.event.EventManager; import org.apache.ivy.core.report.ArtifactDownloadReport; import org.apache.ivy.osgi.obr.xml.OBRXMLParser; import org.apache.ivy.osgi.repo.AbstractOSGiResolver; import org.apache.ivy.plugins.repository.Resource; import org.apache.ivy.plugins.repository.url.URLResource; import org.xml.sax.SAXException; public class OBRResolver extends AbstractOSGiResolver { private String repoXmlURL; private String repoXmlFile; private Long metadataTtl; private Boolean forceMetadataUpdate; public void setRepoXmlFile(String repositoryXmlFile) { this.repoXmlFile = repositoryXmlFile; } public void setRepoXmlURL(String repositoryXmlURL) { this.repoXmlURL = repositoryXmlURL; } public void setMetadataTtl(Long metadataTtl) { this.metadataTtl = metadataTtl; } public void setForceMetadataUpdate(Boolean forceMetadataUpdate) { this.forceMetadataUpdate = forceMetadataUpdate; } protected void init() { if (repoXmlFile != null && repoXmlURL != null) { throw new RuntimeException("The OBR repository resolver " + getName() + " couldn't be configured: repoXmlFile and repoXmlUrl cannot be set both"); } if (repoXmlFile != null) { File f = new File(repoXmlFile); loadRepoFromFile(f.getParentFile().toURI(), f, repoXmlFile); } else if (repoXmlURL != null) { final URL url; try { url = new URL(repoXmlURL); } catch (MalformedURLException e) { throw new RuntimeException("The OBR repository resolver " + getName() + " couldn't be configured: repoXmlURL '" + repoXmlURL + "' is not an URL"); } ArtifactDownloadReport report; EventManager eventManager = getEventManager(); try { if (eventManager != null) { getRepository().addTransferListener(eventManager); } Resource obrResource = new URLResource(url); CacheResourceOptions options = new CacheResourceOptions(); if (metadataTtl != null) { options.setTtl(metadataTtl.longValue()); } if (forceMetadataUpdate != null) { options.setForce(forceMetadataUpdate.booleanValue()); } report = getRepositoryCacheManager().downloadRepositoryResource(obrResource, "obr", "obr", "xml", options, getRepository()); } finally { if (eventManager != null) { getRepository().removeTransferListener(eventManager); } } URI baseURI; try { baseURI = new URI(repoXmlURL); } catch (URISyntaxException e) { throw new RuntimeException("illegal uri"); } loadRepoFromFile(baseURI, report.getLocalFile(), repoXmlURL); } else { throw new RuntimeException("The OBR repository resolver " + getName() + " couldn't be configured: repoXmlFile or repoXmlUrl is missing"); } } private void loadRepoFromFile(URI baseUri, File repoFile, String sourceLocation) { FileInputStream in; try { in = new FileInputStream(repoFile); } catch (FileNotFoundException e) { throw new RuntimeException("The OBR repository resolver " + getName() + " couldn't be configured: the file " + sourceLocation + " was not found"); } try { setRepoDescriptor(OBRXMLParser.parse(baseUri, in)); } catch (ParseException e) { throw new RuntimeException("The OBR repository resolver " + getName() + " couldn't be configured: the file " + sourceLocation + " is incorrectly formed (" + e.getMessage() + ")"); } catch (IOException e) { throw new RuntimeException("The OBR repository resolver " + getName() + " couldn't be configured: the file " + sourceLocation + " could not be read (" + e.getMessage() + ")"); } catch (SAXException e) { throw new RuntimeException("The OBR repository resolver " + getName() + " couldn't be configured: the file " + sourceLocation + " has incorrect XML (" + e.getMessage() + ")"); } try { in.close(); } catch (IOException e) { // don't care } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/xml/0000755000175000017500000000000012126443423020701 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/xml/Requirement.java0000644000175000017500000000347111736412722024055 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.xml; public class Requirement { private final String name; private boolean optional; private final RequirementFilter filter; private boolean multiple = false; private boolean extend = false; public Requirement(String name, RequirementFilter filter) { this.name = name; this.filter = filter; } public String getName() { return name; } public RequirementFilter getFilter() { return filter; } public void setOptional(boolean optional) { this.optional = optional; } public boolean isOptional() { return optional; } public void setExtend(boolean extend) { this.extend = extend; } public boolean isExtend() { return extend; } public void setMultiple(boolean multiple) { this.multiple = multiple; } public boolean isMultiple() { return multiple; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/xml/UnsupportedFilterException.java0000644000175000017500000000200511736412722027122 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.xml; public class UnsupportedFilterException extends Exception { public UnsupportedFilterException(String message) { super(message); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/xml/CapabilityProperty.java0000644000175000017500000000250611736412722025401 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.xml; public class CapabilityProperty { private String name; private String value; private String type; public CapabilityProperty(String name, String value, String type) { this.name = name; this.value = value; this.type = type; } public String getName() { return name; } public String getValue() { return value; } public String getType() { return type; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/xml/OBRXMLParser.java0000644000175000017500000003137211742633050023732 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.xml; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.text.ParseException; import javax.xml.parsers.ParserConfigurationException; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.ExecutionEnvironmentProfileProvider; import org.apache.ivy.osgi.obr.filter.RequirementFilterParser; import org.apache.ivy.osgi.repo.BundleRepoDescriptor; import org.apache.ivy.osgi.util.DelegetingHandler; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.util.Message; import org.apache.ivy.util.XMLHelper; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class OBRXMLParser { public static BundleRepoDescriptor parse(URI baseUri, InputStream in) throws ParseException, IOException, SAXException { RepositoryHandler handler = new RepositoryHandler(baseUri); try { XMLHelper.parse(in, null, handler, null); } catch (ParserConfigurationException e) { throw new SAXException(e); } return handler.repo; } static class RepositoryHandler extends DelegetingHandler { static final String REPOSITORY = "repository"; static final String LASTMODIFIED = "lastmodified"; static final String NAME = "name"; BundleRepoDescriptor repo; private final URI baseUri; public RepositoryHandler(URI baseUri) { super(REPOSITORY); this.baseUri = baseUri; addChild(new ResourceHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { repo.addBundle(((ResourceHandler) child).bundleInfo); } }); } protected void handleAttributes(Attributes atts) { repo = new BundleRepoDescriptor(baseUri, ExecutionEnvironmentProfileProvider.getInstance()); repo.setName(atts.getValue(NAME)); try { Long lastModified = getOptionalLongAttribute(atts, LASTMODIFIED, null); repo.setLastModified(lastModified); } catch (SAXParseException e) { log(Message.MSG_WARN, e.getMessage() + ". It will be ignored."); } } } static class ResourceHandler extends DelegetingHandler { private static final String DEFAULT_VERSION = "1.0.0"; static final String RESOURCE = "resource"; static final String ID = "id"; static final String PRESENTATION_NAME = "presentationname"; static final String SYMBOLIC_NAME = "symbolicname"; static final String URI = "uri"; static final String VERSION = "version"; BundleInfo bundleInfo; public ResourceHandler() { super(RESOURCE); setSkipOnError(true); // if anything bad happen in any children, just ignore the // resource addChild(new ResourceDescriptionHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { bundleInfo.setDescription(child.getBufferedChars().trim()); } }); addChild(new ResourceDocumentationHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { bundleInfo.setDocumentation(child.getBufferedChars().trim()); } }); addChild(new ResourceLicenseHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { bundleInfo.setLicense(child.getBufferedChars().trim()); } }); addChild(new ResourceSizeHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { String size = child.getBufferedChars().trim(); try { bundleInfo.setSize(Integer.valueOf(size)); } catch (NumberFormatException e) { log(Message.MSG_WARN, "Invalid size for the bundle " + bundleInfo.getSymbolicName() + ": " + size + ". This size is then ignored."); } } }); addChild(new CapabilityHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) throws SAXParseException { try { CapabilityAdapter.adapt(bundleInfo, ((CapabilityHandler) child).capability); } catch (ParseException e) { throw new SAXParseException("Invalid capability: " + e.getMessage(), child .getLocator()); } } }); addChild(new RequireHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) throws SAXParseException { try { RequirementAdapter.adapt(bundleInfo, ((RequireHandler) child).requirement); } catch (UnsupportedFilterException e) { throw new SAXParseException("Unsupported requirement filter: " + ((RequireHandler) child).filter + " (" + e.getMessage() + ")", getLocator()); } catch (ParseException e) { throw new SAXParseException( "Error in the requirement filter on the bundle: " + e.getMessage(), getLocator()); } } }); } protected void handleAttributes(Attributes atts) throws SAXException { String symbolicname = atts.getValue(SYMBOLIC_NAME); if (symbolicname == null) { log(Message.MSG_ERR, "Resource with no symobilc name, skipping it."); skip(); return; } String v = getOptionalAttribute(atts, VERSION, DEFAULT_VERSION); Version version; try { version = new Version(v); } catch (ParseException e) { log(Message.MSG_ERR, "Incorrect resource version: " + v + ". The resource " + symbolicname + " is then ignored."); skip(); return; } bundleInfo = new BundleInfo(symbolicname, version); bundleInfo.setPresentationName(atts.getValue(PRESENTATION_NAME)); String uri = atts.getValue(URI); if (uri != null) { try { bundleInfo.setUri(new URI(uri)); } catch (URISyntaxException e) { log(Message.MSG_ERR, "Incorrect uri " + uri + ". The resource " + symbolicname + " is then ignored."); skip(); return; } } bundleInfo.setId(atts.getValue(ID)); } protected String getCurrentElementIdentifier() { return bundleInfo.getSymbolicName() + "/" + bundleInfo.getVersion(); } } static class ResourceDescriptionHandler extends DelegetingHandler { static final String DESCRIPTION = "description"; public ResourceDescriptionHandler() { super(DESCRIPTION); setBufferingChar(true); } } static class ResourceDocumentationHandler extends DelegetingHandler { static final String DOCUMENTATION = "documentation"; public ResourceDocumentationHandler() { super(DOCUMENTATION); setBufferingChar(true); } } static class ResourceLicenseHandler extends DelegetingHandler { static final String LICENSE = "license"; public ResourceLicenseHandler() { super(LICENSE); setBufferingChar(true); } } static class ResourceSizeHandler extends DelegetingHandler { static final String SIZE = "size"; public ResourceSizeHandler() { super(SIZE); setBufferingChar(true); } } static class CapabilityHandler extends DelegetingHandler { static final String CAPABILITY = "capability"; static final String NAME = "name"; Capability capability; public CapabilityHandler() { super(CAPABILITY); addChild(new CapabilityPropertyHandler(), new ChildElementHandler() { public void childHanlded(DelegetingHandler child) { String name = ((CapabilityPropertyHandler) child).name; String value = ((CapabilityPropertyHandler) child).value; String type = ((CapabilityPropertyHandler) child).type; capability.addProperty(name, value, type); } }); } protected void handleAttributes(Attributes atts) throws SAXException { String name = getRequiredAttribute(atts, NAME); capability = new Capability(name); } } static class CapabilityPropertyHandler extends DelegetingHandler { static final String CAPABILITY_PROPERTY = "p"; static final String NAME = "n"; static final String VALUE = "v"; static final String TYPE = "t"; String name; String value; String type; public CapabilityPropertyHandler() { super(CAPABILITY_PROPERTY); } protected void handleAttributes(Attributes atts) throws SAXException { name = getRequiredAttribute(atts, NAME); value = getRequiredAttribute(atts, VALUE); type = atts.getValue(TYPE); } } static class RequireHandler extends DelegetingHandler { static final String REQUIRE = "require"; static final String NAME = "name"; static final String OPTIONAL = "optional"; static final String MULTIPLE = "multiple"; static final String EXTEND = "extend"; static final String FILTER = "filter"; private Requirement requirement; private RequirementFilter filter; public RequireHandler() { super(REQUIRE); } protected void handleAttributes(Attributes atts) throws SAXException { String name = getRequiredAttribute(atts, NAME); String filterText = atts.getValue(FILTER); filter = null; if (filterText != null) { try { filter = RequirementFilterParser.parse(filterText); } catch (ParseException e) { throw new SAXParseException("Requirement with illformed filter: " + filterText, getLocator()); } } Boolean optional = getOptionalBooleanAttribute(atts, OPTIONAL, null); Boolean multiple = getOptionalBooleanAttribute(atts, MULTIPLE, null); Boolean extend = getOptionalBooleanAttribute(atts, EXTEND, null); requirement = new Requirement(name, filter); if (optional != null) { requirement.setOptional(optional.booleanValue()); } if (multiple != null) { requirement.setMultiple(multiple.booleanValue()); } if (extend != null) { requirement.setExtend(extend.booleanValue()); } } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/xml/RequirementAdapter.java0000644000175000017500000001753511742633052025362 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.xml; import java.text.ParseException; import java.util.Iterator; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.BundleRequirement; import org.apache.ivy.osgi.obr.filter.AndFilter; import org.apache.ivy.osgi.obr.filter.CompareFilter; import org.apache.ivy.osgi.obr.filter.CompareFilter.Operator; import org.apache.ivy.osgi.obr.filter.NotFilter; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.osgi.util.VersionRange; public class RequirementAdapter { private Version startVersion = null; private boolean startExclusive = false; private Version endVersion = null; private boolean endExclusive = false; private String type = null; private String name = null; public static void adapt(BundleInfo info, Requirement requirement) throws UnsupportedFilterException, ParseException { RequirementAdapter adapter = new RequirementAdapter(); adapter.extractFilter(requirement.getFilter()); adapter.adapt(info, requirement.isOptional()); } private void extractFilter(RequirementFilter filter) throws UnsupportedFilterException, ParseException { if (filter instanceof AndFilter) { AndFilter andFilter = (AndFilter) filter; Iterator itFilter = andFilter.getSubFilters().iterator(); while (itFilter.hasNext()) { RequirementFilter subFilter = (RequirementFilter) itFilter.next(); extractFilter(subFilter); } } else if (filter instanceof CompareFilter) { CompareFilter compareFilter = ((CompareFilter) filter); parseCompareFilter(compareFilter, false); } else if (filter instanceof NotFilter) { NotFilter notFilter = ((NotFilter) filter); if (notFilter.getSubFilter() instanceof CompareFilter) { CompareFilter compareFilter = ((CompareFilter) notFilter.getSubFilter()); parseCompareFilter(compareFilter, true); } } else { throw new UnsupportedFilterException("Unsupported filter: " + filter.getClass().getName()); } } private void adapt(BundleInfo info, boolean optional) throws ParseException { VersionRange range = getVersionRange(); String resolution = optional ? "optional" : null; if (type == null) { throw new ParseException("No requirement actually specified", 0); } BundleRequirement requirement = new BundleRequirement(type, name, range, resolution); info.addRequirement(requirement); } private VersionRange getVersionRange() { VersionRange range = null; if (startVersion != null || endVersion != null) { range = new VersionRange(startExclusive, startVersion, endExclusive, endVersion); } return range; } private void parseCompareFilter(CompareFilter compareFilter, boolean not) throws UnsupportedFilterException, ParseException { String att = compareFilter.getLeftValue(); if (BundleInfo.PACKAGE_TYPE.equals(att) || BundleInfo.BUNDLE_TYPE.equals(att) || "symbolicname".equals(att) || BundleInfo.SERVICE_TYPE.equals(att)) { if (not) { throw new UnsupportedFilterException( "Not filter on requirement comparaison is not supported"); } if (type != null) { throw new UnsupportedFilterException("Multiple requirement type are not supported"); } if ("symbolicname".equals(att)) { type = BundleInfo.BUNDLE_TYPE; } else { type = att; } if (compareFilter.getOperator() != Operator.EQUALS) { throw new UnsupportedFilterException( "Filtering is only supported with the operator '='"); } name = compareFilter.getRightValue(); } else if ("version".equals(att)) { String v = compareFilter.getRightValue(); Version version; try { version = new Version(v); } catch (ParseException e) { throw new ParseException("Ill formed version: " + v, 0); } Operator operator = compareFilter.getOperator(); if (not) { if (operator == Operator.EQUALS) { throw new UnsupportedFilterException( "Not filter on equals comparaison is not supported"); } else if (operator == Operator.GREATER_OR_EQUAL) { operator = Operator.LOWER_THAN; } else if (operator == Operator.GREATER_THAN) { operator = Operator.LOWER_OR_EQUAL; } else if (operator == Operator.LOWER_OR_EQUAL) { operator = Operator.GREATER_THAN; } else if (operator == Operator.LOWER_THAN) { operator = Operator.GREATER_OR_EQUAL; } } if (operator == Operator.EQUALS) { if (startVersion != null || endVersion != null) { throw new UnsupportedFilterException( "Multiple version matching is not supported"); } startVersion = version; startExclusive = false; endVersion = version; endExclusive = false; } else if (operator == Operator.GREATER_OR_EQUAL) { if (startVersion != null) { throw new UnsupportedFilterException( "Multiple version matching is not supported"); } startVersion = version; startExclusive = false; } else if (operator == Operator.GREATER_THAN) { if (startVersion != null) { throw new UnsupportedFilterException( "Multiple version matching is not supported"); } startVersion = version; startExclusive = true; } else if (operator == Operator.LOWER_OR_EQUAL) { if (endVersion != null) { throw new UnsupportedFilterException( "Multiple version matching is not supported"); } endVersion = version; endExclusive = false; } else if (operator == Operator.LOWER_THAN) { if (endVersion != null) { throw new UnsupportedFilterException( "Multiple version matching is not supported"); } endVersion = version; endExclusive = true; } } else { throw new UnsupportedFilterException("Unsupported attribute: " + att); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/xml/RequirementFilter.java0000644000175000017500000000215711736412722025223 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.xml; public abstract class RequirementFilter { public String toString() { StringBuffer builder = new StringBuffer(); append(builder); return builder.toString(); } public abstract void append(StringBuffer builder); } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/xml/CapabilityAdapter.java0000644000175000017500000001116611736412722025137 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.xml; import java.text.ParseException; import java.util.Iterator; import org.apache.ivy.osgi.core.BundleCapability; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.ExportPackage; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.util.Message; public class CapabilityAdapter { public static void adapt(BundleInfo bundleInfo, Capability capability) throws ParseException { String name = capability.getName(); if (BundleInfo.PACKAGE_TYPE.equals(name)) { ExportPackage exportPackage = getExportPackage(bundleInfo, capability); bundleInfo.addCapability(exportPackage); } else if (BundleInfo.BUNDLE_TYPE.equals(name)) { // nothing to do, already handled at the resource tag level } else if (BundleInfo.SERVICE_TYPE.equals(name)) { BundleCapability service = getOSGiService(bundleInfo, capability); bundleInfo.addCapability(service); } else { Message.warn("Unsupported capability '" + name + "' on the bundle '" + bundleInfo.getSymbolicName() + "'"); } } private static ExportPackage getExportPackage(BundleInfo bundleInfo, Capability capability) throws ParseException { String pkgName = null; Version version = null; String uses = null; Iterator itCapability = capability.getProperties().iterator(); while (itCapability.hasNext()) { CapabilityProperty property = (CapabilityProperty) itCapability.next(); String propName = property.getName(); if ("package".equals(propName)) { pkgName = property.getValue(); } else if ("version".equals(propName)) { version = new Version(property.getValue()); } else if ("uses".equals(propName)) { uses = property.getValue(); } else { Message.warn("Unsupported property '" + propName + "' on the 'package' capability of the bundle '" + bundleInfo.getSymbolicName() + "'"); } } if (pkgName == null) { throw new ParseException("No package name for the capability", 0); } ExportPackage exportPackage = new ExportPackage(pkgName, version); if (uses != null) { String[] split = uses.trim().split(","); for (int i = 0; i < split.length; i++) { String u = split[i]; exportPackage.addUse(u.trim()); } } return exportPackage; } private static BundleCapability getOSGiService(BundleInfo bundleInfo, Capability capability) throws ParseException { String name = null; Version version = null; Iterator itCapability = capability.getProperties().iterator(); while (itCapability.hasNext()) { CapabilityProperty property = (CapabilityProperty) itCapability.next(); String propName = property.getName(); if ("service".equals(propName)) { name = property.getValue(); } else if ("version".equals(propName)) { version = new Version(property.getValue()); } else { Message.warn("Unsupported property '" + propName + "' on the 'package' capability of the bundle '" + bundleInfo.getSymbolicName() + "'"); } } if (name == null) { throw new ParseException("No service name for the capability", 0); } BundleCapability service = new BundleCapability(BundleInfo.SERVICE_TYPE, name, version); return service; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/xml/Capability.java0000644000175000017500000000266711736412722023644 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.xml; import java.util.ArrayList; import java.util.List; public class Capability { private List/* */properties = new ArrayList/* */(); private String name; public Capability(String name) { this.name = name; } public String getName() { return name; } public void addProperty(String n, String value, String type) { properties.add(new CapabilityProperty(n, value, type)); } public List/* */getProperties() { return properties; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/xml/OBRXMLWriter.java0000644000175000017500000002713111736412722023754 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.xml; import java.io.OutputStream; import java.text.ParseException; import java.util.Iterator; import java.util.Set; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.apache.ivy.core.IvyContext; import org.apache.ivy.osgi.core.BundleCapability; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.BundleRequirement; import org.apache.ivy.osgi.core.ExportPackage; import org.apache.ivy.osgi.core.ManifestParser; import org.apache.ivy.osgi.obr.xml.OBRXMLParser.CapabilityHandler; import org.apache.ivy.osgi.obr.xml.OBRXMLParser.CapabilityPropertyHandler; import org.apache.ivy.osgi.obr.xml.OBRXMLParser.RepositoryHandler; import org.apache.ivy.osgi.obr.xml.OBRXMLParser.RequireHandler; import org.apache.ivy.osgi.obr.xml.OBRXMLParser.ResourceHandler; import org.apache.ivy.osgi.repo.ManifestAndLocation; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.osgi.util.VersionRange; import org.apache.ivy.util.Message; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; public class OBRXMLWriter { public static ContentHandler newHandler(OutputStream out, String encoding, boolean indent) throws TransformerConfigurationException { SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler hd = tf.newTransformerHandler(); Transformer serializer = tf.newTransformer(); StreamResult stream = new StreamResult(out); serializer.setOutputProperty(OutputKeys.ENCODING, encoding); serializer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); hd.setResult(stream); return hd; } public static void writeManifests(Iterator/* */it, ContentHandler handler, boolean quiet) throws SAXException { int level = quiet ? Message.MSG_DEBUG : Message.MSG_WARN; handler.startDocument(); AttributesImpl atts = new AttributesImpl(); handler.startElement("", RepositoryHandler.REPOSITORY, RepositoryHandler.REPOSITORY, atts); int nbOk = 0; int nbRejected = 0; while (it.hasNext()) { ManifestAndLocation manifestAndLocation = (ManifestAndLocation) it.next(); BundleInfo bundleInfo; try { bundleInfo = ManifestParser.parseManifest(manifestAndLocation.getManifest()); bundleInfo.setUri(manifestAndLocation.getUri()); nbOk++; } catch (ParseException e) { nbRejected++; IvyContext .getContext() .getMessageLogger() .log("Rejected " + manifestAndLocation.getUri() + ": " + e.getMessage(), level); continue; } saxBundleInfo(bundleInfo, handler); } handler.endElement("", RepositoryHandler.REPOSITORY, RepositoryHandler.REPOSITORY); handler.endDocument(); Message.info(nbOk + " bundle" + (nbOk > 1 ? "s" : "") + " added, " + nbRejected + " bundle" + (nbRejected > 1 ? "s" : "") + " rejected."); } public static void writeBundles(Iterator/* */it, ContentHandler handler) throws SAXException { handler.startDocument(); AttributesImpl atts = new AttributesImpl(); handler.startElement("", RepositoryHandler.REPOSITORY, RepositoryHandler.REPOSITORY, atts); while (it.hasNext()) { BundleInfo bundleInfo = (BundleInfo) it.next(); saxBundleInfo(bundleInfo, handler); } handler.endElement("", RepositoryHandler.REPOSITORY, RepositoryHandler.REPOSITORY); handler.endDocument(); } private static void saxBundleInfo(BundleInfo bundleInfo, ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); addAttr(atts, ResourceHandler.SYMBOLIC_NAME, bundleInfo.getSymbolicName()); addAttr(atts, ResourceHandler.VERSION, bundleInfo.getRawVersion()); if (bundleInfo.getUri() != null) { addAttr(atts, ResourceHandler.URI, bundleInfo.getUri().toString()); } handler.startElement("", ResourceHandler.RESOURCE, ResourceHandler.RESOURCE, atts); Iterator itCapabilities = bundleInfo.getCapabilities().iterator(); while (itCapabilities.hasNext()) { BundleCapability capability = (BundleCapability) itCapabilities.next(); saxCapability(capability, handler); } Iterator itRequirement = bundleInfo.getRequirements().iterator(); while (itRequirement.hasNext()) { BundleRequirement requirement = (BundleRequirement) itRequirement.next(); saxRequirement(requirement, handler); } handler.endElement("", ResourceHandler.RESOURCE, ResourceHandler.RESOURCE); handler.characters("\n".toCharArray(), 0, 1); } private static void saxCapability(BundleCapability capability, ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); String type = capability.getType(); addAttr(atts, CapabilityHandler.NAME, type); handler.startElement("", CapabilityHandler.CAPABILITY, CapabilityHandler.CAPABILITY, atts); if (type.equals(BundleInfo.BUNDLE_TYPE)) { // nothing to do, already handled with the resource tag } else if (type.equals(BundleInfo.PACKAGE_TYPE)) { saxCapabilityProperty("package", capability.getName(), handler); Version v = capability.getRawVersion(); if (v != null) { saxCapabilityProperty("version", v.toString(), handler); } Set/* */uses = ((ExportPackage) capability).getUses(); if (uses != null && !uses.isEmpty()) { StringBuffer builder = new StringBuffer(); Iterator itUse = uses.iterator(); while (itUse.hasNext()) { String use = (String) itUse.next(); if (builder.length() != 0) { builder.append(','); } builder.append(use); } saxCapabilityProperty("uses", builder.toString(), handler); } } else if (type.equals(BundleInfo.SERVICE_TYPE)) { saxCapabilityProperty("service", capability.getName(), handler); Version v = capability.getRawVersion(); if (v != null) { saxCapabilityProperty("version", v.toString(), handler); } } else { // oups } handler.endElement("", CapabilityHandler.CAPABILITY, CapabilityHandler.CAPABILITY); handler.characters("\n".toCharArray(), 0, 1); } private static void saxCapabilityProperty(String n, String v, ContentHandler handler) throws SAXException { saxCapabilityProperty(n, null, v, handler); } private static void saxCapabilityProperty(String n, String t, String v, ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); addAttr(atts, CapabilityPropertyHandler.NAME, n); if (t != null) { addAttr(atts, CapabilityPropertyHandler.TYPE, t); } addAttr(atts, CapabilityPropertyHandler.VALUE, v); handler.startElement("", CapabilityPropertyHandler.CAPABILITY_PROPERTY, CapabilityPropertyHandler.CAPABILITY_PROPERTY, atts); handler.endElement("", CapabilityPropertyHandler.CAPABILITY_PROPERTY, CapabilityPropertyHandler.CAPABILITY_PROPERTY); handler.characters("\n".toCharArray(), 0, 1); } private static void saxRequirement(BundleRequirement requirement, ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); addAttr(atts, RequireHandler.NAME, requirement.getType()); if ("optional".equals(requirement.getResolution())) { addAttr(atts, RequireHandler.OPTIONAL, Boolean.TRUE.toString()); } addAttr(atts, RequireHandler.FILTER, buildFilter(requirement)); handler.startElement("", RequireHandler.REQUIRE, RequireHandler.REQUIRE, atts); handler.endElement("", RequireHandler.REQUIRE, RequireHandler.REQUIRE); handler.characters("\n".toCharArray(), 0, 1); } private static String buildFilter(BundleRequirement requirement) { StringBuffer filter = new StringBuffer(); VersionRange v = requirement.getVersion(); if (v != null) { appendVersion(filter, v); } filter.append('('); filter.append(requirement.getType()); filter.append("="); filter.append(requirement.getName()); filter.append(')'); if (v != null) { filter.append(')'); } return filter.toString(); } private static void appendVersion(StringBuffer filter, VersionRange v) { filter.append("(&"); Version start = v.getStartVersion(); if (start != null) { if (!v.isStartExclusive()) { filter.append("(version>="); filter.append(start.toString()); filter.append(')'); } else { filter.append("(!"); filter.append("(version<="); filter.append(start.toString()); filter.append("))"); } } Version end = v.getEndVersion(); if (end != null) { if (!v.isEndExclusive()) { filter.append("(version<="); filter.append(end.toString()); filter.append(')'); } else { filter.append("(!"); filter.append("(version>="); filter.append(end.toString()); filter.append("))"); } } } private static void addAttr(AttributesImpl atts, String name, String value) { if (value != null) { atts.addAttribute("", name, name, "CDATA", value); } } private static void addAttr(AttributesImpl atts, String name, Object value) { if (value != null) { atts.addAttribute("", name, name, "CDATA", value.toString()); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/filter/0000755000175000017500000000000012126443423021366 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/filter/UniOperatorFilter.java0000644000175000017500000000433211736412722025654 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.filter; import org.apache.ivy.osgi.obr.xml.RequirementFilter; public abstract class UniOperatorFilter extends RequirementFilter { private final RequirementFilter subFilter; public UniOperatorFilter(RequirementFilter subFilter) { this.subFilter = subFilter; } abstract protected char operator(); public void append(StringBuffer builder) { builder.append("("); builder.append(operator()); builder.append(subFilter.toString()); builder.append(")"); } public RequirementFilter getSubFilter() { return subFilter; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((subFilter == null) ? 0 : subFilter.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof UniOperatorFilter)) { return false; } UniOperatorFilter other = (UniOperatorFilter) obj; if (subFilter == null) { if (other.subFilter != null) { return false; } } else if (!subFilter.equals(other.subFilter)) { return false; } return true; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/filter/RequirementFilterParser.java0000644000175000017500000001513611736412722027066 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.filter; import java.text.ParseException; import org.apache.ivy.osgi.obr.filter.CompareFilter.Operator; import org.apache.ivy.osgi.obr.xml.RequirementFilter; public class RequirementFilterParser { public static RequirementFilter parse(String text) throws ParseException { return new Parser(text).parse(); } static class Parser { /** * text to parse */ private final String text; /** * the length of the source */ private int length; /** * position in the source */ private int pos = 0; /** * last read character */ private char c; /** * Default constructor * * @param header * the header to parse */ Parser(String text) { this.text = text; this.length = text.length(); } /** * Do the parsing * * @return * * @throws ParseException */ RequirementFilter parse() throws ParseException { return parseFilter(); } private char readNext() { if (pos == length) { c = '\0'; } else { c = text.charAt(pos++); } return c; } private void unread() { if (pos > 0) { pos--; } } private RequirementFilter parseFilter() throws ParseException { skipWhiteSpace(); readNext(); if (c != '(') { throw new ParseException("Expecting '(' as the start of the filter", pos); } RequirementFilter filter; switch (readNext()) { case '&': filter = parseAnd(); break; case '|': filter = parseOr(); break; case '!': filter = parseNot(); break; default: unread(); filter = parseCompare(); break; } readNext(); if (c != ')') { throw new ParseException("Expecting ')' as the end of the filter", pos); } return filter; } private RequirementFilter parseCompare() throws ParseException { String leftValue = parseCompareValue(); Operator operator = parseCompareOperator(); String rightValue = parseCompareValue(); return new CompareFilter(leftValue, operator, rightValue); } private String parseCompareValue() { StringBuffer builder = new StringBuffer(); do { readNext(); if (!isOperator(c) && c != ')' && c != '(') { builder.append(c); } else { unread(); break; } } while (pos < length); return builder.toString(); } private boolean isOperator(char ch) { return ch == '=' || ch == '<' || ch == '>'; } private Operator parseCompareOperator() throws ParseException { switch (readNext()) { case '=': return Operator.EQUALS; case '>': if (readNext() == '=') { return Operator.GREATER_OR_EQUAL; } unread(); return Operator.GREATER_THAN; case '<': if (readNext() == '=') { return Operator.LOWER_OR_EQUAL; } unread(); return Operator.LOWER_THAN; default: break; } throw new ParseException("Expecting an operator: =, <, <=, > or >=", pos); } private RequirementFilter parseAnd() throws ParseException { AndFilter filter = new AndFilter(); parseMultiOperator(filter); return filter; } private RequirementFilter parseOr() throws ParseException { OrFilter filter = new OrFilter(); parseMultiOperator(filter); return filter; } private void parseMultiOperator(MultiOperatorFilter filter) throws ParseException { do { skipWhiteSpace(); readNext(); if (c == '(') { unread(); filter.add(parseFilter()); } else { unread(); break; } } while (pos < length); if (filter.getSubFilters().size() == 0) { throw new ParseException("Expecting at least one sub filter", pos); } } private RequirementFilter parseNot() throws ParseException { readNext(); if (c != '(') { throw new ParseException("The ! operator is expecting a filter", pos); } unread(); return new NotFilter(parseFilter()); } private void skipWhiteSpace() { do { switch (readNext()) { case ' ': continue; default: unread(); return; } } while (pos < length); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/filter/OrFilter.java0000644000175000017500000000224711736412722023770 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.filter; import org.apache.ivy.osgi.obr.xml.RequirementFilter; public class OrFilter extends MultiOperatorFilter { public OrFilter() { super(); } public OrFilter(RequirementFilter[] filters) { super(filters); } protected char operator() { return '|'; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/filter/CompareFilter.java0000644000175000017500000000760211736412722024776 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.filter; import org.apache.ivy.osgi.obr.xml.RequirementFilter; public class CompareFilter extends RequirementFilter { // enum 1.5 wrote in java 1.4 public static class Operator { public static Operator EQUALS = new Operator(); public static Operator LOWER_THAN = new Operator(); public static Operator LOWER_OR_EQUAL = new Operator(); public static Operator GREATER_THAN = new Operator(); public static Operator GREATER_OR_EQUAL = new Operator(); public String toString() { if (this == EQUALS) return "="; if (this == GREATER_THAN) return ">"; if (this == GREATER_OR_EQUAL) return ">="; if (this == LOWER_THAN) return "<"; if (this == LOWER_OR_EQUAL) return "<="; return super.toString(); } } private Operator operator; private final String rightValue; private final String leftValue; public CompareFilter(String leftValue, Operator operator, String rightValue) { this.leftValue = leftValue; this.rightValue = rightValue; this.operator = operator; } public String getLeftValue() { return leftValue; } public Operator getOperator() { return operator; } public String getRightValue() { return rightValue; } public void append(StringBuffer builder) { builder.append("("); builder.append(leftValue); builder.append(operator.toString()); builder.append(rightValue); builder.append(")"); } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((leftValue == null) ? 0 : leftValue.hashCode()); result = prime * result + ((operator == null) ? 0 : operator.hashCode()); result = prime * result + ((rightValue == null) ? 0 : rightValue.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof CompareFilter)) { return false; } CompareFilter other = (CompareFilter) obj; if (leftValue == null) { if (other.leftValue != null) { return false; } } else if (!leftValue.equals(other.leftValue)) { return false; } if (operator == null) { if (other.operator != null) { return false; } } else if (!operator.equals(other.operator)) { return false; } if (rightValue == null) { if (other.rightValue != null) { return false; } } else if (!rightValue.equals(other.rightValue)) { return false; } return true; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/filter/MultiOperatorFilter.java0000644000175000017500000000627111736412722026217 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.filter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.ivy.osgi.obr.xml.RequirementFilter; public abstract class MultiOperatorFilter extends RequirementFilter { private List/* */subFilters = new ArrayList/* */(); public MultiOperatorFilter() { // default constructor } public MultiOperatorFilter(RequirementFilter[] filters) { for (int i = 0; i < filters.length; i++) { RequirementFilter filter = filters[i]; add(filter); } } abstract protected char operator(); public void append(StringBuffer builder) { builder.append('('); builder.append(operator()); Iterator itSubFilters = subFilters.iterator(); while (itSubFilters.hasNext()) { RequirementFilter filter = (RequirementFilter) itSubFilters.next(); filter.append(builder); } builder.append(')'); } public void add(RequirementFilter subFilter2) { subFilters.add(subFilter2); } public List/* */getSubFilters() { return subFilters; } public int hashCode() { final int prime = 31; int result = 1; Iterator itSubFilters = subFilters.iterator(); while (itSubFilters.hasNext()) { RequirementFilter subFilter = (RequirementFilter) itSubFilters.next(); result = prime * result + ((subFilter == null) ? 0 : subFilter.hashCode()); } return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof MultiOperatorFilter)) { return false; } MultiOperatorFilter other = (MultiOperatorFilter) obj; if (subFilters == null) { if (other.subFilters != null) { return false; } } else if (other.subFilters == null) { return false; } else if (subFilters.size() != other.subFilters.size()) { return false; } else if (!subFilters.containsAll(other.subFilters)) { return false; } return true; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/filter/AndFilter.java0000644000175000017500000000225211736412722024106 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.filter; import org.apache.ivy.osgi.obr.xml.RequirementFilter; public class AndFilter extends MultiOperatorFilter { public AndFilter() { super(); } public AndFilter(RequirementFilter[] filters) { super(filters); } protected char operator() { return '&'; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/obr/filter/NotFilter.java0000644000175000017500000000216511736412722024147 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.obr.filter; import org.apache.ivy.osgi.obr.xml.RequirementFilter; public class NotFilter extends UniOperatorFilter { public NotFilter(RequirementFilter subFilter) { super(subFilter); } protected char operator() { return '!'; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/util/0000755000175000017500000000000012126443423020274 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/osgi/util/Version.java0000644000175000017500000001264011742633110022564 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.util; import java.text.ParseException; /** * Provides OSGi version support. */ public class Version implements Comparable/* */{ private final int major; private final int minor; private final int patch; private final String qualifier; public Version(String versionStr, String qualifier) throws ParseException { this(versionStr + "." + (qualifier != null ? qualifier : "")); } public Version(String versionStr) throws ParseException { String[] splits = versionStr.split("\\."); if (splits == null || splits.length == 0 || splits.length > 4) { throw new ParseException("Ill formed OSGi version", 0); } try { major = Integer.parseInt(splits[0]); } catch (NumberFormatException e) { throw new ParseException("Major part of an OSGi version should be an integer", 0); } try { minor = splits.length >= 2 ? Integer.parseInt(splits[1]) : 0; } catch (NumberFormatException e) { throw new ParseException("Minor part of an OSGi version should be an integer", 0); } try { patch = splits.length >= 3 ? Integer.parseInt(splits[2]) : 0; } catch (NumberFormatException e) { throw new ParseException("Patch part of an OSGi version should be an integer", 0); } qualifier = splits.length == 4 ? splits[3] : null; } public Version(int major, int minor, int patch, String qualifier) { this.major = major; this.minor = minor; this.patch = patch; this.qualifier = qualifier; } /** * Build a version from another one while appending an extra qualifier * * @param baseVersion * @param qualifier */ public Version(Version baseVersion, String extraQualifier) { this.major = baseVersion.major; this.minor = baseVersion.minor; this.patch = baseVersion.patch; this.qualifier = baseVersion.qualifier == null ? extraQualifier : (baseVersion.qualifier + extraQualifier); } public String toString() { return numbersAsString() + (qualifier == null ? "" : "." + qualifier); } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + major; result = prime * result + minor; result = prime * result + patch; result = prime * result + ((qualifier == null) ? 0 : qualifier.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Version)) { return false; } Version other = (Version) obj; if (major != other.major) { return false; } if (minor != other.minor) { return false; } if (patch != other.patch) { return false; } if (qualifier == null) { if (other.qualifier != null) { return false; } } else if (!qualifier.equals(other.qualifier)) { return false; } return true; } public String numbersAsString() { return major + "." + minor + "." + patch; } public Version withNudgedPatch() { return new Version(major, minor, patch + 1, null); } public Version withoutQualifier() { return new Version(major, minor, patch, null); } public String qualifier() { return qualifier == null ? "" : qualifier; } public int compareUnqualified(Version other) { int diff = major - other.major; if (diff != 0) { return diff; } diff = minor - other.minor; if (diff != 0) { return diff; } diff = patch - other.patch; if (diff != 0) { return diff; } return 0; } public int compareTo(Object obj) { return compareTo((Version) obj); } public int compareTo(Version other) { int diff = compareUnqualified(other); if (diff != 0) { return diff; } if (qualifier == null) { return other.qualifier != null ? -1 : 0; } if (other.qualifier == null) { return 1; } return qualifier.compareTo(other.qualifier); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/util/DelegetingHandler.java0000644000175000017500000005024611736412724024521 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.util; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.apache.ivy.util.Message; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; public class DelegetingHandler extends DefaultHandler implements DTDHandler, ContentHandler, ErrorHandler { private DelegetingHandler/* */delegate = null; private DelegetingHandler/* */parent; private final Map/* > */saxHandlerMapping = new HashMap(); private final Map/* > */childHandlerMapping = new HashMap(); private final String tagName; private boolean started = false; private boolean skip = false; private boolean skipOnError = false; private StringBuffer charBuffer = new StringBuffer(); private boolean bufferingChar = false; private Locator locator; public DelegetingHandler(String name) { this.tagName = name; charBuffer.setLength(0); } protected void addChild(DelegetingHandler saxHandler, ChildElementHandler elementHandler) { saxHandlerMapping.put(saxHandler.getName(), saxHandler); childHandlerMapping.put(saxHandler.getName(), elementHandler); saxHandler.parent = this; } public String getName() { return tagName; } public DelegetingHandler getParent() { return parent; } public void setBufferingChar(boolean bufferingChar) { this.bufferingChar = bufferingChar; } public void setSkipOnError(boolean skipOnError) { this.skipOnError = skipOnError; } public boolean isBufferingChar() { return bufferingChar; } public String getBufferedChars() { return charBuffer.toString(); } public void setDocumentLocator(Locator locator) { this.locator = locator; Iterator itHandler = saxHandlerMapping.values().iterator(); while (itHandler.hasNext()) { DelegetingHandler/* */subHandler = (DelegetingHandler) itHandler.next(); subHandler.setDocumentLocator(locator); } } public Locator getLocator() { return locator; } /** * Return an sort of identifier of the current element being parsed. It will only be used for * logging purpose. * * @return an empty string by default */ protected String getCurrentElementIdentifier() { return ""; } public void skip() { skip = true; Iterator itHandler = saxHandlerMapping.values().iterator(); while (itHandler.hasNext()) { DelegetingHandler/* */subHandler = (DelegetingHandler) itHandler.next(); subHandler.stopDelegating(); } } protected void stopDelegating() { parent.delegate = null; skip = false; started = false; Iterator itHandler = saxHandlerMapping.values().iterator(); while (itHandler.hasNext()) { DelegetingHandler/* */subHandler = (DelegetingHandler) itHandler.next(); subHandler.stopDelegating(); } } private interface SkipOnErrorCallback { public void call() throws SAXException; } private void skipOnError(SkipOnErrorCallback callback) throws SAXException { try { callback.call(); } catch (SAXException e) { if (skipOnError) { skip(); log(Message.MSG_ERR, e.getMessage()); } else { throw e; } } } public final void startDocument() throws SAXException { if (skip) { return; } if (delegate != null) { delegate.startDocument(); } else { doStartDocument(); } } /** * @throws SAXException */ protected void doStartDocument() throws SAXException { // by default do nothing } public final void endDocument() throws SAXException { if (skip) { return; } if (delegate != null) { delegate.endDocument(); } else { doEndDocument(); } } /** * @throws SAXException */ protected void doEndDocument() throws SAXException { // by default do nothing } public final void startElement(final String uri, final String localName, final String n, final Attributes atts) throws SAXException { // reset the char buffer charBuffer.setLength(0); if (delegate != null) { // we are already delegating, let's continue skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { delegate.startElement(uri, localName, n, atts); } }); } else { if (!started) { // first time called ? // just for the root, check the expected element name // not need to check the delegated as the mapping is already taking care of it if (parent == null && !localName.equals(tagName)) { // we are at the root and the saxed element doesn't match throw new SAXException("The root element of the parsed document '" + localName + "' didn't matched the expected one: '" + tagName + "'"); } skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { handleAttributes(atts); } }); started = true; } else { if (skip) { // we con't care anymore about that part of the xml tree return; } // time now to delegate for a new element delegate = (DelegetingHandler) saxHandlerMapping.get(localName); if (delegate != null) { skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { delegate.startElement(uri, localName, n, atts); } }); } } } } /** * Called when the expected node is achieved * * @param atts * the xml attributes attached to the expected node * @exception SAXException * in case the parsing should be completely stopped */ protected void handleAttributes(Attributes atts) throws SAXException { // nothing to do by default } /** * @throws SAXException */ protected void doStartElement(String uri, String localName, String name, Attributes atts) throws SAXException { // by default do nothing } public final void endElement(final String uri, final String localName, final String n) throws SAXException { if (delegate != null) { final DelegetingHandler savedDelegate = delegate; // we are already delegating, let's continue skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { delegate.endElement(uri, localName, n); } }); if (delegate == null) { // we just stopped delegating, it means that the child has ended final ChildElementHandler childHandler = (ChildElementHandler) childHandlerMapping .get(localName); if (childHandler != null) { skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { childHandler.childHanlded(savedDelegate); } }); } } } else { if (!skip) { doEndElement(uri, localName, n); } if (parent != null && tagName.equals(localName)) { // the current element is closed, let's tell the parent to stop delegating stopDelegating(); } } } /** * @throws SAXException */ protected void doEndElement(String uri, String localName, String name) throws SAXException { // by default do nothing } public static interface ChildElementHandler/* */{ public void childHanlded(/* DH */DelegetingHandler child) throws SAXParseException; } public final void characters(char[] ch, int start, int length) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.characters(ch, start, length); } else { doCharacters(ch, start, length); } } /** * @throws SAXException */ protected void doCharacters(char[] ch, int start, int length) throws SAXException { if (bufferingChar) { charBuffer.append(ch, start, length); } } public final void startPrefixMapping(String prefix, String uri) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.startPrefixMapping(prefix, uri); } else { doStartPrefixMapping(prefix, uri); } } /** * @throws SAXException */ protected void doStartPrefixMapping(String prefix, String uri) throws SAXException { // by default do nothing } public final void endPrefixMapping(String prefix) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.endPrefixMapping(prefix); } else { doEndPrefixMapping(prefix); } } /** * @throws SAXException */ protected void doEndPrefixMapping(String prefix) throws SAXException { // by default do nothing } public final void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.ignorableWhitespace(ch, start, length); } else { doIgnorableWhitespace(ch, start, length); } } /** * @throws SAXException */ protected void doIgnorableWhitespace(char[] ch, int start, int length) throws SAXException { // by default do nothing } public final void notationDecl(String name, String publicId, String systemId) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.notationDecl(name, publicId, systemId); } else { doNotationDecl(name, publicId, systemId); } } /** * @throws SAXException */ protected void doNotationDecl(String name, String publicId, String systemId) throws SAXException { // by default do nothing } public final void processingInstruction(String target, String data) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.processingInstruction(target, data); } else { doProcessingInstruction(target, data); } } /** * @throws SAXException */ protected void doProcessingInstruction(String target, String data) throws SAXException { // by default do nothing } public final void skippedEntity(String name) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.skippedEntity(name); } else { doSkippedEntity(name); } } /** * @throws SAXException */ protected void doSkippedEntity(String name) throws SAXException { // by default do nothing } /** * @throws SAXException */ public final void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.unparsedEntityDecl(name, publicId, systemId, notationName); } else { doUnparsedEntityDecl(name, publicId, systemId, notationName); } } /** * @throws SAXException */ protected void doUnparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { // by default do nothing } // ERROR HANDLING public final void warning(SAXParseException exception) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.warning(exception); } else { doWarning(exception); } } /** * @throws SAXException */ protected void doWarning(SAXParseException exception) throws SAXException { // by default do nothing } public final void error(SAXParseException exception) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.error(exception); } else { doError(exception); } } /** * @throws SAXException */ protected void doError(SAXParseException exception) throws SAXException { // by default do nothing } public final void fatalError(SAXParseException exception) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.fatalError(exception); } else { doFatalError(exception); } } /** * @throws SAXException */ protected void doFatalError(SAXParseException exception) throws SAXException { // by default do nothing } // ////////////////////// // Functions related to error handling // ////////////////////// protected void log(int logLevel, String message) { Message.log(logLevel, getLocation(getLocator()) + message); } protected static String getLocation(Locator locator) { if (locator == null) { return ""; } return "[line " + locator.getLineNumber() + " col. " + locator.getColumnNumber() + "] "; } private void skipOnError(DelegetingHandler/* */currentHandler, Class/* * */handlerClassToSkip, String message) { DelegetingHandler/* */handlerToSkip = currentHandler; while (!(handlerClassToSkip.isAssignableFrom(handlerToSkip.getClass()))) { handlerToSkip = handlerToSkip.getParent(); } log(Message.MSG_ERR, message + ". The '" + handlerToSkip.getName() + "' element " + getCurrentElementIdentifier() + " is then ignored."); handlerToSkip.skip(); } // ////////////////////// // Helpers to parse the attributes // ////////////////////// protected String getRequiredAttribute(Attributes atts, String name) throws SAXParseException { String value = atts.getValue(name); if (value == null) { throw new SAXParseException("Required attribute '" + name + "' not found", getLocator()); } return value; } protected String getOptionalAttribute(Attributes atts, String name, String defaultValue) { String value = atts.getValue(name); if (value == null) { return defaultValue; } return value; } protected int getRequiredIntAttribute(Attributes atts, String name, Integer logLevel) throws SAXParseException { return parseInt(name, getRequiredAttribute(atts, name)); } protected Integer getOptionalIntAttribute(Attributes atts, String name, Integer defaultValue) throws SAXParseException { String value = atts.getValue(name); if (value == null) { return defaultValue; } return new Integer(parseInt(name, value)); } private int parseInt(String name, String value) throws SAXParseException { try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new SAXParseException("Attribute '" + name + "' is expected to be an integer but was '" + value + "' (" + e.getMessage() + ")", getLocator()); } } protected long getRequiredLongAttribute(Attributes atts, String name) throws SAXParseException { return parseLong(name, getRequiredAttribute(atts, name)); } protected Long getOptionalLongAttribute(Attributes atts, String name, Long defaultValue) throws SAXParseException { String value = atts.getValue(name); if (value == null) { return defaultValue; } return new Long(parseLong(name, value)); } private long parseLong(String name, String value) throws SAXParseException { try { return Long.parseLong(value); } catch (NumberFormatException e) { throw new SAXParseException("Attribute '" + name + "' is expected to be an long but was '" + value + "' (" + e.getMessage() + ")", getLocator()); } } protected boolean getRequiredBooleanAttribute(Attributes atts, String name) throws SAXParseException { return parseBoolean(name, getRequiredAttribute(atts, name)); } protected Boolean getOptionalBooleanAttribute(Attributes atts, String name, Boolean defaultValue) throws SAXParseException { String value = atts.getValue(name); if (value == null) { return defaultValue; } return Boolean.valueOf(parseBoolean(name, value)); } static final String TRUE = Boolean.TRUE.toString().toLowerCase(Locale.US); static final String FALSE = Boolean.FALSE.toString().toLowerCase(Locale.US); private boolean parseBoolean(String name, String value) throws SAXParseException { String lowerValue = value.toLowerCase(Locale.US); if (lowerValue.equals(TRUE)) { return true; } if (lowerValue.equals(FALSE)) { return false; } throw new SAXParseException("Attribute '" + name + "' is expected to be a boolean but was '" + value + "'", getLocator()); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/util/VersionComparator.java0000644000175000017500000000302311736412724024620 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.util; import java.util.Comparator; public class VersionComparator implements Comparator/* */{ public static final Comparator/* */ASCENDING = new VersionComparator(false); public static final Comparator/* */DESCENDING = new VersionComparator(true); public final boolean reverse; private VersionComparator(boolean reverse) { this.reverse = reverse; } public int compare(Object o1, Object o2) { return compare((Version) o1, (Version) o1); } public int compare(Version objA, Version objB) { final int val = objA.compareTo(objB); return (reverse ? -val : val); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/util/ZipUtil.java0000644000175000017500000000503511736412724022550 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Class derived from code posted here: http://forums.sun.com/thread.jspa?messageID=2160923 */ public class ZipUtil { public static void zip(File sourceDir, OutputStream targetStream) throws IOException { if (!sourceDir.isFile() && !sourceDir.isDirectory()) { return; } final ZipOutputStream cpZipOutputStream = new ZipOutputStream(targetStream); cpZipOutputStream.setLevel(9); zipFiles(sourceDir, sourceDir, cpZipOutputStream); cpZipOutputStream.finish(); cpZipOutputStream.close(); } private static void zipFiles(File rootDir, File currDir, ZipOutputStream zos) throws IOException { if (currDir.isDirectory()) { final File[] files = currDir.listFiles(); for (int i = 0; i < files.length; i++) { zipFiles(rootDir, files[i], zos); } } else { final String strAbsPath = currDir.getPath(); final String strZipEntryName = strAbsPath.substring(rootDir.getPath().length() + 1, strAbsPath.length()); final byte[] b = new byte[(int) (currDir.length())]; final FileInputStream fis = new FileInputStream(currDir); fis.read(b); fis.close(); final ZipEntry entry = new ZipEntry(strZipEntryName); zos.putNextEntry(entry); zos.write(b, 0, (int) currDir.length()); zos.closeEntry(); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/util/VersionRange.java0000644000175000017500000002604611742633106023553 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.util; import java.text.ParseException; /** * Provides version range support. */ public class VersionRange { private boolean startExclusive; private Version startVersion; private boolean endExclusive; private Version endVersion; public VersionRange(String versionStr) throws ParseException { if (versionStr == null || versionStr.length() == 0) { startExclusive = false; startVersion = new Version(0, 0, 0, null); endExclusive = true; endVersion = null; } else { new VersionRangeParser(versionStr).parse(); } } class VersionRangeParser { /** * value to parse */ private final String version; /** * the length of the source */ private int length; /** * position in the source */ private int pos = 0; /** * last read character */ private char c; /** * Default constructor * * @param header * the header to parse */ VersionRangeParser(String version) { this.version = version; this.length = version.length(); } /** * Do the parsing * * @throws ParseException */ void parse() throws ParseException { boolean range = parseStart(); startVersion = parseVersion(); if (startVersion == null) { throw new ParseException("Expecting a number", pos); } if (parseVersionSeparator()) { endVersion = parseVersion(); parseEnd(); } else if (range) { throw new ParseException("Expecting ,", pos); } else { // simple number endVersion = null; startExclusive = false; endExclusive = false; } } private char readNext() { if (pos == length) { c = '\0'; } else { c = version.charAt(pos++); } return c; } private void unread() { if (pos > 0) { pos--; } } private boolean parseStart() { skipWhiteSpace(); switch (readNext()) { case '[': startExclusive = false; return true; case '(': startExclusive = true; return true; default: unread(); return false; } } private void skipWhiteSpace() { do { switch (readNext()) { case ' ': continue; default: unread(); return; } } while (pos < length); } private Version parseVersion() { Integer major = parseNumber(); if (major == null) { return null; } Integer minor = new Integer(0); Integer patch = new Integer(0); String qualififer = null; if (parseNumberSeparator()) { minor = parseNumber(); if (minor == null) { minor = new Integer(0); } else if (parseNumberSeparator()) { patch = parseNumber(); if (patch == null) { patch = new Integer(0); } else if (parseNumberSeparator()) { qualififer = parseQualifier(); } } } return new Version(major.intValue(), minor.intValue(), patch.intValue(), qualififer); } private Integer parseNumber() { skipWhiteSpace(); Integer n = null; do { switch (readNext()) { case '\0': return n; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': n = new Integer((n == null ? 0 : n.intValue() * 10) + c - '0'); break; default: unread(); return n; } } while (pos < length); return n; } private boolean parseNumberSeparator() { switch (readNext()) { case '.': return true; default: unread(); return false; } } private boolean parseVersionSeparator() { skipWhiteSpace(); switch (readNext()) { case ',': return true; default: unread(); return false; } } private String parseQualifier() { StringBuffer q = new StringBuffer(); do { readNext(); if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_') { q.append(c); } else { unread(); break; } } while (pos < length); if (q.length() == 0) { return null; } return q.toString(); } private void parseEnd() throws ParseException { skipWhiteSpace(); switch (readNext()) { case ']': endExclusive = false; break; case ')': endExclusive = true; break; default: unread(); throw new ParseException("Expexting ] or )", pos); } } } public VersionRange(boolean startExclusive, Version startVersion, boolean endExclusive, Version endVersion) { this.startExclusive = startExclusive; this.startVersion = startVersion; this.endExclusive = endExclusive; this.endVersion = endVersion; } public VersionRange(Version startVersion) { this.startExclusive = false; this.startVersion = startVersion; this.endExclusive = true; this.endVersion = null; } public String toString() { return (startExclusive ? "(" : "[") + startVersion + "," + (endVersion == null ? "" : endVersion.toString()) + (endExclusive ? ")" : "]"); } public String toIvyRevision() { StringBuffer buffer = new StringBuffer(); buffer.append(startExclusive ? "(" : "["); buffer.append(startVersion); if (endVersion == null) { buffer.append(",)"); } else if (!endExclusive || startVersion.equals(endVersion)) { buffer.append(","); buffer.append(endVersion.withNudgedPatch()); buffer.append(")"); } else { buffer.append(","); buffer.append(endVersion); buffer.append(")"); } return buffer.toString(); } public boolean isEndExclusive() { return this.endExclusive; } public Version getEndVersion() { return this.endVersion; } public boolean isStartExclusive() { return this.startExclusive; } public Version getStartVersion() { return this.startVersion; } public boolean isClosedRange() { return startVersion.equals(endVersion); } public boolean contains(String versionStr) throws ParseException { return contains(new Version(versionStr)); } public boolean contains(Version version) { if (startExclusive ? version.compareUnqualified(startVersion) <= 0 : version .compareUnqualified(startVersion) < 0) { return false; } if (endVersion == null) { return true; } if (endExclusive ? version.compareUnqualified(endVersion) >= 0 : version .compareUnqualified(endVersion) > 0) { return false; } return true; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (endExclusive ? 1231 : 1237); result = prime * result + ((endVersion == null) ? 0 : endVersion.hashCode()); result = prime * result + (startExclusive ? 1231 : 1237); result = prime * result + ((startVersion == null) ? 0 : startVersion.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof VersionRange)) { return false; } VersionRange other = (VersionRange) obj; if (endExclusive != other.endExclusive) { return false; } if (endVersion == null) { if (other.endVersion != null) { return false; } } else if (!endVersion.equals(other.endVersion)) { return false; } if (startExclusive != other.startExclusive) { return false; } if (startVersion == null) { if (other.startVersion != null) { return false; } } else if (!startVersion.equals(other.startVersion)) { return false; } return true; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/util/ParseUtil.java0000644000175000017500000000610211736412724023054 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.util; import java.util.ArrayList; import java.util.List; public class ParseUtil { /** * Parses delimited string and returns an array containing the tokens. This parser obeys quotes, * so the delimiter character will be ignored if it is inside of a quote. This method assumes * that the quote character is not included in the set of delimiter characters. * * @param value * the delimited string to parse. * @param delim * the characters delimiting the tokens. * @return an array of string tokens or null if there were no tokens. */ // method largely inspired by Apache Felix 1.0.4 ManifestParser method public static String[] parseDelimitedString(String value, String delim) { if (value == null) { value = ""; } final List list = new ArrayList(); final int CHAR = 1; final int DELIMITER = 2; final int STARTQUOTE = 4; final int ENDQUOTE = 8; final StringBuffer sb = new StringBuffer(); int expecting = (CHAR | DELIMITER | STARTQUOTE); for (int i = 0; i < value.length(); i++) { final char c = value.charAt(i); final boolean isDelimiter = (delim.indexOf(c) >= 0); final boolean isQuote = (c == '"'); if (isDelimiter && ((expecting & DELIMITER) > 0)) { list.add(sb.toString().trim()); sb.delete(0, sb.length()); expecting = (CHAR | DELIMITER | STARTQUOTE); } else if (isQuote && ((expecting & STARTQUOTE) > 0)) { sb.append(c); expecting = CHAR | ENDQUOTE; } else if (isQuote && ((expecting & ENDQUOTE) > 0)) { sb.append(c); expecting = (CHAR | STARTQUOTE | DELIMITER); } else if ((expecting & CHAR) > 0) { sb.append(c); } else { throw new IllegalArgumentException("Invalid delimited string: " + value); } } if (sb.length() > 0) { list.add(sb.toString().trim()); } return (String[]) list.toArray(new String[list.size()]); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/0000755000175000017500000000000012126443423020247 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/BundleInfoAdapter.java0000644000175000017500000003320211742633074024446 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.ivy.Ivy; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.Configuration; import org.apache.ivy.core.module.descriptor.Configuration.Visibility; import org.apache.ivy.core.module.descriptor.DefaultArtifact; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.DefaultExcludeRule; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.id.ArtifactId; import org.apache.ivy.core.module.id.ModuleId; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.osgi.util.VersionRange; import org.apache.ivy.plugins.matcher.ExactOrRegexpPatternMatcher; import org.apache.ivy.plugins.matcher.PatternMatcher; import org.apache.ivy.plugins.parser.ModuleDescriptorParser; public class BundleInfoAdapter { public static final String CONF_NAME_DEFAULT = "default"; public static final Configuration CONF_DEFAULT = new Configuration(CONF_NAME_DEFAULT); public static final String CONF_NAME_OPTIONAL = "optional"; public static final Configuration CONF_OPTIONAL = new Configuration(CONF_NAME_OPTIONAL, Visibility.PUBLIC, "Optional dependencies", new String[] {CONF_NAME_DEFAULT}, true, null); public static final String CONF_NAME_TRANSITIVE_OPTIONAL = "transitive-optional"; public static final Configuration CONF_TRANSITIVE_OPTIONAL = new Configuration( CONF_NAME_TRANSITIVE_OPTIONAL, Visibility.PUBLIC, "Optional dependencies", new String[] {CONF_NAME_OPTIONAL}, true, null); public static final String CONF_USE_PREFIX = "use_"; public static final String EXTRA_INFO_EXPORT_PREFIX = "_osgi_export_"; /** * * @param baseUri * uri to help build the absolute url if the bundle info has a relative uri. * @param bundle * @param profileProvider * @param parser * @return * @throws ProfileNotFoundException */ public static DefaultModuleDescriptor toModuleDescriptor(ModuleDescriptorParser parser, URI baseUri, BundleInfo bundle, ExecutionEnvironmentProfileProvider profileProvider) throws ProfileNotFoundException { DefaultModuleDescriptor md = new DefaultModuleDescriptor(parser, null); md.addExtraAttributeNamespace("o", Ivy.getIvyHomeURL() + "osgi"); ModuleRevisionId mrid = asMrid(BundleInfo.BUNDLE_TYPE, bundle.getSymbolicName(), bundle.getVersion()); md.setResolvedPublicationDate(new Date()); md.setModuleRevisionId(mrid); md.addConfiguration(CONF_DEFAULT); md.addConfiguration(CONF_OPTIONAL); md.addConfiguration(CONF_TRANSITIVE_OPTIONAL); Set/* */exportedPkgNames = new HashSet/* */(bundle.getExports().size()); Iterator itExport = bundle.getExports().iterator(); while (itExport.hasNext()) { ExportPackage exportPackage = (ExportPackage) itExport.next(); md.getExtraInfo().put(EXTRA_INFO_EXPORT_PREFIX + exportPackage.getName(), exportPackage.getVersion().toString()); exportedPkgNames.add(exportPackage.getName()); String[] confDependencies = new String[exportPackage.getUses().size() + 1]; int i = 0; Iterator itUse = exportPackage.getUses().iterator(); while (itUse.hasNext()) { String use = (String) itUse.next(); confDependencies[i++] = CONF_USE_PREFIX + use; } confDependencies[i] = CONF_NAME_DEFAULT; md.addConfiguration(new Configuration(CONF_USE_PREFIX + exportPackage.getName(), Visibility.PUBLIC, "Exported package " + exportPackage.getName(), confDependencies, true, null)); } requirementAsDependency(md, bundle, exportedPkgNames); URI uri = bundle.getUri(); if (uri != null) { DefaultArtifact artifact = null; if ("ivy".equals(uri.getScheme())) { artifact = decodeIvyURI(uri); } else { if (!uri.isAbsolute()) { uri = baseUri.resolve(uri); } try { artifact = new DefaultArtifact(mrid, null, bundle.getSymbolicName(), "jar", "jar", new URL(uri.toString()), null); } catch (MalformedURLException e) { throw new RuntimeException("Unable to make the uri into the url", e); } } if (artifact != null) { md.addArtifact(CONF_NAME_DEFAULT, artifact); } } if (profileProvider != null) { Iterator itEnv = bundle.getExecutionEnvironments().iterator(); while (itEnv.hasNext()) { String env = (String) itEnv.next(); ExecutionEnvironmentProfile profile = profileProvider.getProfile(env); if (profile == null) { throw new ProfileNotFoundException("Execution environment profile " + env + " not found"); } Iterator itPkg = profile.getPkgNames().iterator(); while (itPkg.hasNext()) { String pkg = (String) itPkg.next(); ArtifactId id = new ArtifactId(ModuleId.newInstance(BundleInfo.BUNDLE_TYPE, pkg), PatternMatcher.ANY_EXPRESSION, PatternMatcher.ANY_EXPRESSION, PatternMatcher.ANY_EXPRESSION); DefaultExcludeRule rule = new DefaultExcludeRule(id, ExactOrRegexpPatternMatcher.INSTANCE, null); String[] confs = md.getConfigurationsNames(); for (int i = 0; i < confs.length; i++) { rule.addConfiguration(confs[i]); } md.addExcludeRule(rule); } } } return md; } public static List/**/ getConfigurations(BundleInfo bundle) { List/**/ confs = new ArrayList(); confs.add(CONF_DEFAULT); confs.add(CONF_OPTIONAL); confs.add(CONF_TRANSITIVE_OPTIONAL); Iterator itExport = bundle.getExports().iterator(); while (itExport.hasNext()) { ExportPackage exportPackage = (ExportPackage) itExport.next(); confs.add(CONF_USE_PREFIX + exportPackage.getName()); } return confs; } public static URI buildIvyURI(Artifact artifact) { ModuleRevisionId mrid = artifact.getModuleRevisionId(); return asIvyURI(mrid.getOrganisation(), mrid.getName(), mrid.getBranch(), mrid.getRevision(), artifact.getType(), artifact.getName(), artifact.getExt()); } private static URI asIvyURI(String org, String name, String branch, String rev, String type, String art, String ext) { StringBuffer builder = new StringBuffer(); builder.append("ivy:///"); builder.append(org); builder.append('/'); builder.append(name); builder.append('?'); if (branch != null) { builder.append("branch="); builder.append(branch); } if (rev != null) { builder.append("&rev="); builder.append(rev); } if (type != null) { builder.append("&type="); builder.append(type); } if (art != null) { builder.append("&art="); builder.append(art); } if (ext != null) { builder.append("&ext="); builder.append(ext); } try { return new URI(builder.toString()); } catch (URISyntaxException e) { throw new RuntimeException("illformed ivy url", e); } } private static DefaultArtifact decodeIvyURI(final URI uri) { String org = null; String name = null; String branch = null; String rev = null; String art = null; String type = null; String ext = null; String path = uri.getPath(); if (!path.startsWith("/")) { throw new IllegalArgumentException("An ivy url should be of the form ivy:///org/module but was : " + uri); } int i = path.indexOf('/', 1); if (i < 0) { throw new IllegalArgumentException("Expecting an organisation in the ivy url: " + uri); } org = path.substring(1, i); name = path.substring(i + 1); String query = uri.getQuery(); String[] parameters = query.split("&"); for (int j = 0; j < parameters.length; j++) { String parameter = parameters[j]; if (parameter.length() == 0) { continue; } String[] nameAndValue = parameter.split("="); if (nameAndValue.length != 2) { throw new IllegalArgumentException("Malformed query string in the ivy url: " + uri); } else if (nameAndValue[0].equals("branch")) { branch = nameAndValue[1]; } else if (nameAndValue[0].equals("rev")) { rev = nameAndValue[1]; } else if (nameAndValue[0].equals("art")) { art = nameAndValue[1]; } else if (nameAndValue[0].equals("type")) { type = nameAndValue[1]; } else if (nameAndValue[0].equals("ext")) { ext = nameAndValue[1]; } else { throw new IllegalArgumentException("Unrecognized parameter '" + nameAndValue[0] + " in the query string of the ivy url: " + uri); } } ModuleRevisionId amrid = ModuleRevisionId.newInstance(org, name, branch, rev); DefaultArtifact artifact = new DefaultArtifact(amrid, null, art, type, ext); return artifact; } private static void requirementAsDependency(DefaultModuleDescriptor md, BundleInfo bundleInfo, Set/* */exportedPkgNames) { Iterator itReq = bundleInfo.getRequirements().iterator(); while (itReq.hasNext()) { BundleRequirement requirement = (BundleRequirement) itReq.next(); String type = requirement.getType(); String name = requirement.getName(); if (BundleInfo.PACKAGE_TYPE.equals(type) && exportedPkgNames.contains(name)) { // don't declare package exported by the current bundle continue; } ModuleRevisionId ddmrid = asMrid(type, name, requirement.getVersion()); DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(ddmrid, false); String conf = CONF_NAME_DEFAULT; if (BundleInfo.PACKAGE_TYPE.equals(type)) { // declare the configuration for the package conf = CONF_USE_PREFIX + name; md.addConfiguration(new Configuration(CONF_USE_PREFIX + name, Visibility.PUBLIC, "Exported package " + name, new String[] {CONF_NAME_DEFAULT}, true, null)); dd.addDependencyConfiguration(conf, conf); } if ("optional".equals(requirement.getResolution())) { dd.addDependencyConfiguration(CONF_NAME_OPTIONAL, conf); dd.addDependencyConfiguration(CONF_NAME_TRANSITIVE_OPTIONAL, CONF_NAME_TRANSITIVE_OPTIONAL); } else { dd.addDependencyConfiguration(CONF_NAME_DEFAULT, conf); } md.addDependency(dd); } } public static ModuleRevisionId asMrid(String type, String name, Version v) { return ModuleRevisionId.newInstance(type, name, v == null ? null : v.toString()); } public static ModuleRevisionId asMrid(String type, String name, VersionRange v) { String revision; if (v == null) { revision = "[0,)"; } else { revision = v.toIvyRevision(); } return ModuleRevisionId.newInstance(type, name, revision); } public static class ProfileNotFoundException extends RuntimeException { public ProfileNotFoundException(String msg) { super(msg); } } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/ExecutionEnvironmentProfile.java0000644000175000017500000000504611736412724026636 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import java.util.Set; import java.util.TreeSet; public class ExecutionEnvironmentProfile { private Set/* */pkgNames = new TreeSet/* */(); private final String name; public ExecutionEnvironmentProfile(String name) { this.name = name; } public String getName() { return name; } public void addPkgName(String pkgName) { if (pkgName != null) { pkgNames.add(pkgName); } } public Set/* */getPkgNames() { return pkgNames; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((pkgNames == null) ? 0 : pkgNames.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof ExecutionEnvironmentProfile)) { return false; } ExecutionEnvironmentProfile other = (ExecutionEnvironmentProfile) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (pkgNames == null) { if (other.pkgNames != null) { return false; } } else if (!pkgNames.equals(other.pkgNames)) { return false; } return true; } public String toString() { return name + ":" + pkgNames; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/jvm-packages.properties0000644000175000017500000001256211736412724024751 0ustar tonytony# *************************************************************** # * Licensed to the Apache Software Foundation (ASF) under one # * or more contributor license agreements. See the NOTICE file # * distributed with this work for additional information # * regarding copyright ownership. The ASF licenses this file # * to you under the Apache License, Version 2.0 (the # * "License"); you may not use this file except in compliance # * with the License. You may obtain a copy of the License at # * # * http://www.apache.org/licenses/LICENSE-2.0 # * # * Unless required by applicable law or agreed to in writing, # * software distributed under the License is distributed on an # * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # * KIND, either express or implied. See the License for the # * specific language governing permissions and limitations # * under the License. # *************************************************************** OSGI_MINIMUM-1.0.pkglist = OSGI_MINIMUM-1.1.extends = OSGI_MINIMUM-1.0 OSGI_MINIMUM-1.1.pkglist = CDC-1.0_Foundation-1.0.pkglist = \ javax.microedition.io CDC-1.1_Foundation-1.1.extends = CDC-1.0_Foundation-1.0 CDC-1.1_Foundation-1.1.pkglist = \ javax.microedition.pki,\ javax.security.auth.x500 J2SE-1.2.pkglist = \ javax.accessibility,\ javax.swing,\ javax.swing.border,\ javax.swing.colorchooser,\ javax.swing.event,\ javax.swing.filechooser,\ javax.swing.plaf,\ javax.swing.plaf.basic,\ javax.swing.plaf.metal,\ javax.swing.plaf.multi,\ javax.swing.table,\ javax.swing.text,\ javax.swing.text.html,\ javax.swing.text.html.parser,\ javax.swing.text.rtf,\ javax.swing.tree,\ javax.swing.undo,\ org.omg.CORBA,\ org.omg.CORBA.DynAnyPackage,\ org.omg.CORBA.ORBPackage,\ org.omg.CORBA.portable,\ org.omg.CORBA.TypeCodePackage,\ org.omg.CosNaming,\ org.omg.CosNaming.NamingContextPackage J2SE-1.3.extends = J2SE-1.2 J2SE-1.3.pkglist = \ javax.naming,\ javax.naming.directory,\ javax.naming.event,\ javax.naming.ldap,\ javax.naming.spi,\ javax.rmi,\ javax.rmi.CORBA,\ javax.sound.midi,\ javax.sound.midi.spi,\ javax.sound.sampled,\ javax.sound.sampled.spi,\ javax.transaction,\ org.omg.CORBA_2_3,\ org.omg.CORBA_2_3.portable,\ org.omg.SendingContext,\ org.omg.stub.java.rmi J2SE-1.4.extends = J2SE-1.3 J2SE-1.4.pkglist = \ javax.crypto,\ javax.crypto.interfaces,\ javax.crypto.spec,\ javax.imageio,\ javax.imageio.event,\ javax.imageio.metadata,\ javax.imageio.plugins.jpeg,\ javax.imageio.spi,\ javax.imageio.stream,\ javax.net,\ javax.net.ssl,\ javax.print,\ javax.print.attribute,\ javax.print.attribute.standard,\ javax.print.event,\ javax.security.auth,\ javax.security.auth.callback,\ javax.security.auth.kerberos,\ javax.security.auth.login,\ javax.security.auth.spi,\ javax.security.auth.x500,\ javax.security.cert,\ javax.sql,\ javax.transaction.xa,\ javax.xml.parsers,\ javax.xml.transform,\ javax.xml.transform.dom,\ javax.xml.transform.sax,\ javax.xml.transform.stream,\ org.ietf.jgss,\ org.omg.Dynamic,\ org.omg.DynamicAny,\ org.omg.DynamicAny.DynAnyFactoryPackage,\ org.omg.DynamicAny.DynAnyPackage,\ org.omg.IOP,\ org.omg.IOP.CodecFactoryPackage,\ org.omg.IOP.CodecPackage,\ org.omg.Messaging,\ org.omg.PortableInterceptor,\ org.omg.PortableInterceptor.ORBInitInfoPackage,\ org.omg.PortableServer,\ org.omg.PortableServer.CurrentPackage,\ org.omg.PortableServer.POAManagerPackage,\ org.omg.PortableServer.POAPackage,\ org.omg.PortableServer.portable,\ org.omg.PortableServer.ServantLocatorPackage,\ org.omg.stub.java.rmi,\ org.w3c.dom,\ org.w3c.dom.css,\ org.w3c.dom.events,\ org.w3c.dom.html,\ org.w3c.dom.stylesheets,\ org.w3c.dom.views ,\ org.xml.sax,\ org.xml.sax.ext,\ org.xml.sax.helpers J2SE-1.5.extends = J2SE-1.4 J2SE-1.5.pkglist = \ javax.activity,\ javax.imageio.plugins.bmp,\ javax.management,\ javax.management.loading,\ javax.management.modelmbean,\ javax.management.monitor,\ javax.management.openmbean,\ javax.management.relation,\ javax.management.remote,\ javax.management.remote.rmi,\ javax.management.timer,\ javax.rmi.ssl,\ javax.security.sasl,\ javax.sql.rowset,\ javax.sql.rowset.serial,\ javax.sql.rowset.spi,\ javax.swing.plaf.synth,\ javax.xml,\ javax.xml.datatype,\ javax.xml.namespace,\ javax.xml.validation,\ org.w3c.dom.bootstrap,\ org.w3c.dom.ls,\ org.w3c.dom.ranges,\ org.w3c.dom.traversal JavaSE-1.6.extends = J2SE-1.5 JavaSE-1.6.pkglist = \ javax.activation,\ javax.annotation,\ javax.annotation.processing,\ javax.jws,\ javax.jws.soap,\ javax.lang.model,\ javax.lang.model.element,\ javax.lang.model.type,\ javax.lang.model.util,\ javax.script,\ javax.tools,\ javax.xml.bind,\ javax.xml.bind.annotation,\ javax.xml.bind.annotation.adapters,\ javax.xml.bind.attachment,\ javax.xml.bind.helpers,\ javax.xml.bind.util,\ javax.xml.crypto,\ javax.xml.crypto.dom,\ javax.xml.crypto.dsig,\ javax.xml.crypto.dsig.dom,\ javax.xml.crypto.dsig.keyinfo,\ javax.xml.crypto.dsig.spec,\ javax.xml.soap,\ javax.xml.stream,\ javax.xml.stream.events,\ javax.xml.stream.util,\ javax.xml.transform.stax,\ javax.xml.ws,\ javax.xml.ws.handler,\ javax.xml.ws.handler.soap,\ javax.xml.ws.http,\ javax.xml.ws.soap,\ javax.xml.ws.spiivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/ManifestHeaderElement.java0000644000175000017500000001066111736412724025315 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class ManifestHeaderElement { private List/* */values = new ArrayList/* */(); private Map/* */attributes = new HashMap/* */(); private Map/* */directives = new HashMap/* */(); public List/* */getValues() { return values; } public void addValue(String value) { values.add(value); } public Map/* */getAttributes() { return attributes; } public void addAttribute(String name, String value) { attributes.put(name, value); } public Map/* */getDirectives() { return directives; } public void addDirective(String name, String value) { directives.put(name, value); } public boolean equals(Object obj) { if (!(obj instanceof ManifestHeaderElement)) { return false; } ManifestHeaderElement other = (ManifestHeaderElement) obj; if (other.values.size() != values.size()) { return false; } Iterator itValues = values.iterator(); while (itValues.hasNext()) { String value = (String) itValues.next(); if (!other.values.contains(value)) { return false; } } if (other.directives.size() != directives.size()) { return false; } Iterator itDirectives = directives.entrySet().iterator(); while (itDirectives.hasNext()) { Entry/* */directive = (Entry) itDirectives.next(); if (!directive.getValue().equals(other.directives.get(directive.getKey()))) { return false; } } if (other.attributes.size() != attributes.size()) { return false; } Iterator itAttributes = attributes.entrySet().iterator(); while (itAttributes.hasNext()) { Entry/* */attribute = (Entry) itAttributes.next(); if (!attribute.getValue().equals(other.attributes.get(attribute.getKey()))) { return false; } } return true; } public String toString() { String string = ""; Iterator/* */itValues = values.iterator(); while (itValues.hasNext()) { string = string.concat((String) itValues.next()); if (itValues.hasNext()) { string = string.concat(";"); } } Iterator itDirectives = directives.entrySet().iterator(); while (itDirectives.hasNext()) { Entry/* */directive = (Entry) itDirectives.next(); string = string.concat(";"); string = string.concat((String) directive.getKey()); string = string.concat(":="); string = string.concat((String) directive.getValue()); } Iterator itAttributes = attributes.entrySet().iterator(); while (itAttributes.hasNext()) { Entry/* */attribute = (Entry) itAttributes.next(); string = string.concat(";"); string = string.concat((String) attribute.getKey()); string = string.concat("="); string = string.concat((String) attribute.getValue()); } return string; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/BundleCapability.java0000644000175000017500000000511011736412724024330 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import org.apache.ivy.osgi.util.Version; public class BundleCapability { private final String name; private final Version version; private final String type; public BundleCapability(String type, String name, Version version) { this.type = type; this.name = name; this.version = version; } public String getType() { return type; } public String getName() { return name; } public Version getVersion() { return version; } public Version getRawVersion() { return version; } public String toString() { return name + (version == null ? "" : ";" + version); } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof BundleCapability)) { return false; } BundleCapability other = (BundleCapability) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (version == null) { if (other.version != null) { return false; } } else if (!version.equals(other.version)) { return false; } return true; } }ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/ExecutionEnvironmentProfileProvider.java0000644000175000017500000001225011736412724030344 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.apache.ivy.util.Message; public class ExecutionEnvironmentProfileProvider { private static final String DEFAULT_PROFILES_FILE = "jvm-packages.properties"; private static final String PACKAGE_PREFIX = "org/apache/ivy/osgi/core/"; private Map/* */profileList; private static final ExecutionEnvironmentProfileProvider INSTANCE; static { try { INSTANCE = new ExecutionEnvironmentProfileProvider(); } catch (IOException e) { throw new RuntimeException(e); } } public static ExecutionEnvironmentProfileProvider getInstance() { return INSTANCE; } public ExecutionEnvironmentProfileProvider() throws IOException { profileList = loadDefaultProfileList(); } public ExecutionEnvironmentProfile getProfile(String profile) { return (ExecutionEnvironmentProfile) profileList.get(profile); } public static Map/* */loadDefaultProfileList() throws IOException { ClassLoader loader = ExecutionEnvironmentProfileProvider.class.getClassLoader(); InputStream defaultProfilesFile = loader.getResourceAsStream(PACKAGE_PREFIX + DEFAULT_PROFILES_FILE); if (defaultProfilesFile == null) { throw new FileNotFoundException(PACKAGE_PREFIX + DEFAULT_PROFILES_FILE + " not found in the classpath"); } Properties props = new Properties(); try { props.load(defaultProfilesFile); } finally { defaultProfilesFile.close(); } Map/* */profiles = new HashMap(); Iterator itProp = props.entrySet().iterator(); while (itProp.hasNext()) { Entry/* */prop = (Entry) itProp.next(); String propName = (String) prop.getKey(); if (propName.endsWith(".pkglist")) { String profileName = propName.substring(0, propName.length() - 8); if (!profiles.containsKey(profileName)) { loadProfile(props, profiles, profileName); } } } return profiles; } private static ExecutionEnvironmentProfile loadProfile(Properties props, Map/* * */profiles, String name) { ExecutionEnvironmentProfile profile = new ExecutionEnvironmentProfile(name); // load the package for the extended profile String extendedProfileName = props.getProperty(name + ".extends"); if (extendedProfileName != null) { ExecutionEnvironmentProfile extendedProfile = (ExecutionEnvironmentProfile) profiles .get(extendedProfileName); if (extendedProfile == null) { // not loaded yet, so load it now extendedProfile = loadProfile(props, profiles, extendedProfileName); } Iterator itExtended = extendedProfile.getPkgNames().iterator(); while (itExtended.hasNext()) { profile.addPkgName((String) itExtended.next()); } } // load the actual list String pkgList = props.getProperty(name + ".pkglist"); String[] packages = pkgList.split(","); for (int i = 0; i < packages.length; i++) { String pkg = packages[i].trim(); if (pkg.length() != 0) { profile.addPkgName(pkg); } } profiles.put(name, profile); Message.verbose("Execution environment profile " + profile.getName() + " loaded"); return profile; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/BundleRequirement.java0000644000175000017500000000652411736412724024561 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import org.apache.ivy.osgi.util.VersionRange; public class BundleRequirement { private final String name; private final String resolution; private final VersionRange version; private final String type; public BundleRequirement(String type, String name, VersionRange version, String resolution) { this.type = type; this.name = name; this.version = version; this.resolution = resolution; } public String getType() { return type; } public String getName() { return name; } public VersionRange getVersion() { return version; } public String getResolution() { return resolution; } public String toString() { return name + (version == null ? "" : ";" + version) + (resolution == null ? "" : " (" + resolution + ")"); } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((resolution == null) ? 0 : resolution.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof BundleRequirement)) { return false; } BundleRequirement other = (BundleRequirement) obj; if (type == null) { if (other.type != null) { return false; } } else if (!type.equals(other.type)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (resolution == null) { if (other.resolution != null) { return false; } } else if (!resolution.equals(other.resolution)) { return false; } if (version == null) { if (other.version != null) { return false; } } else if (!version.equals(other.version)) { return false; } return true; } }ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/ManifestHeaderValue.java0000644000175000017500000003404511736412724025002 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import java.io.PrintStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Parse a header of a manifest. The manifest header is composed with the following rules: * *
 * header ::= header-element (',' header-element)*
 * header-element ::= values (';' (attribute | directive) )*
 * values ::= value (';' value)*
 * value ::= <any string value that does not have ';' or ','>
 * attribute ::= key '=' value
 * directive ::= key '=' value
 * key ::= token
 * value ::= token | quoted-string | double-quoted-string
 * 
*/ public class ManifestHeaderValue { private List/* */elements = new ArrayList/* */(); ManifestHeaderValue() { // just for unit testing } public ManifestHeaderValue(String header) throws ParseException { if (header != null) { new ManifestHeaderParser(header).parse(); } } public List/* */getElements() { return elements; } public String getSingleValue() { if (elements.isEmpty()) { return null; } List/* */values = ((ManifestHeaderElement) getElements().iterator().next()) .getValues(); if (values.isEmpty()) { return null; } return (String) values.iterator().next(); } public List/* */getValues() { if (elements.isEmpty()) { return Collections.EMPTY_LIST; } List/* */list = new ArrayList/* */(); Iterator itElements = getElements().iterator(); while (itElements.hasNext()) { ManifestHeaderElement element = (ManifestHeaderElement) itElements.next(); list.addAll(element.getValues()); } return list; } void addElement(ManifestHeaderElement element) { this.elements.add(element); } class ManifestHeaderParser { /** * header to parse */ private final String header; /** * the length of the source */ private int length; /** * buffer */ private StringBuffer buffer = new StringBuffer(); /** * position in the source */ private int pos = 0; /** * last read character */ private char c; /** * the header element being build */ private ManifestHeaderElement elem = new ManifestHeaderElement(); /** * Once at true (at the first attribute parsed), only parameters are allowed */ private boolean valuesParsed; /** * the last parsed parameter name */ private String paramName; /** * true if the last parsed parameter is a directive (assigned via :=) */ private boolean isDirective; /** * Default constructor * * @param header * the header to parse */ ManifestHeaderParser(String header) { this.header = header; this.length = header.length(); } /** * Do the parsing * * @throws ParseException */ void parse() throws ParseException { do { elem = new ManifestHeaderElement(); int posElement = pos; parseElement(); if (elem.getValues().isEmpty()) { error("No defined value", posElement); // try to recover: ignore that element continue; } addElement(elem); } while (pos < length); } private char readNext() { if (pos == length) { c = '\0'; } else { c = header.charAt(pos++); } return c; } private void error(String message) throws ParseException { error(message, pos - 1); } private void error(String message, int p) throws ParseException { throw new ParseException(message, p); } private void parseElement() throws ParseException { valuesParsed = false; do { parseValueOrParameter(); } while (c == ';' && pos < length); } private void parseValueOrParameter() throws ParseException { // true if the value/parameter parsing has started, white spaces skipped boolean start = false; // true if the value/parameter parsing is ended, then only white spaces are allowed boolean end = false; do { switch (readNext()) { case '\0': break; case ';': case ',': endValue(); return; case ':': case '=': endParameterName(); parseSeparator(); parseParameterValue(); return; case ' ': case '\t': case '\n': case '\r': if (start) { end = true; } break; default: if (end) { error("Expecting the end of a value or of an parameter name"); // try to recover: restart the parsing of the value or parameter end = false; } start = true; buffer.append(c); } } while (pos < length); endValue(); } private void endValue() throws ParseException { if (valuesParsed) { error("Early end of a parameter"); // try to recover: ignore it buffer.setLength(0); return; } if (buffer.length() == 0) { error("Empty value"); // try to recover: just ignore the error } elem.addValue(buffer.toString()); buffer.setLength(0); } private void endParameterName() throws ParseException { if (buffer.length() == 0) { error("Empty parameter name"); // try to recover: won't store the value paramName = null; } paramName = buffer.toString(); buffer.setLength(0); } private void parseSeparator() throws ParseException { if (c == '=') { isDirective = false; return; } if (readNext() != '=') { error("Expecting '='"); // try to recover: will ignore this parameter pos--; paramName = null; } isDirective = true; } private void parseParameterValue() throws ParseException { // true if the value parsing has started, white spaces skipped boolean start = false; // true if the value parsing is ended, then only white spaces are allowed boolean end = false; boolean doubleQuoted = false; do { switch (readNext()) { case '\0': break; case ',': case ';': endParameterValue(); return; case '=': case ':': error("Illegal character '" + c + "' in parameter value of " + paramName); // try to recover: ignore that parameter paramName = null; break; case '\"': doubleQuoted = true; case '\'': if (end && paramName != null) { error("Expecting the end of a parameter value"); // try to recover: ignore that parameter paramName = null; } if (start) { // quote in the middle of the value, just add it as a quote buffer.append(c); } else { start = true; appendQuoted(doubleQuoted); end = true; } break; case '\\': if (end && paramName != null) { error("Expecting the end of a parameter value"); // try to recover: ignore that parameter paramName = null; } start = true; appendEscaped(); break; case ' ': case '\t': case '\n': case '\r': if (start) { end = true; } break; default: if (end && paramName != null) { error("Expecting the end of a parameter value"); // try to recover: ignore that parameter paramName = null; } start = true; buffer.append(c); } } while (pos < length); endParameterValue(); } private void endParameterValue() throws ParseException { if (paramName == null) { // recovering from an incorrect parameter: skip the value return; } if (buffer.length() == 0) { error("Empty parameter value"); // try to recover: do not store the parameter return; } String value = buffer.toString(); if (isDirective) { elem.addDirective(paramName, value); } else { elem.addAttribute(paramName, value); } valuesParsed = true; buffer.setLength(0); } private void appendQuoted(boolean doubleQuoted) { do { switch (readNext()) { case '\0': break; case '\"': if (doubleQuoted) { return; } buffer.append(c); break; case '\'': if (!doubleQuoted) { return; } buffer.append(c); break; case '\\': break; default: buffer.append(c); } } while (pos < length); } private void appendEscaped() { if (pos < length) { buffer.append(readNext()); } else { buffer.append(c); } } } public boolean equals(Object obj) { if (!(obj instanceof ManifestHeaderValue)) { return false; } ManifestHeaderValue other = (ManifestHeaderValue) obj; if (other.elements.size() != elements.size()) { return false; } Iterator itElements = elements.iterator(); while (itElements.hasNext()) { ManifestHeaderElement element = (ManifestHeaderElement) itElements.next(); if (!other.elements.contains(element)) { return false; } } return true; } public String toString() { String string = ""; Iterator/* */it = elements.iterator(); while (it.hasNext()) { string = string.concat(it.next().toString()); if (it.hasNext()) { string = string.concat(","); } } return string; } public static void writeParseException(PrintStream out, String source, ParseException e) { out.println(e.getMessage()); out.print(" " + source + "\n "); for (int i = 0; i < e.getErrorOffset(); i++) { out.print(' '); } out.println('^'); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/OSGiManifestParser.java0000644000175000017500000000756211742633074024577 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.text.ParseException; import java.util.Date; import java.util.Locale; import java.util.jar.Manifest; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.DefaultArtifact; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.plugins.parser.ModuleDescriptorParser; import org.apache.ivy.plugins.parser.ParserSettings; import org.apache.ivy.plugins.parser.xml.XmlModuleDescriptorWriter; import org.apache.ivy.plugins.repository.Resource; import org.apache.ivy.plugins.repository.url.URLResource; public class OSGiManifestParser implements ModuleDescriptorParser { private static final OSGiManifestParser INSTANCE = new OSGiManifestParser(); public static OSGiManifestParser getInstance() { return INSTANCE; } private ExecutionEnvironmentProfileProvider profileProvider; public void add(ExecutionEnvironmentProfileProvider pp) { this.profileProvider = pp; } public boolean accept(Resource res) { if (res == null || res.getName() == null || res.getName().trim().equals("")) { return false; } return res.getName().toUpperCase(Locale.US).endsWith("MANIFEST.MF"); } public ModuleDescriptor parseDescriptor(ParserSettings ivySettings, URL descriptorURL, Resource res, boolean validate) throws ParseException, IOException { Manifest m = new Manifest(res.openStream()); BundleInfo bundleInfo = ManifestParser.parseManifest(m); try { bundleInfo.setUri(new URI(res.getName())); } catch (URISyntaxException e) { throw new RuntimeException("Unsupported repository, resources names are not uris", e); } return BundleInfoAdapter.toModuleDescriptor(this, null, bundleInfo, profileProvider); } public void toIvyFile(InputStream is, Resource res, File destFile, ModuleDescriptor md) throws ParseException, IOException { try { XmlModuleDescriptorWriter.write(md, destFile); } finally { if (is != null) { is.close(); } } } public ModuleDescriptor parseDescriptor(ParserSettings ivySettings, URL descriptorURL, boolean validate) throws ParseException, IOException { URLResource resource = new URLResource(descriptorURL); return parseDescriptor(ivySettings, descriptorURL, resource, validate); } public String getType() { return "manifest"; } public Artifact getMetadataArtifact(ModuleRevisionId mrid, Resource res) { return DefaultArtifact.newIvyArtifact(mrid, new Date(res.getLastModified())); } public String toString() { return "manifest parser"; } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/ExportPackage.java0000644000175000017500000000417511736412724023664 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import java.util.HashSet; import java.util.Set; import org.apache.ivy.osgi.util.Version; public class ExportPackage extends BundleCapability { private final Set/* */uses = new HashSet/* */(); public ExportPackage(String name, Version version) { super(BundleInfo.PACKAGE_TYPE, name, version); } public void addUse(String pkg) { uses.add(pkg); } public Version getVersion() { return super.getVersion() == null ? BundleInfo.DEFAULT_VERSION : super.getVersion(); } public Set/* */getUses() { return uses; } public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((uses == null) ? 0 : uses.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } ExportPackage other = (ExportPackage) obj; if (uses == null) { if (other.uses != null) { return false; } } else if (!uses.equals(other.uses)) { return false; } return true; } }ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/ManifestParser.java0000644000175000017500000002332311742633072024044 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.Iterator; import java.util.List; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.osgi.util.VersionRange; /** * Provides an OSGi manifest parser. * */ public class ManifestParser { private static final String EXPORT_PACKAGE = "Export-Package"; private static final String IMPORT_PACKAGE = "Import-Package"; private static final String EXPORT_SERVICE = "Export-Service"; private static final String IMPORT_SERVICE = "Import-Service"; private static final String REQUIRE_BUNDLE = "Require-Bundle"; private static final String BUNDLE_VERSION = "Bundle-Version"; private static final String BUNDLE_NAME = "Bundle-Name"; private static final String BUNDLE_DESCRIPTION = "Bundle-Description"; private static final String BUNDLE_SYMBOLIC_NAME = "Bundle-SymbolicName"; private static final String BUNDLE_MANIFEST_VERSION = "Bundle-ManifestVersion"; private static final String BUNDLE_REQUIRED_EXECUTION_ENVIRONMENT = "Bundle-RequiredExecutionEnvironment"; private static final String ATTR_RESOLUTION = "resolution"; private static final String ATTR_VERSION = "version"; private static final String ATTR_BUNDLE_VERSION = "bundle-version"; private static final String ATTR_USE = "use"; public static BundleInfo parseJarManifest(InputStream jarStream) throws IOException, ParseException { final JarInputStream jis = new JarInputStream(jarStream); final BundleInfo parseManifest = parseManifest(jis.getManifest()); jis.close(); return parseManifest; } public static BundleInfo parseManifest(File manifestFile) throws IOException, ParseException { final FileInputStream fis = new FileInputStream(manifestFile); final BundleInfo parseManifest = parseManifest(fis); fis.close(); return parseManifest; } public static BundleInfo parseManifest(InputStream manifestStream) throws IOException, ParseException { final BundleInfo parseManifest = parseManifest(new Manifest(manifestStream)); manifestStream.close(); return parseManifest; } public static BundleInfo parseManifest(Manifest manifest) throws ParseException { Attributes mainAttributes = manifest.getMainAttributes(); String manifestVersion = mainAttributes.getValue(BUNDLE_MANIFEST_VERSION); if (manifestVersion == null) { // non OSGi manifest throw new ParseException("No " + BUNDLE_MANIFEST_VERSION + " in the manifest", 0); } String symbolicName = new ManifestHeaderValue(mainAttributes.getValue(BUNDLE_SYMBOLIC_NAME)) .getSingleValue(); if (symbolicName == null) { throw new ParseException("No " + BUNDLE_SYMBOLIC_NAME + " in the manifest", 0); } String description = new ManifestHeaderValue(mainAttributes.getValue(BUNDLE_DESCRIPTION)) .getSingleValue(); if (description == null) { description = new ManifestHeaderValue(mainAttributes.getValue(BUNDLE_DESCRIPTION)) .getSingleValue(); } String vBundle = new ManifestHeaderValue(mainAttributes.getValue(BUNDLE_VERSION)) .getSingleValue(); Version version; try { version = versionOf(vBundle); } catch (NumberFormatException e) { throw new ParseException("The " + BUNDLE_VERSION + " has an incorrect version: " + vBundle + " (" + e.getMessage() + ")", 0); } BundleInfo bundleInfo = new BundleInfo(symbolicName, version); bundleInfo.setDescription(description); List/* */environments = new ManifestHeaderValue( mainAttributes.getValue(BUNDLE_REQUIRED_EXECUTION_ENVIRONMENT)).getValues(); bundleInfo.setExecutionEnvironments(environments); parseRequirement(bundleInfo, mainAttributes, REQUIRE_BUNDLE, BundleInfo.BUNDLE_TYPE, ATTR_BUNDLE_VERSION); parseRequirement(bundleInfo, mainAttributes, IMPORT_PACKAGE, BundleInfo.PACKAGE_TYPE, ATTR_VERSION); parseRequirement(bundleInfo, mainAttributes, IMPORT_SERVICE, BundleInfo.SERVICE_TYPE, ATTR_VERSION); ManifestHeaderValue exportElements = new ManifestHeaderValue( mainAttributes.getValue(EXPORT_PACKAGE)); Iterator itExports = exportElements.getElements().iterator(); while (itExports.hasNext()) { ManifestHeaderElement exportElement = (ManifestHeaderElement) itExports.next(); String vExport = (String) exportElement.getAttributes().get(ATTR_VERSION); Version v = null; try { v = versionOf(vExport); } catch (NumberFormatException e) { throw new ParseException("The " + EXPORT_PACKAGE + " has an incorrect version: " + vExport + " (" + e.getMessage() + ")", 0); } Iterator itNames = exportElement.getValues().iterator(); while (itNames.hasNext()) { String name = (String) itNames.next(); ExportPackage export = new ExportPackage(name, v); String uses = (String) exportElement.getDirectives().get(ATTR_USE); if (uses != null) { String[] split = uses.trim().split(","); for (int i = 0; i < split.length; i++) { export.addUse(split[i].trim()); } } bundleInfo.addCapability(export); } } parseCapability(bundleInfo, mainAttributes, EXPORT_SERVICE, BundleInfo.SERVICE_TYPE); return bundleInfo; } private static void parseRequirement(BundleInfo bundleInfo, Attributes mainAttributes, String headerName, String type, String versionAttr) throws ParseException { ManifestHeaderValue elements = new ManifestHeaderValue(mainAttributes.getValue(headerName)); Iterator itElement = elements.getElements().iterator(); while (itElement.hasNext()) { ManifestHeaderElement element = (ManifestHeaderElement) itElement.next(); String resolution = (String) element.getDirectives().get(ATTR_RESOLUTION); String attVersion = (String) element.getAttributes().get(versionAttr); VersionRange version = null; try { version = versionRangeOf(attVersion); } catch (ParseException e) { throw new ParseException("The " + headerName + " has an incorrect version: " + attVersion + " (" + e.getMessage() + ")", 0); } Iterator itNames = element.getValues().iterator(); while (itNames.hasNext()) { String name = (String) itNames.next(); bundleInfo.addRequirement(new BundleRequirement(type, name, version, resolution)); } } } private static void parseCapability(BundleInfo bundleInfo, Attributes mainAttributes, String headerName, String type) throws ParseException { ManifestHeaderValue elements = new ManifestHeaderValue(mainAttributes.getValue(headerName)); Iterator itElement = elements.getElements().iterator(); while (itElement.hasNext()) { ManifestHeaderElement element = (ManifestHeaderElement) itElement.next(); String attVersion = (String) element.getAttributes().get(ATTR_VERSION); Version version = null; try { version = versionOf(attVersion); } catch (NumberFormatException e) { throw new ParseException("The " + headerName + " has an incorrect version: " + attVersion + " (" + e.getMessage() + ")", 0); } Iterator itNames = element.getValues().iterator(); while (itNames.hasNext()) { String name = (String) itNames.next(); BundleCapability export = new BundleCapability(type, name, version); bundleInfo.addCapability(export); } } } private static VersionRange versionRangeOf(String v) throws ParseException { if (v == null) { return null; } return new VersionRange(v); } private static Version versionOf(String v) throws ParseException { if (v == null) { return null; } return new Version(v); } } ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/BundleInfo.java0000644000175000017500000002125311736412724023150 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import java.net.URI; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.apache.ivy.osgi.util.Version; /** * Bundle info extracted from the bundle manifest. * */ public class BundleInfo { public static final Version DEFAULT_VERSION = new Version(1, 0, 0, null); public static final String PACKAGE_TYPE = "package"; public static final String BUNDLE_TYPE = "bundle"; public static final String SERVICE_TYPE = "service"; private String symbolicName; private String presentationName; private String id; private Version version; private Set/* */requirements = new LinkedHashSet/* */(); private Set/* */capabilities = new LinkedHashSet/* */(); private List/* */executionEnvironments = Collections.EMPTY_LIST; private String description; private String documentation; private String license; private Integer size; private URI uri; public BundleInfo(String name, Version version) { this.symbolicName = name; this.version = version; } public String toString() { StringBuffer builder = new StringBuffer(); builder.append("BundleInfo [executionEnvironments="); builder.append(executionEnvironments); builder.append(", capabilities="); builder.append(capabilities); builder.append(", requirements="); builder.append(requirements); builder.append(", symbolicName="); builder.append(symbolicName); builder.append(", version="); builder.append(version); builder.append("]"); return builder.toString(); } public String getSymbolicName() { return symbolicName; } public Version getVersion() { return version == null ? DEFAULT_VERSION : version; } public Version getRawVersion() { return version; } public void setUri(URI uri) { this.uri = uri; } public URI getUri() { return uri; } public void setId(String id) { this.id = id; } public String getId() { return id; } public void setPresentationName(String presentationName) { this.presentationName = presentationName; } public String getPresentationName() { return presentationName; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setDocumentation(String documentation) { this.documentation = documentation; } public String getDocumentation() { return documentation; } public void setLicense(String license) { this.license = license; } public String getLicense() { return license; } public void setSize(Integer size) { this.size = size; } public Integer getSize() { return size; } public void addRequirement(BundleRequirement requirement) { requirements.add(requirement); } public Set/* */getRequirements() { return requirements; } public void addCapability(BundleCapability capability) { capabilities.add(capability); } public Set/* */getCapabilities() { return capabilities; } public List/* */getExecutionEnvironments() { return executionEnvironments; } public void setExecutionEnvironments(List/* */executionEnvironment) { this.executionEnvironments = executionEnvironment; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((capabilities == null) ? 0 : capabilities.hashCode()); result = prime * result + ((requirements == null) ? 0 : requirements.hashCode()); result = prime * result + ((symbolicName == null) ? 0 : symbolicName.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); result = prime * result + ((executionEnvironments == null) ? 0 : executionEnvironments.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof BundleInfo)) { return false; } BundleInfo other = (BundleInfo) obj; if (capabilities == null) { if (other.capabilities != null) { return false; } } else if (!capabilities.equals(other.capabilities)) { return false; } if (requirements == null) { if (other.requirements != null) { return false; } } else if (!requirements.equals(other.requirements)) { return false; } if (symbolicName == null) { if (other.symbolicName != null) { return false; } } else if (!symbolicName.equals(other.symbolicName)) { return false; } if (version == null) { if (other.version != null) { return false; } } else if (!version.equals(other.version)) { return false; } if (executionEnvironments == null) { if (other.executionEnvironments != null) { return false; } } else if (!executionEnvironments.equals(other.executionEnvironments)) { return false; } return true; } public Set/* */getRequires() { Set/* */set = new LinkedHashSet/* */(); Iterator itRequirements = requirements.iterator(); while (itRequirements.hasNext()) { BundleRequirement requirement = (BundleRequirement) itRequirements.next(); if (requirement.getType().equals(BUNDLE_TYPE)) { set.add(requirement); } } return set; } public Set/* */getImports() { Set/* */set = new LinkedHashSet/* */(); Iterator itRequirements = requirements.iterator(); while (itRequirements.hasNext()) { BundleRequirement requirement = (BundleRequirement) itRequirements.next(); if (requirement.getType().equals(PACKAGE_TYPE)) { set.add(requirement); } } return set; } public Set/* */getExports() { Set/* */set = new LinkedHashSet/* */(); Iterator itCapabilities = capabilities.iterator(); while (itCapabilities.hasNext()) { BundleCapability capability = (BundleCapability) itCapabilities.next(); if (PACKAGE_TYPE.equals(capability.getType())) { set.add((ExportPackage) capability); } } return set; } public Set/* */getServices() { Set/* */set = new LinkedHashSet/* */(); Iterator itCapabilities = capabilities.iterator(); while (itCapabilities.hasNext()) { BundleCapability capability = (BundleCapability) itCapabilities.next(); if (SERVICE_TYPE.equals(capability.getType())) { set.add(capability); } } return set; } }ivy-2.3.0.orig/src/java/org/apache/ivy/osgi/core/OsgiLatestStrategy.java0000644000175000017500000000761312015527244024723 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.core; import java.text.ParseException; import java.util.Comparator; import org.apache.ivy.core.IvyContext; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.plugins.latest.ArtifactInfo; import org.apache.ivy.plugins.latest.ComparatorLatestStrategy; import org.apache.ivy.plugins.version.VersionMatcher; public class OsgiLatestStrategy extends ComparatorLatestStrategy { final class MridComparator implements Comparator/* */{ public int compare(Object o1, Object o2) { return compare((ModuleRevisionId) o1, (ModuleRevisionId) o2); } public int compare(ModuleRevisionId o1, ModuleRevisionId o2) { Version v1; Version v2; try { v1 = new Version(o1.getRevision()); v2 = new Version(o2.getRevision()); } catch (ParseException e) { throw new RuntimeException("Uncomparable versions:" + o1.getRevision() + " and " + o2.getRevision() + " (" + e.getMessage() + ")"); } return v1.compareTo(v2); } } final class ArtifactInfoComparator implements Comparator/* */{ public int compare(Object o1, Object o2) { return compare((ArtifactInfo) o1, (ArtifactInfo) o2); } public int compare(ArtifactInfo o1, ArtifactInfo o2) { String rev1 = o1.getRevision(); String rev2 = o2.getRevision(); /* * The revisions can still be not resolved, so we use the current version matcher to * know if one revision is dynamic, and in this case if it should be considered greater * or lower than the other one. Note that if the version matcher compare method returns * 0, it's because it's not possible to know which revision is greater. In this case we * consider the dynamic one to be greater, because most of the time it will then be * actually resolved and a real comparison will occur. */ VersionMatcher vmatcher = IvyContext.getContext().getSettings().getVersionMatcher(); ModuleRevisionId mrid1 = ModuleRevisionId.newInstance("", "", rev1); ModuleRevisionId mrid2 = ModuleRevisionId.newInstance("", "", rev2); if (vmatcher.isDynamic(mrid1)) { int c = vmatcher.compare(mrid1, mrid2, mridComparator); return c >= 0 ? 1 : -1; } else if (vmatcher.isDynamic(mrid2)) { int c = vmatcher.compare(mrid2, mrid1, mridComparator); return c >= 0 ? -1 : 1; } return mridComparator.compare(mrid1, mrid2); } } private final Comparator/* */mridComparator = new MridComparator(); private final Comparator/* */artifactInfoComparator = new ArtifactInfoComparator(); public OsgiLatestStrategy() { setComparator(artifactInfoComparator); setName("latest-osgi"); } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/0000755000175000017500000000000012126443423017333 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/util/HexEncoder.java0000644000175000017500000000277711736412766022253 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util; /** * Simple encoder of byte arrays into String array using only the hexadecimal alphabet */ public class HexEncoder { private static final char[] ALPHABET = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public static String encode(byte[] packet) { StringBuffer chars = new StringBuffer(16); for (int i = 0; i < packet.length; i++) { int highBits = (packet[i] & 0xF0) >> 4; int lowBits = packet[i] & 0x0F; chars.append(ALPHABET[highBits]); chars.append(ALPHABET[lowBits]); } return chars.toString(); } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/FileUtil.java0000644000175000017500000004225111736412766021733 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Stack; import java.util.StringTokenizer; import org.apache.ivy.util.url.URLHandlerRegistry; /** * Utility class used to deal with file related operations, like copy, full reading, symlink, ... */ public final class FileUtil { private FileUtil() { //Utility class } // according to tests by users, 64kB seems to be a good value for the buffer used during copy // further improvements could be obtained using NIO API private static final int BUFFER_SIZE = 64 * 1024; private static final byte[] EMPTY_BUFFER = new byte[0]; public static void symlink(File src, File dest, CopyProgressListener l, boolean overwrite) throws IOException { try { if (dest.exists()) { if (!dest.isFile()) { throw new IOException("impossible to copy: destination is not a file: " + dest); } if (!overwrite) { Message.verbose(dest + " already exists, nothing done"); return; } } if (dest.getParentFile() != null) { dest.getParentFile().mkdirs(); } Runtime runtime = Runtime.getRuntime(); Message.verbose("executing 'ln -s -f " + src.getAbsolutePath() + " " + dest.getPath() + "'"); Process process = runtime.exec(new String[] {"ln", "-s", "-f", src.getAbsolutePath(), dest.getPath()}); if (process.waitFor() != 0) { InputStream errorStream = process.getErrorStream(); InputStreamReader isr = new InputStreamReader(errorStream); BufferedReader br = new BufferedReader(isr); StringBuffer error = new StringBuffer(); String line; while ((line = br.readLine()) != null) { error.append(line); error.append('\n'); } throw new IOException("error symlinking " + src + " to " + dest + ":\n" + error); } // check if the creation of the symbolic link was successful if (!dest.exists()) { throw new IOException("error symlinking: " + dest + " doesn't exists"); } // check if the result is a true symbolic link if (dest.getAbsolutePath().equals(dest.getCanonicalPath())) { dest.delete(); // just make sure we do delete the invalid symlink! throw new IOException("error symlinking: " + dest + " isn't a symlink"); } } catch (IOException x) { Message.verbose("symlink failed; falling back to copy"); StringWriter buffer = new StringWriter(); x.printStackTrace(new PrintWriter(buffer)); Message.debug(buffer.toString()); copy(src, dest, l, overwrite); } catch (InterruptedException x) { Thread.currentThread().interrupt(); } } public static boolean copy(File src, File dest, CopyProgressListener l) throws IOException { return copy(src, dest, l, false); } public static boolean copy(File src, File dest, CopyProgressListener l, boolean overwrite) throws IOException { if (dest.exists()) { if (!dest.isFile()) { throw new IOException("impossible to copy: destination is not a file: " + dest); } if (overwrite) { if (!dest.canWrite()) { dest.delete(); } // if dest is writable, the copy will overwrite it without requiring a delete } else { Message.verbose(dest + " already exists, nothing done"); return false; } } copy(new FileInputStream(src), dest, l); long srcLen = src.length(); long destLen = dest.length(); if (srcLen != destLen) { dest.delete(); throw new IOException("size of source file " + src.toString() + "(" + srcLen + ") differs from size of dest file " + dest.toString() + "(" + destLen + ") - please retry"); } dest.setLastModified(src.lastModified()); return true; } public static void copy(URL src, File dest, CopyProgressListener l) throws IOException { URLHandlerRegistry.getDefault().download(src, dest, l); } public static void copy(File src, URL dest, CopyProgressListener l) throws IOException { URLHandlerRegistry.getDefault().upload(src, dest, l); } public static void copy(InputStream src, File dest, CopyProgressListener l) throws IOException { if (dest.getParentFile() != null) { dest.getParentFile().mkdirs(); } copy(src, new FileOutputStream(dest), l); } public static void copy(InputStream src, OutputStream dest, CopyProgressListener l) throws IOException { copy(src, dest, l, true); } public static void copy(InputStream src, OutputStream dest, CopyProgressListener l, boolean autoClose) throws IOException { CopyProgressEvent evt = null; if (l != null) { evt = new CopyProgressEvent(); } try { byte[] buffer = new byte[BUFFER_SIZE]; int c; long total = 0; if (l != null) { l.start(evt); } while ((c = src.read(buffer)) != -1) { if (Thread.currentThread().isInterrupted()) { throw new IOException("transfer interrupted"); } dest.write(buffer, 0, c); total += c; if (l != null) { l.progress(evt.update(buffer, c, total)); } } if (l != null) { evt.update(EMPTY_BUFFER, 0, total); } try { dest.flush(); } catch (IOException ex) { // ignore } // close the streams if (autoClose) { src.close(); dest.close(); } } finally { if (autoClose) { try { src.close(); } catch (IOException ex) { // ignore } try { dest.close(); } catch (IOException ex) { // ignore } } } if (l != null) { l.end(evt); } } /** * Reads the whole BufferedReader line by line, using \n as line separator for each line. *

* Note that this method will add a final \n to the last line even though there is no new line * character at the end of last line in the original reader. *

*

* The BufferedReader is closed when this method returns. *

* * @param in * the {@link BufferedReader} to read from * @return a String with the whole content read from the {@link BufferedReader} * @throws IOException * if an IO problems occur during reading */ public static String readEntirely(BufferedReader in) throws IOException { try { StringBuffer buf = new StringBuffer(); String line = in.readLine(); while (line != null) { buf.append(line + "\n"); line = in.readLine(); } return buf.toString(); } finally { in.close(); } } /** * Reads the entire content of the file and returns it as a String. * * @param f * the file to read from * @return a String with the file content * @throws IOException * if an IO problems occurs during reading */ public static String readEntirely(File f) throws IOException { return readEntirely(new FileInputStream(f)); } /** * Reads the entire content of the {@link InputStream} and returns it as a String. *

* The input stream is closed when this method returns. *

* * @param is * the {@link InputStream} to read from * @return a String with the input stream content * @throws IOException * if an IO problems occurs during reading */ public static String readEntirely(InputStream is) throws IOException { try { StringBuffer sb = new StringBuffer(); byte[] buffer = new byte[BUFFER_SIZE]; int c; while ((c = is.read(buffer)) != -1) { sb.append(new String(buffer, 0, c)); } return sb.toString(); } finally { is.close(); } } public static String concat(String dir, String file) { return dir + "/" + file; } /** * Recursively delete file * * @param file * the file to delete * @return true if the deletion completed successfully (ie if the file does not exist on the * filesystem after this call), false if a deletion was not performed successfully. */ public static boolean forceDelete(File file) { if (!file.exists()) { return true; } if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (!forceDelete(files[i])) { return false; } } } } return file.delete(); } /** * Returns a list of Files composed of all directories being parent of file and child of root + * file and root themselves. Example: getPathFiles(new File("test"), new * File("test/dir1/dir2/file.txt")) => {new File("test/dir1"), new File("test/dir1/dir2"), new * File("test/dir1/dir2/file.txt") } Note that if root is not an ancester of file, or if root is * null, all directories from the file system root will be returned. */ public static List getPathFiles(File root, File file) { List ret = new ArrayList(); while (file != null && !file.getAbsolutePath().equals(root.getAbsolutePath())) { ret.add(file); file = file.getParentFile(); } if (root != null) { ret.add(root); } Collections.reverse(ret); return ret; } /** * Returns a collection of all Files being contained in the given directory, recursively, * including directories. * * @param dir The directory from which all files, including files in subdirectory) * are extracted. * @param ignore a Collection of filenames which must be excluded from listing * @return A collectoin containing all the files of the given directory and it's * subdirectories. */ public static Collection listAll(File dir, Collection ignore) { return listAll(dir, new ArrayList(), ignore); } private static Collection listAll(File file, Collection list, Collection ignore) { if (ignore.contains(file.getName())) { return list; } if (file.exists()) { list.add(file); } if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { listAll(files[i], list, ignore); } } return list; } public static File resolveFile(File file, String filename) { File result = new File(filename); if (!result.isAbsolute()) { result = new File(file, filename); } return normalize(result.getPath()); } ////////////////////////////////////////////// // The following code comes from Ant FileUtils ////////////////////////////////////////////// /** * "Normalize" the given absolute path. * *

This includes: *

    *
  • Uppercase the drive letter if there is one.
  • *
  • Remove redundant slashes after the drive spec.
  • *
  • Resolve all ./, .\, ../ and ..\ sequences.
  • *
  • DOS style paths that start with a drive letter will have * \ as the separator.
  • *
* Unlike {@link File#getCanonicalPath()} this method * specifically does not resolve symbolic links. * * @param path the path to be normalized. * @return the normalized version of the path. * * @throws java.lang.NullPointerException if path is null. */ public static File normalize(final String path) { Stack s = new Stack(); String[] dissect = dissect(path); s.push(dissect[0]); StringTokenizer tok = new StringTokenizer(dissect[1], File.separator); while (tok.hasMoreTokens()) { String thisToken = tok.nextToken(); if (".".equals(thisToken)) { continue; } if ("..".equals(thisToken)) { if (s.size() < 2) { // Cannot resolve it, so skip it. return new File(path); } s.pop(); } else { // plain component s.push(thisToken); } } StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.size(); i++) { if (i > 1) { // not before the filesystem root and not after it, since root // already contains one sb.append(File.separatorChar); } sb.append(s.elementAt(i)); } return new File(sb.toString()); } /** * Dissect the specified absolute path. * @param path the path to dissect. * @return String[] {root, remaining path}. * @throws java.lang.NullPointerException if path is null. * @since Ant 1.7 */ private static String[] dissect(String path) { char sep = File.separatorChar; path = path.replace('/', sep).replace('\\', sep); // // make sure we are dealing with an absolute path // if (!isAbsolutePath(path)) { // throw new BuildException(path + " is not an absolute path"); // } String root = null; int colon = path.indexOf(':'); if (colon > 0) { // && (ON_DOS || ON_NETWARE)) { int next = colon + 1; root = path.substring(0, next); char[] ca = path.toCharArray(); root += sep; //remove the initial separator; the root has it. next = (ca[next] == sep) ? next + 1 : next; StringBuffer sbPath = new StringBuffer(); // Eliminate consecutive slashes after the drive spec: for (int i = next; i < ca.length; i++) { if (ca[i] != sep || ca[i - 1] != sep) { sbPath.append(ca[i]); } } path = sbPath.toString(); } else if (path.length() > 1 && path.charAt(1) == sep) { // UNC drive int nextsep = path.indexOf(sep, 2); nextsep = path.indexOf(sep, nextsep + 1); root = (nextsep > 2) ? path.substring(0, nextsep + 1) : path; path = path.substring(root.length()); } else { root = File.separator; path = path.substring(1); } return new String[] {root, path}; } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/Checks.java0000644000175000017500000000426611736412766021422 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util; import java.io.File; /** * Utility class used to perform some checks. */ public final class Checks { private Checks() { } /** * Checks that an object is not null, and throw an exception if the object is null. * * @param o * the object to check * @param objectName * the name of the object to check. This name will be used in the exception message. * @throws IllegalArgumentException * if the object is null */ public static void checkNotNull(Object o, String objectName) { if (o == null) { throw new IllegalArgumentException(objectName + " must not be null"); } } public static File checkAbsolute(File f, String fileName) { checkNotNull(f, fileName); if (!f.isAbsolute()) { throw new IllegalArgumentException(fileName + " must be absolute: " + f.getPath()); } return FileUtil.normalize(f.getPath()); } public static File checkAbsolute(String path, String fileName) { checkNotNull(path, fileName); File f = new File(path); if (!f.isAbsolute()) { throw new IllegalArgumentException(fileName + " must be absolute: " + path); } return FileUtil.normalize(f.getPath()); } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/XMLHelper.java0000644000175000017500000002101212042067004021764 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.ivy.plugins.repository.Resource; import org.apache.ivy.util.url.URLHandlerRegistry; import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.DefaultHandler; public abstract class XMLHelper { static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; static final String XML_NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes"; static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; private static boolean canUseSchemaValidation = true; private static SAXParser newSAXParser(URL schema, InputStream schemaStream) throws ParserConfigurationException, SAXException { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setNamespaceAware(true); parserFactory.setValidating(canUseSchemaValidation && (schema != null)); SAXParser parser = parserFactory.newSAXParser(); if (canUseSchemaValidation && (schema != null)) { try { parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); parser.setProperty(JAXP_SCHEMA_SOURCE, schemaStream); } catch (SAXNotRecognizedException ex) { System.err.println( "WARNING: problem while setting JAXP validating property on SAXParser... " + "XML validation will not be done: " + ex.getMessage()); canUseSchemaValidation = false; parserFactory.setValidating(false); parser = parserFactory.newSAXParser(); } } parser.getXMLReader().setFeature(XML_NAMESPACE_PREFIXES, true); return parser; } /** * Convert an URL to a valid systemId according to RFC 2396. */ public static String toSystemId(URL url) { try { return new URI(url.toExternalForm()).toASCIIString(); } catch (URISyntaxException e) { return url.toExternalForm(); } } // IMPORTANT: validation errors are only notified to the given handler, and // do not cause exception // implement warning error and fatalError methods in handler to be informed // of validation errors public static void parse(URL xmlURL, URL schema, DefaultHandler handler) throws SAXException, IOException, ParserConfigurationException { parse(xmlURL, schema, handler, null); } public static void parse( URL xmlURL, URL schema, DefaultHandler handler, LexicalHandler lHandler) throws SAXException, IOException, ParserConfigurationException { InputStream xmlStream = URLHandlerRegistry.getDefault().openStream(xmlURL); try { InputSource inSrc = new InputSource(xmlStream); inSrc.setSystemId(toSystemId(xmlURL)); parse(inSrc, schema, handler, lHandler); } finally { try { xmlStream.close(); } catch (IOException e) { // ignored } } } public static void parse( InputStream xmlStream, URL schema, DefaultHandler handler, LexicalHandler lHandler) throws SAXException, IOException, ParserConfigurationException { parse(new InputSource(xmlStream), schema, handler, lHandler); } public static void parse( InputSource xmlStream, URL schema, DefaultHandler handler, LexicalHandler lHandler) throws SAXException, IOException, ParserConfigurationException { InputStream schemaStream = null; try { if (schema != null) { schemaStream = URLHandlerRegistry.getDefault().openStream(schema); } SAXParser parser = XMLHelper.newSAXParser(schema, schemaStream); if (lHandler != null) { try { parser.setProperty("http://xml.org/sax/properties/lexical-handler", lHandler); } catch (SAXException ex) { System.err.println( "WARNING: problem while setting the lexical handler property on SAXParser: " + ex.getMessage()); // continue without the lexical handler } } parser.parse(xmlStream, handler); } finally { if (schemaStream != null) { try { schemaStream.close(); } catch (IOException ex) { // ignored } } } } public static boolean canUseSchemaValidation() { return canUseSchemaValidation; } /** * Escapes invalid XML characters in the given character data using XML entities. * For the moment, only the following characters are being escaped: (<), (&), (') * and ("). * * Remark: we don't escape the (>) character to keep the readability of the * configuration mapping! The XML spec only requires that the (&) and (<) * characters are being escaped inside character data. * * @param text the character data to escape * @return the escaped character data */ public static String escape(String text) { if (text == null) { return null; } StringBuffer result = new StringBuffer(text.length()); char[] chars = text.toCharArray(); for (int i = 0; i < chars.length; i++) { switch (chars[i]) { case '&': result.append("&"); break; case '<': result.append("<"); break; case '\'': result.append("'"); break; case '\"': result.append("""); break; default: result.append(chars[i]); } } return result.toString(); } public static Document parseToDom(InputSource source, EntityResolver entityResolver) throws IOException, SAXException { DocumentBuilder docBuilder = getDocBuilder(entityResolver); return docBuilder.parse(source); } public static DocumentBuilder getDocBuilder(EntityResolver entityResolver) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder docBuilder = factory.newDocumentBuilder(); if (entityResolver != null) { docBuilder.setEntityResolver(entityResolver); } return docBuilder; } catch (ParserConfigurationException e) { throw new RuntimeException(e); } } private XMLHelper() { } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/ConfigurationUtils.java0000644000175000017500000000724611736412766024053 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import org.apache.ivy.core.module.descriptor.Configuration; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.descriptor.Configuration.Visibility; /** * Class containing several utility methods for working with configurations. */ public final class ConfigurationUtils { /** * Private constructor to avoid instantiation of this class. */ private ConfigurationUtils() { } /** * Replace the wildcards in the given configuration array, by the name of the given * ModuleDescriptor * * The supported wildcards are: *
    *
  • * : all configurations
  • *
  • *(public) : all public configurations
  • *
  • *(private) : all private configurations
  • *
* If the given array of configurations is null, all configurations * from the given module descriptor are returned, including if this array is empty. * * @param confs * the configurations, can contain wildcards * @param md * the configurations where the wildcards are replaced * @return */ public static String[] replaceWildcards(String[] confs, ModuleDescriptor md) { if (confs == null) { return md.getConfigurationsNames(); } Set result = new LinkedHashSet(); Set excluded = new LinkedHashSet(); for (int i = 0; i < confs.length; i++) { if ("*".equals(confs[i])) { result.addAll(Arrays.asList(md.getConfigurationsNames())); } else if ("*(public)".equals(confs[i])) { Configuration[] all = md.getConfigurations(); for (int j = 0; j < all.length; j++) { if (all[j].getVisibility().equals(Visibility.PUBLIC)) { result.add(all[j].getName()); } } } else if ("*(private)".equals(confs[i])) { Configuration[] all = md.getConfigurations(); for (int j = 0; j < all.length; j++) { if (all[j].getVisibility().equals(Visibility.PRIVATE)) { result.add(all[j].getName()); } } } else if (confs[i].startsWith("!")) { excluded.add(confs[i].substring(1)); } else { result.add(confs[i]); } } for (Iterator iter = excluded.iterator(); iter.hasNext();) { result.remove(iter.next()); } return (String[]) result.toArray(new String[result.size()]); } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/StringUtils.java0000644000175000017500000001702411736412766022505 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.util.Locale; /** * Convenient class used only for uncapitalization Usually use commons lang but here we do not want * to have such a dependency for only one feature */ public final class StringUtils { private StringUtils() { //Utility class } public static String uncapitalize(String string) { if (string == null || string.length() == 0) { return string; } if (string.length() == 1) { return string.toLowerCase(Locale.US); } return string.substring(0, 1).toLowerCase(Locale.US) + string.substring(1); } /** * Returns the error message associated with the given Throwable. The error message returned * will try to be as precise as possible, handling cases where e.getMessage() is not meaningful, * like {@link NullPointerException} for instance. * * @param t * the throwable to get the error message from * @return the error message of the given exception */ public static String getErrorMessage(Throwable t) { if (t == null) { return ""; } if (t instanceof InvocationTargetException) { InvocationTargetException ex = (InvocationTargetException) t; t = ex.getTargetException(); } String errMsg = t instanceof RuntimeException ? t.getMessage() : t.toString(); if (errMsg == null || errMsg.length() == 0 || "null".equals(errMsg)) { errMsg = t.getClass().getName() + " at " + t.getStackTrace()[0].toString(); } return errMsg; } /** * Returns the exception stack trace as a String. * * @param e * the exception to get the stack trace from. * @return the exception stack trace */ public static String getStackTrace(Exception e) { if (e == null) { return ""; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter printWriter = new PrintWriter(baos); e.printStackTrace(printWriter); printWriter.flush(); String stackTrace = new String(baos.toByteArray()); printWriter.close(); return stackTrace; } /** * Joins the given object array in one string, each separated by the given separator. * * Example: *
     * join(new String[] {"one", "two", "three"}, ", ") -> "one, two, three"
     * 
* * @param objs The array of objects (toString() is used). * @param sep The separator to use. * @return The concatinated string. */ public static String join(Object[] objs, String sep) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < objs.length; i++) { buf.append(objs[i]).append(sep); } if (objs.length > 0) { buf.setLength(buf.length() - sep.length()); // delete sep } return buf.toString(); } // basic string codec (same algo as CVS passfile, inspired by ant CVSPass class /** Array contain char conversion data */ private static final char[] SHIFTS = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 114, 120, 53, 79, 96, 109, 72, 108, 70, 64, 76, 67, 116, 74, 68, 87, 111, 52, 75, 119, 49, 34, 82, 81, 95, 65, 112, 86, 118, 110, 122, 105, 41, 57, 83, 43, 46, 102, 40, 89, 38, 103, 45, 50, 42, 123, 91, 35, 125, 55, 54, 66, 124, 126, 59, 47, 92, 71, 115, 78, 88, 107, 106, 56, 36, 121, 117, 104, 101, 100, 69, 73, 99, 63, 94, 93, 39, 37, 61, 48, 58, 113, 32, 90, 44, 98, 60, 51, 33, 97, 62, 77, 84, 80, 85, 223, 225, 216, 187, 166, 229, 189, 222, 188, 141, 249, 148, 200, 184, 136, 248, 190, 199, 170, 181, 204, 138, 232, 218, 183, 255, 234, 220, 247, 213, 203, 226, 193, 174, 172, 228, 252, 217, 201, 131, 230, 197, 211, 145, 238, 161, 179, 160, 212, 207, 221, 254, 173, 202, 146, 224, 151, 140, 196, 205, 130, 135, 133, 143, 246, 192, 159, 244, 239, 185, 168, 215, 144, 139, 165, 180, 157, 147, 186, 214, 176, 227, 231, 219, 169, 175, 156, 206, 198, 129, 164, 150, 210, 154, 177, 134, 127, 182, 128, 158, 208, 162, 132, 167, 209, 149, 241, 153, 251, 237, 236, 171, 195, 243, 233, 253, 240, 194, 250, 191, 155, 142, 137, 245, 235, 163, 242, 178, 152}; /** * Encrypt the given string in a way which anybody having access to this method algorithm can * easily decrypt. This is useful only to avoid clear string storage in a file for example, but * shouldn't be considered as a real mean of security. This only works with simple characters * (char < 256). * * @param str * the string to encrypt * @return the encrypted version of the string */ public static final String encrypt(String str) { if (str == null) { return null; } StringBuffer buf = new StringBuffer(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= SHIFTS.length) { throw new IllegalArgumentException( "encrypt method can only be used with simple characters. '" + c + "' not allowed"); } buf.append(SHIFTS[c]); } return buf.toString(); } /** * Decrypts a string encrypted with encrypt. * * @param str * the encrypted string to decrypt * @return The decrypted string. */ public static final String decrypt(String str) { if (str == null) { return null; } StringBuffer buf = new StringBuffer(); for (int i = 0; i < str.length(); i++) { buf.append(decrypt(str.charAt(i))); } return buf.toString(); } private static char decrypt(char c) { for (char i = 0; i < SHIFTS.length; i++) { if (SHIFTS[i] == c) { return i; } } throw new IllegalArgumentException("Impossible to decrypt '" + c + "'. Unhandled character."); } public static String repeat(String str, int count) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < count; i++) { sb.append(str); } return sb.toString(); } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/HostUtil.java0000644000175000017500000000342211736412766021766 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util; import java.net.InetAddress; import java.net.UnknownHostException; /** * This class contains basic helper methods for the Host. * */ public final class HostUtil { private static String localHostName = null; /** * This default constructor is to hide this class from initialization through other classes. */ private HostUtil() { } /** * This method returns the name of the current Host, if this name cannot be determined, * localhost will be returned. * * @return The name of the current "local" Host. */ public static String getLocalHostName() { if (localHostName == null) { try { localHostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { localHostName = "localhost"; } } return localHostName; } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/Configurator.java0000644000175000017500000007014211736412766022660 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Stack; import org.apache.ivy.core.IvyPatternHelper; /** * Ant 1.6.1 like Configurator *

* This configurator is used to configure elements (initialised with * setRoot) using the behaviour defined by ant for its tasks. *

* Example (based on Ant Example): *

 * Configurator conf = new Configurator(); 
 * conf.typeDef("buildpath", "Sample$BuildPath");
 * conf.typeDef("xinterface", "Sample$XInterface"); 
 * Sample.MyFileSelector mfs = new Sample.MyFileSelector(); 
 * conf.setRoot(mfs); 
 * conf.startCreateChild("buildpath");
 * conf.setAttribute("path", "."); 
 * conf.setAttribute("url", "abc");
 * conf.startCreateChild("xinterface"); 
 * conf.setAttribute("count", "4"); 
 * conf.endCreateChild(); // xinterface 
 * conf.endCreateChild(); // buildpath
 * 
*/ public class Configurator { public static class Macro { private MacroDef macrodef; private Map attValues = new HashMap(); private Map macroRecords = new HashMap(); public Macro(MacroDef def) { macrodef = def; } public void defineAttribute(String attributeName, String value) { if (macrodef.getAttribute(attributeName) == null) { throw new IllegalArgumentException("undeclared attribute " + attributeName + " on macro " + macrodef.getName()); } attValues.put(attributeName, value); } public MacroRecord recordCreateChild(String name) { MacroRecord macroRecord = new MacroRecord(name); List records = (List) macroRecords.get(name); if (records == null) { records = new ArrayList(); macroRecords.put(name, records); } records.add(macroRecord); return macroRecord; } public Object play(Configurator conf) { return macrodef.play(conf, attValues, macroRecords); } } public static class Attribute { private String name; private String defaultValue; public String getDefault() { return defaultValue; } public void setDefault(String default1) { defaultValue = default1; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static class Element { private String name; private boolean optional = false; public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isOptional() { return optional; } public void setOptional(boolean optional) { this.optional = optional; } } public static class MacroRecord { private String name; private Map attributes = new LinkedHashMap(); private List children = new ArrayList(); private Object object; public MacroRecord(String name) { this.name = name; } public String getName() { return name; } public void recordAttribute(String name, String value) { attributes.put(name, value); } public MacroRecord recordChild(String name) { MacroRecord child = new MacroRecord(name); children.add(child); return child; } public MacroRecord recordChild(String name, Object object) { MacroRecord child = recordChild(name); child.object = object; return child; } public Map getAttributes() { return attributes; } public List getChildren() { return children; } public Object getObject() { return object; } } public static class MacroDef { private String name; private Map attributes = new HashMap(); private Map elements = new HashMap(); private MacroRecord macroRecord; public MacroDef(String macroName) { name = macroName; } public Attribute getAttribute(String attributeName) { return (Attribute) attributes.get(attributeName); } public Object play(Configurator conf, Map attValues, Map macroRecords) { for (Iterator iter = attributes.values().iterator(); iter.hasNext();) { Attribute att = (Attribute) iter.next(); String val = (String) attValues.get(att.getName()); if (val == null) { if (att.getDefault() == null) { throw new IllegalArgumentException("attribute " + att.getName() + " is required in " + getName()); } else { attValues.put(att.getName(), att.getDefault()); } } } return play(conf, macroRecord, attValues, macroRecords); } private Object play(Configurator conf, MacroRecord macroRecord, Map attValues, Map childrenRecords) { if (macroRecord.getObject() != null) { // this is a recorded reference, we can add the referenced object directly conf.addChild(macroRecord.getName(), macroRecord.getObject()); conf.endCreateChild(); return macroRecord.getObject(); } conf.startCreateChild(macroRecord.getName()); Map attributes = macroRecord.getAttributes(); for (Iterator iter = attributes.keySet().iterator(); iter.hasNext();) { String attName = (String) iter.next(); String attValue = replaceParam((String) attributes.get(attName), attValues); conf.setAttribute(attName, attValue); } for (Iterator iter = macroRecord.getChildren().iterator(); iter.hasNext();) { MacroRecord child = (MacroRecord) iter.next(); Element elt = (Element) elements.get(child.getName()); if (elt != null) { List elements = (List) childrenRecords.get(child.getName()); if (elements != null) { for (Iterator iterator = elements.iterator(); iterator.hasNext();) { MacroRecord element = (MacroRecord) iterator.next(); for (Iterator it2 = element.getChildren().iterator(); it2.hasNext();) { MacroRecord r = (MacroRecord) it2.next(); play(conf, r, attValues, Collections.EMPTY_MAP); } } } else if (!elt.isOptional()) { throw new IllegalArgumentException( "non optional element is not specified: " + elt.getName() + " in macro " + getName()); } continue; } play(conf, child, attValues, childrenRecords); } return conf.endCreateChild(); } private String replaceParam(String string, Map attValues) { return IvyPatternHelper.substituteParams(string, attValues); } public String getName() { return name; } public void addConfiguredAttribute(Attribute att) { attributes.put(att.getName(), att); } public void addConfiguredElement(Element elt) { elements.put(elt.getName(), elt); } public Macro createMacro() { return new Macro(this); } public void addAttribute(String attName, String attDefaultValue) { Attribute att = new Attribute(); att.setName(attName); att.setDefault(attDefaultValue); addConfiguredAttribute(att); } public void addElement(String elementName, boolean optional) { Element elt = new Element(); elt.setName(elementName); elt.setOptional(optional); addConfiguredElement(elt); } public MacroRecord recordCreateChild(String name) { macroRecord = new MacroRecord(name); return macroRecord; } } private static class ObjectDescriptor { private Object obj; private String objName; private Map createMethods = new HashMap(); private Map addMethods = new HashMap(); private Map addConfiguredMethods = new HashMap(); private Map setMethods = new HashMap(); private Map typeAddMethods = new HashMap(); private Map typeAddConfiguredMethods = new HashMap(); public ObjectDescriptor(Object object, String objName) { obj = object; this.objName = objName; Method[] methods = object.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (m.getName().startsWith("create") && m.getParameterTypes().length == 0 && !Void.TYPE.equals(m.getReturnType())) { String name = StringUtils .uncapitalize(m.getName().substring("create".length())); if (name.length() == 0) { continue; } addCreateMethod(name, m); } else if (m.getName().startsWith("addConfigured") && m.getParameterTypes().length == 1 && Void.TYPE.equals(m.getReturnType())) { String name = StringUtils.uncapitalize(m.getName().substring( "addConfigured".length())); if (name.length() == 0) { addAddConfiguredMethod(m); } addAddConfiguredMethod(name, m); } else if (m.getName().startsWith("add") && !m.getName().startsWith("addConfigured") && m.getParameterTypes().length == 1 && Void.TYPE.equals(m.getReturnType())) { String name = StringUtils.uncapitalize(m.getName().substring("add".length())); if (name.length() == 0) { addAddMethod(m); } addAddMethod(name, m); } else if (m.getName().startsWith("set") && m.getParameterTypes().length == 1 && Void.TYPE.equals(m.getReturnType())) { String name = StringUtils.uncapitalize(m.getName().substring("set".length())); if (name.length() == 0) { continue; } addSetMethod(name, m); } } } public void addCreateMethod(String name, Method m) { createMethods.put(name, m); } public void addAddMethod(String name, Method m) { addMethods.put(name, m); } public void addAddConfiguredMethod(String name, Method m) { addConfiguredMethods.put(name, m); } private void addAddMethod(Method m) { typeAddMethods.put(m.getParameterTypes()[0], m); } private void addAddConfiguredMethod(Method m) { typeAddConfiguredMethods.put(m.getParameterTypes()[0], m); } public void addSetMethod(String name, Method m) { Method current = (Method) setMethods.get(name); if (current != null && current.getParameterTypes()[0] == String.class) { // setter methods with String attribute take precedence return; } setMethods.put(name, m); } public Object getObject() { return obj; } public Method getCreateMethod(String name) { return (Method) createMethods.get(name); } public Method getAddMethod(String name) { return (Method) addMethods.get(name); } public Method getAddConfiguredMethod(String name) { return (Method) addConfiguredMethods.get(name); } public Method getAddMethod(Class type) { return getTypeMatchingMethod(type, typeAddMethods); } public Method getAddConfiguredMethod(Class type) { return getTypeMatchingMethod(type, typeAddConfiguredMethods); } private Method getTypeMatchingMethod(Class type, Map typeMethods) { Method m = (Method) typeMethods.get(type); if (m != null) { return m; } for (Iterator iter = typeMethods.keySet().iterator(); iter.hasNext();) { Class clss = (Class) iter.next(); if (clss.isAssignableFrom(type)) { return (Method) typeMethods.get(clss); } } return null; } public Method getSetMethod(String name) { return (Method) setMethods.get(name); } public String getObjectName() { return objName; } } private FileResolver fileResolver = FileResolver.DEFAULT; private Map typedefs = new HashMap(); private Map macrodefs = new HashMap(); // stack in which the top is current configured object descriptor private Stack objectStack = new Stack(); private static final List TRUE_VALUES = Arrays.asList(new String[] {"true", "yes", "on"}); public void typeDef(String name, String className) throws ClassNotFoundException { typeDef(name, Class.forName(className)); } public void typeDef(String name, Class clazz) { typedefs.put(name, clazz); } public void setRoot(Object root) { if (root == null) { throw new NullPointerException(); } objectStack.clear(); setCurrent(root, null); } public void clear() { objectStack.clear(); } private void setCurrent(Object object, String name) { objectStack.push(new ObjectDescriptor(object, name)); } public Object startCreateChild(String name) { if (objectStack.isEmpty()) { throw new IllegalStateException("set root before creating child"); } ObjectDescriptor parentOD = (ObjectDescriptor) objectStack.peek(); Object parent = parentOD.getObject(); if (parent instanceof MacroDef) { if (!"attribute".equals(name) && !"element".equals(name)) { MacroRecord record = ((MacroDef) parent).recordCreateChild(name); setCurrent(record, name); return record; } } if (parent instanceof Macro) { MacroRecord record = ((Macro) parent).recordCreateChild(name); setCurrent(record, name); return record; } if (parent instanceof MacroRecord) { MacroRecord record = ((MacroRecord) parent).recordChild(name); setCurrent(record, name); return record; } Object child = null; MacroDef macrodef = (MacroDef) macrodefs.get(name); if (macrodef != null) { Macro macro = macrodef.createMacro(); setCurrent(macro, name); return macro; } Class childClass = (Class) typedefs.get(name); Method addChild = null; try { if (childClass != null) { return addChild(parentOD, childClass, name, null); } else { addChild = parentOD.getCreateMethod(name); if (addChild != null) { child = addChild.invoke(parent, new Object[0]); setCurrent(child, name); return child; } addChild = parentOD.getAddMethod(name); if (addChild != null) { childClass = addChild.getParameterTypes()[0]; child = childClass.newInstance(); addChild.invoke(parent, new Object[] {child}); setCurrent(child, name); return child; } addChild = parentOD.getAddConfiguredMethod(name); if (addChild != null) { childClass = addChild.getParameterTypes()[0]; if (Map.class == childClass) { child = new HashMap(); } else { child = childClass.newInstance(); } setCurrent(child, name); return child; } } } catch (InstantiationException ex) { throw new IllegalArgumentException("no default constructor on " + childClass + " for adding " + name + " on " + parent.getClass()); } catch (Exception ex) { IllegalArgumentException iae = new IllegalArgumentException("bad method found for " + name + " on " + parent.getClass()); iae.initCause(ex); throw iae; } throw new IllegalArgumentException("no appropriate method found for adding " + name + " on " + parent.getClass()); } public void addChild(String name, Object child) { if (objectStack.isEmpty()) { throw new IllegalStateException("set root before creating child"); } ObjectDescriptor parentOD = (ObjectDescriptor) objectStack.peek(); try { addChild(parentOD, child.getClass(), name, child); } catch (InstantiationException ex) { throw new IllegalArgumentException("no default constructor on " + child.getClass() + " for adding " + name + " on " + parentOD.getObject().getClass()); } catch (Exception ex) { IllegalArgumentException iae = new IllegalArgumentException("bad method found for " + name + " on " + parentOD.getObject().getClass()); iae.initCause(ex); throw iae; } } private Object addChild(ObjectDescriptor parentOD, Class childClass, String name, Object child) throws InstantiationException, IllegalAccessException, InvocationTargetException { Object parent = parentOD.getObject(); if (parent instanceof MacroRecord) { MacroRecord record = (MacroRecord) parent; MacroRecord recordChild = record.recordChild(name, child); setCurrent(recordChild, name); return recordChild; } Method addChild = parentOD.getAddMethod(childClass); if (addChild != null) { if (child == null) { child = childClass.newInstance(); } addChild.invoke(parent, new Object[] {child}); setCurrent(child, name); return child; } addChild = parentOD.getAddConfiguredMethod(childClass); if (addChild != null) { if (child == null) { if (Map.class == childClass) { child = new HashMap(); } else { child = childClass.newInstance(); } } setCurrent(child, name); return child; } throw new IllegalArgumentException("no appropriate method found for adding " + name + " on " + parent.getClass()); } public boolean isTopLevelMacroRecord() { if (objectStack.isEmpty()) { return false; } ObjectDescriptor od = (ObjectDescriptor) objectStack.peek(); return (od.getObject() instanceof MacroDef); } public void setAttribute(String attributeName, String value) { if (objectStack.isEmpty()) { throw new IllegalStateException("set root before setting attribute"); } ObjectDescriptor od = (ObjectDescriptor) objectStack.peek(); if (od.getObject() instanceof Macro) { ((Macro) od.getObject()).defineAttribute(attributeName, value); return; } if (od.getObject() instanceof MacroRecord) { ((MacroRecord) od.getObject()).recordAttribute(attributeName, value); return; } Method m = od.getSetMethod(attributeName); if (m == null) { if (od.getObject() instanceof Map) { ((Map) od.getObject()).put(attributeName, value); return; } throw new IllegalArgumentException("no set method found for " + attributeName + " on " + od.getObject().getClass()); } Object convertedValue = null; Class paramClass = m.getParameterTypes()[0]; try { if (paramClass.equals(String.class)) { convertedValue = value; } else if (paramClass.equals(Boolean.class) || paramClass.equals(boolean.class)) { convertedValue = Boolean.valueOf(TRUE_VALUES.contains(value)); } else if (paramClass.equals(Character.class) || paramClass.equals(char.class)) { convertedValue = new Character(value.length() > 0 ? value.charAt(0) : ' '); } else if (paramClass.equals(Short.class) || paramClass.equals(short.class)) { convertedValue = Short.valueOf(value); } else if (paramClass.equals(Integer.class) || paramClass.equals(int.class)) { convertedValue = Integer.valueOf(value); } else if (paramClass.equals(Long.class) || paramClass.equals(long.class)) { convertedValue = Long.valueOf(value); } else if (paramClass.equals(Class.class)) { convertedValue = Class.forName(value); } else if (paramClass.equals(File.class)) { convertedValue = fileResolver.resolveFile( value, od.getObjectName() + "." + attributeName); } else { convertedValue = paramClass.getConstructor(new Class[] {String.class}).newInstance( new Object[] {value}); } } catch (Exception ex) { IllegalArgumentException iae = new IllegalArgumentException("impossible to convert " + value + " to " + paramClass + " for setting " + attributeName + " on " + od.getObject().getClass() + ": " + ex.getMessage()); iae.initCause(ex); throw iae; } try { m.invoke(od.getObject(), new Object[] {convertedValue}); } catch (Exception ex) { IllegalArgumentException iae = new IllegalArgumentException("impossible to set " + attributeName + " to " + convertedValue + " on " + od.getObject().getClass()); iae.initCause(ex); throw iae; } } public void addText(String text) { if (objectStack.isEmpty()) { throw new IllegalStateException("set root before adding text"); } ObjectDescriptor od = (ObjectDescriptor) objectStack.peek(); try { od.getObject().getClass().getMethod("addText", new Class[] {String.class}).invoke( od.getObject(), new Object[] {text}); } catch (Exception ex) { IllegalArgumentException iae = new IllegalArgumentException( "impossible to add text on " + od.getObject().getClass()); iae.initCause(ex); throw iae; } } /** * @return the finished child */ public Object endCreateChild() { if (objectStack.isEmpty()) { throw new IllegalStateException("set root before ending child"); } ObjectDescriptor od = (ObjectDescriptor) objectStack.pop(); if (objectStack.isEmpty()) { objectStack.push(od); // back to previous state throw new IllegalStateException("cannot end root"); } if (od.getObject() instanceof Macro) { return ((Macro) od.getObject()).play(this); } ObjectDescriptor parentOD = (ObjectDescriptor) objectStack.peek(); String name = od.getObjectName(); Class childClass = (Class) typedefs.get(name); Method m = null; if (childClass != null) { m = parentOD.getAddConfiguredMethod(childClass); } else { m = parentOD.getAddConfiguredMethod(name); } try { if (m != null) { m.invoke(parentOD.getObject(), new Object[] {od.getObject()}); } return od.getObject(); } catch (Exception ex) { IllegalArgumentException iae = new IllegalArgumentException( "impossible to add configured child for " + name + " on " + parentOD.getObject().getClass() + ": " + StringUtils.getErrorMessage(ex)); iae.initCause(ex); throw iae; } } public Object getCurrent() { return objectStack.isEmpty() ? null : ((ObjectDescriptor) objectStack.peek()).getObject(); } public int getDepth() { return objectStack.size(); } public MacroDef startMacroDef(String macroName) { MacroDef macroDef = new MacroDef(macroName); setCurrent(macroDef, macroName); return macroDef; } public void addMacroAttribute(String attName, String attDefaultValue) { ((MacroDef) getCurrent()).addAttribute(attName, attDefaultValue); } public void addMacroElement(String elementName, boolean optional) { ((MacroDef) getCurrent()).addElement(elementName, optional); } public void endMacroDef() { addConfiguredMacrodef(((MacroDef) getCurrent())); objectStack.pop(); } public void addConfiguredMacrodef(MacroDef macrodef) { macrodefs.put(macrodef.getName(), macrodef); } public Class getTypeDef(String name) { return (Class) typedefs.get(name); } public FileResolver getFileResolver() { return fileResolver; } public void setFileResolver(FileResolver fileResolver) { Checks.checkNotNull(fileResolver, "fileResolver"); this.fileResolver = fileResolver; } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/EncrytedProperties.java0000644000175000017500000000473511736412766024055 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Properties; /** * An implementation of Properties which stores the values encrypted. The use is transparent from * the user point of view (use as any Properties instance), except that get, put and putAll do not * handle encryption/decryption. This means that get returns the encrypted value, while put and * putAll puts given values without encrypting them. It this thus recommended to void using them, * use setProperty and getProperty instead. */ public class EncrytedProperties extends Properties { public EncrytedProperties() { super(); } public synchronized Object setProperty(String key, String value) { return StringUtils.decrypt((String) super.setProperty(key, StringUtils.encrypt(value))); } public String getProperty(String key) { return StringUtils.decrypt(super.getProperty(key)); } public String getProperty(String key, String defaultValue) { return StringUtils.decrypt(super.getProperty(key, StringUtils.encrypt(defaultValue))); } public boolean containsValue(Object value) { return super.containsValue(StringUtils.encrypt((String) value)); } public synchronized boolean contains(Object value) { return super.contains(StringUtils.encrypt((String) value)); } public Collection values() { List ret = new ArrayList(super.values()); for (int i = 0; i < ret.size(); i++) { ret.set(i, StringUtils.decrypt((String) ret.get(i))); } return ret; } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/CopyProgressEvent.java0000644000175000017500000000331711736412766023657 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util; /** * Event reporting a stream copy progression */ public class CopyProgressEvent { private long totalReadBytes; private byte[] buffer; private int readBytes; public CopyProgressEvent() { } public CopyProgressEvent(byte[] buffer, int read, long total) { update(buffer, read, total); } public CopyProgressEvent(byte[] buffer, long total) { update(buffer, 0, total); } protected CopyProgressEvent update(byte[] buffer, int read, long total) { this.buffer = buffer; this.readBytes = read; this.totalReadBytes = total; return this; } public long getTotalReadBytes() { return totalReadBytes; } public byte[] getBuffer() { return buffer; } public int getReadBytes() { return readBytes; } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/cli/0000755000175000017500000000000012126443423020102 5ustar tonytonyivy-2.3.0.orig/src/java/org/apache/ivy/util/cli/CommandLine.java0000644000175000017500000000361411736412764023151 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util.cli; import java.util.HashMap; import java.util.Map; public class CommandLine { private Map/**/ optionValues = new HashMap(); private String[] leftOverArgs; void addOptionValues(String option, String[] values) { optionValues.put(option, values); } void setLeftOverArgs(String[] args) { leftOverArgs = args; } public boolean hasOption(String option) { return optionValues.containsKey(option); } public String getOptionValue(String option) { String[] values = getOptionValues(option); return values == null || values.length == 0 ? null : values[0]; } public String getOptionValue(String option, String defaultValue) { String value = getOptionValue(option); return value == null ? defaultValue : value; } public String[] getOptionValues(String option) { return (String[]) optionValues.get(option); } public String[] getLeftOverArgs() { return leftOverArgs; } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/cli/ParseException.java0000644000175000017500000000174511736412764023717 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util.cli; public class ParseException extends Exception { public ParseException(String reason) { super(reason); } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/cli/OptionBuilder.java0000644000175000017500000000405011736412764023535 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util.cli; import java.util.ArrayList; import java.util.List; public class OptionBuilder { private String name; private List/**/ args = new ArrayList(); private String description = ""; private boolean required = false; private boolean countArgs = true; private boolean deprecated = false; public OptionBuilder(String name) { this.name = name; } public OptionBuilder required(boolean required) { this.required = required; return this; } public OptionBuilder description(String description) { this.description = description; return this; } public OptionBuilder arg(String argName) { this.args.add(argName); return this; } public OptionBuilder countArgs(boolean countArgs) { this.countArgs = countArgs; return this; } public OptionBuilder deprecated() { this.deprecated = true; return this; } public Option create() { return new Option( name, (String[]) args.toArray(new String[args.size()]), description, required, countArgs, deprecated); } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/cli/Option.java0000644000175000017500000000722211736412764022232 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util.cli; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class Option { private String name; private String[] args; private String description; private boolean required; private boolean countArgs; private boolean deprecated; Option(String name, String[] args, String description, boolean required, boolean countArgs, boolean deprecated) { this.name = name; this.args = args; this.description = description; this.required = required; this.countArgs = countArgs; this.deprecated = deprecated; if (required) { throw new UnsupportedOperationException("required option not supported yet"); } } public String getName() { return name; } public String[] getArgs() { return args; } public String getDescription() { return description; } public boolean isRequired() { return required; } public boolean isCountArgs() { return countArgs; } public boolean isDeprecated() { return deprecated; } String[] parse(ListIterator iterator) throws ParseException { if (isCountArgs()) { String[] values = new String[args.length]; for (int i = 0; i < values.length; i++) { if (!iterator.hasNext()) { missingArgument(i); } values[i] = (String) iterator.next(); if (values[i].startsWith("-")) { missingArgument(i); } } return values; } else { List values = new ArrayList(); while (iterator.hasNext()) { String value = (String) iterator.next(); if (value.startsWith("-")) { iterator.previous(); break; } values.add(value); } return (String[]) values.toArray(new String[values.size()]); } } private void missingArgument(int i) throws ParseException { if (i == 0) { throw new ParseException("no argument for: " + name); } else { throw new ParseException("missing argument for: " + name + ". Expected: " + getArgsSpec()); } } public String getSpec() { return "-" + name + " " + getArgsSpec(); } private String getArgsSpec() { if (args.length == 0) { return ""; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < args.length; i++) { sb.append("<").append(args[i]).append("> "); } return sb.toString(); } } ivy-2.3.0.orig/src/java/org/apache/ivy/util/cli/CommandLineParser.java0000644000175000017500000001301011736412764024315 0ustar tonytony/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.util.cli; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; 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 org.apache.ivy.util.StringUtils; public class CommandLineParser { private static final int MIN_DESC_WIDTH = 40; private static final int MAX_SPEC_WIDTH = 30; private Map/**/ options = new LinkedHashMap(); private Map/*>*/ categories = new LinkedHashMap(); public CommandLineParser() { } public CommandLineParser addCategory(String category) { categories.put(category, new ArrayList()); return this; } public CommandLineParser addOption(Option option) { options.put(option.getName(), option); if (!categories.isEmpty()) { ((List) categories.values().toArray()[categories.values().size() - 1]) .add(option); } return this; } public CommandLine parse(String[] args) throws ParseException { CommandLine line = new CommandLine(); int index = args.length; ListIterator iterator = Arrays.asList(args).listIterator(); while (iterator.hasNext()) { String arg = (String) iterator.next(); if ("--".equals(arg)) { // skip this argument and stop looping index = iterator.nextIndex(); break; } if (!arg.startsWith("-")) { index = iterator.previousIndex(); break; } Option option = (Option) options.get(arg.substring(1)); if (option == null) { throw new ParseException("Unrecognized option: " + arg); } line.addOptionValues(arg.substring(1), option.parse(iterator)); } // left over args String[] leftOverArgs = new String[args.length - index]; System.arraycopy(args, index, leftOverArgs, 0, leftOverArgs.length); line.setLeftOverArgs(leftOverArgs); return line; } public void printHelp(PrintWriter pw, int width, String command, boolean showDeprecated) { pw.println("usage: " + command); // compute the largest option spec int specWidth = 0; for (Iterator iterator = options.values().iterator(); iterator.hasNext();) { Option option = (Option) iterator.next(); if (option.isDeprecated() && !showDeprecated) { continue; } specWidth = Math.min(MAX_SPEC_WIDTH, Math.max(specWidth, option.getSpec().length())); } // print options help for (Iterator iterator = categories.entrySet().iterator(); iterator.hasNext();) { Entry entry = (Entry) iterator.next(); String category = (String) entry.getKey(); pw.println("==== " + category); List/*