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.invoker.mvnsh;
20  
21  import java.util.ArrayList;
22  import java.util.List;
23  
24  import org.jline.console.CommandRegistry;
25  
26  import static java.util.Objects.requireNonNull;
27  
28  public class ShellCommandRegistryHolder implements AutoCloseable {
29      private final List<CommandRegistry> commandRegistries;
30  
31      public ShellCommandRegistryHolder() {
32          this.commandRegistries = new ArrayList<>();
33      }
34  
35      public void addCommandRegistry(CommandRegistry commandRegistry) {
36          requireNonNull(commandRegistry, "commandRegistry");
37          this.commandRegistries.add(commandRegistry);
38      }
39  
40      public CommandRegistry[] getCommandRegistries() {
41          return commandRegistries.toArray(new CommandRegistry[0]);
42      }
43  
44      @Override
45      public void close() throws Exception {
46          ArrayList<Exception> exceptions = new ArrayList<>();
47          for (CommandRegistry commandRegistry : commandRegistries) {
48              if (commandRegistry instanceof AutoCloseable closeable) {
49                  try {
50                      closeable.close();
51                  } catch (Exception e) {
52                      exceptions.add(e);
53                  }
54              }
55          }
56          if (!exceptions.isEmpty()) {
57              IllegalStateException ex = new IllegalStateException("Could not close commandRegistries");
58              exceptions.forEach(ex::addSuppressed);
59              throw ex;
60          }
61      }
62  }