├── .gitignore ├── LICENSE.md ├── README.md ├── loader ├── pom.xml └── src │ ├── main │ └── java │ │ └── at │ │ └── yawk │ │ └── mdep │ │ ├── DependencyLoader.java │ │ ├── DependencyStore.java │ │ ├── Environment.java │ │ ├── FileDependencyStore.java │ │ ├── JulLogger.java │ │ ├── Logger.java │ │ ├── ParentLastURLClassLoader.java │ │ ├── StreamLogger.java │ │ └── model │ │ ├── Dependency.java │ │ └── DependencySet.java │ └── test │ └── java │ └── at │ └── yawk │ └── mdep │ ├── DependencyLoaderTest.java │ └── TempDependencyStore.java ├── maven-plugin ├── pom.xml └── src │ ├── main │ └── java │ │ └── at │ │ └── yawk │ │ └── mdep │ │ ├── AntArtifactMatcher.java │ │ ├── ArtifactMatcher.java │ │ └── GenerateMojo.java │ └── test │ └── java │ └── at │ └── yawk │ └── mdep │ ├── AntArtifactMatcherTest.java │ └── GenerateMojoTest.java └── pom.xml /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | *.iml 3 | target/ -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | mdep 2 | ==== 3 | 4 | Java dependency loader 5 | 6 | General Setup 7 | ------------- 8 | 9 | **Maven:** 10 | ``` 11 | 12 | [...] 13 | 14 | 15 | [...] 16 | 17 | 18 | at.yawk.mdep 19 | mdep-loader 20 | 1.0-SNAPSHOT 21 | 22 | 23 | 24 | 25 | 26 | 27 | at.yawk.mdep 28 | mdep-maven-plugin 29 | 1.0-SNAPSHOT 30 | 31 | 32 | 33 | generate-resources 34 | 35 | generate 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | [...] 44 | 45 | 46 | 47 | 48 | 49 | 50 | ``` 51 | 52 | **Java:** 53 | ``` 54 | new DependencyLoader() 55 | .downloadDependencies() 56 | .toParentLastClassLoader() 57 | .loadClass("MyClass"); 58 | ``` 59 | 60 | Bukkit 61 | ------ 62 | 63 | ``` 64 | public class MyLoader extends JavaPlugin { 65 | @Override 66 | public void onLoad() { 67 | try { 68 | new DependencyLoader(getLogger()) 69 | .downloadDependencies() 70 | .addUrls(((URLClassLoader) getClassLoader()).getURLs()) 71 | .toParentLastClassLoader() 72 | .loadClass("MyPlugin").newInstance(); 73 | } catch (IOException e) { 74 | getLogger().log(Level.SEVERE, "Failed to load cricket dependencies, cricket will not start!", e); 75 | return; 76 | } 77 | } 78 | } -------------------------------------------------------------------------------- /loader/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | mdep-parent 11 | at.yawk.mdep 12 | 1.0.2-SNAPSHOT 13 | 14 | 4.0.0 15 | 16 | mdep-loader 17 | -------------------------------------------------------------------------------- /loader/src/main/java/at/yawk/mdep/DependencyLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import at.yawk.mdep.model.Dependency; 10 | import at.yawk.mdep.model.DependencySet; 11 | import java.io.ByteArrayOutputStream; 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | import java.io.PrintStream; 15 | import java.lang.reflect.Method; 16 | import java.net.URL; 17 | import java.net.URLClassLoader; 18 | import java.security.MessageDigest; 19 | import java.security.NoSuchAlgorithmException; 20 | import java.util.ArrayList; 21 | import java.util.Arrays; 22 | import java.util.Collections; 23 | import java.util.List; 24 | import javax.annotation.concurrent.NotThreadSafe; 25 | import javax.xml.bind.DatatypeConverter; 26 | import javax.xml.bind.JAXBContext; 27 | import javax.xml.bind.JAXBException; 28 | import lombok.SneakyThrows; 29 | 30 | /** 31 | * @author yawkat 32 | */ 33 | @NotThreadSafe 34 | public class DependencyLoader { 35 | private final Logger logger; 36 | private final List urls = new ArrayList<>(); 37 | 38 | // visible for testing 39 | DependencyStore dependencyStore; 40 | 41 | @SuppressWarnings("UseOfSystemOutOrSystemErr") 42 | public DependencyLoader() { 43 | this(System.err); 44 | } 45 | 46 | public DependencyLoader(PrintStream streamLogger) { 47 | this(new StreamLogger(streamLogger)); 48 | } 49 | 50 | public DependencyLoader(java.util.logging.Logger julLogger) { 51 | this(new JulLogger(julLogger)); 52 | } 53 | 54 | private DependencyLoader(Logger logger) { 55 | this.logger = logger; 56 | } 57 | 58 | private void initDependencyStore() { 59 | if (dependencyStore == null) { 60 | dependencyStore = Environment.createDependencyStore(logger); 61 | } 62 | } 63 | 64 | public DependencyLoader addUrls(URL... urls) { 65 | Collections.addAll(this.urls, urls); 66 | return this; 67 | } 68 | 69 | @SneakyThrows(NoSuchAlgorithmException.class) 70 | public DependencyLoader downloadDependencies(DependencySet dependencySet) throws IOException { 71 | initDependencyStore(); 72 | for (Dependency dependency : dependencySet.getDependencies()) { 73 | URL cached = dependencyStore.getCachedDependency(dependency); 74 | if (cached == null) { 75 | logger.info("Downloading " + dependency.getUrl()); 76 | MessageDigest digest = MessageDigest.getInstance("SHA-512"); 77 | @SuppressWarnings("resource") 78 | ByteArrayOutputStream memoryStream = new ByteArrayOutputStream(); 79 | try (InputStream stream = dependency.getUrl().openStream()) { 80 | byte[] buf = new byte[4096]; 81 | int len; 82 | while ((len = stream.read(buf)) >= 0) { 83 | digest.update(buf, 0, len); 84 | memoryStream.write(buf, 0, len); 85 | } 86 | } 87 | byte[] hash = digest.digest(); 88 | if (!Arrays.equals(hash, dependency.getSha512sum())) { 89 | throw new IOException("Mismatched hash on " + dependency.getUrl() + ": expected " + 90 | DatatypeConverter.printHexBinary(dependency.getSha512sum()) + " but got " + 91 | DatatypeConverter.printHexBinary(hash)); 92 | } 93 | cached = dependencyStore.saveDependency(dependency, memoryStream.toByteArray()); 94 | } 95 | urls.add(cached); 96 | } 97 | logger.info("Added " + dependencySet.getDependencies().size() + " dependencies."); 98 | return this; 99 | } 100 | 101 | public DependencyLoader downloadDependencies() throws IOException { 102 | DependencySet dependencies; 103 | try { 104 | dependencies = (DependencySet) JAXBContext.newInstance(DependencySet.class) 105 | .createUnmarshaller().unmarshal(DependencyLoader.class.getResource("/mdep-dependencies.xml")); 106 | } catch (JAXBException e) { 107 | throw new RuntimeException(e); 108 | } 109 | return downloadDependencies(dependencies); 110 | } 111 | 112 | @SneakyThrows(ReflectiveOperationException.class) 113 | public void appendToClassLoader(URLClassLoader classLoader) { 114 | Method addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); 115 | addUrlMethod.setAccessible(true); 116 | for (URL url : urls) { 117 | addUrlMethod.invoke(classLoader, url); 118 | } 119 | } 120 | 121 | public ClassLoader toParentFirstClassLoader() { 122 | return toParentFirstClassLoader(DependencyLoader.class.getClassLoader()); 123 | } 124 | 125 | public ClassLoader toParentFirstClassLoader(ClassLoader parent) { 126 | return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent); 127 | } 128 | 129 | public ClassLoader toParentLastClassLoader() { 130 | return toParentLastClassLoader(DependencyLoader.class.getClassLoader()); 131 | } 132 | 133 | public ClassLoader toParentLastClassLoader(ClassLoader parent) { 134 | return new ParentLastURLClassLoader(urls.toArray(new URL[urls.size()]), parent); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /loader/src/main/java/at/yawk/mdep/DependencyStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import at.yawk.mdep.model.Dependency; 10 | import java.io.IOException; 11 | import java.io.InputStream; 12 | import java.net.URL; 13 | import javax.annotation.Nullable; 14 | 15 | /** 16 | * @author yawkat 17 | */ 18 | interface DependencyStore { 19 | @Nullable 20 | URL getCachedDependency(Dependency dependency); 21 | 22 | URL saveDependency(Dependency dependency, byte[] bytes) throws IOException; 23 | } 24 | -------------------------------------------------------------------------------- /loader/src/main/java/at/yawk/mdep/Environment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import java.io.IOException; 10 | import java.nio.file.Files; 11 | import java.nio.file.Path; 12 | import java.nio.file.Paths; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | /** 17 | * @author yawkat 18 | */ 19 | class Environment { 20 | public static DependencyStore createDependencyStore(Logger logger) { 21 | return new FileDependencyStore(createCacheStore(logger, "mdep")); 22 | } 23 | 24 | public static Path createCacheStore(Logger logger, String directoryName) { 25 | List candidates = new ArrayList<>(); 26 | 27 | String cacheHome = System.getenv("XDG_CACHE_HOME"); 28 | if (cacheHome != null) { 29 | candidates.add(Paths.get(cacheHome)); 30 | } 31 | candidates.add(Paths.get(System.getProperty("user.home")).resolve(".cache")); 32 | 33 | String appdata = System.getenv("APPDATA"); 34 | if (appdata != null) { 35 | candidates.add(Paths.get(appdata)); 36 | } 37 | 38 | candidates.add(Paths.get(".")); 39 | 40 | for (Path candidate : candidates) { 41 | if (!Files.exists(candidate)) { 42 | try { 43 | Files.createDirectories(candidate); 44 | } catch (IOException e) { 45 | logger.warn("Could not create " + candidate + ": " + e); 46 | continue; 47 | } 48 | } 49 | if (!Files.isDirectory(candidate)) { 50 | logger.warn("Did not expect regular file at " + candidate); 51 | continue; 52 | } 53 | 54 | Path mdepDirectory = candidate.resolve(directoryName); 55 | boolean exists = Files.exists(mdepDirectory); 56 | if (exists && !Files.isDirectory(mdepDirectory)) { 57 | logger.warn("Did not expect regular file at " + mdepDirectory); 58 | continue; 59 | } 60 | 61 | if (!exists) { 62 | try { 63 | Files.createDirectories(mdepDirectory); 64 | } catch (IOException ignored) {} 65 | } 66 | 67 | if (!Files.isWritable(mdepDirectory)) { 68 | logger.warn(mdepDirectory + " is not writable"); 69 | continue; 70 | } 71 | 72 | return mdepDirectory; 73 | } 74 | 75 | throw new RuntimeException("No suitable dependency storage directory found"); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /loader/src/main/java/at/yawk/mdep/FileDependencyStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import at.yawk.mdep.model.Dependency; 10 | import java.io.IOException; 11 | import java.io.UncheckedIOException; 12 | import java.net.MalformedURLException; 13 | import java.net.URL; 14 | import java.nio.file.FileAlreadyExistsException; 15 | import java.nio.file.Files; 16 | import java.nio.file.Path; 17 | import java.nio.file.StandardCopyOption; 18 | import java.util.Base64; 19 | import javax.annotation.Nullable; 20 | import lombok.Getter; 21 | import lombok.RequiredArgsConstructor; 22 | 23 | /** 24 | * @author yawkat 25 | */ 26 | @RequiredArgsConstructor 27 | class FileDependencyStore implements DependencyStore { 28 | // visible for testing 29 | final Path base; 30 | 31 | private Path getDependencyPath(Dependency dependency) { 32 | String subPath = Base64.getUrlEncoder().withoutPadding().encodeToString(dependency.getSha512sum()); 33 | return base.resolve(subPath); 34 | } 35 | 36 | @Nullable 37 | @Override 38 | public URL getCachedDependency(Dependency dependency) { 39 | Path path = getDependencyPath(dependency); 40 | try { 41 | return Files.exists(path) ? path.toUri().toURL() : null; 42 | } catch (MalformedURLException e) { 43 | throw new UncheckedIOException(e); 44 | } 45 | } 46 | 47 | @Override 48 | public URL saveDependency(Dependency dependency, byte[] bytes) throws IOException { 49 | Path path = getDependencyPath(dependency); 50 | try { 51 | Files.createDirectories(path.getParent()); 52 | } catch (FileAlreadyExistsException ignored) { 53 | } 54 | Path tmp = Files.createTempFile(path.getParent(), "dl", ".jar"); 55 | Files.write(tmp, bytes); 56 | Files.move(tmp, path, StandardCopyOption.REPLACE_EXISTING); 57 | return path.toUri().toURL(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /loader/src/main/java/at/yawk/mdep/JulLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import lombok.RequiredArgsConstructor; 10 | 11 | /** 12 | * @author yawkat 13 | */ 14 | @RequiredArgsConstructor 15 | class JulLogger implements Logger { 16 | private final java.util.logging.Logger julLogger; 17 | 18 | @Override 19 | public void info(String msg) { 20 | julLogger.info(msg); 21 | } 22 | 23 | @Override 24 | public void warn(String msg) { 25 | julLogger.warning(msg); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /loader/src/main/java/at/yawk/mdep/Logger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | /** 10 | * @author yawkat 11 | */ 12 | public interface Logger { 13 | void info(String msg); 14 | 15 | void warn(String msg); 16 | } 17 | -------------------------------------------------------------------------------- /loader/src/main/java/at/yawk/mdep/ParentLastURLClassLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | import java.lang.reflect.Field; 12 | import java.net.URL; 13 | import java.net.URLClassLoader; 14 | import java.nio.ByteBuffer; 15 | import java.security.CodeSigner; 16 | import java.security.CodeSource; 17 | import java.util.ArrayList; 18 | import java.util.Enumeration; 19 | import java.util.Iterator; 20 | import java.util.List; 21 | import java.util.jar.Manifest; 22 | import lombok.SneakyThrows; 23 | import sun.misc.PerfCounter; 24 | import sun.misc.Resource; 25 | import sun.misc.URLClassPath; 26 | 27 | /** 28 | * http://stackoverflow.com/a/6424879/1116343 29 | */ 30 | public class ParentLastURLClassLoader extends URLClassLoader { 31 | public ParentLastURLClassLoader(URL[] urls, ClassLoader parent) { 32 | super(urls, parent); 33 | } 34 | 35 | /** 36 | * Defines a Class using the class bytes obtained from the specified 37 | * Resource. The resulting Class must be resolved before it can be 38 | * used. 39 | */ 40 | private Class defineClass(String name, Resource res) throws IOException { 41 | long t0 = System.nanoTime(); 42 | int i = name.lastIndexOf('.'); 43 | URL url = res.getCodeSourceURL(); 44 | if (i != -1) { 45 | String pkgname = name.substring(0, i); 46 | // Check if package already loaded. 47 | Manifest man = res.getManifest(); 48 | if (getPackage(pkgname) == null) { 49 | try { 50 | if (man != null) { 51 | definePackage(pkgname, man, url); 52 | } else { 53 | definePackage(pkgname, null, null, null, null, null, null, null); 54 | } 55 | } catch (IllegalArgumentException iae) { 56 | // parallel-capable class loaders: re-verify in case of a 57 | // race condition 58 | if (getPackage(pkgname) == null) { 59 | // Should never happen 60 | throw new AssertionError("Cannot find package " + 61 | pkgname); 62 | } 63 | } 64 | } 65 | } 66 | // Now read the class bytes and define the class 67 | ByteBuffer bb = res.getByteBuffer(); 68 | if (bb != null) { 69 | // Use (direct) ByteBuffer: 70 | CodeSigner[] signers = res.getCodeSigners(); 71 | CodeSource cs = new CodeSource(url, signers); 72 | PerfCounter.getReadClassBytesTime().addElapsedTimeFrom(t0); 73 | return defineClass(name, bb, cs); 74 | } else { 75 | byte[] b = res.getBytes(); 76 | // must read certificates AFTER reading bytes. 77 | CodeSigner[] signers = res.getCodeSigners(); 78 | CodeSource cs = new CodeSource(url, signers); 79 | PerfCounter.getReadClassBytesTime().addElapsedTimeFrom(t0); 80 | return defineClass(name, b, 0, b.length, cs); 81 | } 82 | } 83 | 84 | /** 85 | * Finds and loads the class with the specified name from the URL search 86 | * path. Any URLs referring to JAR files are loaded and opened as needed 87 | * until the class is found. 88 | * 89 | * @param name the name of the class 90 | * @return the resulting class 91 | * @throws ClassNotFoundException if the class could not be found, 92 | * or if the loader is closed. 93 | * @throws NullPointerException if {@code name} is {@code null}. 94 | */ 95 | @Override 96 | @SneakyThrows(ReflectiveOperationException.class) 97 | protected Class findClass(String name) 98 | throws ClassNotFoundException { 99 | String path = name.replace('.', '/') + ".class"; 100 | 101 | Field ucpField = URLClassLoader.class.getDeclaredField("ucp"); 102 | ucpField.setAccessible(true); 103 | Resource res = ((URLClassPath) ucpField.get(this)).getResource(path, false); 104 | if (res != null) { 105 | try { 106 | return defineClass(name, res); 107 | } catch (IOException e) { 108 | throw new ClassNotFoundException(name, e); 109 | } 110 | } else { 111 | throw new ClassNotFoundException(name); 112 | } 113 | } 114 | 115 | @Override 116 | protected synchronized Class loadClass(String name, boolean resolve) 117 | throws ClassNotFoundException { 118 | // First, check if the class has already been loaded 119 | Class c = findLoadedClass(name); 120 | if (c == null) { 121 | try { 122 | // checking local 123 | c = findClass(name); 124 | } catch (ClassNotFoundException e) { 125 | // checking parent 126 | // This call to loadClass may eventually call findClass again, in case the parent 127 | // doesn't find anything. 128 | c = super.loadClass(name, resolve); 129 | } 130 | } 131 | if (resolve) { 132 | resolveClass(c); 133 | } 134 | return c; 135 | } 136 | 137 | @Override 138 | public URL getResource(String name) { 139 | URL url = findResource(name); 140 | if (url == null) { 141 | // This call to getResource may eventually call findResource again, in case the 142 | // parent doesn't find anything. 143 | url = super.getResource(name); 144 | } 145 | return url; 146 | } 147 | 148 | @Override 149 | public Enumeration getResources(String name) throws IOException { 150 | /* 151 | * Similar to super, but local resources are enumerated before parent resources 152 | */ 153 | Enumeration localUrls = findResources(name); 154 | Enumeration parentUrls = null; 155 | if (getParent() != null) { 156 | parentUrls = getParent().getResources(name); 157 | } 158 | List urls = new ArrayList<>(); 159 | while (localUrls.hasMoreElements()) { 160 | urls.add(localUrls.nextElement()); 161 | } 162 | if (parentUrls != null) { 163 | while (parentUrls.hasMoreElements()) { 164 | urls.add(parentUrls.nextElement()); 165 | } 166 | } 167 | return new Enumeration() { 168 | Iterator iter = urls.iterator(); 169 | 170 | @Override 171 | public boolean hasMoreElements() { 172 | return iter.hasNext(); 173 | } 174 | 175 | @Override 176 | public URL nextElement() { 177 | return iter.next(); 178 | } 179 | }; 180 | } 181 | 182 | @SuppressWarnings("resource") 183 | @Override 184 | public InputStream getResourceAsStream(String name) { 185 | URL url = getResource(name); 186 | try { 187 | return url != null ? url.openStream() : null; 188 | } catch (IOException ignored) {} 189 | return null; 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /loader/src/main/java/at/yawk/mdep/StreamLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import java.io.PrintStream; 10 | import lombok.RequiredArgsConstructor; 11 | 12 | /** 13 | * @author yawkat 14 | */ 15 | @RequiredArgsConstructor 16 | class StreamLogger implements Logger { 17 | private final PrintStream stream; 18 | 19 | @Override 20 | public void info(String msg) { 21 | stream.println("[INFO] " + msg); 22 | } 23 | 24 | @Override 25 | public void warn(String msg) { 26 | stream.println("[WARN] " + msg); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /loader/src/main/java/at/yawk/mdep/model/Dependency.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep.model; 8 | 9 | import java.net.URL; 10 | import javax.xml.bind.annotation.XmlRootElement; 11 | import javax.xml.bind.annotation.XmlType; 12 | import lombok.Data; 13 | 14 | /** 15 | * @author yawkat 16 | */ 17 | @XmlType 18 | @XmlRootElement 19 | @Data 20 | public class Dependency { 21 | URL url; 22 | byte[] sha512sum; 23 | } 24 | -------------------------------------------------------------------------------- /loader/src/main/java/at/yawk/mdep/model/DependencySet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep.model; 8 | 9 | import java.util.List; 10 | import javax.xml.bind.annotation.XmlRootElement; 11 | import javax.xml.bind.annotation.XmlType; 12 | import lombok.Data; 13 | 14 | /** 15 | * @author yawkat 16 | */ 17 | @Data 18 | @XmlType 19 | @XmlRootElement 20 | public class DependencySet { 21 | List dependencies; 22 | } 23 | -------------------------------------------------------------------------------- /loader/src/test/java/at/yawk/mdep/DependencyLoaderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import at.yawk.mdep.model.Dependency; 10 | import at.yawk.mdep.model.DependencySet; 11 | import com.google.common.collect.Sets; 12 | import java.io.IOException; 13 | import java.net.URL; 14 | import java.util.Collections; 15 | import javax.xml.bind.DatatypeConverter; 16 | import org.testng.Assert; 17 | import org.testng.annotations.AfterMethod; 18 | import org.testng.annotations.BeforeMethod; 19 | import org.testng.annotations.Test; 20 | 21 | /** 22 | * @author yawkat 23 | */ 24 | public class DependencyLoaderTest { 25 | private TempDependencyStore store; 26 | 27 | @BeforeMethod 28 | public void setUp() throws Exception { 29 | store = new TempDependencyStore(); 30 | } 31 | 32 | @AfterMethod 33 | public void tearDown() throws Exception { 34 | store.close(); 35 | } 36 | 37 | @Test 38 | public void testDependencyLoader() throws IOException, ClassNotFoundException { 39 | DependencyLoader loader = new DependencyLoader(); 40 | loader.dependencyStore = store; 41 | 42 | Dependency dependency = new Dependency(); 43 | dependency.setUrl(new URL("https://repo.maven.apache.org/maven2/com/google/guava/guava/18.0/guava-18.0.jar")); 44 | dependency.setSha512sum(DatatypeConverter.parseHexBinary( 45 | "c84ad9f1646b52b6e19f55c3c63936c6dbe59597d53cec6855f85e21ad26f9bc27b0c541b793fab117e2359b1bf3fcd59b222255345fce858bc03cc48cbffd65")); 46 | 47 | DependencySet dependencySet = new DependencySet(); 48 | dependencySet.setDependencies(Collections.singletonList(dependency)); 49 | 50 | loader.downloadDependencies(dependencySet); 51 | 52 | // test parent-last 53 | Assert.assertNotSame(loader.toParentLastClassLoader().loadClass("com.google.common.collect.Sets"), Sets.class); 54 | // test parent-first 55 | Assert.assertSame(loader.toParentFirstClassLoader().loadClass("com.google.common.collect.Sets"), Sets.class); 56 | } 57 | 58 | @Test(expectedExceptions = IOException.class, 59 | expectedExceptionsMessageRegExp = "Mismatched hash on .+: expected \\w+ but got \\w+") 60 | public void testChecksum() throws IOException { 61 | DependencyLoader loader = new DependencyLoader(); 62 | loader.dependencyStore = store; 63 | 64 | Dependency dependency = new Dependency(); 65 | dependency.setUrl(new URL("https://repo.maven.apache.org/maven2/com/google/guava/guava/18.0/guava-18.0.jar")); 66 | dependency.setSha512sum(DatatypeConverter.parseHexBinary( 67 | "a84ad9f1646b52b6e19f55c3c63936c6dbe59597d53cec6855f85e21ad26f9bc27b0c541b793fab117e2359b1bf3fcd59b222255345fce858bc03cc48cbffd65")); 68 | 69 | DependencySet dependencySet = new DependencySet(); 70 | dependencySet.setDependencies(Collections.singletonList(dependency)); 71 | 72 | loader.downloadDependencies(dependencySet); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /loader/src/test/java/at/yawk/mdep/TempDependencyStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import java.io.Closeable; 10 | import java.io.IOException; 11 | import java.nio.file.FileVisitResult; 12 | import java.nio.file.Files; 13 | import java.nio.file.Path; 14 | import java.nio.file.SimpleFileVisitor; 15 | import java.nio.file.attribute.BasicFileAttributes; 16 | 17 | /** 18 | * @author yawkat 19 | */ 20 | public class TempDependencyStore extends FileDependencyStore implements Closeable { 21 | public TempDependencyStore() throws IOException { 22 | super(Files.createTempDirectory("mdep")); 23 | } 24 | 25 | @Override 26 | public void close() throws IOException { 27 | if (Files.exists(base)) { 28 | Files.walkFileTree(base, new SimpleFileVisitor() { 29 | @Override 30 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { 31 | Files.delete(file); 32 | return FileVisitResult.CONTINUE; 33 | } 34 | 35 | @Override 36 | public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { 37 | Files.delete(dir); 38 | return FileVisitResult.CONTINUE; 39 | } 40 | }); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /maven-plugin/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | mdep-parent 11 | at.yawk.mdep 12 | 1.0.2-SNAPSHOT 13 | 14 | 4.0.0 15 | 16 | mdep-maven-plugin 17 | maven-plugin 18 | 19 | 20 | 21 | org.apache.maven 22 | maven-plugin-api 23 | 3.3.3 24 | 25 | 26 | org.apache.maven.shared 27 | maven-dependency-tree 28 | 2.2 29 | 30 | 31 | org.apache.maven.plugin-tools 32 | maven-plugin-annotations 33 | 3.4 34 | provided 35 | 36 | 37 | 38 | org.apache.maven 39 | maven-core 40 | 3.3.3 41 | 42 | 43 | at.yawk.mdep 44 | mdep-loader 45 | ${project.version} 46 | 47 | 48 | 49 | 50 | 51 | 52 | org.apache.maven.plugins 53 | maven-plugin-plugin 54 | 3.4 55 | 56 | mdep 57 | 58 | 59 | 60 | mojo-descriptor 61 | 62 | descriptor 63 | 64 | 65 | 66 | help-goal 67 | 68 | helpmojo 69 | 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /maven-plugin/src/main/java/at/yawk/mdep/AntArtifactMatcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import java.util.Arrays; 10 | import java.util.List; 11 | import javax.annotation.Nullable; 12 | import org.apache.maven.artifact.Artifact; 13 | 14 | /** 15 | * @author yawkat 16 | */ 17 | public class AntArtifactMatcher implements ArtifactMatcher { 18 | private final List patterns; 19 | 20 | public AntArtifactMatcher(String pattern) { 21 | this.patterns = Arrays.asList(pattern.split(":")); 22 | } 23 | 24 | @Override 25 | public boolean matches(Artifact artifact) { 26 | List parts = Arrays.asList( 27 | artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getClassifier()); 28 | for (int i = 0; i < this.patterns.size(); i++) { 29 | if (i > parts.size()) { 30 | // too specific 31 | return false; 32 | } 33 | if (!patternMatches(patterns.get(i), parts.get(i))) { 34 | return false; 35 | } 36 | } 37 | return true; 38 | } 39 | 40 | static boolean patternMatches(String pattern, @Nullable String s) { 41 | if (pattern.isEmpty() || pattern.equals("*")) { 42 | return true; 43 | } 44 | 45 | if (s == null) { 46 | return false; 47 | } 48 | 49 | if (pattern.startsWith("*") && pattern.endsWith("*")) { 50 | return s.contains(pattern.substring(1, pattern.length() - 1)); 51 | } 52 | 53 | if (pattern.startsWith("*")) { 54 | return s.endsWith(pattern.substring(1)); 55 | } 56 | 57 | if (pattern.endsWith("*")) { 58 | return s.startsWith(pattern.substring(0, pattern.length() - 1)); 59 | } 60 | 61 | return pattern.equals(s); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /maven-plugin/src/main/java/at/yawk/mdep/ArtifactMatcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import org.apache.maven.artifact.Artifact; 10 | 11 | /** 12 | * @author yawkat 13 | */ 14 | public interface ArtifactMatcher { 15 | static ArtifactMatcher acceptAll() { 16 | return artifact -> true; 17 | } 18 | 19 | static ArtifactMatcher anyMatch(Iterable matchers) { 20 | return artifact -> { 21 | for (ArtifactMatcher matcher : matchers) { 22 | if (matcher.matches(artifact)) { 23 | return true; 24 | } 25 | } 26 | return false; 27 | }; 28 | } 29 | 30 | static ArtifactMatcher allMatch(Iterable matchers) { 31 | return artifact -> { 32 | for (ArtifactMatcher matcher : matchers) { 33 | if (matcher.matches(artifact)) { 34 | return true; 35 | } 36 | } 37 | return false; 38 | }; 39 | } 40 | 41 | boolean matches(Artifact artifact); 42 | 43 | @SuppressWarnings("InstanceMethodNamingConvention") 44 | default ArtifactMatcher and(ArtifactMatcher other) { 45 | return artifact -> this.matches(artifact) && other.matches(artifact); 46 | } 47 | 48 | @SuppressWarnings("InstanceMethodNamingConvention") 49 | default ArtifactMatcher or(ArtifactMatcher other) { 50 | return artifact -> this.matches(artifact) || other.matches(artifact); 51 | } 52 | 53 | @SuppressWarnings("InstanceMethodNamingConvention") 54 | default ArtifactMatcher not() { 55 | return artifact -> !this.matches(artifact); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /maven-plugin/src/main/java/at/yawk/mdep/GenerateMojo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import at.yawk.mdep.model.Dependency; 10 | import at.yawk.mdep.model.DependencySet; 11 | import com.google.common.annotations.VisibleForTesting; 12 | import java.io.File; 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | import java.io.OutputStream; 16 | import java.net.MalformedURLException; 17 | import java.net.URL; 18 | import java.net.URLConnection; 19 | import java.nio.file.Files; 20 | import java.nio.file.InvalidPathException; 21 | import java.nio.file.Path; 22 | import java.security.MessageDigest; 23 | import java.security.NoSuchAlgorithmException; 24 | import java.time.Instant; 25 | import java.util.ArrayList; 26 | import java.util.Arrays; 27 | import java.util.Collection; 28 | import java.util.Collections; 29 | import java.util.List; 30 | import java.util.Set; 31 | import java.util.stream.Collectors; 32 | import javax.annotation.Nullable; 33 | import javax.xml.bind.JAXBContext; 34 | import javax.xml.bind.JAXBException; 35 | import javax.xml.bind.Marshaller; 36 | import lombok.SneakyThrows; 37 | import org.apache.maven.artifact.Artifact; 38 | import org.apache.maven.artifact.repository.ArtifactRepository; 39 | import org.apache.maven.artifact.repository.metadata.ArtifactRepositoryMetadata; 40 | import org.apache.maven.artifact.repository.metadata.Metadata; 41 | import org.apache.maven.artifact.repository.metadata.Snapshot; 42 | import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader; 43 | import org.apache.maven.artifact.resolver.filter.ArtifactFilter; 44 | import org.apache.maven.model.Resource; 45 | import org.apache.maven.plugin.AbstractMojo; 46 | import org.apache.maven.plugin.MojoExecutionException; 47 | import org.apache.maven.plugin.MojoFailureException; 48 | import org.apache.maven.plugins.annotations.Component; 49 | import org.apache.maven.plugins.annotations.LifecyclePhase; 50 | import org.apache.maven.plugins.annotations.Mojo; 51 | import org.apache.maven.plugins.annotations.Parameter; 52 | import org.apache.maven.plugins.annotations.ResolutionScope; 53 | import org.apache.maven.project.MavenProject; 54 | import org.apache.maven.shared.dependency.tree.DependencyNode; 55 | import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder; 56 | import org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException; 57 | import org.apache.maven.shared.dependency.tree.traversal.DependencyNodeVisitor; 58 | import org.codehaus.plexus.util.xml.pull.XmlPullParserException; 59 | 60 | /** 61 | * @author yawkat 62 | */ 63 | @SuppressWarnings("WeakerAccess") 64 | @Mojo(name = "generate", 65 | defaultPhase = LifecyclePhase.GENERATE_RESOURCES, 66 | requiresDependencyCollection = ResolutionScope.COMPILE) 67 | public class GenerateMojo extends AbstractMojo { 68 | @Parameter(defaultValue = "${project}", readonly = true) 69 | MavenProject project; 70 | 71 | @Parameter(defaultValue = "${localRepository}", readonly = true) 72 | ArtifactRepository localRepository; 73 | 74 | @Parameter(name = "outputDirectory", defaultValue = "${project.build.directory}/generated-resources/mdep") 75 | File outputDirectory; 76 | 77 | @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true) 78 | Collection remoteArtifactRepositories; 79 | 80 | @Parameter(name = "includes") 81 | @Nullable 82 | List includes = null; 83 | 84 | @Parameter(name = "excludes") 85 | List excludes = Collections.emptyList(); 86 | 87 | @Parameter(name = "repositories") 88 | @Nullable 89 | Set repositories = null; 90 | 91 | // one week caching by default 92 | @Parameter(name = "cacheHours", defaultValue = "168") 93 | double cacheHours; 94 | 95 | @Component DependencyTreeBuilder dependencyTreeBuilder; 96 | 97 | private Path cacheStore; 98 | 99 | @Override 100 | public void execute() throws MojoExecutionException, MojoFailureException { 101 | if (cacheHours > 0) { 102 | cacheStore = Environment.createCacheStore(new Logger() { 103 | @Override 104 | public void info(String msg) { 105 | getLog().info(msg); 106 | } 107 | 108 | @Override 109 | public void warn(String msg) { 110 | getLog().warn(msg); 111 | } 112 | }, "mdep-maven-plugin"); 113 | } 114 | 115 | ArtifactMatcher includesMatcher; 116 | if (includes == null) { 117 | includesMatcher = ArtifactMatcher.acceptAll(); 118 | } else { 119 | includesMatcher = ArtifactMatcher.anyMatch(toAntMatchers(includes)); 120 | } 121 | ArtifactMatcher excludesMatcher = ArtifactMatcher.anyMatch(toAntMatchers(excludes)); 122 | ArtifactMatcher matcher = includesMatcher.and(excludesMatcher.not()); 123 | 124 | List artifacts = new ArrayList<>(); 125 | 126 | try { 127 | ArtifactFilter subtreeFilter = artifact -> artifact.getScope() == null || 128 | artifact.getScope().equals(Artifact.SCOPE_COMPILE) || 129 | artifact.getScope().equals(Artifact.SCOPE_RUNTIME); 130 | DependencyNode root = dependencyTreeBuilder.buildDependencyTree(project, localRepository, subtreeFilter); 131 | root.accept(new DependencyNodeVisitor() { 132 | @Override 133 | public boolean visit(DependencyNode node) { 134 | if (node.getArtifact() != null) { 135 | if (!subtreeFilter.include(node.getArtifact())) { return false; } 136 | artifacts.add(node.getArtifact()); 137 | } 138 | return true; 139 | } 140 | 141 | @Override 142 | public boolean endVisit(DependencyNode node) { 143 | return true; 144 | } 145 | }); 146 | } catch (DependencyTreeBuilderException e) { 147 | throw new MojoExecutionException("Failed to build dependency tree", e); 148 | } 149 | 150 | List dependencies = new ArrayList<>(); 151 | for (Artifact artifact : artifacts) { 152 | if (matcher.matches(artifact)) { 153 | dependencies.add(findArtifact(artifact)); 154 | } 155 | } 156 | 157 | getLog().info("Saving dependency xml"); 158 | 159 | DependencySet dependencySet = new DependencySet(); 160 | dependencySet.setDependencies(dependencies); 161 | 162 | if (!outputDirectory.mkdirs()) { 163 | throw new MojoExecutionException("Failed to create output directory"); 164 | } 165 | File outputFile = new File(outputDirectory, "mdep-dependencies.xml"); 166 | 167 | try { 168 | JAXBContext jaxbContext = JAXBContext.newInstance(DependencySet.class); 169 | Marshaller marshaller = jaxbContext.createMarshaller(); 170 | marshaller.marshal(dependencySet, outputFile); 171 | 172 | } catch (JAXBException e) { 173 | throw new MojoExecutionException("Failed to serialize dependency set", e); 174 | } 175 | Resource resource = new Resource(); 176 | resource.setDirectory(outputDirectory.toString()); 177 | resource.setFiltering(false); 178 | project.addResource(resource); 179 | } 180 | 181 | private Dependency findArtifact(Artifact artifact) throws MojoExecutionException { 182 | // all are scanned, the first is used to store the dependency 183 | List cacheSearchLocations = new ArrayList<>(); 184 | 185 | List coordinateComponents = Arrays.asList( 186 | artifact.getGroupId(), 187 | artifact.getArtifactId(), 188 | artifact.getVersion(), 189 | artifact.getScope()); 190 | 191 | // in 1.0, we used only ':' as the separator. This does not work on windows, and the following code fixes 192 | // that problem. 193 | 194 | for (String separator : Arrays.asList(":", "/")) { 195 | try { 196 | cacheSearchLocations.add(cacheStore.resolve(String.join(separator, coordinateComponents))); 197 | } catch (InvalidPathException ignored) {} 198 | } 199 | 200 | // check local cache 201 | if (cacheHours > 0) { 202 | for (Path searchLocation : cacheSearchLocations) { 203 | if (Files.exists(searchLocation)) { 204 | Instant cacheDeadline = Instant.now().minusSeconds((long) (60 * 60 * cacheHours)); 205 | try { 206 | if (Files.getLastModifiedTime(searchLocation).toInstant() 207 | .isAfter(cacheDeadline)) { 208 | 209 | try (InputStream in = Files.newInputStream(searchLocation)) { 210 | Dependency dependency = (Dependency) JAXBContext.newInstance(Dependency.class) 211 | .createUnmarshaller().unmarshal(in); 212 | 213 | getLog().info("Checksum was present in local cache: " + artifact); 214 | return dependency; 215 | } 216 | } 217 | } catch (IOException | JAXBException e) { 218 | throw new MojoExecutionException("Failed to read local cache", e); 219 | } 220 | } 221 | } 222 | } 223 | 224 | for (ArtifactRepository repository : remoteArtifactRepositories) { 225 | // only scan configured repositories 226 | if (this.repositories != null && 227 | !this.repositories.contains(repository.getId())) { 228 | continue; 229 | } 230 | 231 | Dependency dependency = findArtifactInRepository(artifact, repository); 232 | if (dependency != null) { 233 | 234 | if (cacheHours > 0) { 235 | try { 236 | Path target = cacheSearchLocations.get(0); 237 | if (!Files.isDirectory(target.getParent())) { 238 | Files.createDirectories(target.getParent()); 239 | } 240 | try (OutputStream out = Files.newOutputStream(target)) { 241 | JAXBContext.newInstance(Dependency.class) 242 | .createMarshaller().marshal(dependency, out); 243 | } 244 | } catch (IOException | JAXBException e) { 245 | getLog().warn("Could not save dependency to local cache", e); 246 | } 247 | } 248 | return dependency; 249 | } 250 | } 251 | 252 | throw new MojoExecutionException("Could not find " + artifact + " in configured repositories"); 253 | } 254 | 255 | @Nullable 256 | @SneakyThrows({ MalformedURLException.class, NoSuchAlgorithmException.class }) 257 | @VisibleForTesting 258 | Dependency findArtifactInRepository(Artifact artifact, ArtifactRepository repository) 259 | throws MojoExecutionException { 260 | 261 | String artifactPath = getArtifactPath(artifact, artifact.getVersion()); 262 | if (artifact.isSnapshot()) { 263 | ArtifactRepositoryMetadata metadata = new ArtifactRepositoryMetadata(artifact) { 264 | // maven is weird - i have yet to find a better solution. 265 | 266 | @Override 267 | public boolean storedInArtifactVersionDirectory() { 268 | return true; 269 | } 270 | 271 | @Override 272 | public String getBaseVersion() { 273 | return artifact.getBaseVersion(); 274 | } 275 | }; 276 | 277 | // try to load maven-metadata.xml in case we need to use a different version for snapshots 278 | URL metaUrl = new URL(repository.getUrl() + '/' + repository.pathOfRemoteRepositoryMetadata(metadata)); 279 | 280 | Metadata loadedMetadata; 281 | try (InputStream input = openStream(metaUrl)) { 282 | loadedMetadata = new MetadataXpp3Reader().read(input, true); 283 | } catch (IOException e) { 284 | // could not find metadata 285 | loadedMetadata = null; 286 | } catch (XmlPullParserException e) { 287 | throw new MojoExecutionException("Failed to parse metadata", e); 288 | } 289 | 290 | if (loadedMetadata != null) { 291 | Snapshot snapshot = loadedMetadata.getVersioning().getSnapshot(); 292 | 293 | String versionWithoutSuffix = artifact.getVersion() 294 | .substring(0, artifact.getBaseVersion().lastIndexOf('-')); 295 | artifactPath = getArtifactPath(artifact, 296 | versionWithoutSuffix + '-' + snapshot.getTimestamp() + '-' + 297 | snapshot.getBuildNumber()); 298 | } 299 | } 300 | 301 | URL url = new URL(repository.getUrl() + '/' + artifactPath); 302 | try (InputStream input = openStream(url)) { 303 | getLog().info("Getting checksum for " + artifact); 304 | 305 | MessageDigest digest = MessageDigest.getInstance("SHA-512"); 306 | byte[] buf = new byte[4096]; 307 | int len; 308 | while ((len = input.read(buf)) >= 0) { 309 | digest.update(buf, 0, len); 310 | } 311 | 312 | Dependency dependency = new Dependency(); 313 | dependency.setUrl(url); 314 | dependency.setSha512sum(digest.digest()); 315 | return dependency; 316 | } catch (IOException ignored) { 317 | // not in this repo 318 | return null; 319 | } 320 | } 321 | 322 | private static String getArtifactPath(Artifact artifact, String version) { 323 | StringBuilder builder = new StringBuilder() 324 | .append(artifact.getGroupId().replace('.', '/')).append('/') 325 | .append(artifact.getArtifactId()).append('/') 326 | .append(artifact.getBaseVersion()).append('/') 327 | .append(artifact.getArtifactId()).append('-').append(version); 328 | if (artifact.getArtifactHandler().getClassifier() != null) { 329 | builder.append('-').append(artifact.getArtifactHandler().getClassifier()); 330 | } 331 | String extension = artifact.getArtifactHandler().getExtension(); 332 | if (extension == null) { 333 | extension = "jar"; 334 | } 335 | return builder.append('.').append(extension).toString(); 336 | } 337 | 338 | private static InputStream openStream(URL metaUrl) throws IOException { 339 | URLConnection urlConnection = metaUrl.openConnection(); 340 | // Java user agent is blocked in some cases 341 | urlConnection.setRequestProperty("User-Agent", "mdep"); 342 | return urlConnection.getInputStream(); 343 | } 344 | 345 | private static List toAntMatchers(List antPatterns) { 346 | return antPatterns.stream() 347 | .map(AntArtifactMatcher::new) 348 | .collect(Collectors.toList()); 349 | } 350 | } 351 | -------------------------------------------------------------------------------- /maven-plugin/src/test/java/at/yawk/mdep/AntArtifactMatcherTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import org.apache.maven.artifact.Artifact; 10 | import org.mockito.Mockito; 11 | import org.testng.annotations.Test; 12 | 13 | import static org.testng.Assert.assertFalse; 14 | import static org.testng.Assert.assertTrue; 15 | 16 | /** 17 | * @author yawkat 18 | */ 19 | public class AntArtifactMatcherTest { 20 | @Test 21 | public void testMatcher() { 22 | assertTrue(new AntArtifactMatcher("").matches(createArtifact("com.example", "test", "1.0", "jar"))); 23 | assertTrue(new AntArtifactMatcher("com.example").matches(createArtifact("com.example", "test", "1.0", "jar"))); 24 | assertFalse(new AntArtifactMatcher("at.yawk").matches(createArtifact("com.example", "test", "1.0", "jar"))); 25 | } 26 | 27 | private static Artifact createArtifact(String group, String artifactId, String version, String classifier) { 28 | Artifact artifact = Mockito.mock(Artifact.class); 29 | Mockito.when(artifact.getGroupId()).thenReturn(group); 30 | Mockito.when(artifact.getArtifactId()).thenReturn(artifactId); 31 | Mockito.when(artifact.getVersion()).thenReturn(version); 32 | Mockito.when(artifact.getClassifier()).thenReturn(classifier); 33 | return artifact; 34 | } 35 | 36 | @Test 37 | public void testPartMatch() { 38 | assertTrue(AntArtifactMatcher.patternMatches("abc", "abc")); 39 | assertFalse(AntArtifactMatcher.patternMatches("abcd", "abc")); 40 | 41 | assertTrue(AntArtifactMatcher.patternMatches("", "abc")); 42 | assertTrue(AntArtifactMatcher.patternMatches("*", "abc")); 43 | 44 | assertTrue(AntArtifactMatcher.patternMatches("abc*", "abc")); 45 | assertTrue(AntArtifactMatcher.patternMatches("abc*", "abcde")); 46 | assertFalse(AntArtifactMatcher.patternMatches("abc*", "ab")); 47 | assertFalse(AntArtifactMatcher.patternMatches("abc*", "xabcd")); 48 | 49 | assertTrue(AntArtifactMatcher.patternMatches("*cde", "abcde")); 50 | assertTrue(AntArtifactMatcher.patternMatches("*cde", "bcde")); 51 | assertTrue(AntArtifactMatcher.patternMatches("*cde", "cde")); 52 | 53 | assertTrue(AntArtifactMatcher.patternMatches("*cde*", "cde")); 54 | assertTrue(AntArtifactMatcher.patternMatches("*cde*", "abcdefg")); 55 | } 56 | } -------------------------------------------------------------------------------- /maven-plugin/src/test/java/at/yawk/mdep/GenerateMojoTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | package at.yawk.mdep; 8 | 9 | import at.yawk.mdep.model.Dependency; 10 | import org.apache.maven.artifact.DefaultArtifact; 11 | import org.apache.maven.artifact.handler.DefaultArtifactHandler; 12 | import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; 13 | import org.apache.maven.artifact.repository.MavenArtifactRepository; 14 | import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; 15 | import org.apache.maven.plugin.MojoExecutionException; 16 | import org.apache.maven.plugin.logging.SystemStreamLog; 17 | import org.testng.Assert; 18 | import org.testng.annotations.Test; 19 | 20 | /** 21 | * @author yawkat 22 | */ 23 | public class GenerateMojoTest { 24 | @Test 25 | public void testFindArtifactInRepository() throws MojoExecutionException { 26 | GenerateMojo mojo = new GenerateMojo(); 27 | mojo.setLog(new SystemStreamLog()); 28 | 29 | Dependency dependency = mojo.findArtifactInRepository( 30 | new DefaultArtifact("org.spigotmc", "spigot-api", "1.8-R0.1-SNAPSHOT", 31 | "compile", "jar", "jar", new DefaultArtifactHandler()), 32 | new MavenArtifactRepository("yawkat", 33 | "http://mvn.yawk.at", 34 | new DefaultRepositoryLayout(), 35 | new ArtifactRepositoryPolicy(), 36 | new ArtifactRepositoryPolicy()) 37 | ); 38 | Assert.assertNotNull(dependency); 39 | } 40 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | at.yawk.mdep 6 | mdep-parent 7 | pom 8 | 1.0.2-SNAPSHOT 9 | 10 | 11 | maven-plugin 12 | loader 13 | 14 | 15 | 16 | 17 | MPL 2.0 18 | https://www.mozilla.org/en-US/MPL/2.0/ 19 | 20 | 21 | 22 | ${project.groupId}:${project.artifactId} 23 | Maven plugin and library for loading maven dependencies remotely at runtime. 24 | https://github.com/yawkat/mdep 25 | 26 | 27 | 28 | Jonas Konrad 29 | http://yawk.at 30 | 31 | 32 | 33 | 34 | https://github.com/yawkat/mdep 35 | scm:git:https://github.com/yawkat/mdep.git 36 | scm:git:git@github.com:yawkat/mdep.git 37 | HEAD 38 | 39 | 40 | 41 | 42 | ossrh 43 | https://oss.sonatype.org/content/repositories/snapshots 44 | 45 | 46 | ossrh 47 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 48 | 49 | 50 | 51 | 52 | 1.8 53 | 1.8 54 | UTF-8 55 | 56 | 57 | 58 | 59 | org.projectlombok 60 | lombok 61 | 1.16.4 62 | provided 63 | 64 | 65 | com.google.code.findbugs 66 | annotations 67 | 3.0.0 68 | provided 69 | 70 | 71 | 72 | org.testng 73 | testng 74 | 6.9.6 75 | test 76 | 77 | 78 | org.mockito 79 | mockito-core 80 | 2.0.31-beta 81 | test 82 | 83 | 84 | 85 | 86 | 87 | 88 | org.apache.maven.plugins 89 | maven-source-plugin 90 | 2.2.1 91 | 92 | 93 | org.apache.maven.plugins 94 | maven-javadoc-plugin 95 | 2.9.1 96 | 97 | 98 | org.apache.maven.plugins 99 | maven-gpg-plugin 100 | 1.5 101 | 102 | 103 | 104 | sign 105 | deploy 106 | 107 | sign 108 | 109 | 110 | 111 | 112 | 113 | org.apache.maven.plugins 114 | maven-release-plugin 115 | 2.5.3 116 | 117 | 118 | org.apache.maven.plugins 119 | maven-deploy-plugin 120 | 2.8.2 121 | 122 | 123 | 124 | deploy 125 | deploy 126 | 127 | deploy 128 | 129 | 130 | 131 | 132 | 133 | 134 | --------------------------------------------------------------------------------