Exemplo n.º 1
0
  protected GroovyClassLoader buildClassLoaderFor() {
    // GROOVY-5044
    if (!fork && !getIncludeantruntime()) {
      throw new IllegalArgumentException(
          "The includeAntRuntime=false option is not compatible with fork=false");
    }
    ClassLoader parent =
        getIncludeantruntime()
            ? getClass().getClassLoader()
            : new AntClassLoader(
                new RootLoader(EMPTY_URL_ARRAY, null), getProject(), getClasspath());
    if (parent instanceof AntClassLoader) {
      AntClassLoader antLoader = (AntClassLoader) parent;
      String[] pathElm = antLoader.getClasspath().split(File.pathSeparator);
      List<String> classpath = configuration.getClasspath();
      /*
       * Iterate over the classpath provided to groovyc, and add any missing path
       * entries to the AntClassLoader.  This is a workaround, since for some reason
       * 'directory' classpath entries were not added to the AntClassLoader' classpath.
       */
      for (String cpEntry : classpath) {
        boolean found = false;
        for (String path : pathElm) {
          if (cpEntry.equals(path)) {
            found = true;
            break;
          }
        }
        /*
         * fix for GROOVY-2284
         * seems like AntClassLoader doesn't check if the file
         * may not exist in the classpath yet
         */
        if (!found && new File(cpEntry).exists()) {
          try {
            antLoader.addPathElement(cpEntry);
          } catch (BuildException e) {
            log.warn("The classpath entry " + cpEntry + " is not a valid Java resource");
          }
        }
      }
    }

    GroovyClassLoader loader = new GroovyClassLoader(parent, configuration);
    if (!forceLookupUnnamedFiles) {
      // in normal case we don't need to do script lookups
      loader.setResourceLoader(
          new GroovyResourceLoader() {
            public URL loadGroovySource(String filename) throws MalformedURLException {
              return null;
            }
          });
    }
    return loader;
  }
 @Override
 protected ClassLoader getClassLoader() throws ServletException {
   if (cl == null) {
     final CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
     compilerConfiguration.setRecompileGroovySource(true);
     cl = new GroovyClassLoader(super.getClassLoader(), compilerConfiguration);
     String scriptsPath = getServletConfig().getInitParameter("scriptsPath");
     if (scriptsPath != null) {
       // Zemian Deng 2012/11/22 - Allow scriptsPath to set in relative to /WEB-INF folder.
       if (scriptsPath.startsWith("/WEB-INF")) {
         scriptsPath = getServletContext().getRealPath(scriptsPath);
       }
       final String scriptsPathFinal = scriptsPath;
       cl.setResourceLoader(
           new GroovyResourceLoader() {
             public URL loadGroovySource(final String name) throws MalformedURLException {
               return (URL)
                   AccessController.doPrivileged(
                       new PrivilegedAction() {
                         public Object run() {
                           String filename =
                               name.replace('.', '/')
                                   + compilerConfiguration.getDefaultScriptExtension();
                           try {
                             final File file = new File(scriptsPathFinal + "/" + filename);
                             if (!file.exists() || !file.isFile()) {
                               return null;
                             }
                             return new URL("file:///" + scriptsPathFinal + "/" + filename);
                           } catch (MalformedURLException e) {
                             return null;
                           }
                         }
                       });
             }
           });
     }
   }
   return cl;
 }
Exemplo n.º 3
0
 public void setResourceLoader(GroovyResourceLoader resourceLoader) {
   delegate.setResourceLoader(resourceLoader);
 }
  private void compileScript(
      final ScriptSource source,
      ClassLoader classLoader,
      CompilerConfiguration configuration,
      File classesDir,
      File metadataDir,
      final CompileOperation<?> extractingTransformer,
      final Action<? super ClassNode> customVerifier) {
    final Transformer transformer =
        extractingTransformer != null ? extractingTransformer.getTransformer() : null;
    logger.info(
        "Compiling {} using {}.",
        source.getDisplayName(),
        transformer != null ? transformer.getClass().getSimpleName() : "no transformer");

    final EmptyScriptDetector emptyScriptDetector = new EmptyScriptDetector();
    final PackageStatementDetector packageDetector = new PackageStatementDetector();
    GroovyClassLoader groovyClassLoader =
        new GroovyClassLoader(classLoader, configuration, false) {
          @Override
          protected CompilationUnit createCompilationUnit(
              CompilerConfiguration compilerConfiguration, CodeSource codeSource) {
            ImportCustomizer customizer = new ImportCustomizer();
            customizer.addStarImports(defaultImportPackages);
            compilerConfiguration.addCompilationCustomizers(customizer);

            CompilationUnit compilationUnit =
                new CustomCompilationUnit(
                    compilerConfiguration, codeSource, customVerifier, source, this);

            if (transformer != null) {
              transformer.register(compilationUnit);
            }

            compilationUnit.addPhaseOperation(packageDetector, Phases.CANONICALIZATION);
            compilationUnit.addPhaseOperation(emptyScriptDetector, Phases.CANONICALIZATION);
            return compilationUnit;
          }
        };

    groovyClassLoader.setResourceLoader(NO_OP_GROOVY_RESOURCE_LOADER);
    String scriptText = source.getResource().getText();
    String scriptName = source.getClassName();
    GroovyCodeSource codeSource =
        new GroovyCodeSource(scriptText == null ? "" : scriptText, scriptName, "/groovy/script");
    try {
      groovyClassLoader.parseClass(codeSource, false);
    } catch (MultipleCompilationErrorsException e) {
      wrapCompilationFailure(source, e);
    } catch (CompilationFailedException e) {
      throw new GradleException(String.format("Could not compile %s.", source.getDisplayName()), e);
    }

    if (packageDetector.hasPackageStatement) {
      throw new UnsupportedOperationException(
          String.format(
              "%s should not contain a package statement.",
              StringUtils.capitalize(source.getDisplayName())));
    }
    serializeMetadata(
        source,
        extractingTransformer,
        metadataDir,
        emptyScriptDetector.isEmptyScript(),
        emptyScriptDetector.getHasMethods());
  }