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

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

Introduction

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

Prototype

public void setVariable(String name, Object value) 

Source Link

Document

Sets the value of the named variable

Usage

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

/**
 * Create new Jelly context with all variables in given context
 * //from w  w w . ja v  a 2 s.c o m
 * @param context Given clib context
 * @return JellyContext object
 */
public JellyContext createJellyContext(com.cyclopsgroup.waterview.Context context) {
    JellyContext jc = new JellyContext(getGlobalContext());
    for (Iterator i = context.keys(); i.hasNext();) {
        String name = (String) i.next();
        Object value = context.get(name);
        jc.setVariable(name, value);
    }
    jc.setVariable(com.cyclopsgroup.waterview.Context.NAME, context);
    return jc;
}

From source file:hudson.model.View.java

/**
 * An API REST method to get the allowed {$link TopLevelItem}s and its categories.
 *
 * @return A {@link Categories} entity that is shown as JSON file.
 *//* w  w  w.j a va  2 s. c o  m*/
@Restricted(DoNotUse.class)
public Categories doItemCategories(StaplerRequest req, StaplerResponse rsp, @QueryParameter String iconStyle)
        throws IOException, ServletException {
    getOwner().checkPermission(Item.CREATE);

    rsp.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    rsp.addHeader("Pragma", "no-cache");
    rsp.addHeader("Expires", "0");
    Categories categories = new Categories();
    int order = 0;
    JellyContext ctx;

    if (StringUtils.isNotBlank(iconStyle)) {
        ctx = new JellyContext();
        ctx.setVariable("resURL", req.getContextPath() + Jenkins.RESOURCE_PATH);
    } else {
        ctx = null;
    }
    for (TopLevelItemDescriptor descriptor : DescriptorVisibilityFilter.apply(getOwner().getItemGroup(),
            Items.all(Jenkins.getAuthentication(), getOwner().getItemGroup()))) {
        ItemCategory ic = ItemCategory.getCategory(descriptor);
        Map<String, Serializable> metadata = new HashMap<String, Serializable>();

        // Information about Item.
        metadata.put("class", descriptor.getId());
        metadata.put("order", ++order);
        metadata.put("displayName", descriptor.getDisplayName());
        metadata.put("description", descriptor.getDescription());
        metadata.put("iconFilePathPattern", descriptor.getIconFilePathPattern());
        String iconClassName = descriptor.getIconClassName();
        if (StringUtils.isNotBlank(iconClassName)) {
            metadata.put("iconClassName", iconClassName);
            if (ctx != null) {
                Icon icon = IconSet.icons
                        .getIconByClassSpec(StringUtils.join(new String[] { iconClassName, iconStyle }, " "));
                if (icon != null) {
                    metadata.put("iconQualifiedUrl", icon.getQualifiedUrl(ctx));
                }
            }
        }

        Category category = categories.getItem(ic.getId());
        if (category != null) {
            category.getItems().add(metadata);
        } else {
            List<Map<String, Serializable>> temp = new ArrayList<Map<String, Serializable>>();
            temp.add(metadata);
            category = new Category(ic.getId(), ic.getDisplayName(), ic.getDescription(), ic.getOrder(),
                    ic.getMinToShow(), temp);
            categories.getItems().add(category);
        }
    }
    return categories;
}

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

public void buildPage(String template, JellyContext ctx) {

    //        try {
    ////from  w w w  .j a va 2  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 ww w  .j a  va  2  s. c  om
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);
    }
}

From source file:org.jenkins.ui.icon.IconSet.java

public static void initPageVariables(JellyContext context) {
    context.setVariable("icons", icons);
}

From source file:org.jenkinsci.plugins.github_branch_source.GitHubLink.java

@Override
public String getIconFileName() {
    String iconClassName = getIconClassName();
    if (iconClassName != null) {
        Icon icon = IconSet.icons.getIconByClassSpec(iconClassName + " icon-md");
        if (icon != null) {
            JellyContext ctx = new JellyContext();
            ctx.setVariable("resURL", Stapler.getCurrentRequest().getContextPath() + Jenkins.RESOURCE_PATH);
            return icon.getQualifiedUrl(ctx);
        }//  w w  w  .j  av  a  2s .  c om
    }
    return null;
}

From source file:org.kohsuke.stapler.jelly.groovy.JellyBuilder.java

private void _include(Object it, Klass clazz, String view) throws IOException, JellyException {
    JellyClassTearOff t = request.getWebApp().getMetaClass(clazz).getTearOff(JellyClassTearOff.class);
    Script s = t.findScript(view);//  w w w . j  a va 2s .  c o m
    if (s == null)
        throw new IllegalArgumentException("No such view: " + view + " for " + clazz);

    JellyContext context = new JellyContext(getContext());
    if (it != null)
        context.setVariable("it", it);
    context.setVariable("from", it);

    ClassLoader old = Thread.currentThread().getContextClassLoader();
    if (clazz.clazz instanceof Class)
        Thread.currentThread().setContextClassLoader(((Class) clazz.clazz).getClassLoader());
    try {
        s.run(context, output);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}

From source file:org.sapia.soto.state.cocoon.view.JellyUtils.java

/**
 * Copies the objects in the given parameter map to the given Jelly context.
 * This method spare existing variables the context.
 * //  w  w w  .  j  a v a  2 s .  c  o  m
 * @param ctx
 *          a <code>JellyContext</code>.
 * @param params
 *          a <code>Map</code> of parameters to bind into the context.
 */
public static void copyParamsTo(JellyContext ctx, Map params) {
    Map.Entry entry;
    Iterator itr = params.entrySet().iterator();
    while (itr.hasNext()) {
        entry = (Map.Entry) itr.next();
        ctx.setVariable(entry.getKey().toString(), entry.getValue());
    }
}

From source file:org.sapia.soto.state.cocoon.view.JellyView.java

protected void execute(Object model, Map viewParams, ContentHandler handler) throws Throwable {
    if (_jelly == null) {
        throw new IllegalStateException("Jelly script not set on Jelly view");
    }/*ww w . ja  v  a  2  s  .  co m*/

    if (_lastModified != _res.lastModified()) {
        reload();
    }

    JellyContext jelly = new JellyContext();
    JellyUtils.copyParamsTo(jelly, viewParams);
    jelly.setCurrentURL(new URL(_res.getURI()));
    jelly.setVariable(CocoonContext.MODEL_KEY, model);

    Param p;
    for (int i = 0; i < _params.size(); i++) {
        p = (Param) _params.get(i);
        if (p.getName() != null && p.getValue() != null) {
            jelly.setVariable(p.getName(), p.getValue());
        }
    }

    XMLOutput output = new XMLOutput(handler);
    output.startDocument();
    _jelly.run(jelly, output);
    output.endDocument();
}

From source file:org.wyona.yanel.impl.resources.usecase.UsecaseResource.java

/**
 * Generate jelly view.//w  w w  . j av a2s .  c  o m
 */
private InputStream getJellyInputStream(String viewID, String viewTemplate, boolean XMLoutput)
        throws UsecaseException {
    try {

        if (log.isDebugEnabled())
            log.debug("viewTemplate: " + viewTemplate);
        Repository repo = this.getRealm().getRepository();

        JellyContext jellyContext = new JellyContext();
        jellyContext.setVariable("resource", this);
        jellyContext.setVariable("yanel.back2context", PathUtil.backToContext(realm, getPath()));
        jellyContext.setVariable("yanel.back2realm", PathUtil.backToRealm(getPath()));
        jellyContext.setVariable("yanel.globalHtdocsPath", PathUtil.getGlobalHtdocsPath(this));
        jellyContext.setVariable("yanel.resourcesHtdocsPath", PathUtil.getResourcesHtdocsPathURLencoded(this));
        jellyContext.setVariable("yanel.reservedPrefix", this.getYanel().getReservedPrefix());
        //jellyContext.setVariable("request", request);

        ByteArrayOutputStream jellyResultStream = new ByteArrayOutputStream();
        XMLOutput jellyOutput = XMLOutput.createXMLOutput(jellyResultStream, XMLoutput);
        InputStream templateInputStream;
        String templatePublicId;
        String templateSystemId;
        if (viewTemplate.startsWith("/")) {
            if (log.isDebugEnabled())
                log.debug(
                        "Accessing view template directly from the repo (no protocol specified). View Template: "
                                + viewTemplate);
            // for backwards compatibility. when not using a protocol
            templateInputStream = repo.getNode(viewTemplate).getInputStream();
            templatePublicId = "yanelrepo:" + viewTemplate;
            /*XXX HACK the following does not work: Jelly wants URLs => protocol must be registered by the JVM!
            templateSystemId = "yanelrepo:"+viewTemplate;
            */
            templateSystemId = "file:///yanelrepo" + viewTemplate;

        } else {
            if (log.isDebugEnabled())
                log.debug(
                        "Accessing view template through the source-resolver (protocol specified). View Template: "
                                + viewTemplate);
            SourceResolver resolver = new SourceResolver(this);
            Source templateSource = resolver.resolve(viewTemplate, null);
            templateInputStream = ((StreamSource) templateSource).getInputStream();
            templatePublicId = templateSource.getSystemId();
            /*XXX HACK the following does not work: Jelly wants URLs => protocol must be registered by the JVM!
            templateSystemId = templateSource.getSystemId();
            */
            templateSystemId = "file:///" + viewTemplate.replaceFirst(":", "/");
        }
        InputSource inputSource = new InputSource(templateInputStream);
        inputSource.setPublicId(templatePublicId);
        inputSource.setSystemId(templateSystemId);
        jellyContext.runScript(inputSource, jellyOutput);
        //XXX should we close templateInputStream here?!?

        jellyOutput.flush();
        byte[] result = jellyResultStream.toByteArray();
        //System.out.println(new String(result, "utf-8"));
        return new ByteArrayInputStream(result);
    } catch (Exception e) {
        String errorMsg = "Error creating 'jelly' view '" + viewID + "' of usecase resource: " + getName()
                + ": " + e;
        log.error(errorMsg, e);
        throw new UsecaseException(errorMsg, e);
    }
}