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

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

Introduction

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

Prototype

public JellyContext() 

Source Link

Document

Create a new context with the currentURL set to the rootURL

Usage

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

/**
 * Init global context/*from w  ww. jav a2s  .com*/
 *
 * @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: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  ww . j  av a  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 HomepageBuilder() {

    System.out.println("Starting Homepage Builder");

    JPanel leftPanel = new JPanel();
    leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));

    leftPanel.add(new JLabel("Name:"));

    nameField = new JTextField("James Bond");
    leftPanel.add(nameField);// www .  j  a  v  a2  s  .c  o  m

    leftPanel.add(new JLabel("Favorite Color:"));

    colorField = new JTextField("#007007");
    leftPanel.add(colorField);

    leftPanel.add(new JLabel("Picture URL:"));

    urlField = new JTextField("http://www.ianfleming.org/007news/images3/c2002_pierce1.jpg");
    leftPanel.add(urlField);

    leftPanel.add(new JLabel("Choose template:"));

    templateList = new JComboBox(new String[] { "template1.jelly", "template2.jelly" });
    leftPanel.add(templateList);

    //        JPanel rightPanel = new JPanel();
    //        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));

    leftPanel.add(new JLabel("Add a Hobby:"));

    addField = new JTextField();
    leftPanel.add(addField);

    JButton addButton = new JButton("Add >>>");
    addButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            listModel.addElement(addField.getText());
        }
    });
    leftPanel.add(addButton);

    listModel = new DefaultListModel();
    listModel.addElement("Killing bad guys");
    listModel.addElement("Wrecking cars");
    listModel.addElement("Eating jelly");
    interestList = new JList(listModel);

    JButton submit = new JButton("Build and preview your page!");
    submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            buildPage(templateList.getSelectedItem().toString(), new JellyContext());
            showPage();
        }
    });

    // Layout the demo
    setLayout(new BorderLayout());
    add(submit, BorderLayout.SOUTH);
    add(leftPanel, BorderLayout.WEST);
    add(new JScrollPane(interestList), BorderLayout.EAST);
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}

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

public void buildPage(String template, JellyContext ctx) {

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

From source file:org.codehaus.nanning.definition.AspectRepository.java

/**
 * Merges all defined aspect-repositories of the xml-file into this one, at least one needs to be defined.
 *
 * @param resource/*from   w w w.  ja v  a 2 s . com*/
 * @throws org.codehaus.nanning.definition.ConfigureException
 */
public void configure(URL resource) throws ConfigureException {
    JellyContext context = new JellyContext();
    try {
        context.registerTagLibrary(AspectTagLibrary.TAG_LIBRARY_URI, new AspectTagLibrary());
        context.registerTagLibrary("", new AspectTagLibrary());
        XMLOutput xmlOutput = XMLOutput.createXMLOutput(new ByteArrayOutputStream());
        context.runScript(resource, xmlOutput);
    } catch (Exception e) {
        throw new ConfigureException(e);
    }

    Collection aspectRepositories = AspectTagLibrary.findDefinedRepositories(context);
    Iterator iterator = aspectRepositories.iterator();
    if (!iterator.hasNext()) {
        throw new ConfigureException("No aspect-repository defined.");
    }
    while (iterator.hasNext()) {
        AspectRepository configuredRepository = (AspectRepository) iterator.next();
        this.interceptorDefinitions.putAll(configuredRepository.interceptorDefinitions);
        this.aspectClasses.putAll(configuredRepository.aspectClasses);
        this.aspectDefinitions.putAll(configuredRepository.aspectDefinitions);
    }
}

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

@Test
public void test_no_url() {
    Icon icon = new Icon("icon-aborted icon-sm", Icon.ICON_SMALL_STYLE);
    Assert.assertEquals("", icon.getQualifiedUrl(new JellyContext()));
}

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);
        }/*from  w  ww .  ja v  a  2 s.  com*/
    }
    return null;
}

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");
    }//from  w w w.  j a  v  a  2s . c om

    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.//from ww w .  java2s . 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);
    }
}