org.codehaus.groovy.control.CompilationFailedException Java Examples

The following examples show how to use org.codehaus.groovy.control.CompilationFailedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
@Override
public void call(SourceUnit source) throws CompilationFailedException {
    ModelRegistryDslHelperStatementGenerator statementGenerator = new ModelRegistryDslHelperStatementGenerator();
    BlockStatement rootStatementBlock = source.getAST().getStatementBlock();
    ListIterator<Statement> statementsIterator = rootStatementBlock.getStatements().listIterator();
    while (statementsIterator.hasNext()) {
        Statement statement = statementsIterator.next();
        ScriptBlock scriptBlock = AstUtils.detectScriptBlock(statement, SCRIPT_BLOCK_NAMES);
        if (scriptBlock != null) {
            statementsIterator.remove();
            ScopeVisitor scopeVisitor = new ScopeVisitor(source, statementGenerator);
            scriptBlock.getClosureExpression().getCode().visit(scopeVisitor);
        }
    }
    rootStatementBlock.addStatements(statementGenerator.getGeneratedStatements());
}
 
Example #2
@Override
public void call(final SourceUnit source) throws CompilationFailedException {
    // currently we only look in script code; could extend this to build script classes
    AstUtils.visitScriptCode(source, new ClassCodeVisitorSupport() {
        @Override
        protected SourceUnit getSourceUnit() {
            return source;
        }

        @Override
        protected void visitStatement(Statement statement) {
            if (statement.getStatementLabel() != null) {
                String message = String.format("Statement labels may not be used in build scripts.%nIn case you tried to configure a property named '%s', replace ':' with '=' or ' ', otherwise it will not have the desired effect.",
                        statement.getStatementLabel());
                addError(message, statement);
            }
        }
    });
}
 
Example #3
@Override
public void call(final SourceUnit source) throws CompilationFailedException {
    // currently we only look in script code; could extend this to build script classes
    AstUtils.visitScriptCode(source, new ClassCodeVisitorSupport() {
        @Override
        protected SourceUnit getSourceUnit() {
            return source;
        }

        @Override
        protected void visitStatement(Statement statement) {
            if (statement.getStatementLabel() != null) {
                String message = String.format("Statement labels may not be used in build scripts.%nIn case you tried to configure a property named '%s', replace ':' with '=' or ' ', otherwise it will not have the desired effect.",
                        statement.getStatementLabel());
                addError(message, statement);
            }
        }
    });
}
 
Example #4
Source Project: warnings-ng-plugin   Author: jenkinsci   File: GroovyParser.java    License: MIT License 6 votes vote down vote up
/**
 * Performs on-the-fly validation on the Groovy script.
 *
 * @param script
 *         the script
 *
 * @return the validation result
 */
@RequirePOST
public FormValidation doCheckScript(@QueryParameter(required = true) final String script) {
    if (isNotAllowedToRunScripts()) {
        return NO_RUN_SCRIPT_PERMISSION_WARNING;
    }
    try {
        if (StringUtils.isBlank(script)) {
            return FormValidation.error(Messages.GroovyParser_Error_Script_isEmpty());
        }

        GroovyExpressionMatcher matcher = new GroovyExpressionMatcher(script);
        Script compiled = matcher.compile();
        Ensure.that(compiled).isNotNull();

        return FormValidation.ok();
    }
    catch (CompilationFailedException exception) {
        return FormValidation.error(
                Messages.GroovyParser_Error_Script_invalid(exception.getLocalizedMessage()));
    }
}
 
Example #5
Source Project: groovy   Author: apache   File: GroovyClassLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * (Re)Compiles the given source.
 * This method starts the compilation of a given source, if
 * the source has changed since the class was created. For
 * this isSourceNewer is called.
 *
 * @param source    the source pointer for the compilation
 * @param className the name of the class to be generated
 * @param oldClass  a possible former class
 * @return the old class if the source wasn't new enough, the new class else
 * @throws CompilationFailedException if the compilation failed
 * @throws IOException                if the source is not readable
 * @see #isSourceNewer(URL, Class)
 */
protected Class recompile(URL source, String className, Class oldClass) throws CompilationFailedException, IOException {
    if (source != null) {
        // found a source, compile it if newer
        if (oldClass == null || isSourceNewer(source, oldClass)) {
            String name = source.toExternalForm();

            sourceCache.remove(name);

            if (isFile(source)) {
                try {
                    return parseClass(new GroovyCodeSource(new File(source.toURI()), sourceEncoding));
                } catch (URISyntaxException e) {
                    // do nothing and fall back to the other version
                }
            }
            return parseClass(new InputStreamReader(URLStreams.openUncachedStream(source), sourceEncoding), name);
        }
    }
    return oldClass;
}
 
Example #6
Source Project: imputationserver   Author: genepi   File: ImputationPipelineTest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void testWithWrongReferencePanel() throws IOException, CompilationFailedException, ClassNotFoundException {

		String template = "--refHaps ${ref} --haps ${vcf} --start ${start} --end ${end} --window ${window} --prefix ${prefix} --chr ${chr} --noPhoneHome --format GT,DS,GP --allTypedSites --meta --minRatio 0.00001 ${unphased ? '--unphasedOutput' : ''} ${mapMinimac != null ? '--referenceEstimates --map ' + mapMinimac : ''}";

		Map<String, Object> binding = new HashMap<String, Object>();
		binding.put("ref", "ref.txt");
		binding.put("vcf", "vcf.txt");
		binding.put("start", 55);
		binding.put("end", 100);
		binding.put("window", 22);
		binding.put("prefix", "output-prefix");
		binding.put("chr", 22);
		binding.put("unphased", true);
		binding.put("mapMinimac", null);

		SimpleTemplateEngine engine = new SimpleTemplateEngine();
		String outputTemplate = engine.createTemplate(template).make(binding).toString();

		assertEquals(
				"--refHaps ref.txt --haps vcf.txt --start 55 --end 100 --window 22 --prefix output-prefix --chr 22 --noPhoneHome --format GT,DS,GP --allTypedSites --meta --minRatio 0.00001 --unphasedOutput ",
				outputTemplate);

	}
 
Example #7
Source Project: imputationserver   Author: genepi   File: ImputationPipelineTest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void testWithWrongReferencePanelUnphased()
		throws IOException, CompilationFailedException, ClassNotFoundException {

	String template = "--refHaps ${ref} --haps ${vcf} --start ${start} --end ${end} --window ${window} --prefix ${prefix} --chr ${chr} --noPhoneHome --format GT,DS,GP --allTypedSites --meta --minRatio 0.00001 ${unphased ? '--unphasedOutput' : ''} ${mapMinimac != null ? '--referenceEstimates --map ' + mapMinimac : ''}";

	Map<String, Object> binding = new HashMap<String, Object>();
	binding.put("ref", "ref.txt");
	binding.put("vcf", "vcf.txt");
	binding.put("start", 55);
	binding.put("end", 100);
	binding.put("window", 22);
	binding.put("prefix", "output-prefix");
	binding.put("chr", 22);
	binding.put("unphased", false);
	binding.put("mapMinimac", null);

	SimpleTemplateEngine engine = new SimpleTemplateEngine();
	String outputTemplate = engine.createTemplate(template).make(binding).toString();

	assertEquals(
			"--refHaps ref.txt --haps vcf.txt --start 55 --end 100 --window 22 --prefix output-prefix --chr 22 --noPhoneHome --format GT,DS,GP --allTypedSites --meta --minRatio 0.00001  ",
			outputTemplate);

}
 
Example #8
Source Project: stendhal   Author: arianne   File: AccessCheckingPortalFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
   * Creates a new ChatAction from ConfigurableFactoryContext.
   *
   * @param ctx
   * 		ConfigurableFactoryContext
   * @return
   * 		ChatAction instance
   */
  protected ChatAction getRejectedAction(final ConfigurableFactoryContext ctx) {
String value = ctx.getString("rejectedAction", null);
if (value == null) {
	return null;
}
Binding groovyBinding = new Binding();
final GroovyShell interp = new GroovyShell(groovyBinding);
try {
	String code = "import games.stendhal.server.entity.npc.action.*;\r\n"
		+ value;
	return (ChatAction) interp.evaluate(code);
} catch (CompilationFailedException e) {
	throw new IllegalArgumentException(e);
}
  }
 
Example #9
Source Project: stendhal   Author: arianne   File: ConditionAndActionPortalFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Extract the quest name from a context.
 *
 * @param ctx
 *            The configuration context.
 * @return The quest name.
 * @throws IllegalArgumentException
 *             If the quest attribute is missing.
 */
protected ChatCondition getCondition(final ConfigurableFactoryContext ctx) {
	String value = ctx.getString("condition", null);
	if (value == null) {
		return null;
	}
	Binding groovyBinding = new Binding();
	final GroovyShell interp = new GroovyShell(groovyBinding);
	try {
		String code = "import games.stendhal.server.entity.npc.condition.*;\r\n"
			+ value;
		return (ChatCondition) interp.evaluate(code);
	} catch (CompilationFailedException e) {
		throw new IllegalArgumentException(e);
	}
}
 
Example #10
Source Project: spring-analysis-note   Author: Vip-Augus   File: GroovyScriptFactory.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public Class<?> getScriptedObjectType(ScriptSource scriptSource)
		throws IOException, ScriptCompilationException {

	synchronized (this.scriptClassMonitor) {
		try {
			if (this.scriptClass == null || scriptSource.isModified()) {
				// New script content...
				this.wasModifiedForTypeCheck = true;
				this.scriptClass = getGroovyClassLoader().parseClass(
						scriptSource.getScriptAsString(), scriptSource.suggestedClassName());

				if (Script.class.isAssignableFrom(this.scriptClass)) {
					// A Groovy script, probably creating an instance: let's execute it.
					Object result = executeScript(scriptSource, this.scriptClass);
					this.scriptResultClass = (result != null ? result.getClass() : null);
					this.cachedResult = new CachedResultHolder(result);
				}
				else {
					this.scriptResultClass = this.scriptClass;
				}
			}
			return this.scriptResultClass;
		}
		catch (CompilationFailedException ex) {
			this.scriptClass = null;
			this.scriptResultClass = null;
			this.cachedResult = null;
			throw new ScriptCompilationException(scriptSource, ex);
		}
	}
}
 
Example #11
Source Project: pushfish-android   Author: PushFish   File: ModelBlockTransformer.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void call(SourceUnit source) throws CompilationFailedException {
    if (!isEnabled()) {
        return;
    }

    List<Statement> statements = source.getAST().getStatementBlock().getStatements();
    for (Statement statement : statements) {
        ScriptBlock scriptBlock = AstUtils.detectScriptBlock(statement, SCRIPT_BLOCK_NAMES);
        if (scriptBlock == null) {
            // Look for model(«») (i.e. call to model with anything other than non literal closure)
            MethodCallExpression methodCall = AstUtils.extractBareMethodCall(statement);
            if (methodCall == null) {
                continue;
            }

            String methodName = AstUtils.extractConstantMethodName(methodCall);
            if (methodName == null) {
                continue;
            }

            if (methodName.equals(MODEL)) {
                source.getErrorCollector().addError(
                        new SyntaxException(NON_LITERAL_CLOSURE_TO_TOP_LEVEL_MODEL_MESSAGE, statement.getLineNumber(), statement.getColumnNumber()),
                        source
                );
            }
        } else {
            RuleVisitor ruleVisitor = new RuleVisitor(source);
            RulesVisitor rulesVisitor = new RulesVisitor(source, ruleVisitor);
            scriptBlock.getClosureExpression().getCode().visit(rulesVisitor);
        }
    }
}
 
Example #12
Source Project: tddl   Author: cpsing   File: GroovyRule.java    License: Apache License 2.0 5 votes vote down vote up
private void initGroovy() {
    if (expression == null) {
        throw new IllegalArgumentException("未指定 expression");
    }
    GroovyClassLoader loader = new GroovyClassLoader(GroovyRule.class.getClassLoader());
    String groovyRule = getGroovyRule(expression, extraPackagesStr);
    Class<?> c_groovy;
    try {
        c_groovy = loader.parseClass(groovyRule);
    } catch (CompilationFailedException e) {
        throw new IllegalArgumentException(groovyRule, e);
    }

    try {
        // 新建类实例
        Object ruleObj = c_groovy.newInstance();
        if (ruleObj instanceof ShardingFunction) {
            shardingFunction = (ShardingFunction) ruleObj;
        } else {
            throw new IllegalArgumentException("should not be here");
        }
        // 获取方法

    } catch (Throwable t) {
        throw new IllegalArgumentException("实例化规则对象失败", t);
    }
}
 
Example #13
@Override
public void call(final SourceUnit source) throws CompilationFailedException {
    final List<Statement> logStats = Lists.newArrayList();

    // currently we only look in script code; could extend this to build script classes
    AstUtils.visitScriptCode(source, new ClassCodeVisitorSupport() {
        @Override
        protected SourceUnit getSourceUnit() {
            return source;
        }

        @Override
        protected void visitStatement(Statement statement) {
            if (statement.getStatementLabel() != null) {
                // Because we aren't failing the build, the script will be cached and this transformer won't run the next time.
                // In order to make the deprecation warning stick, we have to weave the call to StatementLabelsDeprecationLogger
                // into the build script.
                String label = statement.getStatementLabel();
                String sample = source.getSample(statement.getLineNumber(), statement.getColumnNumber(), null);
                Expression logExpr = new StaticMethodCallExpression(ClassHelper.makeWithoutCaching(StatementLabelsDeprecationLogger.class), "log",
                        new ArgumentListExpression(new ConstantExpression(label), new ConstantExpression(sample)));
                logStats.add(new ExpressionStatement(logExpr));
            }
        }
    });

    source.getAST().getStatementBlock().addStatements(logStats);
}
 
Example #14
Source Project: groovy   Author: apache   File: TemplateTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testMixedTemplateText() throws CompilationFailedException, ClassNotFoundException, IOException {
    Template template1 = new SimpleTemplateEngine().createTemplate("<%= \"test\" %> of expr and <% test = 1 %>${test} script.");
    assertEquals("test of expr and 1 script.", template1.make().toString());

    Template template2 = new GStringTemplateEngine().createTemplate("<%= \"test\" %> of expr and <% test = 1 %>${test} script.");
    assertEquals("test of expr and 1 script.", template2.make().toString());

}
 
Example #15
Source Project: netbeans   Author: apache   File: ClassNodeCache.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Class loadClass(
        final String name,
        final boolean lookupScriptFiles,
        final boolean preferClassOverScript,
        final boolean resolve) throws ClassNotFoundException, CompilationFailedException {
    if (preferClassOverScript && !lookupScriptFiles) {
        //Ideally throw CNF but we need to workaround fix of issue #206811
        //which hurts performance.
        if (cache.isNonExistent(name)) {
            throw CNF;
        }
    }
    return super.loadClass(name, lookupScriptFiles, preferClassOverScript, resolve);
}
 
Example #16
Source Project: james   Author: tomtom-international   File: GroovyScriptEngine.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void invokeErrorHandler(InformationPoint informationPoint,
                               Method origin,
                               List<RuntimeInformationPointParameter> parameters,
                               Object instance,
                               Thread currentThread,
                               Instant eventTime,
                               Duration executionTime,
                               String[] callStack,
                               Throwable errorCause,
                               CompletableFuture<Object> initialContextProvider) {
    LOG.trace(() -> "Invoking error handler for " + getIdentifier(informationPoint));
    try {
        Stopwatch stopwatch = Stopwatch.createStarted();
        InformationPointHandler handler = createOrGetCachedHandler(informationPoint);
        ErrorHandlerContext handlerContext = new ErrorHandlerContext(
                informationPoint.getClassName(), informationPoint.getMethodName(), origin, parameters, instance,
                currentThread, eventTime, executionTime, callStack, errorCause, initialContextProvider.get());
        handler.invokeMethod(ERROR_HANDLER_FUNCTION, new Object[]{handlerContext});
        stopwatch.stop();
        LOG.trace(() -> "Error handler invocation took " + stopwatch.elapsed());
    } catch (CompilationFailedException cfe) {
        LOG.error(() -> "Script compilation failed when calling error handler for " + getIdentifier(informationPoint), cfe);
    } catch (MissingMethodException mme) {
        LOG.error(() -> "Error handler function missing for " + getIdentifier(informationPoint), mme);
    } catch (Throwable t) {
        LOG.error(() -> "Error handler invocation failed for " + getIdentifier(informationPoint), t);
    }
}
 
Example #17
Source Project: james   Author: tomtom-international   File: GroovyScriptEngine.java    License: Apache License 2.0 5 votes vote down vote up
private InformationPointHandler createOrGetCachedHandler(InformationPoint informationPoint)
        throws CompilationFailedException {
    InformationPointHandler handlerFromCache = handlersCache.computeIfAbsent(informationPoint.getScript().get(), scriptTextKey -> {
        InformationPointHandler handler = (InformationPointHandler) getOrCreateShell(informationPoint.getBaseScript()).parse(scriptTextKey);
        handler.setEventPublisher(publisher);
        handler.setToolkitManager(toolkitManager);
        return handler;
    });
    handlerFromCache.setMetadata(informationPoint.getMetadata());
    return handlerFromCache;
}
 
Example #18
Source Project: groovy   Author: apache   File: GroovyShell.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates some script against the current Binding and returns the result
 *
 * @param in       the stream reading the script
 * @param fileName is the logical file name of the script (which is used to create the class name of the script)
 */
public Object evaluate(Reader in, String fileName) throws CompilationFailedException {
    Script script = null;
    try {
        script = parse(in, fileName);
        return script.run();
    } finally {
        if (script != null) {
            InvokerHelper.removeClass(script.getClass());
        }
    }
}
 
Example #19
Source Project: Pushjet-Android   Author: Pushjet   File: FixMainScriptTransformer.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void call(SourceUnit source) throws CompilationFailedException {
    ClassNode scriptClass = AstUtils.getScriptClass(source);
    if (scriptClass == null) {
        return;
    }
    for (MethodNode methodNode : scriptClass.getMethods()) {
        if (methodNode.getName().equals("main")) {
            AstUtils.removeMethod(scriptClass, methodNode);
            break;
        }
    }
}
 
Example #20
Source Project: scipio-erp   Author: ilscipio   File: ContentWorker.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns a boolean, result of whenStr evaluation with context.
 * If whenStr is empty return defaultReturn.
 * @param context A <code>Map</code> containing initial variables
 * @param whenStr A <code>String</code> condition expression
 * @param defaultReturn A <code>boolean</code> default return value
 * @return A <code>boolan</code> result of evaluation
 */
public static boolean checkWhen(Map<String, Object> context, String whenStr, boolean defaultReturn) {
    boolean isWhen = defaultReturn;
    if (UtilValidate.isNotEmpty(whenStr)) {
        FlexibleStringExpander fse = FlexibleStringExpander.getInstance(whenStr);
        String newWhen = fse.expandString(context);
        try {
            // SCIPIO: 2018-09-19: use Groovy
            // FIXME?: NO SCRIPT CACHING: It is not currently possible to cache this condition script safely,
            // because the method and transforms calling it are public so it is unknown who will call this from where,
            // so we could be receiving parametrized input and exploding the cache.
            //final boolean useCache = fse.isConstant();
            final boolean useCache = false;
            Object retVal = GroovyUtil.evalConditionExpr(newWhen, context, useCache);
            // retVal should be a Boolean, if not something weird is up...
            if (retVal instanceof Boolean) {
                Boolean boolVal = (Boolean) retVal;
                isWhen = boolVal;
            } else {
                throw new IllegalArgumentException("Return value from use-when condition eval was not a Boolean: "
                        + (retVal != null ? retVal.getClass().getName() : "null") + " [" + retVal + "]");
            }
        } catch (CompilationFailedException e) {
            Debug.logError("Error in evaluating :" + whenStr + " : " + e.getMessage(), module);
            throw new RuntimeException(e.getMessage());
        }
    }
    return isWhen;
}
 
Example #21
Source Project: groovy   Author: apache   File: TemplateTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testBinding() throws CompilationFailedException, ClassNotFoundException, IOException {
    Map binding = new HashMap();
    binding.put("sam", "pullara");

    Template template1 = new SimpleTemplateEngine().createTemplate("<%= sam %><% print sam %>");
    assertEquals("pullarapullara", template1.make(binding).toString());

    Template template2 = new GStringTemplateEngine().createTemplate("<%= sam %><% out << sam %>");
    assertEquals("pullarapullara", template2.make(binding).toString());

    Template template3 = new GStringTemplateEngine().createTemplate("<%= sam + \" \" + sam %><% out << sam %>");
    assertEquals("pullara pullarapullara", template3.make(binding).toString());
}
 
Example #22
Source Project: scipio-erp   Author: ilscipio   File: ModelForm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * iterate through alt-row-styles list to see if should be used, then add style
 * @return The style for item row
 */
public String getStyleAltRowStyle(Map<String, Object> context) {
    String styles = "";
    try {
        for (AltRowStyle altRowStyle : this.altRowStyles) {
            String useWhen = altRowStyle.useWhen.expandString(context); // SCIPIO: added FlexibleStringExpander support
            // SCIPIO: 2018-09-19: Now using Groovy as second interpreter
            // IMPORTANT: Only enable cache if the flexible expression was a constant, otherwise the cache could blow up!
            final boolean useCache = altRowStyle.useWhen.isConstant();
            Object retVal = GroovyUtil.evalConditionExpr(useWhen, context, useCache);
            // retVal should be a Boolean, if not something weird is up...
            if (retVal instanceof Boolean) {
                // SCIPIO: Slight refactor here
                if ((Boolean) retVal) {
                    styles += altRowStyle.style;
                }
            } else {
                throw new IllegalArgumentException("Return value from style condition eval was not a Boolean: "
                        + retVal.getClass().getName() + " [" + retVal + "] of form " + getName());
            }
        }
    } catch (CompilationFailedException e) {
        String errmsg = "Error evaluating groovy style conditions on form " + getName();
        Debug.logError(e, errmsg, module);
        throw new IllegalArgumentException(errmsg);
    }
    return styles;
}
 
Example #23
Source Project: scipio-erp   Author: ilscipio   File: ModelForm.java    License: Apache License 2.0 5 votes vote down vote up
/** iterate through altTargets list to see if any should be used, if not return original target
 * @return The target for this Form
 */
public String getTarget(Map<String, Object> context, String targetType) {
    Map<String, Object> expanderContext = UtilCodec.EncodingMapWrapper.getEncodingMapWrapper(context, WidgetWorker.getEarlyEncoder(context)); // SCIPIO: simplified
    try {
        for (AltTarget altTarget : this.altTargets) {
            String useWhen = altTarget.useWhen.expandString(context); // SCIPIO: changed for useWhen as FlexibleStringExpander
         // SCIPIO: 2018-09-19: Now using Groovy as second interpreter
            // IMPORTANT: Only enable cache if the flexible expression was a constant, otherwise the cache could blow up!
            final boolean useCache = altTarget.useWhen.isConstant();
            Object retVal = GroovyUtil.evalConditionExpr(useWhen, context, useCache);
            // retVal should be a Boolean, if not something weird is up...
            if (retVal instanceof Boolean) {
                // SCIPIO: Slight refactor here
                if (((boolean) retVal) && !"inter-app".equals(targetType)) {
                    return altTarget.targetExdr.expandString(expanderContext);
                }
            } else {
                throw new IllegalArgumentException("Return value from target condition eval was not a Boolean: "
                        + retVal.getClass().getName() + " [" + retVal + "] of form " + getName());
            }
        }
    } catch (CompilationFailedException e) {
        String errmsg = "Error evaluating groovy target conditions on form " + getName();
        Debug.logError(e, errmsg, module);
        throw new IllegalArgumentException(errmsg);
    }
    return target.expandString(expanderContext);
}
 
Example #24
Source Project: herddb   Author: diennea   File: HerdDBCLI.java    License: Apache License 2.0 5 votes vote down vote up
private static void executeScript(final Connection connection, final HerdDBDataSource datasource,
                                  final Statement statement, String script) throws IOException, CompilationFailedException {
    Map<String, Object> variables = new HashMap<>();
    variables.put("connection", connection);
    variables.put("datasource", datasource);
    variables.put("statement", statement);
    GroovyShell shell = new GroovyShell(new Binding(variables));
    shell.evaluate(new File(script));
}
 
Example #25
Source Project: groovy   Author: apache   File: AllTestSuite.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected void loadTest(String filename) throws CompilationFailedException, IOException {
    Class type = compile(filename);
    if (TestCase.class.isAssignableFrom(type)) {
        addTestSuite((Class<? extends TestCase>)type);
    } else if (Script.class.isAssignableFrom(type)) {
        addTest(new ScriptTestAdapter(type, EMPTY_ARGS));
    } else {
        throw new RuntimeException("Don't know how to treat " + filename + " as a JUnit test");
    }
}
 
Example #26
Source Project: imputationserver   Author: genepi   File: ImputationPipeline.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean imputeVCF(VcfChunkOutput output)
		throws InterruptedException, IOException, CompilationFailedException {

	String chr = "";
	if (build.equals("hg38")) {
		chr = "chr" + output.getChromosome();
	} else {
		chr = output.getChromosome();
	}

	// set parameters
	Map<String, Object> binding = new HashMap<String, Object>();
	binding.put("ref", refFilename);
	binding.put("vcf", output.getPhasedVcfFilename());
	binding.put("start", output.getStart());
	binding.put("end", output.getEnd());
	binding.put("window", minimacWindow);
	binding.put("prefix", output.getPrefix());
	binding.put("chr", chr);
	binding.put("unphased", false);
	binding.put("mapMinimac", mapMinimac);

	String[] params = createParams(minimacParams, binding);

	// minimac command
	Command minimac = new Command(minimacCommand);
	minimac.setSilent(false);
	minimac.setParams(params);
	minimac.saveStdOut(output.getPrefix() + ".minimac.out");
	minimac.saveStdErr(output.getPrefix() + ".minimac.err");

	System.out.println(minimac.getExecutedCommand());

	return (minimac.execute() == 0);

}
 
Example #27
Source Project: hasor   Author: zycgit   File: GroovyScriptEngineImpl.java    License: Apache License 2.0 5 votes vote down vote up
Class getScriptClass(String script) throws SyntaxException, CompilationFailedException, IOException {
    Class clazz = classMap.get(script);
    if (clazz != null) {
        return clazz;
    }
    clazz = loader.parseClass(script, generateScriptName());
    classMap.put(script, clazz);
    return clazz;
}
 
Example #28
Source Project: stendhal   Author: arianne   File: DigAreaFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected ChatAction getAction(final ConfigurableFactoryContext ctx) {
    String value = ctx.getString("action", null);
    if (value == null) {
        return null;
    }
    Binding groovyBinding = new Binding();
    final GroovyShell interp = new GroovyShell(groovyBinding);
    try {
        String code = "import games.stendhal.server.entity.npc.action.*;\r\n"
            + value;
        return (ChatAction) interp.evaluate(code);
    } catch (CompilationFailedException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #29
Source Project: groovy   Author: apache   File: SourceAwareCustomizer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException {
    String fileName = source.getName();
    ReaderSource reader = source.getSource();
    if (reader instanceof FileReaderSource) {
        FileReaderSource file = (FileReaderSource) reader;
        fileName = file.getFile().getName();
    }
    if (acceptSource(source) && acceptClass(classNode) && accept(fileName)) {
        delegate.call(source, context, classNode);
    }
}
 
Example #30
Source Project: stendhal   Author: arianne   File: ConditionAndActionAreaFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected ChatAction getAction(final ConfigurableFactoryContext ctx) {
    String value = ctx.getString("action", null);
    if (value == null) {
        return null;
    }
    Binding groovyBinding = new Binding();
    final GroovyShell interp = new GroovyShell(groovyBinding);
    try {
        String code = "import games.stendhal.server.entity.npc.action.*;\r\n"
            + value;
        return (ChatAction) interp.evaluate(code);
    } catch (CompilationFailedException e) {
        throw new IllegalArgumentException(e);
    }
}