Example usage for org.apache.commons.jelly JellyContext runScript

List of usage examples for org.apache.commons.jelly JellyContext runScript

Introduction

In this page you can find the example usage for org.apache.commons.jelly JellyContext runScript.

Prototype

public JellyContext runScript(String uri, XMLOutput output) throws JellyException 

Source Link

Document

Parses the script from the given uri using the JellyContext.getResource() API then compiles it and runs it.

Usage

From source file:com.cyclopsgroup.waterview.jelly.JellyRunner.java

/**
 * Main entry to run a script/*from  w  ww .  j a va 2 s  .com*/
 * 
 * @param args Script paths
 * @throws Exception Throw it out
 */
public static final void main(String[] args) throws Exception {
    List scripts = new ArrayList();
    for (int i = 0; i < args.length; i++) {
        String path = args[i];
        File file = new File(path);
        if (file.isFile()) {
            scripts.add(file.toURL());
        } else {
            Enumeration enu = JellyRunner.class.getClassLoader().getResources(path);
            CollectionUtils.addAll(scripts, enu);
        }
    }
    if (scripts.isEmpty()) {
        System.out.println("No script to run, return!");
        return;
    }

    String basedir = new File("").getAbsolutePath();
    Properties initProperties = new Properties(System.getProperties());
    initProperties.setProperty("basedir", basedir);
    initProperties.setProperty("plexus.home", basedir);

    WaterviewPlexusContainer container = new WaterviewPlexusContainer();
    for (Iterator j = initProperties.keySet().iterator(); j.hasNext();) {
        String initPropertyName = (String) j.next();
        container.addContextValue(initPropertyName, initProperties.get(initPropertyName));
    }

    container.addContextValue(Waterview.INIT_PROPERTIES, initProperties);
    container.initialize();
    container.start();

    JellyEngine je = (JellyEngine) container.lookup(JellyEngine.ROLE);
    JellyContext jc = new JellyContext(je.getGlobalContext());

    for (Iterator i = scripts.iterator(); i.hasNext();) {
        URL script = (URL) i.next();
        System.out.print("Running script " + script);
        jc.runScript(script, XMLOutput.createDummyXMLOutput());
        System.out.println("... Done!");
    }
    container.dispose();
}

From source file:com.cyclopsgroup.waterview.jelly.JellyScriptsRunner.java

/**
 * Main entry to run a script// w  ww  .  j  a  va2  s. com
 *
 * @param args Script paths
 * @throws Exception Throw it out
 */
public static final void main(String[] args) throws Exception {
    List scripts = new ArrayList();
    for (int i = 0; i < args.length; i++) {
        String path = args[i];
        File file = new File(path);
        if (file.isFile()) {
            scripts.add(file.toURL());
        } else {
            Enumeration enu = JellyScriptsRunner.class.getClassLoader().getResources(path);
            CollectionUtils.addAll(scripts, enu);
        }
    }
    if (scripts.isEmpty()) {
        System.out.println("No script to run, return!");
        return;
    }

    String basedir = new File("").getAbsolutePath();
    Properties initProperties = new Properties(System.getProperties());
    initProperties.setProperty("basedir", basedir);
    initProperties.setProperty("plexus.home", basedir);

    WaterviewPlexusContainer container = new WaterviewPlexusContainer();
    for (Iterator j = initProperties.keySet().iterator(); j.hasNext();) {
        String initPropertyName = (String) j.next();
        container.addContextValue(initPropertyName, initProperties.get(initPropertyName));
    }

    container.addContextValue(Waterview.INIT_PROPERTIES, initProperties);
    container.initialize();
    container.start();

    JellyEngine je = (JellyEngine) container.lookup(JellyEngine.ROLE);
    JellyContext jc = new JellyContext(je.getGlobalContext());
    XMLOutput output = XMLOutput.createXMLOutput(System.out);
    for (Iterator i = scripts.iterator(); i.hasNext();) {
        URL script = (URL) i.next();
        System.out.print("Running script " + script);
        ExtendedProperties ep = new ExtendedProperties();
        ep.putAll(initProperties);
        ep.load(script.openStream());
        for (Iterator j = ep.getKeys("script"); j.hasNext();) {
            String name = (String) j.next();
            if (name.endsWith(".file")) {
                File file = new File(ep.getString(name));
                if (file.exists()) {
                    System.out.println("Runner jelly file " + file);
                    jc.runScript(file, output);
                }
            } else if (name.endsWith(".resource")) {
                Enumeration k = JellyScriptsRunner.class.getClassLoader().getResources(ep.getString(name));
                while (j != null && k.hasMoreElements()) {
                    URL s = (URL) k.nextElement();
                    System.out.println("Running jelly script " + s);
                    jc.runScript(s, output);
                }
            }
        }
        //jc.runScript( script, XMLOutput.createDummyXMLOutput() );
        System.out.println("... Done!");
    }
    container.dispose();
}

From source file:com.latticeware.xecute.Engine.java

public Object execute(String script, Map<String, Object> env)
        throws UnsupportedEncodingException, JellyException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(5120);
    ByteArrayInputStream bais = new ByteArrayInputStream(script.getBytes());
    XMLOutput xo = XMLOutput.createXMLOutput(baos);
    InputSource is = new InputSource(bais);

    JellyContext context = new JellyContext();
    env.keySet().forEach((key) -> {/*  w  w w.  j  a v  a2s  .  co  m*/
        context.setVariable(key, env.get(key));
    });
    context.runScript(is, xo);
    return baos.toString();
}

From source file:com.groupon.jenkins.buildsetup.GithubRepoAction.java

public String getHtml(ProjectConfigInfo projectConfigInfo)
        throws IOException, ClassNotFoundException, JellyException {
    String name = getClass().getName().replace('.', '/').replace('$', '/') + "/" + "index.jelly";
    URL actionTemplate = getClass().getClassLoader().getResource(name);
    JellyContext context = new JellyContext();
    context.setVariable("p", projectConfigInfo);
    context.setVariable("it", this);
    OutputStream outputStream = new ByteArrayOutputStream();
    XMLOutput output = XMLOutput.createXMLOutput(outputStream);
    context.runScript(actionTemplate, output);
    output.flush();//from   w  w w . j a  va  2  s .com
    return "<p>" + outputStream.toString() + " </p>";
}

From source file:com.marvelution.hudson.plugins.jirareporter.utils.IssueTextUtils.java

/**
 * Create the text content for a specific issue field
 * /* w  w  w. ja  v a 2s  .  c o m*/
 * @param type the {@link Type} of text to create
 * @param build the {@link AbstractBuild}
 * @param site the {@link JIRASite}
 * @return the created text content
 */
public static String createFieldText(Type type, AbstractBuild<?, ?> build, JIRASite site) {
    final StringWriter writer = new StringWriter();
    final XMLOutput output = XMLOutput.createXMLOutput(writer);
    final JellyContext context = new JellyContext();
    context.setVariable("rootURL", Hudson.getInstance().getRootUrl());
    context.setVariable("build", build);
    context.setVariable("site", site);
    try {
        Class.forName("jenkins.model.Jenkins");
        context.setVariable("system", "Jenkins");
    } catch (ClassNotFoundException e) {
        context.setVariable("system", "Hudson");
    }
    context.setVariable("version", Hudson.getVersion().toString());
    try {
        context.setVariable("environment", build.getEnvironment(new LogTaskListener(LOGGER, Level.INFO)));
    } catch (Exception e) {
        context.setVariable("environment", Collections.emptyMap());
    }
    // Utilize the Dozer Mapper and its convertors of the API V2 plugin to get the ChangeLog and TestResults
    try {
        context.setVariable("changelog", DozerUtils.getMapper().map(build.getChangeSet(), ChangeLog.class));
    } catch (Exception e) {
        context.setVariable("changelog", new ChangeLog());
    }
    try {
        context.setVariable("testresults", DozerUtils.getMapper().map(build, TestResult.class));
    } catch (Exception e) {
        context.setVariable("testresults", new TestResult());
    }
    try {
        context.runScript(
                HudsonPluginUtils.getPluginClassloader().getResource("fields/" + type.field(site) + ".jelly"),
                output);
    } catch (JellyException e) {
        LOGGER.log(Level.SEVERE, "Failed to create Text of type " + type.name(), e);
        throw new IllegalStateException("Cannot raise an issue if no text is available", e);
    }
    return writer.toString().trim();
}

From source file:com.cyclopsgroup.waterview.navigator.impl.DefaultNavigatorHome.java

/**
 * Overwrite or implement method in DefaultNavigatorHome
 *
 * @see org.apache.avalon.framework.activity.Initializable#initialize()
 *//*ww w.j a v  a2s  .  c o  m*/
public void initialize() throws Exception {
    pathIndex = new Hashtable();
    parentPathIndex = new MultiHashMap();
    pageIndex = new Hashtable();

    rootNode = new DefaultNavigatorNode(this, "/", null);
    rootNode.getAttributes().set(DefaultNavigatorNode.PAGE_NAME, "/Index.jelly");
    rootNode.getAttributes().set(DefaultNavigatorNode.TITLE_NAME, "Start");
    addNode(rootNode);

    JellyContext jc = new JellyContext();
    jc.setVariable(getClass().getName(), this);
    jc.registerTagLibrary("http://waterview.cyclopsgroup.com/navigator", new NavigatorTagLibrary());
    for (Enumeration en = getClass().getClassLoader()
            .getResources("META-INF/cyclopsgroup/waterview-navigation.xml"); en.hasMoreElements();) {
        URL resource = (URL) en.nextElement();
        getLogger().info("Reading navigation from " + resource);
        jc.runScript(resource, XMLOutput.createDummyXMLOutput());
    }
    populateNode(rootNode);
}

From source file:com.cyclopsgroup.waterview.navigator.impl.DefaultNavigatorService.java

/**
 * Overwrite or implement method in DefaultNavigatorHome
 *
 * @see org.apache.avalon.framework.activity.Initializable#initialize()
 *//*from  w w w .  ja v  a 2  s .c  o  m*/
public void initialize() throws Exception {
    pathIndex = new Hashtable();
    parentPathIndex = new MultiHashMap();
    pageIndex = new Hashtable();

    rootNode = new DefaultNavigatorNode(this, "/", null);
    rootNode.getAttributes().set(DefaultNavigatorNode.PAGE_NAME, "/Index.jelly");
    rootNode.getAttributes().set(DefaultNavigatorNode.TITLE_NAME, "%waterview.navigation.start");
    addNode(rootNode);

    JellyContext jc = new JellyContext();
    jc.setVariable(DefaultNavigatorService.class.getName(), this);
    jc.registerTagLibrary("http://waterview.cyclopsgroup.com/navigator", new NavigatorTagLibrary());
    for (Enumeration en = getClass().getClassLoader().getResources(path); en.hasMoreElements();) {
        URL resource = (URL) en.nextElement();
        getLogger().info("Reading navigation from " + resource);
        jc.runScript(resource, XMLOutput.createDummyXMLOutput());
    }
    populateNode(rootNode);
}

From source file:com.cyclopsgroup.waterview.jelly.JellyEngine.java

/**
 * Init global context/* w w w  .j a  va2s. c o  m*/
 *
 * @throws Exception Throw it out
 */
private void initGlobalContext() throws Exception {
    JellyContext jc = new JellyContext();
    jc.setVariable(SERVICE_MANAGER, serviceManager);
    jc.setVariable(ROLE, this);
    TagLibrary deftaglib = new TagLibrary();
    deftaglib.registerPackage((TagPackage) Class.forName(DEFINITION_TAG_PACKAGE).newInstance());
    jc.registerTagLibrary(DEFINITION_TAGLIB_URL, deftaglib);

    Enumeration e = getClass().getClassLoader().getResources("META-INF/cyclopsgroup/waterview.xml");
    while (e.hasMoreElements()) {
        URL resource = (URL) e.nextElement();
        getLogger().info("Load definition from " + resource);
        jc.runScript(resource, XMLOutput.createDummyXMLOutput());
    }

    globalContext = new JellyContext();
    globalContext.setVariables(initProperties);
    for (Iterator i = tagLibraries.keySet().iterator(); i.hasNext();) {
        String uri = (String) i.next();
        TagLibrary taglib = (TagLibrary) tagLibraries.get(uri);
        globalContext.registerTagLibrary(uri, taglib);
    }
    globalContext.setVariable(SERVICE_MANAGER, serviceManager);
    globalContext.setVariable(ROLE, this);
}

From source file:org.apache.commons.jelly.demos.HomepageBuilder.java

public void buildPage(String template, JellyContext ctx) {

    //        try {
    ///*  w  w  w  .  ja va2 s.c o m*/
    //        Embedded embedded = new Embedded();
    //        embedded.setOutputStream(new FileOutputStream("out.html"));
    //        //embedded.setVariable("some-var","some-object");
    //
    //        embedded.setScript("file:///anoncvs/jakarta-commons-sandbox/jelly/sample.jelly");
    //        //or one can do.
    //        //embedded.setScript(scriptAsInputStream);
    //
    //        boolean bStatus=embedded.execute();
    //        if(!bStatus) //if error
    //        {
    //        System.out.println(embedded.getErrorMsg());
    //        }
    //
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //        }

    try {

        OutputStream output = new FileOutputStream("demopage.html");

        JellyContext context = new JellyContext();
        context.setVariable("name", nameField.getText());
        context.setVariable("background", colorField.getText());
        context.setVariable("url", urlField.getText());

        Vector v = new Vector();
        Enumeration items = listModel.elements();
        while (items.hasMoreElements()) {
            v.add(items.nextElement());
        }
        context.setVariable("hobbies", v);

        XMLOutput xmlOutput = XMLOutput.createXMLOutput(output);
        context.runScript(resolveURL("src/test/org/apache/commons/jelly/demos/" + template), xmlOutput);
        xmlOutput.flush();
        System.out.println("Finished merging template");

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.codehaus.mojo.AbstractJellyMojo.java

/**
 * Execute the .jelly script associated with the concrete class
 *//*from w w w  . ja  v  a 2 s. c o  m*/
public void execute() throws MojoExecutionException {
    try {
        final String scriptName = this.getClass().getSimpleName() + ".jelly";
        if (scriptName == null || scriptName.equals(""))
            throw new MojoExecutionException("script name unspecified");
        URL fileName = this.getClass().getResource(scriptName);
        if (fileName == null)
            throw new MojoExecutionException(scriptName + " not found");

        setParams();

        // add plugin's parameters to the groovy context
        JellyContext context = new JellyContext();
        if (params != null) {
            Iterator i = params.keySet().iterator();
            while (i.hasNext()) {
                String key = (String) i.next();
                context.setVariable(key, params.get(key));
            }
        }

        XMLOutput xmlOutput = XMLOutput.createXMLOutput(System.out);
        context.runScript(fileName, xmlOutput);
        xmlOutput.flush();
    } catch (Exception e) {
        throw new MojoExecutionException("Mojo error occurred:", e);
    }
}