1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.cling;
20
21 import java.io.IOException;
22
23 import org.apache.maven.api.cli.Invoker;
24 import org.apache.maven.api.cli.InvokerException;
25 import org.apache.maven.api.cli.InvokerRequest;
26 import org.apache.maven.api.cli.Options;
27 import org.apache.maven.api.cli.ParserException;
28 import org.codehaus.plexus.classworlds.ClassWorld;
29
30 import static java.util.Objects.requireNonNull;
31
32
33
34
35
36
37
38 public abstract class ClingSupport<O extends Options, R extends InvokerRequest<O>> {
39 static final String CORE_CLASS_REALM_ID = "plexus.core";
40
41 protected final ClassWorld classWorld;
42 protected final boolean classWorldManaged;
43
44
45
46
47 public ClingSupport() {
48 this(new ClassWorld(CORE_CLASS_REALM_ID, Thread.currentThread().getContextClassLoader()), true);
49 }
50
51
52
53
54 public ClingSupport(ClassWorld classWorld) {
55 this(classWorld, false);
56 }
57
58 private ClingSupport(ClassWorld classWorld, boolean classWorldManaged) {
59 this.classWorld = requireNonNull(classWorld);
60 this.classWorldManaged = classWorldManaged;
61 }
62
63
64
65
66 public int run(String[] args) throws IOException {
67 try (Invoker<R> invoker = createInvoker()) {
68 return invoker.invoke(parseArguments(args));
69 } catch (ParserException e) {
70 System.err.println(e.getMessage());
71 return 1;
72 } catch (InvokerException e) {
73 return 1;
74 } finally {
75 if (classWorldManaged) {
76 classWorld.close();
77 }
78 }
79 }
80
81 protected abstract Invoker<R> createInvoker();
82
83 protected abstract R parseArguments(String[] args) throws ParserException, IOException;
84 }