pax_global_header00006660000000000000000000000064135203571150014514gustar00rootroot0000000000000052 comment=4dd94716bd3ccc4d5cc0bd706de90dcb9cfb33a9 uber-pom-1.0.3/000077500000000000000000000000001352035711500132435ustar00rootroot00000000000000uber-pom-1.0.3/.gitignore000066400000000000000000000002231352035711500152300ustar00rootroot00000000000000target/ pom.xml.tag pom.xml.releaseBackup pom.xml.versionsBackup pom.xml.next release.properties dependency-reduced-pom.xml buildNumber.properties uber-pom-1.0.3/.projectKnowledge/000077500000000000000000000000001352035711500166275ustar00rootroot00000000000000uber-pom-1.0.3/.projectKnowledge/main.mmd000066400000000000000000000006501352035711500202530ustar00rootroot00000000000000Mind Map generated by NB MindMap plugin > __version__=`1.0` --- # UberPom - LINK
https://github.com/raydac/uber-pom
## Backlog > fillColor=`#99FF99` ### Feature Request: Create uber pom from root and children > fillColor=`#99FF99` - LINK
https://github.com/raydac/uber-pom/issues/1
## Issues > fillColor=`#FF9999` ## ReadMe > fillColor=`#9999FF`,leftSide=`true` - FILE
README.md
uber-pom-1.0.3/LICENSE000066400000000000000000000261361352035711500142600ustar00rootroot00000000000000 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. uber-pom-1.0.3/README.md000066400000000000000000000140561352035711500145300ustar00rootroot00000000000000[![License Apache 2.0](https://img.shields.io/badge/license-Apache%20License%202.0-green.svg)](http://www.apache.org/licenses/LICENSE-2.0) [![Java 6.0+](https://img.shields.io/badge/java-6.0%2b-green.svg)](http://www.oracle.com/technetwork/java/javase/downloads/index.html) [![Maven central](https://maven-badges.herokuapp.com/maven-central/com.igormaznitsa/uber-pom/badge.svg)](http://search.maven.org/#artifactdetails|com.igormaznitsa|uber-pom|1.0.3|jar) [![Maven 3.0.3+](https://img.shields.io/badge/maven-3.0.3%2b-green.svg)](https://maven.apache.org/) [![PayPal donation](https://img.shields.io/badge/donation-PayPal-red.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=AHWJHJFBAWGL2) [![Yandex.Money donation](https://img.shields.io/badge/donation-Я.деньги-yellow.svg)](https://money.yandex.ru/embed/small.xml?account=41001158080699&quickpay=small&yamoney-payment-type=on&button-text=01&button-size=l&button-color=orange&targets=%D0%9F%D0%BE%D0%B6%D0%B5%D1%80%D1%82%D0%B2%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5+%D0%BD%D0%B0+%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D1%8B+%D1%81+%D0%BE%D1%82%D0%BA%D1%80%D1%8B%D1%82%D1%8B%D0%BC+%D0%B8%D1%81%D1%85%D0%BE%D0%B4%D0%BD%D1%8B%D0%BC+%D0%BA%D0%BE%D0%B4%D0%BE%D0%BC&default-sum=100&successURL=) # Introduction Sometime I develop and publish maven plugins in maven central. The Most comfortable way to organize maven plugin testing is to make a pom module hierarchy because maven keeps module build in defined order, also it allows to share common options between modules. But in the case there is some issue, all child modules have link to their parent and the parent must be published also together with children. So I developed the uber-pom plugin to make some around way. # Changelog __1.0.3 (31-jul-2019)__ - refactoring __1.0.2 (04-apr-2019)__ - added `removeDependencies` with wildcard support __1.0.1 (17-apr-2016)__ - issue #3, added flag `removeSiblingDuplications` to find sibling duplications in the result uber pom XML and removing them. By default it is turned off. - issue #2, added support for system property 'upom.delete.on.exit' to override value of 'deleteOnExit' parameter __1.0__ - Initial version # How it works? The Plugin just merging all pom.xml in project module hierarchy (or only defined depth of the hierarchy) and saves the generated uber-pom into defined place, then it saves link to the file into the current maven project model. It works on the VALIDATE phase. So the result packed artifact will have the uber-pom packed into the result archive. # May be there is official solution? May be yes, I have found [pre-released maven-flatten](http://mojo.codehaus.org/flatten-maven-plugin/) which may be doing the same business but I prefer my own solutions. # How to use? ## Add the plugin in pom.xml Just add the plugin into pom.xml of the project which needs uber-pom ``` ... com.igormaznitsa uber-pom 1.0.3
parent
modules
profiles/profile/modules
true test *
upom
...
``` __NB! By default the plugin just merging pom models in hierarchy, so you should add `` section to remove the 'parent' and 'modules' from the result uber-pom. I don't make that automaticaly to keep universality.__ ## I want to remove some sections in the result Just add list of paths to the sections into `` and the sections will be removed from the result. ```
developers
build/plugins
developers/developer/email
``` ## I want keep some sections unchanged! Add paths to such sections into `` ```
developers
description
``` The Sections in the result will be the same as in the original project pom.xml. ## How to change value of some pom parameters? Sometime it is good to change some record in the pom.xml, the plugin allows to do that ``` description It is new description of the pom.xml developers/developer/email newemail@alldevelopers.com ``` ## How to save uber-pom in another place? The Generated uber-pom by default will be placed in the same folder where the project pom is. You can change that through `` setting. ``` /anotherFolderToSaveUberPom ``` ## I wanna change the result uber-pom name By default the uber-pom has name `uber-pom.xml` but sometime it is needed to be changed, it is possible through `` setting. ``` customUberPom.xml ``` ## I can't find uber-pom after session By default the generated and saved uber-pom will be removed after session. If you want to keep the file then disable its deleting with flag `` ``` false ``` ## How to merge only restricted number of hierarchy levels? By default the plugin merges all hierarchy levels, but you can restrict the number through the `` parameter ``` 2 ``` In the example, only two upper levels will be involved into merging. uber-pom-1.0.3/pom.xml000066400000000000000000000210041352035711500145550ustar00rootroot00000000000000 4.0.0 com.igormaznitsa uber-pom 1.0.3 maven-plugin UberPom Merging pom hierarchy parameters UTF-8 UTF-8 ${maven.build.timestamp} yyyyMMddHHmm https://github.com/raydac/uber-pom GitHub Issues https://github.com/raydac/uber-pom/issues 2015 raydac Igor Maznitsa rrg4400@gmail.com http://www.igormaznitsa.com +3 developer 3.0 https://github.com/raydac/uber-pom scm:git:git://github.com/raydac/uber-pom.git scm:git:git@github.com:raydac/uber-pom.git Igor Maznitsa http://www.igormaznitsa.com The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo org.apache.maven.plugin-tools maven-plugin-annotations 3.4 org.apache.maven maven-plugin-api 3.0 provided org.apache.maven maven-core 3.0 provided org.apache.maven maven-artifact 3.0 provided commons-io commons-io 2.4 org.apache.maven.plugin-testing maven-plugin-testing-harness 2.1 test org.apache.maven maven-compat 3.0 test org.apache.maven.shared maven-verifier 1.5 test junit junit 4.12 test publish org.apache.maven.plugins maven-assembly-plugin 2.5.4 make-distributive install single false ${project.artifactId}-${project.version}-${timestamp}-distr src/assemble/distribution.xml make-bundle install single src/assemble/bundle.xml org.apache.maven.plugins maven-javadoc-plugin 3.1.1 generate-javadoc package jar org.apache.maven.plugins maven-source-plugin 3.1.0 generate-sources package jar org.apache.maven.plugins maven-gpg-plugin 1.6 sign-artifacts verify sign com.igormaznitsa meta-checker 1.1.3 check 6 org.apache.maven.plugins maven-compiler-plugin 3.3 -Xlint:all false 1.6 1.6 true true org.codehaus.mojo animal-sniffer-maven-plugin 1.18 ensure-java-1.6-class-library test check org.codehaus.mojo.signature java16-sun 1.0 org.apache.maven.plugins maven-plugin-plugin 3.4 true upom mojo-descriptor process-classes descriptor generated-helpmojo helpmojo uber-pom-1.0.3/src/000077500000000000000000000000001352035711500140325ustar00rootroot00000000000000uber-pom-1.0.3/src/assemble/000077500000000000000000000000001352035711500156255ustar00rootroot00000000000000uber-pom-1.0.3/src/assemble/bundle.xml000066400000000000000000000020101352035711500176110ustar00rootroot00000000000000 bundle false false jar ${project.build.directory} ${file.separator} *.jar.asc *.jar *.pom *.pom.asc original*.* *.zip uber-pom-1.0.3/src/assemble/distribution.xml000066400000000000000000000027661352035711500211010ustar00rootroot00000000000000 distr false false tar.gz ${project.basedir} ${file.separator}project target/ texts/ nbactions.xml catalog.xml **/.* ${file.separator}lib ${project.basedir}/target ${project.build.finalName}.jar ${file.separator}lib ${project.basedir} pom.xml ${file.separator} ${basedir}/texts *.* uber-pom-1.0.3/src/main/000077500000000000000000000000001352035711500147565ustar00rootroot00000000000000uber-pom-1.0.3/src/main/java/000077500000000000000000000000001352035711500156775ustar00rootroot00000000000000uber-pom-1.0.3/src/main/java/com/000077500000000000000000000000001352035711500164555ustar00rootroot00000000000000uber-pom-1.0.3/src/main/java/com/igormaznitsa/000077500000000000000000000000001352035711500211645ustar00rootroot00000000000000uber-pom-1.0.3/src/main/java/com/igormaznitsa/upom/000077500000000000000000000000001352035711500221445ustar00rootroot00000000000000uber-pom-1.0.3/src/main/java/com/igormaznitsa/upom/DependencyPattern.java000066400000000000000000000144771352035711500264400ustar00rootroot00000000000000/* * Copyright 2019 Igor Maznitsa. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.igormaznitsa.upom; import java.util.regex.Pattern; import org.apache.maven.model.Dependency; import org.apache.maven.plugins.annotations.Parameter; /** * Dependency pattern. * * @since 1.0.2 */ public class DependencyPattern { /** * Group ID, allowed wildcard pattern. */ @Parameter(name = "groupId") private String groupId = null; /** * Artifact ID, allowed wildcard pattern. */ @Parameter(name = "artifactId") private String artifactId = null; /** * Version, allowed wildcard pattern. */ @Parameter(name = "version") private String version = null; /** * Scope, allowed wildcard pattern. */ @Parameter(name = "scope") private String scope = null; /** * Optional flag, allowed wildcard pattern. */ @Parameter(name = "optional") private String optional = null; /** * System path, allowed wildcard pattern. */ @Parameter(name = "systemPath") private String systemPath = null; /** * Type, allowed wildcard pattern. */ @Parameter(name = "type") private String type = null; /** * Classifier, allowed wildcard pattern. */ @Parameter(name = "classifier") private String classifier = null; private Pattern groupIdPattern; private Pattern artifactIdPattern; private Pattern versionPattern; private Pattern scopePattern; private Pattern optionalPattern; private Pattern systemPathPattern; private Pattern typePattern; private Pattern classifierPattern; public String getClassifier() { return this.classifier; } public void setClassifier(final String value) { this.classifier = value; } public String getType() { return this.type; } public void setType(final String value) { this.type = value; } public String getGroupId() { return this.groupId; } public void setGroupId(final String value) { this.groupId = value; } public String getArtifactId() { return this.artifactId; } public void setArtifactId(final String value) { this.artifactId = value; } public String getVersion() { return this.version; } public void setVersion(final String value) { this.version = value; } public String getScope() { return this.scope; } public void setScope(final String value) { this.scope = value; } public String getOptional() { return this.optional; } public void setOptional(final String value) { this.optional = value; } public String getSystemPath() { return this.systemPath; } public void setSystemPath(final String value) { this.systemPath = value; } public boolean maths(final Dependency dependency) { if (dependency == null) { return false; } ensurePatterns(); int counter = 0; int totalCounter = 0; if (this.groupId != null) { totalCounter++; if (dependency.getGroupId() != null && this.groupIdPattern.matcher(dependency.getGroupId()).matches()) { counter++; } } if (this.artifactId != null) { totalCounter++; if (dependency.getArtifactId() != null && this.artifactIdPattern.matcher(dependency.getArtifactId()).matches()) { counter++; } } if (this.version != null) { totalCounter++; if (dependency.getVersion() != null && this.versionPattern.matcher(dependency.getVersion()).matches()) { counter++; } } if (this.classifier != null) { totalCounter++; if (dependency.getClassifier() != null && this.classifierPattern.matcher(dependency.getClassifier()).matches()) { counter++; } } if (this.type != null) { totalCounter++; if (dependency.getType() != null && this.typePattern.matcher(dependency.getType()).matches()) { counter++; } } if (this.optional != null) { totalCounter++; if (dependency.getOptional() != null && this.optionalPattern.matcher(dependency.getOptional()).matches()) { counter++; } } if (this.systemPath != null) { totalCounter++; if (dependency.getSystemPath() != null && this.systemPathPattern.matcher(dependency.getSystemPath()).matches()) { counter++; } } if (this.scope != null) { totalCounter++; if (dependency.getScope() != null && this.scopePattern.matcher(dependency.getScope()).matches()) { counter++; } } return totalCounter > 0 && totalCounter == counter; } private void ensurePatterns() { if (this.artifactIdPattern == null) { this.artifactIdPattern = makePattern(this.artifactId); } if (this.groupIdPattern == null) { this.groupIdPattern = makePattern(this.groupId); } if (this.optionalPattern == null) { this.optionalPattern = makePattern(this.optional); } if (this.scopePattern == null) { this.scopePattern = makePattern(this.scope); } if (this.systemPathPattern == null) { this.systemPathPattern = makePattern(this.systemPath); } if (this.versionPattern == null) { this.versionPattern = makePattern(this.version); } if (this.classifierPattern == null) { this.classifierPattern = makePattern(this.classifier); } if (this.typePattern == null) { this.typePattern = makePattern(this.type); } } private static Pattern makePattern(final String text) { if (text == null) { return Pattern.compile(".*"); } final StringBuilder builder = new StringBuilder(); for (final char c : text.toCharArray()) { switch (c) { case '*': builder.append(".*"); break; case '?': builder.append("."); break; default: builder.append(Pattern.quote(Character.toString(c))); break; } } return Pattern.compile(builder.toString()); } } uber-pom-1.0.3/src/main/java/com/igormaznitsa/upom/UPomException.java000066400000000000000000000015251352035711500255510ustar00rootroot00000000000000/* * Copyright 2015 Igor Maznitsa (http://www.igormaznitsa.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.igormaznitsa.upom; public class UPomException extends RuntimeException { private static final long serialVersionUID = 4961549799040350155L; public UPomException(String message) { super(message); } } uber-pom-1.0.3/src/main/java/com/igormaznitsa/upom/UPomModel.java000066400000000000000000000460051352035711500246550ustar00rootroot00000000000000/* * Copyright 2015 Igor Maznitsa (http://www.igormaznitsa.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.igormaznitsa.upom; import java.io.*; import java.lang.reflect.*; import java.util.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.io.IOUtils; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; import org.apache.maven.model.merge.ModelMerger; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; @SuppressWarnings({"unchecked", "rawtypes"}) public final class UPomModel { private static final String MAVEN_MODEL_PACKAGE_PREFIX = "org.apache.maven.model."; private final Model model; private final Map savedValues = new HashMap(); public UPomModel(final File modelFile) throws Exception { final FileInputStream in = new FileInputStream(modelFile); try { final MavenXpp3Reader reader = new MavenXpp3Reader(); this.model = reader.read(in, true); } finally { IOUtils.closeQuietly(in); } } public UPomModel(final Model pom) { this.model = pom.clone(); } public List removeDependencies(final List patterns) { final List kept = new ArrayList(); final List removed = new ArrayList(); for (final Dependency d : this.model.getDependencies()) { boolean remove = false; for (final DependencyPattern p : patterns) { if (p.maths(d)) { remove = true; break; } } if (remove) { removed.add(d); } else { kept.add(d); } } this.model.setDependencies(kept); return removed; } private static Node findFirstElement(final Node node) { if (node == null) { return null; } Node result = node.getFirstChild(); while (result != null && result.getNodeType() != Node.ELEMENT_NODE) { result = result.getNextSibling(); } return result; } private static Node nextSiblingElement(final Node node) { if (node == null) { return null; } Node next = node.getNextSibling(); while (next != null && next.getNodeType() != Node.ELEMENT_NODE) { next = next.getNextSibling(); } return next; } private static void insideElementJanitor(final Log log, final Node node, final List path) { path.add(node.getNodeName()); Node element = findFirstElement(node); while (element != null) { duplicatedSiblingJanitor(log, element, path); element = nextSiblingElement(element); } path.remove(path.size() - 1); } private static String pathToString(final List path) { final StringBuilder result = new StringBuilder(); for (final String s : path) { if (result.length() > 0) { result.append('/'); } result.append(s); } return result.toString(); } private static void duplicatedSiblingJanitor(final Log log, final Node node, final List path) { if (node == null) { return; } insideElementJanitor(log, node, path); Node sibling = nextSiblingElement(node); while (sibling != null) { insideElementJanitor(log, sibling, path); sibling = nextSiblingElement(sibling); } sibling = nextSiblingElement(node); while (sibling != null) { if (node.isEqualNode(sibling)) { path.add(node.getNodeName()); final Node deleting = sibling; sibling = nextSiblingElement(sibling); if (log != null) { log.warn("Removing duplicated element : " + pathToString(path)); } deleting.getParentNode().removeChild(deleting); path.remove(path.size() - 1); } else { sibling = nextSiblingElement(sibling); } } } private static String findAndRemoveDuplicatedSiblings(final Log log, final String xmlText) throws Exception { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document xmldoc = builder.parse(new InputSource(new StringReader(xmlText))); insideElementJanitor(log, xmldoc, new ArrayList()); final TransformerFactory tFactory = TransformerFactory.newInstance(); final Transformer transformer = tFactory.newTransformer(); final DOMSource source = new DOMSource(xmldoc); final StringWriter buffer = new StringWriter(xmlText.length()); final StreamResult result = new StreamResult(buffer); transformer.transform(source, result); return ((StringWriter) result.getWriter()).toString(); } public String asXML(final Log log, final boolean removeDuplicatedSiblings) throws Exception { final MavenXpp3Writer mavenWritter = new MavenXpp3Writer(); final StringWriter buffer = new StringWriter(16384); mavenWritter.write(buffer, this.model); String result = buffer.toString(); if (removeDuplicatedSiblings) { if (log != null) { log.warn("Activated search and removing of duplicated sibling elements!"); } result = findAndRemoveDuplicatedSiblings(log, result); } else if (log != null) { log.info("Search and removing of duplicated sibling elements is OFF"); } return result; } public void saveState(final String... keepPaths) throws Exception { this.savedValues.clear(); for (final String p : keepPaths) { this.savedValues.put(p, this.processPathStepToGet(splitPath(p), 0, this.model)); } } public void restoreState() throws Exception { for (final Map.Entry e : this.savedValues.entrySet()) { this.processPathStepToSet(splitPath(e.getKey()), 0, this.model, e.getValue()); } } public void restoreStateFrom(final UPomModel model) throws Exception { for (final Map.Entry e : model.savedValues.entrySet()) { this.processPathStepToSet(splitPath(e.getKey()), 0, this.model, e.getValue()); } } public Model getModel() { return this.model; } public UPomModel merge(final UPomModel other) throws Exception { final ModelMerger merger = new ModelMerger(); merger.merge(this.model, other.model, true, null); return this; } public boolean remove(final String removePath) throws Exception { return processPathStepToSet(splitPath(removePath), 0, this.model, null); } public void set(final String path, final String value) throws Exception { this.processPathStepToSet(splitPath(path), 0, this.model, value); } public Object get(final String path) throws Exception { return this.processPathStepToGet(splitPath(path), 0, this.model); } private static Method findMethod(final Class klazz, final String methodName, final boolean onlyPublic) { Method result = null; for (final Method m : klazz.getMethods()) { if (onlyPublic && !Modifier.isPublic(m.getModifiers())) { continue; } if (m.getName().equalsIgnoreCase(methodName)) { result = m; break; } } return result; } private static Field findDeclaredFieldForName(final Class klazz, final String fieldName) { Field result = null; Class curr = klazz; while (curr.getName().startsWith(MAVEN_MODEL_PACKAGE_PREFIX)) { for (final Field m : curr.getDeclaredFields()) { if (m.getName().equalsIgnoreCase(fieldName)) { result = m; break; } } if (result != null) { result.setAccessible(true); break; } curr = klazz.getSuperclass(); } return result; } private static String makePathStr(final String[] path, final int toIndex) { final StringBuilder result = new StringBuilder(); for (int i = 0; i <= toIndex; i++) { if (result.length() > 0) { result.append('/'); } result.append(path[i]); } return result.toString(); } private static Collection cloneCollection(final Collection collection) throws Exception { final Class collectionClass = collection.getClass(); final Constructor constructor = collectionClass.getConstructor(Collection.class); return (Collection) constructor.newInstance(collection); } private static Map cloneMap(final Map map) throws Exception { final Class mapClass = map.getClass(); final Constructor constructor = mapClass.getConstructor(Map.class); return (Map) constructor.newInstance(map); } private static Object ensureCloning(final Object obj) throws Exception { if (obj == null) { return null; } final Method clone = findMethod(obj.getClass(), "clone", true); final Object result; if (clone == null) { if (obj instanceof Map) { result = cloneMap((Map) obj); } else if (obj instanceof Collection) { result = cloneCollection((Collection) obj); } else { result = obj; } } else { result = clone.invoke(obj); } return result; } private static void setField(final Object instance, final Field field, final Object value) throws Exception { final Object currentValue = field.get(instance); if (currentValue == null) { if (value != null) { field.setAccessible(true); field.set(instance, value); } } else if (currentValue instanceof Map) { ((Map) currentValue).clear(); if (value != null) { ((Map) currentValue).putAll((Map) value); } } else if (currentValue instanceof Collection) { ((Collection) currentValue).clear(); if (value != null) { ((Collection) currentValue).addAll((Collection) value); } } else { field.set(instance, ensureCloning(value)); } } private static Object getField(final Object instance, final Field field) throws Exception { return ensureCloning(field.get(instance)); } private boolean processPathStepToSet(final String[] path, final int pathStart, final Object instance, final Object value) throws Exception { final String fieldName = path[pathStart]; if (pathStart == path.length - 1) { // last step // find setter final Method setter = findMethod(instance.getClass(), "set" + fieldName, true); if (setter == null) { throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\''); } final Class[] params = setter.getParameterTypes(); if (params.length == 0) { throw new UPomException("Detected zero setter '" + makePathStr(path, pathStart) + "\'"); } else if (params.length == 1) { setter.invoke(instance, ensureCloning(value)); } else { final Field field = findDeclaredFieldForName(instance.getClass(), fieldName); if (field != null) { setField(instance, field, value); } else { throw new UPomException("Unsupported type for '" + makePathStr(path, pathStart) + "\'"); } } return true; } else { // find getter final Method getter = findMethod(instance.getClass(), "get" + fieldName, true); if (getter == null) { throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\''); } final Object nextInstance = getter.invoke(instance); if (nextInstance == null) { return false; } final boolean theNextPathItemIsLastOne = path.length - 1 == pathStart + 1; if (nextInstance instanceof Collection) { final Type returnType = getter.getGenericReturnType(); if (returnType instanceof ParameterizedType) { final ParameterizedType paramType = (ParameterizedType) returnType; final Type[] argTypes = paramType.getActualTypeArguments(); if (theNextPathItemIsLastOne) { if (value == null) { ((Collection) nextInstance).clear(); return true; } else if (value instanceof Collection) { ((Collection) nextInstance).clear(); for (final Object obj : ((Collection) value)) { ((Collection) nextInstance).add(obj); } return true; } else { ((Collection) nextInstance).clear(); return ((Collection) nextInstance).add(value); } } final String nextPathItem = path[pathStart + 1].toLowerCase(Locale.ENGLISH); if (argTypes[0].toString().toLowerCase(Locale.ENGLISH).endsWith(nextPathItem)) { boolean result = false; for (final Object collectionItem : (Collection) nextInstance) { result |= processPathStepToSet(path, pathStart + 2, collectionItem, value); } return result; } else { throw new UPomException("Collection element type is not '" + makePathStr(path, pathStart + 1) + '\''); } } else { throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\''); } } else if (nextInstance instanceof Map) { final Map map = (Map) nextInstance; final String nextPathItem = path[pathStart + 1]; if (theNextPathItemIsLastOne) { if (value == null) { map.remove(nextPathItem); } else { map.put(nextPathItem, value); } return true; } else { return map.containsKey(nextPathItem) ? processPathStepToSet(path, pathStart + 2, map.get(nextPathItem), value) : false; } } else { return processPathStepToSet(path, pathStart + 1, nextInstance, value); } } } private Object processPathStepToGet(final String[] path, final int pathStart, final Object instance) throws Exception { final String fieldName = path[pathStart]; if (pathStart == path.length - 1) { // last step // find getter final Method getter = findMethod(instance.getClass(), "get" + fieldName, true); if (getter == null) { throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\''); } final Class[] params = getter.getParameterTypes(); if (params.length == 0) { return ensureCloning(getter.invoke(instance)); } else { final Field field = findDeclaredFieldForName(instance.getClass(), fieldName); if (field != null) { return getField(instance, field); } else { throw new UPomException("Unsupported type for '" + makePathStr(path, pathStart) + "\'"); } } } else { // find getter final Method getter = findMethod(instance.getClass(), "get" + fieldName, true); if (getter == null) { throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\''); } final Object nextInstance = getter.invoke(instance); if (nextInstance == null) { return false; } final boolean theNextPathItemIsLastOne = path.length - 1 == pathStart + 1; if (nextInstance instanceof Collection) { final Type returnType = getter.getGenericReturnType(); if (returnType instanceof ParameterizedType) { final ParameterizedType paramType = (ParameterizedType) returnType; final Type[] argTypes = paramType.getActualTypeArguments(); if (theNextPathItemIsLastOne) { // take only the first value return ((Collection) nextInstance).isEmpty() ? null : ((Collection) nextInstance).iterator().next(); } final String nextPathItem = path[pathStart + 1].toLowerCase(Locale.ENGLISH); if (argTypes[0].toString().toLowerCase(Locale.ENGLISH).endsWith(nextPathItem)) { return ((Collection) nextInstance).isEmpty() ? null : processPathStepToGet(path, pathStart + 2, ((Collection) nextInstance).iterator().next()); } else { throw new UPomException("Collection element type is not '" + makePathStr(path, pathStart + 1) + '\''); } } else { throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\''); } } else if (nextInstance instanceof Map) { final Map map = (Map) nextInstance; final String nextPathItem = path[pathStart + 1]; if (theNextPathItemIsLastOne) { return map.get(nextPathItem); } else { return map.containsKey(nextPathItem) ? processPathStepToGet(path, pathStart + 2, map.get(nextPathItem)) : null; } } else { return processPathStepToGet(path, pathStart + 1, nextInstance); } } } public void injectIntoProject(final Log log, final MavenProject project) throws Exception { for (final Method setter : project.getClass().getMethods()) { if (Modifier.isAbstract(setter.getModifiers()) || Modifier.isStatic(setter.getModifiers())) { continue; } final String methodName = setter.getName(); final Class[] setterParams = setter.getParameterTypes(); if (setterParams.length == 1 && methodName.startsWith("set")) { final String paramName = methodName.substring(3).toLowerCase(Locale.ENGLISH); if (paramName.equals("build")) { continue; } Method getter = null; for (final Method g : this.model.getClass().getMethods()) { final Class[] getterParams = g.getParameterTypes(); if (getterParams.length == 0 && (g.getName().equalsIgnoreCase("get" + paramName) || g.getName().equalsIgnoreCase("is" + paramName))) { getter = g; break; } } if (getter != null && setterParams[0].isAssignableFrom(getter.getReturnType())) { final Object value = getter.invoke(this.model); if (value == null) { log.debug(getter.getName() + "() X-> " + setter.getName() + "()"); } else { log.debug(getter.getName() + "() --> " + setter.getName() + "()"); setter.invoke(project, getter.invoke(this.model)); } } } } } private static String[] splitPath(final String path) { final String[] result = path.trim().split("\\/"); return result; } public void assignTo(final MavenProject project) { project.setOriginalModel(this.model); } @Override public String toString() { return this.model.toString(); } } uber-pom-1.0.3/src/main/java/com/igormaznitsa/upom/UPomMojo.java000066400000000000000000000334311352035711500245200ustar00rootroot00000000000000/* * Copyright 2015 Igor Maznitsa (http://www.igormaznitsa.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.igormaznitsa.upom; import java.io.File; import java.util.*; import org.apache.commons.io.FileUtils; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.*; import org.apache.maven.project.MavenProject; /** * Maven plugin to merge pom files in project hierarchy, also it can make * modifications in the result pom. * * @author Igor Maznitsa (http://www.igormaznitsa.com) */ @Mojo(name = "upom", defaultPhase = LifecyclePhase.INITIALIZE, threadSafe = true, requiresDependencyResolution = ResolutionScope.NONE) public class UPomMojo extends AbstractMojo { public static final String LINE_SEPARATOR = System.getProperty("line.separator", "/r/n"); /** * The Project to be processed. */ @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; /** * The Folder where the uber-pom should be saved. */ @Parameter(name = "folder", defaultValue = "${basedir}") protected File folder; /** * Turn on checking of result XML for duplicated sibling elements and remove * all them. * * @since 1.0.1 */ @Parameter(name = "removeSiblingDuplications", defaultValue = "false") protected boolean removeSiblingDuplications; /** * The Name of the uber-pom file. */ @Parameter(name = "name", defaultValue = "uber-pom.xml") protected String name; /** * List of paths to be removed from the result pom file. Example of a path: * "build/plugins" */ @Parameter(name = "remove") protected String[] remove; /** * List of sections to not be modified in the result. Example of a path: * "build/plugins" */ @Parameter(name = "keep") protected String[] keep; /** * Enforce filling project parameters by values the generated uber-pom. By * default the uber-pom will be just saved and link to new the file will be * redirected. If the parameter is true then uber-pom model values will be * injected in fields of the current maven project model. */ @Parameter(name = "enforceInjecting", defaultValue = "false") protected boolean enforceInjecting; /** * Delete generated pom file after session. Also can be replaced externally * through system property 'upom.delete.on.exit' which has bigger priority */ @Parameter(name = "deleteOnExit", property = "upom.delete.on.exit", defaultValue = "true") protected boolean deleteOnExit; /** * List of dependency patterns to be removed. Wildcards ('*' and '?') are * supported. Patterns can be provided for all dependency qualifiers. * * @since 1.0.2 */ @Parameter(name = "removeDependencies") protected List removeDependencies = new ArrayList(); /** * Number of levels in hierarchy to merge, If less than zero then whole * hierarchy will be merged. */ @Parameter(name = "depth", defaultValue = "-1") protected int depth; /** * String properties to be set in the result pom. */ @Parameter(name = "set") protected Properties set; public List getRemoveDependencies() { return this.removeDependencies; } public File getFolder() { return this.folder; } public String getName() { return this.name; } public boolean isRemoveSiblingDuplications() { return this.removeSiblingDuplications; } public boolean isDeleteOnExit() { return this.deleteOnExit; } public int getDepth() { return this.depth; } public String[] getRemove() { return this.remove == null ? null : this.remove.clone(); } public String[] getKeep() { return this.keep == null ? null : this.keep.clone(); } public boolean isEnforceInjecting() { return this.enforceInjecting; } public Properties getSet() { return this.set; } private Model[] collectFullHierarchy(final MavenProject project) { final List result = new ArrayList(); MavenProject current = project; while (current != null) { result.add(0, current.getOriginalModel()); current = current.getParent() == null ? null : current.getParent(); } return result.toArray(new Model[result.size()]); } private static UPomModel[] collectModels(final MavenProject project, final int depth) { final List result = new ArrayList(); int levels = depth < 0 ? Integer.MAX_VALUE : depth; MavenProject current = project; while (current != null && levels-- >= 0) { result.add(0, new UPomModel(current.getOriginalModel())); current = current.getParent(); } return result.toArray(new UPomModel[result.size()]); } private void updateProjectForNewPom(final UPomModel upomModel, final File uberPomFile) throws Exception { upomModel.assignTo(this.project); getLog().debug("Model assigned to project"); this.project.setFile(uberPomFile); getLog().debug("File has been set to project"); } private File saveUberPom(final UPomModel model) throws Exception { final File uberPomFile = new File(this.folder, this.name); FileUtils.write(uberPomFile, model.asXML(getLog(), isRemoveSiblingDuplications()), "UTF-8"); if (isDeleteOnExit()) { getLog().info("NB! The Result uber-pom file marked to be removed after JVM session"); uberPomFile.deleteOnExit(); } return uberPomFile; } private static String getNameOfModel(final Model model) { if (model == null) { return ""; } final String group = model.getGroupId(); final String artifact = model.getArtifactId(); final String name = model.getName(); final String version = model.getVersion(); final StringBuilder result = new StringBuilder(); if (group == null) { result.append("[inherited]"); } else { result.append(group); } result.append(':'); if (artifact == null) { result.append("[inherited]"); } else { result.append(artifact); } result.append(':'); if (name == null) { result.append("[inherited]"); } else { result.append(name); } result.append(':'); if (version == null) { result.append("[inherited]"); } else { result.append(version); } return result.toString(); } private static void spaces(final StringBuilder buffer, int len) { while (len-- > 0) { buffer.append(' '); } } private static String drawHierarchy(final Model[] fullHierarchy, final UPomModel[] processedHierarchy) { final StringBuilder result = new StringBuilder(); final int TAB = 4; int startIndex = fullHierarchy.length - processedHierarchy.length; int insets = 0; // draw non-included for (int i = 0; i <= startIndex; i++) { if (result.length() > 0) { result.append(LINE_SEPARATOR); spaces(result, insets); result.append((char) 0x2506); result.append(LINE_SEPARATOR); spaces(result, insets); result.append((char) 0x2570).append((char) 0x2504); } result.append(getNameOfModel(fullHierarchy[i])); insets += TAB; } // draw included for (int i = 1; i < processedHierarchy.length; i++) { if (result.length() > 0) { result.append(LINE_SEPARATOR); spaces(result, insets); result.append((char) 0x2503); result.append(LINE_SEPARATOR); spaces(result, insets); result.append((char) 0x2517).append((char) 0x2501); } result.append(getNameOfModel(processedHierarchy[i].getModel())); insets += TAB; } return result.toString(); } private static int getMaxStrLength(final String[] strs) { if (strs == null || strs.length == 0) { return 0; } int max = 0; for (final String s : strs) { if (s.length() > max) { max = s.length(); } } return max; } private static String makeDotString(final int length) { final StringBuilder result = new StringBuilder(length); for (int i = 0; i < length; i++) { result.append('.'); } return result.toString(); } private static String dependency2str(final Dependency dependency) { final StringBuilder result = new StringBuilder(); result.append("groupId=").append(dependency.getGroupId()).append(',') .append("artifactId=").append(dependency.getArtifactId()).append(',') .append("version=").append(dependency.getVersion()).append(',') .append("type=").append(dependency.getType()).append(',') .append("scope=").append(dependency.getScope()).append(',') .append("systemPath=").append(dependency.getSystemPath()).append(',') .append("classifier=").append(dependency.getClassifier()).append(',') .append("optional=").append(dependency.getOptional()); return result.toString(); } @Override public void execute() throws MojoExecutionException { String strToPrint = null; try { final Model[] fullModuleHierarchy = collectFullHierarchy(this.project); final UPomModel[] modelsForProcessing = collectModels(this.project, this.depth); getLog().debug("Full hierarchy: " + Arrays.toString(fullModuleHierarchy)); getLog().debug("Models to be processed: " + Arrays.toString(modelsForProcessing)); getLog().info("........................................................."); for (final String s : drawHierarchy(fullModuleHierarchy, modelsForProcessing).split("\\n")) { getLog().info(s); } getLog().info("........................................................."); final UPomModel main = modelsForProcessing[0]; for (int i = 1; i < modelsForProcessing.length; i++) { final boolean last = i == modelsForProcessing.length - 1; final UPomModel model = modelsForProcessing[i]; if (last && this.keep != null && this.keep.length > 0) { getLog().info(""); getLog().debug("Freezing state of sections for result project pom:" + Arrays.toString(this.keep)); model.saveState(this.keep); for (final String s : this.keep) { getLog().info("Freezing path \'" + s + "\' in the result pom"); } getLog().debug("Merging last model"); main.merge(model); getLog().debug("Restoring state of sections for project pom:" + Arrays.toString(this.keep)); main.restoreStateFrom(model); } else { getLog().debug("Merging model"); main.merge(model); } } getLog().info(""); final String REMOVE_PREFIX = "Remove "; int maxLength = REMOVE_PREFIX.length() + getMaxStrLength(this.remove) + 12; if (this.remove != null && this.remove.length > 0) { for (final String path : this.remove) { final String prefix = REMOVE_PREFIX + '\'' + path + '\''; strToPrint = prefix + makeDotString(maxLength - prefix.length()); final boolean removed = main.remove(path); getLog().info(strToPrint + (removed ? "OK" : "NOT FOUND")); } } getLog().info(""); if (this.set != null && !this.set.isEmpty()) { strToPrint = null; for (final String key : this.set.stringPropertyNames()) { final String value = this.set.getProperty(key); try { getLog().info("Set value to path : '" + key + "\'=\'" + value + '\''); main.set(key, value); } catch (Exception ex) { getLog().debug(ex); throw new UPomException("Can't set string value to '" + key + '\''); } } getLog().info(""); } final List removedDependencies = main.removeDependencies(this.removeDependencies); if (!removedDependencies.isEmpty()) { for (final Dependency d : removedDependencies) { getLog().info("Removed dependency: " + dependency2str(d)); } } getLog().debug("Saving uber-pom into project"); final File saveUberPom = saveUberPom(main); getLog().info("Uber-pom saved as '" + saveUberPom.getAbsolutePath() + '\''); getLog().debug("Injecting new uber-pom into project"); updateProjectForNewPom(main, saveUberPom); getLog().info("Uber-pom assigned to project"); if (this.isEnforceInjecting()) { getLog().info("NB! Injecting generated uber-pom parameters into internal project fields!"); main.injectIntoProject(getLog(), this.project); } } catch (UPomException ex) { getLog().debug(ex); if (strToPrint != null) { getLog().info(strToPrint + "ERROR"); } getLog().error(ex.getMessage()); throw new MojoExecutionException("Error during processing", ex); } catch (Exception ex) { throw new MojoExecutionException("Error during processing", ex); } } public static String findProperty( final MavenProject project, final String key, final String dflt ) { String projectProperty; MavenProject curProject = project; do { projectProperty = curProject.getProperties().getProperty(key); curProject = curProject.getParent(); } while (projectProperty == null && curProject != null); return projectProperty == null ? System.getProperty(key, dflt) : projectProperty; } } uber-pom-1.0.3/src/test/000077500000000000000000000000001352035711500150115ustar00rootroot00000000000000uber-pom-1.0.3/src/test/java/000077500000000000000000000000001352035711500157325ustar00rootroot00000000000000uber-pom-1.0.3/src/test/java/com/000077500000000000000000000000001352035711500165105ustar00rootroot00000000000000uber-pom-1.0.3/src/test/java/com/igormaznitsa/000077500000000000000000000000001352035711500212175ustar00rootroot00000000000000uber-pom-1.0.3/src/test/java/com/igormaznitsa/upom/000077500000000000000000000000001352035711500221775ustar00rootroot00000000000000uber-pom-1.0.3/src/test/java/com/igormaznitsa/upom/UPomMojoConfigTest.java000066400000000000000000000067741352035711500265530ustar00rootroot00000000000000package com.igormaznitsa.upom; /* * Copyright 2015 Igor Maznitsa (http://www.igormaznitsa.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.util.Properties; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.plugin.testing.AbstractMojoTestCase; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuilder; import org.apache.maven.project.ProjectBuildingRequest; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class UPomMojoConfigTest extends AbstractMojoTestCase { private UPomMojo init(final File config) throws Exception { final MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest(); final ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest(); final ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class); final MavenProject project = projectBuilder.build(config, buildingRequest).getProject(); final UPomMojo mojo = (UPomMojo) this.lookupConfiguredMojo(project, "upom"); return mojo; } @Before public void before(){ System.clearProperty("upom.delete.on.exit"); } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } @Test public void testDefaultConfig() throws Exception { final File pom = getTestFile("src/test/resources/com/igormaznitsa/upom/testcfgs/testDefaultConfig.xml"); assertNotNull(pom); assertTrue(pom.exists()); final UPomMojo myMojo = init(pom); assertNotNull(myMojo); assertTrue(myMojo.isDeleteOnExit()); assertFalse(myMojo.isEnforceInjecting()); assertNull(myMojo.getSet()); assertNull(myMojo.getKeep()); assertNull(myMojo.getRemove()); assertNotNull(myMojo.getFolder()); assertEquals("uber-pom.xml", myMojo.getName()); assertEquals(-1, myMojo.getDepth()); assertFalse(myMojo.isRemoveSiblingDuplications()); } @Test public void testNonDefaultConfig() throws Exception { final File pom = getTestFile("src/test/resources/com/igormaznitsa/upom/testcfgs/testNonDefaultConfig.xml"); assertNotNull(pom); assertTrue(pom.exists()); final UPomMojo myMojo = init(pom); assertTrue(myMojo.isDeleteOnExit()); assertTrue(myMojo.isEnforceInjecting()); final Properties props = myMojo.getSet(); assertEquals(2,props.size()); assertEquals("value1",props.get("set1")); assertEquals("value2",props.get("set2")); assertArrayEquals(new String[]{"keep/keep1", "keep1/keep2"}, myMojo.getKeep()); assertArrayEquals(new String[]{"path/path1", "path1/path2"}, myMojo.getRemove()); assertEquals("/test/folder", myMojo.getFolder().getAbsolutePath()); assertEquals("testName.xml", myMojo.getName()); assertEquals(678, myMojo.getDepth()); assertTrue(myMojo.isRemoveSiblingDuplications()); } } uber-pom-1.0.3/src/test/java/com/igormaznitsa/upom/logictests/000077500000000000000000000000001352035711500243575ustar00rootroot00000000000000uber-pom-1.0.3/src/test/java/com/igormaznitsa/upom/logictests/AbstractLogicTest.java000066400000000000000000000011711352035711500306030ustar00rootroot00000000000000package com.igormaznitsa.upom.logictests; import java.io.File; import java.io.InputStream; import static org.junit.Assert.*; public abstract class AbstractLogicTest { public File getFolder(final String name) throws Exception { final String classFolder = AbstractLogicTest.class.getPackage().getName().replace('.', File.separatorChar); final File baseFolder = new File(new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()), classFolder); final File testFolder = new File(baseFolder,name); assertTrue("can't find "+testFolder, testFolder.isDirectory()); return testFolder; } } uber-pom-1.0.3/src/test/java/com/igormaznitsa/upom/logictests/LogicTest.java000066400000000000000000000250071352035711500271230ustar00rootroot00000000000000package com.igormaznitsa.upom.logictests; import com.igormaznitsa.upom.DependencyPattern; import com.igormaznitsa.upom.UPomException; import com.igormaznitsa.upom.UPomModel; import java.io.File; import java.util.*; import org.apache.maven.model.Dependency; import org.junit.Test; import static org.junit.Assert.*; public class LogicTest extends AbstractLogicTest { @Test public void testThreeLevelMerging() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base,"pom1.xml")); final UPomModel model2 = new UPomModel(new File(base,"pom2.xml")); final UPomModel model3 = new UPomModel(new File(base,"pom3.xml")); final UPomModel result = model1.merge(model2).merge(model3); assertEquals(1,result.getModel().getLicenses().size()); assertEquals(1,result.getModel().getProfiles().size()); assertEquals(7,result.getModel().getDependencies().size()); assertEquals(3,result.getModel().getDevelopers().size()); assertEquals(9,result.getModel().getModules().size()); assertEquals("test.group",result.getModel().getGroupId()); assertEquals("test-artifact3",result.getModel().getArtifactId()); assertEquals("1.2.3-SNAPSHOT",result.getModel().getVersion()); assertEquals("jar",result.getModel().getPackaging()); assertEquals("parent3",result.getModel().getParent().getArtifactId()); assertNull(result.getModel().getScm()); assertNull(result.getModel().getReporting()); assertEquals(0,result.getModel().getRepositories().size()); final Properties properties = result.getModel().getProperties(); assertTrue(properties.containsKey("property.number1")); assertTrue(properties.containsKey("property.number2")); assertTrue(properties.containsKey("property.number3")); } @Test public void testThreeLevel_RemoveDependenciesForPattern() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); final UPomModel model2 = new UPomModel(new File(base, "pom2.xml")); final UPomModel model3 = new UPomModel(new File(base, "pom3.xml")); final UPomModel result = model1.merge(model2).merge(model3); int normalDependencies = 0; int systemPathDependencies = 0; for(final Dependency d : result.getModel().getDependencies()) { if (d.getSystemPath()!=null) systemPathDependencies++; else normalDependencies++; } assertEquals(4, normalDependencies); assertEquals(3, systemPathDependencies); final DependencyPattern dependencyPattern = new DependencyPattern(); dependencyPattern.setSystemPath("*"); assertEquals(3, result.removeDependencies(Collections.singletonList(dependencyPattern)).size()); int normalDependencies2 = 0; int systemPathDependencies2 = 0; for (final Dependency d : result.getModel().getDependencies()) { if (d.getSystemPath() != null) { systemPathDependencies2++; } else { normalDependencies2++; } } assertEquals(normalDependencies, normalDependencies2); assertEquals(0, systemPathDependencies2); } @Test public void testThreeLevel_SaveAndRestoreState() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base,"pom1.xml")); final UPomModel model2 = new UPomModel(new File(base,"pom2.xml")); final UPomModel model3 = new UPomModel(new File(base,"pom3.xml")); model1.saveState("dependencies","modules"); final UPomModel result = model1.merge(model2).merge(model3); model1.restoreState(); assertEquals(3,result.getModel().getDependencies().size()); assertEquals("artifact1",result.getModel().getDependencies().get(0).getArtifactId()); assertEquals("artifact2",result.getModel().getDependencies().get(1).getArtifactId()); assertEquals(3,result.getModel().getDevelopers().size()); assertEquals(3,result.getModel().getModules().size()); assertEquals("modul1", result.getModel().getModules().get(0)); assertEquals("modul2", result.getModel().getModules().get(1)); assertEquals("modul3", result.getModel().getModules().get(2)); assertEquals("test.group",result.getModel().getGroupId()); assertEquals("test-artifact3",result.getModel().getArtifactId()); assertEquals("1.2.3-SNAPSHOT",result.getModel().getVersion()); assertEquals("jar",result.getModel().getPackaging()); assertEquals("parent3",result.getModel().getParent().getArtifactId()); assertNull(result.getModel().getScm()); assertNull(result.getModel().getReporting()); assertEquals(0,result.getModel().getRepositories().size()); } @Test public void testAsXML() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); final String xml = model1.asXML(null,false); assertNotNull(xml); assertTrue(xml.length()>100); assertTrue(xml.contains("")); } @Test public void testThreeLevel_RemoveEmailOfDevelopers() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); final UPomModel model2 = new UPomModel(new File(base, "pom2.xml")); final UPomModel model3 = new UPomModel(new File(base, "pom3.xml")); final UPomModel result = model1.merge(model2).merge(model3); result.remove("developers/developer/email"); assertEquals(3, result.getModel().getDevelopers().size()); assertNull(result.getModel().getDevelopers().get(0).getEmail()); assertNull(result.getModel().getDevelopers().get(1).getEmail()); assertNull(result.getModel().getDevelopers().get(2).getEmail()); } @Test public void testThreeLevel_KeepEmailForAllDevelopers() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); final UPomModel model2 = new UPomModel(new File(base, "pom2.xml")); final UPomModel model3 = new UPomModel(new File(base, "pom3.xml")); model1.saveState("developers/developer/email"); final UPomModel result = model1.merge(model2).merge(model3); model1.restoreState(); assertEquals(3, result.getModel().getDevelopers().size()); assertEquals("email1@email",result.getModel().getDevelopers().get(0).getEmail()); assertEquals("email1@email",result.getModel().getDevelopers().get(1).getEmail()); assertEquals("email1@email",result.getModel().getDevelopers().get(2).getEmail()); } @Test public void testThreeLevel_KeepDependency() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); final UPomModel model2 = new UPomModel(new File(base, "pom2.xml")); final UPomModel model3 = new UPomModel(new File(base, "pom3.xml")); model1.saveState("dependencies/dependency"); final UPomModel result = model1.merge(model2).merge(model3); model1.restoreState(); assertEquals(1, result.getModel().getDependencies().size()); assertEquals("com.test", result.getModel().getDependencies().get(0).getGroupId()); assertEquals("artifact1", result.getModel().getDependencies().get(0).getArtifactId()); assertEquals("1.0.0", result.getModel().getDependencies().get(0).getVersion()); assertEquals("test", result.getModel().getDependencies().get(0).getScope()); } @Test public void testPath_SetGet() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); model1.set("parent/version", "testparent872364"); assertEquals("testparent872364",model1.get("parent/version")); assertEquals("testparent872364",model1.getModel().getParent().getVersion()); assertNull(model1.get("url")); assertArrayEquals(new String[]{"modul1","modul2","modul3"}, ((Collection)model1.get("modules")).toArray()); } @Test public void testPath_GetFromCollection() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); assertEquals("modul1",model1.get("modules/module")); } @Test public void testPath_GetFrom_PrerequisitesMaven() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); assertEquals("3.0.5",model1.get("prerequisites/maven")); } @Test public void testPath_GetFrom_Property() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); assertEquals(null,model1.get("properties/property.number000")); assertEquals("Hello",model1.get("properties/property.number1")); } @Test public void testPath_SetTo_Property() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); assertEquals(null,model1.get("properties/property.number000")); model1.set("properties/property.number000", "HAHAHA"); assertEquals("HAHAHA",model1.get("properties/property.number000")); } @Test public void testPath_SetTo_PrerequisitesMaven() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); model1.set("prerequisites/maven","1.2.3"); assertEquals("1.2.3",model1.get("prerequisites/maven")); } @Test(expected = UPomException.class) public void testSet_WrongPathOnStart() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); model1.set("pardent/version", "testparent872364"); } @Test(expected = UPomException.class) public void testSet_WrongPathAtEnd() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); model1.set("parent/verbsion", "testparent872364"); } @Test(expected = UPomException.class) public void testGet_WrongPathOnStart() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); model1.get("pardent/version"); } @Test(expected = UPomException.class) public void testGet_WrongPathAtEnd() throws Exception { final File base = getFolder("threeLevels"); final UPomModel model1 = new UPomModel(new File(base, "pom1.xml")); model1.get("parent/verbsion"); } } uber-pom-1.0.3/src/test/resources/000077500000000000000000000000001352035711500170235ustar00rootroot00000000000000uber-pom-1.0.3/src/test/resources/com/000077500000000000000000000000001352035711500176015ustar00rootroot00000000000000uber-pom-1.0.3/src/test/resources/com/igormaznitsa/000077500000000000000000000000001352035711500223105ustar00rootroot00000000000000uber-pom-1.0.3/src/test/resources/com/igormaznitsa/upom/000077500000000000000000000000001352035711500232705ustar00rootroot00000000000000uber-pom-1.0.3/src/test/resources/com/igormaznitsa/upom/logictests/000077500000000000000000000000001352035711500254505ustar00rootroot00000000000000uber-pom-1.0.3/src/test/resources/com/igormaznitsa/upom/logictests/threeLevels/000077500000000000000000000000001352035711500277325ustar00rootroot00000000000000uber-pom-1.0.3/src/test/resources/com/igormaznitsa/upom/logictests/threeLevels/pom1.xml000066400000000000000000000035031352035711500313310ustar00rootroot00000000000000 4.0.0 test.group test-artifact1 0.0.0-SNAPSHOT pom test1 TestTest1 com.parent parent1 1.0.0 TestInc http://www,test.com The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo 3.0.5 Hello modul1 modul2 modul3 developer1 Developer1 email1@email com.test artifact1 1.0.0 test com.test artifact2 2.0.0 com.test.system artifact1 1.0.0 some/system/path uber-pom-1.0.3/src/test/resources/com/igormaznitsa/upom/logictests/threeLevels/pom2.xml000066400000000000000000000024431352035711500313340ustar00rootroot00000000000000 4.0.0 test.group test-artifact2 0.0.0-SNAPSHOT pom test2 TestTest2 com.parent parent2 1.0.0 modul4 modul5 modul6 World developer2 Developer2 email2@email com.test artifact2 1.0.0 com.test.system artifact2 1.0.1 some/system/path2 uber-pom-1.0.3/src/test/resources/com/igormaznitsa/upom/logictests/threeLevels/pom3.xml000066400000000000000000000027771352035711500313470ustar00rootroot00000000000000 4.0.0 test.group test-artifact3 1.2.3-SNAPSHOT jar test3 TestTest3 com.parent parent3 1.0.0 profile1 onemodul1 onemodul2 onemodul3 modul7 modul8 modul9 developer3 Developer3 email3@email Ugums com.test artifact3 1.0.0 com.test.system artifact3 1.0.3 some/system/path2 uber-pom-1.0.3/src/test/resources/com/igormaznitsa/upom/testcfgs/000077500000000000000000000000001352035711500251125ustar00rootroot00000000000000uber-pom-1.0.3/src/test/resources/com/igormaznitsa/upom/testcfgs/testDefaultConfig.xml000066400000000000000000000012321352035711500312440ustar00rootroot00000000000000 4.0.0 com.igormaznitsa upom-config-test 0.0.1-SNAPSHOT jar com.igormaznitsa uber-pom 1.0.0-SNAPSHOT uber-pom-1.0.3/src/test/resources/com/igormaznitsa/upom/testcfgs/testNonDefaultConfig.xml000066400000000000000000000026151352035711500317250ustar00rootroot00000000000000 4.0.0 com.igormaznitsa upom-config-test 0.0.1-SNAPSHOT jar com.igormaznitsa uber-pom 1.0.0-SNAPSHOT /test/folder testName.xml path/path1 path1/path2 keep/keep1 keep1/keep2 set1 value1 set2 value2 true true false 678