예제 #1
0
  public static CompilerConfiguration generateCompilerConfigurationFromOptions(CommandLine cli)
      throws IOException {
    //
    // Setup the configuration data

    CompilerConfiguration configuration = new CompilerConfiguration();

    if (cli.hasOption("classpath")) {
      configuration.setClasspath(cli.getOptionValue("classpath"));
    }

    if (cli.hasOption('d')) {
      configuration.setTargetDirectory(cli.getOptionValue('d'));
    }

    if (cli.hasOption("encoding")) {
      configuration.setSourceEncoding(cli.getOptionValue("encoding"));
    }

    if (cli.hasOption("basescript")) {
      configuration.setScriptBaseClass(cli.getOptionValue("basescript"));
    }

    // joint compilation parameters
    if (cli.hasOption('j')) {
      Map<String, Object> compilerOptions = new HashMap<String, Object>();

      String[] opts = cli.getOptionValues("J");
      compilerOptions.put("namedValues", opts);

      opts = cli.getOptionValues("F");
      compilerOptions.put("flags", opts);

      configuration.setJointCompilationOptions(compilerOptions);
    }

    if (cli.hasOption("indy")) {
      configuration.getOptimizationOptions().put("int", false);
      configuration.getOptimizationOptions().put("indy", true);
    }

    if (cli.hasOption("configscript")) {
      String path = cli.getOptionValue("configscript");
      File groovyConfigurator = new File(path);
      Binding binding = new Binding();
      binding.setVariable("configuration", configuration);

      CompilerConfiguration configuratorConfig = new CompilerConfiguration();
      ImportCustomizer customizer = new ImportCustomizer();
      customizer.addStaticStars(
          "org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
      configuratorConfig.addCompilationCustomizers(customizer);

      GroovyShell shell = new GroovyShell(binding, configuratorConfig);
      shell.evaluate(groovyConfigurator);
    }

    return configuration;
  }
예제 #2
0
  /** Sets the Flags to defaults. */
  public CompilerConfiguration() {
    //
    // Set in safe defaults

    setWarningLevel(WarningMessage.LIKELY_ERRORS);
    setOutput(null);
    setTargetDirectory((File) null);
    setClasspath("");
    setVerbose(false);
    setDebug(false);
    setTolerance(10);
    setScriptBaseClass(null);
    setRecompileGroovySource(false);
    setMinimumRecompilationInterval(100);
    setTargetBytecode(getVMVersion());
    setDefaultScriptExtension(".groovy");

    //
    // Source file encoding
    String encoding = null;
    try {
      encoding = System.getProperty("file.encoding", "US-ASCII");
    } catch (Exception e) {
      // IGNORE
    }
    try {
      encoding = System.getProperty("groovy.source.encoding", encoding);
    } catch (Exception e) {
      // IGNORE
    }
    setSourceEncoding(encoding);

    try {
      setOutput(new PrintWriter(System.err));
    } catch (Exception e) {
      // IGNORE
    }

    try {
      String target = System.getProperty("groovy.target.directory");
      if (target != null) {
        setTargetDirectory(target);
      }
    } catch (Exception e) {
      // IGNORE
    }
  }
예제 #3
0
 /**
  * Copy constructor. Use this if you have a mostly correct configuration for your compilation but
  * you want to make a some changes programmatically. An important reason to prefer this approach
  * is that your code will most likely be forward compatible with future changes to this
  * configuration API.<br>
  * An example of this copy constructor at work:<br>
  *
  * <pre>
  *    // In all likelihood there is already a configuration in your code's context
  *    // for you to copy, but for the sake of this example we'll use the global default.
  *    CompilerConfiguration myConfiguration = new CompilerConfiguration(CompilerConfiguration.DEFAULT);
  *    myConfiguration.setDebug(true);
  * </pre>
  *
  * @param configuration The configuration to copy.
  */
 public CompilerConfiguration(CompilerConfiguration configuration) {
   setWarningLevel(configuration.getWarningLevel());
   setOutput(configuration.getOutput());
   setTargetDirectory(configuration.getTargetDirectory());
   setClasspathList(new LinkedList(configuration.getClasspath()));
   setVerbose(configuration.getVerbose());
   setDebug(configuration.getDebug());
   setTolerance(configuration.getTolerance());
   setScriptBaseClass(configuration.getScriptBaseClass());
   setRecompileGroovySource(configuration.getRecompileGroovySource());
   setMinimumRecompilationInterval(configuration.getMinimumRecompilationInterval());
   setTargetBytecode(configuration.getTargetBytecode());
   setDefaultScriptExtension(configuration.getDefaultScriptExtension());
   setSourceEncoding(configuration.getSourceEncoding());
   setOutput(configuration.getOutput());
   setTargetDirectory(configuration.getTargetDirectory());
   Map jointCompilationOptions = configuration.getJointCompilationOptions();
   if (jointCompilationOptions != null) {
     jointCompilationOptions = new HashMap(jointCompilationOptions);
   }
   setJointCompilationOptions(jointCompilationOptions);
   setPluginFactory(configuration.getPluginFactory());
 }
예제 #4
0
  /**
   * Method to configure a this CompilerConfiguration by using Properties. For a list of available
   * properties look at {link {@link #CompilerConfiguration(Properties)}.
   *
   * @param configuration The properties to get flag values from.
   */
  public void configure(Properties configuration) throws ConfigurationException {
    String text = null;
    int numeric = 0;

    //
    // Warning level

    numeric = getWarningLevel();
    try {
      text = configuration.getProperty("groovy.warnings", "likely errors");
      numeric = Integer.parseInt(text);
    } catch (NumberFormatException e) {
      text = text.toLowerCase();
      if (text.equals("none")) {
        numeric = WarningMessage.NONE;
      } else if (text.startsWith("likely")) {
        numeric = WarningMessage.LIKELY_ERRORS;
      } else if (text.startsWith("possible")) {
        numeric = WarningMessage.POSSIBLE_ERRORS;
      } else if (text.startsWith("paranoia")) {
        numeric = WarningMessage.PARANOIA;
      } else {
        throw new ConfigurationException("unrecogized groovy.warnings: " + text);
      }
    }
    setWarningLevel(numeric);

    //
    // Source file encoding
    //
    text = configuration.getProperty("groovy.source.encoding");
    if (text != null) setSourceEncoding(text);

    //
    // Target directory for classes
    //
    text = configuration.getProperty("groovy.target.directory");
    if (text != null) setTargetDirectory(text);

    text = configuration.getProperty("groovy.target.bytecode");
    if (text != null) setTargetBytecode(text);

    //
    // Classpath
    //
    text = configuration.getProperty("groovy.classpath");
    if (text != null) setClasspath(text);

    //
    // Verbosity
    //
    text = configuration.getProperty("groovy.output.verbose");
    if (text != null && text.equalsIgnoreCase("true")) setVerbose(true);

    //
    // Debugging
    //
    text = configuration.getProperty("groovy.output.debug");
    if (text != null && text.equalsIgnoreCase("true")) setDebug(true);

    //
    // Tolerance
    //
    numeric = 10;
    try {
      text = configuration.getProperty("groovy.errors.tolerance", "10");
      numeric = Integer.parseInt(text);
    } catch (NumberFormatException e) {
      throw new ConfigurationException(e);
    }
    setTolerance(numeric);

    //
    // Script Base Class
    //
    text = configuration.getProperty("groovy.script.base");
    if (text != null) setScriptBaseClass(text);

    //
    // recompilation options
    //
    text = configuration.getProperty("groovy.recompile");
    if (text != null) {
      setRecompileGroovySource(text.equalsIgnoreCase("true"));
    }

    numeric = 100;
    try {
      text = configuration.getProperty("groovy.recompile.minimumIntervall");
      if (text == null) text = configuration.getProperty("groovy.recompile.minimumInterval");
      if (text != null) {
        numeric = Integer.parseInt(text);
      } else {
        numeric = 100;
      }
    } catch (NumberFormatException e) {
      throw new ConfigurationException(e);
    }
    setMinimumRecompilationInterval(numeric);
  }
예제 #5
0
    public void compile() {
        if (compiledTemplate == null) {
            try {
                long start = System.currentTimeMillis();

                TClassLoader tClassLoader = new TClassLoader();

                // Let's compile the groovy source
                final List<GroovyClass> groovyClassesForThisTemplate = new ArrayList<GroovyClass>();
                // ~~~ Please !
                CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
                compilerConfiguration.setSourceEncoding("utf-8"); // ouf
                CompilationUnit compilationUnit = new CompilationUnit(compilerConfiguration);
                compilationUnit.addSource(new SourceUnit(name, compiledSource, compilerConfiguration, tClassLoader, compilationUnit.getErrorCollector()));
                Field phasesF = compilationUnit.getClass().getDeclaredField("phaseOperations");
                phasesF.setAccessible(true);
                LinkedList[] phases = (LinkedList[]) phasesF.get(compilationUnit);
                LinkedList<GroovyClassOperation> output = new LinkedList<GroovyClassOperation>();
                phases[Phases.OUTPUT] = output;
                output.add(new GroovyClassOperation() {
                    public void call(GroovyClass gclass) {
                        groovyClassesForThisTemplate.add(gclass);
                    }
                });
                compilationUnit.compile();
                // ouf 

                // Define script classes
                StringBuilder sb = new StringBuilder();
                sb.append("LINESMATRIX" + "\n");
                sb.append(Codec.encodeBASE64(Java.serialize(linesMatrix)).replaceAll("\\s", ""));
                sb.append("\n");
                sb.append("DOBODYLINES" + "\n");
                sb.append(Codec.encodeBASE64(Java.serialize(doBodyLines)).replaceAll("\\s", ""));
                sb.append("\n");
                for (GroovyClass gclass : groovyClassesForThisTemplate) {
                    tClassLoader.defineTemplate(gclass.getName(), gclass.getBytes());
                    sb.append(gclass.getName() + "\n");
                    sb.append(Codec.encodeBASE64(gclass.getBytes()).replaceAll("\\s", ""));
                    sb.append("\n");
                }
                // Cache
                BytecodeCache.cacheBytecode(sb.toString().getBytes("utf-8"), name, source);
                compiledTemplate = tClassLoader.loadClass(groovyClassesForThisTemplate.get(0).getName());
                if (System.getProperty("precompile") != null) {
                    try {
                        // emit bytecode to standard class layout as well
                        File f = Play.getFile("precompiled/templates/" + name.replaceAll("\\{(.*)\\}", "from_$1").replace(":", "_").replace("..", "parent"));
                        f.getParentFile().mkdirs();
                        FileOutputStream fos = new FileOutputStream(f);
                        fos.write(sb.toString().getBytes("utf-8"));
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                Logger.trace("%sms to compile template %s to %d classes", System.currentTimeMillis() - start, name, groovyClassesForThisTemplate.size());

            } catch (MultipleCompilationErrorsException e) {
                if (e.getErrorCollector().getLastError() != null) {
                    SyntaxErrorMessage errorMessage = (SyntaxErrorMessage) e.getErrorCollector().getLastError();
                    SyntaxException syntaxException = errorMessage.getCause();
                    Integer line = this.linesMatrix.get(syntaxException.getLine());
                    if (line == null) {
                        line = 0;
                    }
                    String message = syntaxException.getMessage();
                    if (message.indexOf("@") > 0) {
                        message = message.substring(0, message.lastIndexOf("@"));
                    }
                    throw new TemplateCompilationException(this, line, message);
                }
                throw new UnexpectedException(e);
            } catch (Exception e) {
                throw new UnexpectedException(e);
            }
        }
        compiledTemplateName = compiledTemplate.getName();
    }
 private GroovyClassLoader initGroovyClassLoader(ClassLoader parent) {
   CompilerConfiguration compConfig = new CompilerConfiguration();
   compConfig.setSourceEncoding(GroovyPageParser.GROOVY_SOURCE_CHAR_ENCODING);
   return new GroovyClassLoader(parent, compConfig);
 }