Debian Codegraph @

src/main/java/MavenCapsule.java

raw symbols SCIP
1 /*
2 * Copyright (c) 2015, Parallel Universe Software Co. and Contributors. All rights reserved.
3 *
4 * This program and the accompanying materials are licensed under the terms
5 * of the Eclipse Public License v1.0, available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 */
8
9 import capsule.DependencyManager;
10 import capsule.PomReader;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.lang.reflect.AccessibleObject;
14 import java.nio.file.Files;
15 import java.nio.file.Path;
16 import java.nio.file.Paths;
17 import java.util.ArrayList;
18 import java.util.Map.Entry;
19 import static java.util.Arrays.asList;
20 import java.util.Collection;
21 import static java.util.Collections.emptyList;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import org.eclipse.aether.graph.Dependency;
26
27 /**
28 *
29 * @author pron
30 */
31 public class MavenCapsule extends Capsule {
32 private static final String PROP_TREE = OPTION("capsule.tree", "false", "printDependencyTree", "Prints the capsule's dependency tree.");
33 private static final String PROP_RESOLVE = OPTION("capsule.resolve", "false", "resolve", "Downloads all un-cached dependencies.");
34 private static final String PROP_USE_LOCAL_REPO = OPTION("capsule.local", null, null, "Sets the path of the local Maven repository to use.");
35 private static final String PROP_RESET = "capsule.reset";
36 private static final String PROP_USER_HOME = "user.home";
37
38 private static final String PROP_PROFILE = "capsule.profile";
39 private static final int PROFILE = emptyOrTrue(System.getProperty(PROP_PROFILE)) ? LOG_QUIET : LOG_DEBUG;
40
41 private static final Entry<String, List<String>> ATTR_REPOSITORIES = ATTRIBUTE("Repositories", T_LIST(T_STRING()), asList("central"), true, "A list of Maven repositories, each formatted as URL or NAME(URL)");
42 private static final Entry<String, Boolean> ATTR_ALLOW_SNAPSHOTS = ATTRIBUTE("Allow-Snapshots", T_BOOL(), false, true, "Whether or not SNAPSHOT dependencies are allowed");
43
44 private static final String ENV_CAPSULE_REPOS = "CAPSULE_REPOS";
45 private static final String ENV_CAPSULE_LOCAL_REPO = "CAPSULE_LOCAL_REPO";
46
47 private static final String POM_FILE = "pom.xml";
48 private static final String DEPS_CACHE_NAME = "deps";
49
50 private DependencyManager dependencyManager;
51 private PomReader pom;
52 private Path localRepo;
53 private String version; // app version cache
54
55 private static final List<Path> UNRESOLVED = new ArrayList<>();
56 private final Map<Dependency, List<Path>> dependencies = new HashMap<>();
57
58 //<editor-fold defaultstate="collapsed" desc="Constructors">
59 /////////// Constructors ///////////////////////////////////
60 public MavenCapsule(Path jarFile) {
61 super(jarFile);
62 }
63
64 public MavenCapsule(Capsule pred) {
65 super(pred);
66 }
67
68 @Override
69 protected void finalizeCapsule() {
70 this.pom = createPomReader();
71 if (dependencyManager != null)
72 setDependencyRepositories(getAttribute(ATTR_REPOSITORIES));
73
74 super.finalizeCapsule();
75 }
76 //</editor-fold>
77
78 //<editor-fold defaultstate="collapsed" desc="Main Operations">
79 /////////// Main Operations ///////////////////////////////////
80 void printDependencyTree(List<String> args) {
81 verifyNonEmpty("Cannot print dependencies of a wrapper capsule.");
82 STDOUT.println("Dependencies for " + getAppId());
83
84 if (hasAttribute(ATTR_APP_ARTIFACT)) {
85 final String appArtifact = getAttribute(ATTR_APP_ARTIFACT);
86 if (isDependency(appArtifact))
87 getDependencyManager().printDependencyTree(appArtifact, "jar", STDOUT);
88 } else {
89 lookupAllDependencies();
90 if (dependencies.isEmpty())
91 STDOUT.println("No external dependencies.");
92 else
93 getDependencyManager().printDependencyTree(getUnresolved(), STDOUT);
94 }
95 }
96
97 void resolve(List<String> args) throws IOException, InterruptedException {
98 verifyNonEmpty("Cannot resolve a wrapper capsule.");
99
100 if (hasAttribute(ATTR_APP_ARTIFACT)) {
101 final String appArtifact = getAttribute(ATTR_APP_ARTIFACT);
102 lookup(appArtifact);
103 }
104 lookupAllDependencies();
105
106 getDependencyManager().resolveDependencies(getUnresolved());
107 log(LOG_QUIET, "Capsule resolved");
108 }
109
110 private void verifyNonEmpty(String message) {
111 if (isEmptyCapsule())
112 throw new IllegalArgumentException(message);
113 }
114
115 private void lookupAllDependencies() {
116 try {
117 accessible(Capsule.class.getDeclaredMethod("lookupAllDependencies")).invoke(this);
118 } catch (ReflectiveOperationException e) {
119 throw new AssertionError(e);
120 }
121 // for (Map.Entry<String, ?> attr : asList(
122 // ATTR_DEPENDENCIES,
123 // ATTR_NATIVE_DEPENDENCIES,
124 // ATTR_APP_CLASS_PATH,
125 // ATTR_BOOT_CLASS_PATH,
126 // ATTR_BOOT_CLASS_PATH_P,
127 // ATTR_BOOT_CLASS_PATH_A,
128 // ATTR_JAVA_AGENTS,
129 // ATTR_NATIVE_AGENTS))
130 // getAttribute(attr);
131 }
132
133 private List<Dependency> getUnresolved() {
134 final List<Dependency> unresolved = new ArrayList<>();
135 for (Map.Entry<Dependency, List<Path>> e : dependencies.entrySet()) {
136 if (e.getValue() == UNRESOLVED)
137 unresolved.add(e.getKey());
138 }
139 return unresolved;
140 }
141 //</editor-fold>
142
143 //<editor-fold desc="Capsule Overrides">
144 /////////// Capsule Overrides ///////////////////////////////////
145 @Override
146 @SuppressWarnings("unchecked")
147 protected <T> T attribute(Entry<String, T> attr) {
148 if (ATTR_APP_ID.equals(attr)) {
149 String id = super.attribute(ATTR_APP_ID);
150 if (id == null && pom != null)
151 id = pom.getGroupId() + "." + pom.getArtifactId();
152 return (T) id;
153 }
154
155 if (ATTR_APP_VERSION.equals(attr)) {
156 String ver = super.attribute(ATTR_APP_VERSION);
157 if (ver == null && version != null)
158 ver = version;
159 if (ver == null && hasAttribute(ATTR_APP_ARTIFACT) && isDependency(getAttribute(ATTR_APP_ARTIFACT)))
160 ver = getAppArtifactVersion(getDependencyManager().getLatestVersion(getAttribute(ATTR_APP_VERSION), "jar"));
161 if (ver == null && pom != null)
162 ver = pom.getVersion();
163 this.version = ver; // cache
164 return (T) ver;
165 }
166
167 if (ATTR_DEPENDENCIES.equals(attr)) {
168 List<Object> deps = super.attribute(ATTR_DEPENDENCIES);
169 if ((deps == null || deps.isEmpty()) && pom != null) {
170 deps = new ArrayList<>();
171 for (String[] d : pom.getDependencies())
172 deps.add(lookup(pom.resolve(d[0]), d[1], ATTR_DEPENDENCIES, null));
173 }
174 return (T) deps;
175 }
176
177 if (ATTR_REPOSITORIES.equals(attr)) {
178 final List<String> repos = new ArrayList<String>();
179 repos.addAll(nullToEmpty(split(getenv(ENV_CAPSULE_REPOS), "[,\\s]\\s*")));
180 repos.addAll(super.attribute(ATTR_REPOSITORIES));
181 if (pom != null)
182 addAllIfAbsent(repos, nullToEmpty(pom.getRepositories()));
183
184 return (T) repos;
185 }
186 return super.attribute(attr);
187 }
188
189 @Override
190 protected Object lookup0(Object x, String type, Entry<String, ?> attrContext, Object context) {
191 final Object res = super.lookup0(x, type, attrContext, context);
192
193 if (res == null && x instanceof String) {
194 final String s = (String) x;
195 if (isDependency(s)) {
196 final Dependency dep = DependencyManager.toDependency(s, type.isEmpty() ? "jar" : type);
197 if (!dependencies.containsKey(dep))
198 dependencies.put(dep, UNRESOLVED);
199 return super.lookup0(dep, type, attrContext, context);
200 }
201 } else if (x instanceof String && res instanceof Path) { // If found also lookup its transitive deps, see #14
202 final String s = (String) x;
203 final List<Object> ret = new ArrayList<>();
204 ret.add(res);
205 if (isDependency(s)) {
206 final Dependency dep = DependencyManager.toDependency(s, type.isEmpty() ? "jar" : type);
207 final PomReader pom = createPomReader(getWritableAppCache().resolve((Path) res), getPomJarEntryName(dep));
208 if (pom != null && pom.getDependencies() != null) {
209 for (final String[] d : pom.getDependencies())
210 addFlat(lookup0(pom.resolve(d[0]), d[1], ATTR_DEPENDENCIES, null), ret);
211 }
212 }
213 return ret;
214 }
215 return res;
216 }
217
218 @Override
219 protected List<Path> resolve0(final Object x) {
220 if (x instanceof Dependency) {
221 final Dependency d = (Dependency) x;
222 if (dependencies.get(d) == UNRESOLVED) {
223 long start = clock();
224 Map<Dependency, List<Path>> resolved = getDependencyManager().resolveDependencies(getUnresolved());
225 log(LOG_DEBUG, "Maven resolved: " + resolved);
226 dependencies.putAll(resolved);
227 time("resolveAll", start);
228 }
229 assert dependencies.get(d) != UNRESOLVED : d;
230 final Object y = dependencies.get(d);
231 if (y == null) // there's another MavenCapsule in the chain
232 return super.resolve0(x);
233 return resolve(y);
234 }
235 return super.resolve0(x);
236 }
237 //</editor-fold>
238
239 //<editor-fold defaultstate="collapsed" desc="Internal Methods">
240 /////////// Internal Methods ///////////////////////////////////
241 private PomReader createPomReader() {
242 return createPomReader(getJarFile(), POM_FILE);
243 }
244
245 private PomReader createPomReader(Path jarFile, String entry) {
246 try (InputStream is = getEntryInputStream(jarFile, entry)) {
247 return is != null ? new PomReader(is) : null;
248 } catch (IOException e) {
249 throw new RuntimeException("Could not read " + entry, e);
250 }
251 }
252
253 private DependencyManager getDependencyManager() {
254 final DependencyManager dm = initDependencyManager();
255 if (dm == null)
256 throw new RuntimeException("Capsule " + getJarFile() + " uses dependencies, while the necessary dependency management classes are not found in the capsule JAR");
257 return dm;
258 }
259
260 private DependencyManager initDependencyManager() {
261 if (dependencyManager == null) {
262 dependencyManager = createDependencyManager();
263 if (dependencyManager != null)
264 setDependencyRepositories(getAttribute(ATTR_REPOSITORIES));
265 }
266 return dependencyManager;
267 }
268
269 private DependencyManager createDependencyManager() {
270 final boolean reset = systemPropertyEmptyOrTrue(PROP_RESET);
271 return createDependencyManager(getLocalRepo().toAbsolutePath(), reset, getLogLevel());
272 }
273
274 protected DependencyManager createDependencyManager(Path localRepo, boolean reset, int logLevel) {
275 MavenCapsule ct;
276 return (ct = getCallTarget(MavenCapsule.class)) != null ? ct.createDependencyManager(localRepo, reset, logLevel) : createDependencyManager0(localRepo, reset, logLevel);
277 }
278
279 private DependencyManager createDependencyManager0(Path localRepo, boolean reset, int logLevel) {
280 return new DependencyManager(localRepo, reset, logLevel);
281 }
282
283 private void setDependencyRepositories(List<String> repositories) {
284 getDependencyManager().setRepos(repositories, getAttribute(ATTR_ALLOW_SNAPSHOTS));
285 }
286
287 private Path getLocalRepo() {
288 if (localRepo == null) {
289 Path repo;
290 final String local = emptyToNull(expandCommandLinePath(propertyOrEnv(PROP_USE_LOCAL_REPO, ENV_CAPSULE_LOCAL_REPO)));
291 if (local != null)
292 repo = toAbsolutePath(Paths.get(local));
293 else {
294 repo = getCacheDir().resolve(DEPS_CACHE_NAME);
295 try {
296 if (!Files.exists(repo))
297 Files.createDirectory(repo, getPermissions(repo.getParent()));
298 return repo;
299 } catch (IOException e) {
300 log(LOG_VERBOSE, "Could not create local repo at " + repo);
301 if (isLogging(LOG_VERBOSE))
302 e.printStackTrace(STDERR);
303 repo = null;
304 }
305 }
306 localRepo = repo;
307 }
308 return localRepo;
309 }
310
311 private static String getPomJarEntryName(Dependency dep) {
312 return
313 "META-INF/maven/" +
314 dep.getArtifact().getGroupId() + "/" +
315 dep.getArtifact().getArtifactId() + "/" +
316 POM_FILE;
317 }
318
319 private static void addFlat(Object o, List<Object> ret) {
320 if (o instanceof Collection)
321 ret.addAll((Collection) o);
322 else
323 ret.add(o);
324 }
325
326 private static boolean isDependency(String lib) {
327 return lib.contains(":") && !lib.contains(":\\");
328 }
329 //</editor-fold>
330
331 //<editor-fold defaultstate="collapsed" desc="Utils">
332 /////////// Utils ///////////////////////////////////
333 private static boolean systemPropertyEmptyOrTrue(String property) {
334 return emptyOrTrue(getProperty(property));
335 }
336
337 private static boolean emptyOrTrue(String value) {
338 if (value == null)
339 return false;
340 return value.isEmpty() || Boolean.parseBoolean(value);
341 }
342
343 private static String propertyOrEnv(String propName, String envVar) {
344 String val = getProperty(propName);
345 if (val == null)
346 val = emptyToNull(getenv(envVar));
347 return val;
348 }
349
350 private static String expandCommandLinePath(String str) {
351 if (str == null)
352 return null;
353 // if (isWindows())
354 // return str;
355 // else
356 return str.startsWith("~/") ? str.replace("~", getProperty(PROP_USER_HOME)) : str;
357 }
358
359 private static Path toAbsolutePath(Path p) {
360 return p != null ? p.toAbsolutePath().normalize() : null;
361 }
362
363 private static <C extends Collection<T>, T> C addAllIfAbsent(C c, Collection<T> c1) {
364 for (T e : c1) {
365 if (!c.contains(e))
366 c.add(e);
367 }
368 return c;
369 }
370
371 @SuppressWarnings("unchecked")
372 private static <T> List<T> nullToEmpty(List<T> list) {
373 return list != null ? list : (List<T>) emptyList();
374 }
375
376 private static <T extends Collection<?>> T emptyToNull(T c) {
377 return (c == null || c.isEmpty()) ? null : c;
378 }
379
380 private static String emptyToNull(String s) {
381 if (s == null)
382 return null;
383 s = s.trim();
384 return s.isEmpty() ? null : s;
385 }
386
387 private static List<String> split(String str, String separator) {
388 if (str == null)
389 return null;
390 final String[] es = str.split(separator);
391 final List<String> list = new ArrayList<>(es.length);
392 for (String e : es) {
393 e = e.trim();
394 if (!e.isEmpty())
395 list.add(e);
396 }
397 return list;
398 }
399
400 private static <T extends AccessibleObject> T accessible(T obj) {
401 if (obj == null)
402 return null;
403 obj.setAccessible(true);
404 return obj;
405 }
406
407 private static long clock() {
408 return isLogging(PROFILE) ? System.nanoTime() : 0;
409 }
410
411 private static void time(String op, long start) {
412 time(op, start, isLogging(PROFILE) ? System.nanoTime() : 0);
413 }
414
415 private static void time(String op, long start, long stop) {
416 if (isLogging(PROFILE))
417 log(PROFILE, "PROFILE " + op + " " + ((stop - start) / 1_000_000) + "ms");
418 }
419 //</editor-fold>
420 }