View Javadoc
1   /*
2    * Copyright (c) 2006-present the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.codehaus.gmaven.adapter.impl;
17  
18  import java.util.Map;
19  
20  import javax.annotation.Nullable;
21  
22  import groovy.lang.Binding;
23  import groovy.lang.GroovyClassLoader;
24  import org.codehaus.gmaven.adapter.ResourceLoader;
25  import org.codehaus.gmaven.adapter.ShellRunner;
26  import org.codehaus.groovy.tools.shell.Groovysh;
27  import org.codehaus.groovy.tools.shell.IO;
28  import org.slf4j.Logger;
29  import org.slf4j.LoggerFactory;
30  
31  import static com.google.common.base.Preconditions.checkNotNull;
32  
33  /**
34   * Default {@link ShellRunner} implementation.
35   *
36   * @since 2.0
37   */
38  public class ShellRunnerImpl
39      implements ShellRunner
40  {
41    private final Logger log = LoggerFactory.getLogger(getClass());
42  
43    private final GroovyRuntimeImpl runtime;
44  
45    ShellRunnerImpl(final GroovyRuntimeImpl runtime) {
46      this.runtime = checkNotNull(runtime);
47    }
48  
49    @Override
50    public void run(final ClassLoader classLoader,
51                    final ResourceLoader resourceLoader,
52                    final Map<String, Object> context,
53                    final @Nullable Map<String, Object> options)
54        throws Exception
55    {
56      checkNotNull(classLoader);
57      checkNotNull(resourceLoader);
58      checkNotNull(context);
59  
60      log.trace("Running; class-loader: {}, resource-loader: {}, context: {}",
61          classLoader, resourceLoader, context);
62  
63      GroovyClassLoader gcl = runtime.createGroovyClassLoader(classLoader, resourceLoader);
64      Binding binding = runtime.createBinding(context);
65  
66      Groovysh shell = new Groovysh(gcl, binding, new IO());
67  
68      if (options != null) {
69        configureOptions(shell, options);
70      }
71  
72      try {
73        shell.run(null);
74      }
75      finally {
76        gcl.clearCache();
77      }
78    }
79  
80    private void configureOptions(final Groovysh shell, final Map<String, Object> options) {
81      // TODO:
82    }
83  }