groovy.lang.GroovyShell.getClassLoader()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(12.1k)|赞(0)|评价(0)|浏览(249)

本文整理了Java中groovy.lang.GroovyShell.getClassLoader()方法的一些代码示例,展示了GroovyShell.getClassLoader()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。GroovyShell.getClassLoader()方法的具体详情如下:
包路径:groovy.lang.GroovyShell
类名称:GroovyShell
方法名:getClassLoader

GroovyShell.getClassLoader介绍

暂无

代码示例

代码示例来源:origin: org.codehaus.groovy/groovy

private static void setupContextClassLoader(GroovyShell shell) {
  final Thread current = Thread.currentThread();
  class DoSetContext implements PrivilegedAction {
    ClassLoader classLoader;
    public DoSetContext(ClassLoader loader) {
      classLoader = loader;
    }
    public Object run() {
      current.setContextClassLoader(classLoader);
      return null;
    }
  }
  AccessController.doPrivileged(new DoSetContext(shell.getClassLoader()));
}

代码示例来源:origin: apache/nifi

throw new ProcessException("Path not found `" + fcp + "` for `" + ADD_CLASSPATH.getDisplayName() + "`");
      shell.getClassLoader().addClasspath(fcp.toString());
    shell.getClassLoader().addClasspath(groovyClasspath);
  script = compiled.newInstance();
Thread.currentThread().setContextClassLoader(shell.getClassLoader());
return script;

代码示例来源:origin: apache/groovy

thread.setContextClassLoader(GroovyShell.class.getClassLoader());

代码示例来源:origin: palantir/atlasdb

private void evalFiles(String[] filepaths, CommandLine cli) throws CompilationFailedException, IOException {
  Binding binding = setupBinding(new Binding(), cli.hasOption(MUTATIONS_ENABLED_FLAG_SHORT));
  GroovyShell shell = new GroovyShell(binding);
  if(cli.hasOption(CLASSPATH_FLAG_SHORT)) {
    shell.getClassLoader().addClasspath(cli.getOptionValue(CLASSPATH_FLAG_SHORT));
  }
  for(String filepath : filepaths) {
    File file = new File(filepath);
    shell.evaluate(file);
  }
}

代码示例来源:origin: info.cukes/cucumber-groovy

public GroovyBackend(GroovyShell shell, ResourceLoader resourceLoader) {
  this.shell = shell;
  this.resourceLoader = resourceLoader;
  instanceThreadLocal.set(this);
  classFinder = new ResourceLoaderClassFinder(resourceLoader, shell.getClassLoader());
}

代码示例来源:origin: org.jenkins-ci.plugins.workflow/workflow-cps-global-lib

@Override
  public void configureShell(CpsFlowExecution context, GroovyShell shell) {
    try {
      shell.getClassLoader().addURL(new File(repo.workspace,"src").toURI().toURL());
      shell.getClassLoader().addURL(new File(repo.workspace, UserDefinedGlobalVariable.PREFIX).toURI().toURL());
    } catch (MalformedURLException e) {
      throw new AssertionError(e);
    }
  }
};

代码示例来源:origin: jenkinsci/workflow-cps-plugin

public CpsGroovyShellFactory withParent(GroovyShell parent) {
  return withParent(parent.getClassLoader());
}

代码示例来源:origin: com.palantir.atlasdb/atlasdb-console

private void evalFiles(String[] filepaths, CommandLine cli) throws CompilationFailedException, IOException {
  Binding binding = setupBinding(new Binding(), cli.hasOption(MUTATIONS_ENABLED_FLAG_SHORT));
  GroovyShell shell = new GroovyShell(binding);
  if(cli.hasOption(CLASSPATH_FLAG_SHORT)) {
    shell.getClassLoader().addClasspath(cli.getOptionValue(CLASSPATH_FLAG_SHORT));
  }
  for(String filepath : filepaths) {
    File file = new File(filepath);
    shell.evaluate(file);
  }
}

代码示例来源:origin: com.b2international.snowowl/com.b2international.snowowl.datastore.server

MigrationReplicationContext(final RepositoryContext context, final int initialBranchId, final long initialLastCommitTime, final InternalSession session, final String scriptLocation) {
  this.context = context;
  this.lastReplicatedBranchId = initialBranchId;
  this.initialLastCommitTime = initialLastCommitTime;
  this.replicatorSession = session;
  if (!Strings.isNullOrEmpty(scriptLocation)) {
    try {
      this.scriptClass = shell.getClassLoader().parseClass(new File(scriptLocation));
    } catch (CompilationFailedException | IOException e) {
      throw new SnowowlRuntimeException("Couldn't compile script", e);
    }
  }
}

代码示例来源:origin: org.sonatype.nexus.plugins/nexus-groovyremote-client

public GroovyRemoteClient(final ClassLoader classLoader,
             final File classesDir,
             final List<File> extraDirs,
             final URL url)
  throws IOException
{
 checkNotNull(classLoader);
 log.debug("Class loader: {}", classLoader);
 checkNotNull(classesDir);
 log.debug("Classes dir: {}", classesDir);
 checkNotNull(url);
 log.debug("URL: {}", url);
 Binding binding = new Binding();
 CompilerConfiguration cc = new CompilerConfiguration();
 cc.setTargetDirectory(classesDir);
 this.shell = new GroovyShell(classLoader, binding, cc);
 HttpTransport transport = new HttpTransport(url.toExternalForm());
 // provide transport with custom class-loader which includes generated classes
 List<URL> urls = Lists.newArrayList();
 urls.add(classesDir.toURI().toURL());
 for (File dir : extraDirs) {
  urls.add(dir.toURI().toURL());
 }
 // TODO: Could probably use GCL here instead, would be simpler
 ClassLoader cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), shell.getClassLoader());
 this.remote = new RemoteControl(transport, cl);
}

代码示例来源:origin: org.jenkins-ci.plugins.workflow/workflow-cps-global-lib

void addTo(@Nonnull CpsFlowExecution execution) {
  GroovyShell shell = trusted ? execution.getTrustedShell() : execution.getShell();
  shell.getClassLoader().addURL(url);
}

代码示例来源:origin: jenkinsci/workflow-cps-plugin

@Override
  public void configureShell(@CheckForNull CpsFlowExecution context, GroovyShell shell) {
    try {
      URL u = TrustedShell.class.getClassLoader().getResource("trusted/foo.groovy");
      shell.getClassLoader().addURL(new URL(u,"."));
    } catch (MalformedURLException e) {
      throw new AssertionError(e);
    }
  }
}

代码示例来源:origin: org.jenkins-ci.plugins.workflow/workflow-cps-global-lib

private Class<?> loadClass(String name) {
  CpsFlowExecution exec = CpsThread.current().getExecution();
  GroovyClassLoader loader = (trusted ? exec.getTrustedShell() : exec.getShell()).getClassLoader();
  try {
    Class<?> c = loader.loadClass(name);
    ClassLoader definingLoader = c.getClassLoader();
    if (definingLoader instanceof GroovyClassLoader.InnerLoader) {
      definingLoader = definingLoader.getParent();
    }
    if (definingLoader != loader) {
      throw new IllegalAccessException("cannot access " + c + " via library handle: " + definingLoader + " is not " + loader);
    }
    // Note that this goes through GroovyCodeSource.<init>(File, String), which unlike (say) URLClassLoader set the “location” to the actual file, *not* the root.
    CodeSource codeSource = c.getProtectionDomain().getCodeSource();
    if (codeSource == null) {
      throw new IllegalAccessException(name + " had no defined code source");
    }
    String actual = canonicalize(codeSource.getLocation().toString());
    String srcUrlC = canonicalize(srcUrl); // do not do this in constructor: path might not actually exist
    if (!actual.startsWith(srcUrlC)) {
      throw new IllegalAccessException(name + " was defined in " + actual + " which was not inside " + srcUrlC);
    }
    if (!Modifier.isPublic(c.getModifiers())) { // unlikely since Groovy makes classes implicitly public
      throw new IllegalAccessException(c + " is not public");
    }
    return c;
  } catch (ClassNotFoundException | IllegalAccessException x) {
    throw new GroovyRuntimeException(x);
  }
}

代码示例来源:origin: jenkinsci/simple-build-for-pipeline-plugin

@Override
public Object getValue(CpsScript script) throws Exception {
  Binding binding = script.getBinding();
  CpsThread c = CpsThread.current();
  if (c == null)
    throw new IllegalStateException("Expected to be called from CpsThread");
  ClassLoader cl = getClass().getClassLoader();
  String scriptPath = "dsl/" + getFunctionName() + ".groovy";
  Reader r = new InputStreamReader(cl.getResourceAsStream(scriptPath), "UTF-8");
  GroovyCodeSource gsc = new GroovyCodeSource(r, getFunctionName() + ".groovy", cl.getResource(scriptPath).getFile());
  gsc.setCachable(true);
  Object pipelineDSL = c.getExecution()
      .getShell()
      .getClassLoader()
      .parseClass(gsc)
      .newInstance();
  binding.setVariable(getName(), pipelineDSL);
  r.close();
  return pipelineDSL;
}

代码示例来源:origin: jenkinsci/workflow-cps-plugin

private ThreadContext setUp() {
  CpsFlowExecution execution = cpsThreadGroup.getExecution();
  ACL.impersonate(execution.getAuthentication());
  CURRENT.set(cpsThreadGroup);
  cpsThreadGroup.busy = true;
  Thread t = Thread.currentThread();
  ThreadContext context = new ThreadContext(t, execution);
  t.setName("Running " + execution);
  assert cpsThreadGroup.getExecution() != null;
  if (cpsThreadGroup.getExecution().getShell() != null) {
    assert cpsThreadGroup.getExecution().getShell().getClassLoader() != null;
    t.setContextClassLoader(cpsThreadGroup.getExecution().getShell().getClassLoader());
  }
  return context;
}

代码示例来源:origin: org.apache.camel/camel-groovy

@SuppressWarnings("unchecked")
private Script instantiateScript(Exchange exchange) {
  // Get the script from the cache, or create a new instance
  GroovyLanguage language = (GroovyLanguage) exchange.getContext().resolveLanguage("groovy");
  Class<Script> scriptClass = language.getScriptFromCache(text);
  if (scriptClass == null) {
    GroovyShell shell;
    Set<GroovyShellFactory> shellFactories = exchange.getContext().getRegistry().findByType(GroovyShellFactory.class);
    if (shellFactories.size() > 1) {
      throw new IllegalStateException("Too many GroovyShellFactory instances found: " + shellFactories.size());
    } else if (shellFactories.size() == 1) {
      shell = shellFactories.iterator().next().createGroovyShell(exchange);
    } else {
      ClassLoader cl = exchange.getContext().getApplicationContextClassLoader();
      shell = cl != null ? new GroovyShell(cl) : new GroovyShell();
    }
    scriptClass = shell.getClassLoader().parseClass(text);
    language.addScriptToCache(text, scriptClass);
  }
  // New instance of the script
  try {
    return scriptClass.newInstance();
  } catch (InstantiationException e) {
    throw new RuntimeCamelException(e);
  } catch (IllegalAccessException e) {
    throw new RuntimeCamelException(e);
  }
}

代码示例来源:origin: bonitasoft/bonita-engine

Class getScriptFromCache(final String expressionContent, final Long definitionId) throws SCacheException, SClassLoaderException {
  if (definitionId == null) {
    throw new SBonitaRuntimeException("Unable to evaluate expression without a definitionId");
  }
  final GroovyShell shell = getShell(definitionId);
  final String key = getScriptKey(expressionContent);
  GroovyCodeSource gcs = (GroovyCodeSource) cacheService.get(GROOVY_SCRIPT_CACHE_NAME, key);
  if (gcs == null) {
    gcs = AccessController.doPrivileged(new PrivilegedAction<GroovyCodeSource>() {
      public GroovyCodeSource run() {
        return new GroovyCodeSource(expressionContent, generateScriptName(), GroovyShell.DEFAULT_CODE_BASE);
      }
    });
    cacheService.store(GROOVY_SCRIPT_CACHE_NAME, key, gcs);
  }
  // parse the groovy source code with cache set to true
  return shell.getClassLoader().parseClass(gcs, true);
}

代码示例来源:origin: bonitasoft/bonita-engine

Class getScriptFromCache(final String expressionContent, final Long definitionId) throws SCacheException, SClassLoaderException {
  if (definitionId == null) {
    throw new SBonitaRuntimeException("Unable to evaluate expression without a definitionId");
  }
  final GroovyShell shell = getShell(definitionId);
  final String key = getScriptKey(expressionContent);
  GroovyCodeSource gcs = (GroovyCodeSource) cacheService.get(GROOVY_SCRIPT_CACHE_NAME, key);
  if (gcs == null) {
    gcs = AccessController.doPrivileged(new PrivilegedAction<GroovyCodeSource>() {
      public GroovyCodeSource run() {
        return new GroovyCodeSource(expressionContent, generateScriptName(), GroovyShell.DEFAULT_CODE_BASE);
      }
    });
    cacheService.store(GROOVY_SCRIPT_CACHE_NAME, key, gcs);
  }
  // parse the groovy source code with cache set to true
  return shell.getClassLoader().parseClass(gcs, true);
}

代码示例来源:origin: org.jenkins-ci.plugins/extended-choice-parameter

private Object executeGroovyScript(String groovyScript, String bindings, String groovyClasspath) throws IOException {
  GroovyShell groovyShell = getGroovyShell(groovyClasspath);
  groovyShell.getClassLoader().parseClass(new GroovyCodeSource(groovyScript, computeMD5Hash(groovyScript), "/groovy/shell"), true);
  setBindings(groovyShell, bindings);
  Object groovyValue = groovyShell.evaluate(groovyScript);
  return groovyValue;
}

代码示例来源:origin: org.jenkins-ci.plugins.workflow/workflow-cps-global-lib

@Nonnull
@Override
public Object getValue(@Nonnull CpsScript script) throws Exception {
  Binding binding = script.getBinding();
  Object instance;
  if (binding.hasVariable(getName())) {
    instance = binding.getVariable(getName());
  } else {
    CpsThread c = CpsThread.current();
    if (c==null)
      throw new IllegalStateException("Expected to be called from CpsThread");
    instance = c.getExecution().getShell().getClassLoader().loadClass(getName()).newInstance();
    /* We could also skip registration of vars in GroovyShellDecoratorImpl and use:
       instance = c.getExecution().getShell().parse(source(".groovy"));
      But then the source will appear in CpsFlowExecution.loadedScripts and be offered up for ReplayAction.
      We might *want* to support replay of global vars & classes at some point, but to make it actually work
      we would also need to start calling LoadStepExecution.Replacer.
    */
    binding.setVariable(getName(), instance);
  }
  return instance;
}

相关文章