Search in sources :

Example 66 with Binding

use of groovy.lang.Binding in project maven-archetype by apache.

the class DefaultFilesetArchetypeGenerator method generateArchetype.

public void generateArchetype(ArchetypeGenerationRequest request, File archetypeFile) throws UnknownArchetype, ArchetypeNotConfigured, ProjectDirectoryExists, PomFileExists, OutputFileExists, ArchetypeGenerationFailure {
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    try {
        ArchetypeDescriptor archetypeDescriptor = archetypeArtifactManager.getFileSetArchetypeDescriptor(archetypeFile);
        if (!isArchetypeConfigured(archetypeDescriptor, request)) {
            if (request.isInteractiveMode()) {
                throw new ArchetypeNotConfigured("No archetype was chosen.", null);
            }
            StringBuffer exceptionMessage = new StringBuffer("Archetype " + request.getArchetypeGroupId() + ":" + request.getArchetypeArtifactId() + ":" + request.getArchetypeVersion() + " is not configured");
            List<String> missingProperties = new ArrayList<String>(0);
            for (RequiredProperty requiredProperty : archetypeDescriptor.getRequiredProperties()) {
                if (StringUtils.isEmpty(request.getProperties().getProperty(requiredProperty.getKey()))) {
                    exceptionMessage.append("\n\tProperty " + requiredProperty.getKey() + " is missing.");
                    missingProperties.add(requiredProperty.getKey());
                }
            }
            throw new ArchetypeNotConfigured(exceptionMessage.toString(), missingProperties);
        }
        Context context = prepareVelocityContext(request);
        String packageName = request.getPackage();
        String artifactId = request.getArtifactId();
        File outputDirectoryFile = new File(request.getOutputDirectory(), artifactId);
        File basedirPom = new File(request.getOutputDirectory(), Constants.ARCHETYPE_POM);
        File pom = new File(outputDirectoryFile, Constants.ARCHETYPE_POM);
        List<String> archetypeResources = archetypeArtifactManager.getFilesetArchetypeResources(archetypeFile);
        ZipFile archetypeZipFile = archetypeArtifactManager.getArchetypeZipFile(archetypeFile);
        ClassLoader archetypeJarLoader = archetypeArtifactManager.getArchetypeJarLoader(archetypeFile);
        Thread.currentThread().setContextClassLoader(archetypeJarLoader);
        if (archetypeDescriptor.isPartial()) {
            getLogger().debug("Processing partial archetype " + archetypeDescriptor.getName());
            if (outputDirectoryFile.exists()) {
                if (!pom.exists()) {
                    throw new PomFileExists("This is a partial archetype and the pom.xml file doesn't exist.");
                }
                processPomWithMerge(context, pom, "");
                processArchetypeTemplatesWithWarning(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, outputDirectoryFile);
            } else {
                if (basedirPom.exists()) {
                    processPomWithMerge(context, basedirPom, "");
                    processArchetypeTemplatesWithWarning(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, new File(request.getOutputDirectory()));
                } else {
                    processPom(context, pom, "");
                    processArchetypeTemplates(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, outputDirectoryFile);
                }
            }
            if (archetypeDescriptor.getModules().size() > 0) {
                getLogger().info("Modules ignored in partial mode");
            }
        } else {
            getLogger().debug("Processing complete archetype " + archetypeDescriptor.getName());
            if (outputDirectoryFile.exists() && pom.exists()) {
                throw new ProjectDirectoryExists("A Maven 2 project already exists in the directory " + outputDirectoryFile.getPath());
            }
            if (outputDirectoryFile.exists()) {
                getLogger().warn("The directory " + outputDirectoryFile.getPath() + " already exists.");
            }
            context.put("rootArtifactId", artifactId);
            processFilesetModule(artifactId, artifactId, archetypeResources, pom, archetypeZipFile, "", basedirPom, outputDirectoryFile, packageName, archetypeDescriptor, context);
        }
        String postGenerationScript = archetypeArtifactManager.getPostGenerationScript(archetypeFile);
        if (postGenerationScript != null) {
            getLogger().info("Executing " + Constants.ARCHETYPE_POST_GENERATION_SCRIPT + " post-generation script");
            Binding binding = new Binding();
            final Properties archetypeGeneratorProperties = new Properties();
            archetypeGeneratorProperties.putAll(System.getProperties());
            if (request.getProperties() != null) {
                archetypeGeneratorProperties.putAll(request.getProperties());
            }
            for (Map.Entry<Object, Object> entry : archetypeGeneratorProperties.entrySet()) {
                binding.setVariable(entry.getKey().toString(), entry.getValue());
            }
            binding.setVariable("request", request);
            GroovyShell shell = new GroovyShell(binding);
            shell.evaluate(postGenerationScript);
        }
        // ----------------------------------------------------------------------
        if (getLogger().isInfoEnabled()) {
            getLogger().info("Project created from Archetype in dir: " + outputDirectoryFile.getAbsolutePath());
        }
    } catch (FileNotFoundException ex) {
        throw new ArchetypeGenerationFailure(ex);
    } catch (IOException ex) {
        throw new ArchetypeGenerationFailure(ex);
    } catch (XmlPullParserException ex) {
        throw new ArchetypeGenerationFailure(ex);
    } catch (DocumentException ex) {
        throw new ArchetypeGenerationFailure(ex);
    } catch (ArchetypeGenerationFailure ex) {
        throw new ArchetypeGenerationFailure(ex);
    } catch (InvalidPackaging ex) {
        throw new ArchetypeGenerationFailure(ex);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}
Also used : ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) Properties(java.util.Properties) ArchetypeNotConfigured(org.apache.maven.archetype.exception.ArchetypeNotConfigured) RequiredProperty(org.apache.maven.archetype.metadata.RequiredProperty) DocumentException(org.dom4j.DocumentException) PomFileExists(org.apache.maven.archetype.exception.PomFileExists) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) ProjectDirectoryExists(org.apache.maven.archetype.exception.ProjectDirectoryExists) Context(org.apache.velocity.context.Context) VelocityContext(org.apache.velocity.VelocityContext) Binding(groovy.lang.Binding) InvalidPackaging(org.apache.maven.archetype.exception.InvalidPackaging) IOException(java.io.IOException) AbstractArchetypeDescriptor(org.apache.maven.archetype.metadata.AbstractArchetypeDescriptor) ArchetypeDescriptor(org.apache.maven.archetype.metadata.ArchetypeDescriptor) GroovyShell(groovy.lang.GroovyShell) ZipFile(java.util.zip.ZipFile) ZipFile(java.util.zip.ZipFile) File(java.io.File) Map(java.util.Map) ArchetypeGenerationFailure(org.apache.maven.archetype.exception.ArchetypeGenerationFailure)

Example 67 with Binding

use of groovy.lang.Binding in project promoted-builds-plugin by jenkinsci.

the class GroovyCondition method isMet.

@Override
public PromotionBadge isMet(final PromotionProcess promotionProcess, final AbstractBuild<?, ?> build) {
    final Jenkins jenkins = Jenkins.get();
    final PluginManager pluginManager = jenkins.getPluginManager();
    final ClassLoader classLoader = pluginManager.uberClassLoader;
    final Binding binding = new Binding();
    binding.setVariable("promotionProcess", promotionProcess);
    binding.setVariable("build", build);
    binding.setVariable("jenkins", jenkins);
    Object result = null;
    try {
        result = script.evaluate(classLoader, binding);
    } catch (final RejectedAccessException e) {
        LOGGER.log(Level.WARNING, "Sandbox exception", e);
        return null;
    } catch (final UnapprovedUsageException e) {
        LOGGER.log(Level.WARNING, "Unapproved script", e);
        return null;
    } catch (final UnapprovedClasspathException e) {
        LOGGER.log(Level.WARNING, "Unapproved classpath", e);
        return null;
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Evaluation error", e);
        return null;
    }
    final String displayLabel = metQualificationLabel == null ? Messages.GroovyCondition_MetQualificationLabel() : metQualificationLabel;
    if (Boolean.TRUE.equals(result)) {
        return new Badge(displayLabel, Collections.<String, String>emptyMap());
    } else if (result instanceof Map && !((Map) result).isEmpty()) {
        final Map<String, String> variables = new HashMap<String, String>(((Map) result).size());
        for (final Map.Entry entry : ((Map<Object, Object>) result).entrySet()) {
            final Object key = entry.getKey();
            final Object value = entry.getValue();
            if (key == null) {
                continue;
            }
            variables.put(key.toString(), value == null ? "" : value.toString());
        }
        return new Badge(displayLabel, variables);
    }
    return null;
}
Also used : Binding(groovy.lang.Binding) RejectedAccessException(org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException) UnapprovedUsageException(org.jenkinsci.plugins.scriptsecurity.scripts.UnapprovedUsageException) UnapprovedClasspathException(org.jenkinsci.plugins.scriptsecurity.scripts.UnapprovedClasspathException) PromotionBadge(hudson.plugins.promoted_builds.PromotionBadge) UnapprovedClasspathException(org.jenkinsci.plugins.scriptsecurity.scripts.UnapprovedClasspathException) UnapprovedUsageException(org.jenkinsci.plugins.scriptsecurity.scripts.UnapprovedUsageException) RejectedAccessException(org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException) Jenkins(jenkins.model.Jenkins) PluginManager(hudson.PluginManager) HashMap(java.util.HashMap) Map(java.util.Map)

Example 68 with Binding

use of groovy.lang.Binding in project qi4j-sdk by Qi4j.

the class GroovyMixin method invokeAsScript.

private Object invokeAsScript(Method method, Object[] args, URL groovySource) throws Throwable {
    try {
        Binding binding = new Binding();
        binding.setVariable("This", me);
        binding.setVariable("args", args);
        GroovyShell shell = new GroovyShell(binding);
        InputStream is = null;
        try {
            is = groovySource.openStream();
            return shell.evaluate(new InputStreamReader(is));
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}
Also used : Binding(groovy.lang.Binding) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) GroovyShell(groovy.lang.GroovyShell) MissingPropertyException(groovy.lang.MissingPropertyException)

Example 69 with Binding

use of groovy.lang.Binding in project gitblit by gitblit.

the class GitblitReceivePack method runGroovy.

/**
 * Runs the specified Groovy hook scripts.
 *
 * @param repository
 * @param user
 * @param commands
 * @param scripts
 */
private void runGroovy(Collection<ReceiveCommand> commands, Set<String> scripts) {
    if (scripts == null || scripts.size() == 0) {
        // no Groovy scripts to execute
        return;
    }
    Binding binding = new Binding();
    binding.setVariable("gitblit", gitblit);
    binding.setVariable("repository", repository);
    binding.setVariable("receivePack", this);
    binding.setVariable("user", user);
    binding.setVariable("commands", commands);
    binding.setVariable("url", gitblitUrl);
    binding.setVariable("logger", LOGGER);
    binding.setVariable("clientLogger", new ClientLogger(this));
    for (String script : scripts) {
        if (StringUtils.isEmpty(script)) {
            continue;
        }
        // allow script to be specified without .groovy extension
        // this is easier to read in the settings
        File file = new File(groovyDir, script);
        if (!file.exists() && !script.toLowerCase().endsWith(".groovy")) {
            file = new File(groovyDir, script + ".groovy");
            if (file.exists()) {
                script = file.getName();
            }
        }
        try {
            Object result = gse.run(script, binding);
            if (result instanceof Boolean) {
                if (!((Boolean) result)) {
                    LOGGER.error(MessageFormat.format("Groovy script {0} has failed!  Hook scripts aborted.", script));
                    break;
                }
            }
        } catch (Exception e) {
            LOGGER.error(MessageFormat.format("Failed to execute Groovy script {0}", script), e);
        }
    }
}
Also used : Binding(groovy.lang.Binding) ClientLogger(com.gitblit.utils.ClientLogger) File(java.io.File) IOException(java.io.IOException)

Example 70 with Binding

use of groovy.lang.Binding in project gitblit by gitblit.

the class GroovyScriptTest method test.

private void test(String script, MockGitblit gitblit, MockLogger logger, MockClientLogger clientLogger, List<ReceiveCommand> commands, RepositoryModel repository) throws Exception {
    UserModel user = new UserModel("mock");
    String gitblitUrl = GitBlitSuite.url;
    File groovyDir = repositories().getHooksFolder();
    GroovyScriptEngine gse = new GroovyScriptEngine(groovyDir.getAbsolutePath());
    Binding binding = new Binding();
    binding.setVariable("gitblit", gitblit);
    binding.setVariable("repository", repository);
    binding.setVariable("user", user);
    binding.setVariable("commands", commands);
    binding.setVariable("url", gitblitUrl);
    binding.setVariable("logger", logger);
    binding.setVariable("clientLogger", clientLogger);
    Object result = gse.run(script, binding);
    if (result instanceof Boolean) {
        if (!((Boolean) result)) {
            throw new GitBlitException(MessageFormat.format("Groovy script {0} has failed!  Hook scripts aborted.", script));
        }
    }
}
Also used : UserModel(com.gitblit.models.UserModel) Binding(groovy.lang.Binding) GroovyScriptEngine(groovy.util.GroovyScriptEngine) GitBlitException(com.gitblit.GitBlitException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) File(java.io.File)

Aggregations

Binding (groovy.lang.Binding)213 GroovyShell (groovy.lang.GroovyShell)76 Script (groovy.lang.Script)55 Test (org.junit.Test)41 IOException (java.io.IOException)29 File (java.io.File)24 HashMap (java.util.HashMap)23 Closure (groovy.lang.Closure)22 CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)22 Map (java.util.Map)20 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)13 ImportCustomizer (org.codehaus.groovy.control.customizers.ImportCustomizer)12 GroovyService (eu.esdihumboldt.util.groovy.sandbox.GroovyService)11 MissingPropertyException (groovy.lang.MissingPropertyException)11 GroovyClassLoader (groovy.lang.GroovyClassLoader)10 StringWriter (java.io.StringWriter)10 InstanceBuilder (eu.esdihumboldt.hale.common.instance.groovy.InstanceBuilder)9 InputStreamReader (java.io.InputStreamReader)9 Writer (java.io.Writer)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)9