View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
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.ParserException;
27  import org.codehaus.plexus.classworlds.ClassWorld;
28  
29  import static java.util.Objects.requireNonNull;
30  
31  /**
32   * The CLI "new-gen".
33   */
34  public abstract class ClingSupport {
35      static final String CORE_CLASS_REALM_ID = "plexus.core";
36  
37      protected final ClassWorld classWorld;
38      protected final boolean classWorldManaged;
39  
40      /**
41       * Ctor that creates "managed" ClassWorld. This constructor is not used in "normal" circumstances.
42       */
43      public ClingSupport() {
44          this(new ClassWorld(CORE_CLASS_REALM_ID, Thread.currentThread().getContextClassLoader()), true);
45      }
46  
47      /**
48       * Ctor to be used when running in ClassWorlds Launcher.
49       */
50      public ClingSupport(ClassWorld classWorld) {
51          this(classWorld, false);
52      }
53  
54      private ClingSupport(ClassWorld classWorld, boolean classWorldManaged) {
55          this.classWorld = requireNonNull(classWorld);
56          this.classWorldManaged = classWorldManaged;
57      }
58  
59      /**
60       * The main entry point.
61       */
62      public int run(String[] args) throws IOException {
63          try (Invoker invoker = createInvoker()) {
64              return invoker.invoke(parseArguments(args));
65          } catch (ParserException e) {
66              System.err.println(e.getMessage());
67              return 1;
68          } catch (InvokerException e) {
69              return 1;
70          } finally {
71              if (classWorldManaged) {
72                  classWorld.close();
73              }
74          }
75      }
76  
77      protected abstract Invoker createInvoker();
78  
79      protected abstract InvokerRequest parseArguments(String[] args) throws ParserException, IOException;
80  }