Example usage for javax.servlet.jsp PageContext REQUEST_SCOPE

List of usage examples for javax.servlet.jsp PageContext REQUEST_SCOPE

Introduction

In this page you can find the example usage for javax.servlet.jsp PageContext REQUEST_SCOPE.

Prototype

int REQUEST_SCOPE

To view the source code for javax.servlet.jsp PageContext REQUEST_SCOPE.

Click Source Link

Document

Request scope: the named reference remains available from the ServletRequest associated with the Servlet until the current request is completed.

Usage

From source file:org.jahia.taglibs.facet.SetupQueryAndMetadataTag.java

@SuppressWarnings("unchecked")
@Override/*  w w  w .  jav  a  2s  .  c om*/
public int doStartTag() throws JspException {
    try {
        final JCRNodeWrapper currentNode = getCurrentResource().getNode();
        final JCRSessionWrapper session = currentNode.getSession();
        QueryObjectModelFactory factory = session.getWorkspace().getQueryManager().getQOMFactory();
        QOMBuilder qomBuilder = new QOMBuilder(factory, session.getValueFactory());

        String selectorName;
        if (existing == null) {
            // here we assume that if existing is null, then bound component is not of type jnt:query
            String wantedNodeType = "jnt:content";
            if (currentNode.hasProperty("j:type")) {
                wantedNodeType = currentNode.getPropertyAsString("j:type");
            }

            selectorName = wantedNodeType;
            qomBuilder.setSource(factory.selector(wantedNodeType, selectorName));

            // replace the site name in bound component by the one from the render context
            String path = boundComponent.getPath();
            final String siteName = getRenderContext().getSite().getName();
            final int afterSites = "/sites/".length();
            final int afterSite = path.indexOf('/', afterSites + 1);
            if (afterSite > 0 && afterSite < path.length()) {
                String restOfPath = path.substring(afterSite);
                path = "/sites/" + siteName + restOfPath;
            }
            qomBuilder.andConstraint(factory.descendantNode(selectorName, path));
        } else {
            final Selector selector = (Selector) existing.getSource();
            selectorName = selector.getSelectorName();
            qomBuilder.setSource(selector);
            qomBuilder.andConstraint(existing.getConstraint());
        }

        // metadata for display, passed to JSP
        Map<String, ExtendedNodeType> facetValueNodeTypes = (Map<String, ExtendedNodeType>) pageContext
                .getAttribute("facetValueNodeTypes", PageContext.REQUEST_SCOPE);
        Map<String, String> facetLabels = (Map<String, String>) pageContext.getAttribute("facetLabels",
                PageContext.REQUEST_SCOPE);
        Map<String, String> facetValueLabels = (Map<String, String>) pageContext
                .getAttribute("facetValueLabels", PageContext.REQUEST_SCOPE);
        Map<String, String> facetValueFormats = (Map<String, String>) pageContext
                .getAttribute("facetValueFormats", PageContext.REQUEST_SCOPE);
        Map<String, String> facetValueRenderers = (Map<String, String>) pageContext
                .getAttribute("facetValueRenderers", PageContext.REQUEST_SCOPE);

        // specify query for unapplied facets
        final List<JCRNodeWrapper> facets = JCRContentUtils.getNodes(currentNode, "jnt:facet");
        for (JCRNodeWrapper facet : facets) {

            // extra query parameters
            String extra = null;

            // min count
            final String minCount = facet.getPropertyAsString("mincount");

            // field components
            final String field = facet.getPropertyAsString("field");
            final String[] fieldComponents = StringUtils.split(field, ";");
            int i = 0;
            final String facetNodeTypeName = fieldComponents != null && fieldComponents.length > 1
                    ? fieldComponents[i++]
                    : null;
            final String facetPropertyName = fieldComponents != null ? fieldComponents[i] : null;

            // are we dealing with a query facet?
            boolean isQuery = facet.hasProperty("query");

            // query value if it exists
            final String queryProperty = isQuery ? facet.getPropertyAsString("query") : null;

            // key used in metadata maps
            final String metadataKey = isQuery ? queryProperty : facetPropertyName;

            // get node type if we can
            ExtendedNodeType nodeType = null;
            if (StringUtils.isNotEmpty(facetNodeTypeName)) {
                // first check if we don't already have resolved the nodeType to avoid resolving it again
                if (facetValueNodeTypes != null) {
                    nodeType = (ExtendedNodeType) facetValueNodeTypes.get(metadataKey);
                }

                // since we haven't already resolved it, try that now
                if (nodeType == null) {
                    nodeType = NodeTypeRegistry.getInstance().getNodeType(facetNodeTypeName);
                    if (facetValueNodeTypes != null && StringUtils.isNotEmpty(metadataKey)) {
                        facetValueNodeTypes.put(metadataKey, nodeType);
                    }
                }
            }

            // label
            String currentFacetLabel = null;
            // use label property if it exists
            if (facet.hasProperty("label")) {
                currentFacetLabel = facet.getPropertyAsString("label");
            }
            // otherwise try to derive a label from node type and field name
            if (StringUtils.isEmpty(currentFacetLabel) && StringUtils.isNotEmpty(facetNodeTypeName)
                    && StringUtils.isNotEmpty(facetPropertyName)) {
                final String labelKey = facetNodeTypeName.replace(':', '_') + "."
                        + facetPropertyName.replace(':', '_');

                currentFacetLabel = getMessage(labelKey);
            }
            if (facetLabels != null && StringUtils.isNotEmpty(currentFacetLabel)) {
                facetLabels.put(metadataKey, currentFacetLabel);
            }

            // value format
            if (facetValueFormats != null && facet.hasProperty("labelFormat")) {
                facetValueFormats.put(metadataKey, facet.getPropertyAsString("labelFormat"));
            }

            // label renderer
            String labelRenderer = null;
            if (facetValueRenderers != null && facet.hasProperty("labelRenderer")) {
                labelRenderer = facet.getPropertyAsString("labelRenderer");
                facetValueRenderers.put(metadataKey, labelRenderer);
            }

            // value label
            if (facetValueLabels != null && facet.hasProperty("valueLabel")) {
                facetValueLabels.put(metadataKey, facet.getPropertyAsString("valueLabel"));
            }

            // is the current facet applied?
            final ExtendedPropertyDefinition propDef = nodeType != null
                    ? nodeType.getPropertyDefinition(facetPropertyName)
                    : null;
            final boolean isFacetApplied = Functions.isFacetApplied(metadataKey, activeFacets, propDef);

            if (nodeType != null && StringUtils.isNotEmpty(facetPropertyName) && !isFacetApplied) {
                StringBuilder extraBuilder = new StringBuilder();

                // deal with facets with labelRenderers, currently only jnt:dateFacet or jnt:rangeFacet
                String prefix = facet.isNodeType("jnt:dateFacet") ? "date."
                        : (facet.isNodeType("jnt:rangeFacet") ? "range." : "");
                if (StringUtils.isNotEmpty(labelRenderer)) {
                    extraBuilder.append(prefixedNameValuePair(prefix, "labelRenderer", labelRenderer));
                }

                for (ExtendedPropertyDefinition propertyDefinition : Functions.getPropertyDefinitions(facet)) {
                    final String name = propertyDefinition.getName();
                    if (facet.hasProperty(name)) {
                        final JCRPropertyWrapper property = facet.getProperty(name);

                        if (property.isMultiple()) {
                            // if property is multiple append prefixed name value pair to query
                            for (JCRValueWrapper value : property.getValues()) {
                                extraBuilder.append(prefixedNameValuePair(prefix, name, value.getString()));
                            }
                        } else {
                            String value = property.getString();

                            // adjust value for hierarchical facets
                            if (facet.isNodeType("jnt:fieldHierarchicalFacet") && name.equals("prefix")) {
                                final List<KeyValue> active = activeFacets != null
                                        ? this.activeFacets.get(facetPropertyName)
                                        : Collections.<KeyValue>emptyList();
                                if (active == null || active.isEmpty()) {
                                    value = Functions.getIndexPrefixedPath(value,
                                            getRenderContext().getWorkspace());
                                } else {
                                    value = Functions.getDrillDownPrefix(
                                            (String) active.get(active.size() - 1).getKey());
                                }
                            }

                            extraBuilder.append(prefixedNameValuePair(prefix, name, value));
                        }
                    }
                }

                extra = extraBuilder.toString();

            }

            if (isQuery && !isFacetApplied) {
                extra = "&facet.query=" + queryProperty;
            }

            // only add a column if the facet isn't already applied
            if (!isFacetApplied) {
                // key used in the solr query string
                final String key = isQuery ? facet.getName() : facetPropertyName;
                String query = buildQueryString(facetNodeTypeName, key, minCount, extra);
                final String columnPropertyName = StringUtils.isNotEmpty(facetPropertyName) ? facetPropertyName
                        : "rep:facet()";
                qomBuilder.getColumns().add(factory.column(selectorName, columnPropertyName, query));
            }
        }

        // repeat applied facets
        if (activeFacets != null) {
            for (Map.Entry<String, List<KeyValue>> appliedFacet : activeFacets.entrySet()) {
                for (KeyValue keyValue : appliedFacet.getValue()) {
                    final String propertyName = "rep:filter("
                            + Text.escapeIllegalJcrChars(appliedFacet.getKey()) + ")";
                    qomBuilder.andConstraint(factory.fullTextSearch(selectorName, propertyName, factory.literal(
                            qomBuilder.getValueFactory().createValue(keyValue.getValue().toString()))));
                }
            }
        }

        pageContext.setAttribute(var, qomBuilder.createQOM(), PageContext.REQUEST_SCOPE);
    } catch (RepositoryException e) {
        throw new JspException(e);
    }

    return SKIP_BODY;
}

From source file:org.jahia.taglibs.template.CaptchaTag.java

@Override
public int doEndTag() throws JspException {
    JspWriter out = pageContext.getOut();

    try {/*from  ww w .  j a  v  a2  s.  c om*/
        URLGenerator urlGen = (URLGenerator) pageContext.findAttribute("url");
        StringBuilder url = new StringBuilder();
        String formId = (String) pageContext.findAttribute("currentFormId");
        url.append(urlGen.getContext()).append(urlGen.getCaptcha()).append("?token=##formtoken(").append(formId)
                .append(")##");

        if (StringUtils.isNotEmpty(var)) {
            pageContext.setAttribute(var, url);
        }
        if (display) {
            out.append("<img id=\"jahia-captcha-").append(formId).append("\" alt=\"captcha\" src=\"")
                    .append(url).append("\" />");
        }
        if (displayReloadLink) {
            out.append("&nbsp;").append(
                    "<a href=\"#reload-captcha\" onclick=\"var captcha=document.getElementById('jahia-captcha-")
                    .append(formId)
                    .append("'); var captchaUrl=captcha.src; if (captchaUrl.indexOf('&amp;tst=') != -1){"
                            + "captchaUrl=captchaUrl.substring(0,captchaUrl.indexOf('&amp;tst='));}"
                            + "captchaUrl=captchaUrl+'&amp;tst='+new Date().getTime();"
                            + " captcha.src=captchaUrl; return false;\"><img src=\"")
                    .append(urlGen.getContext()).append("/icons/refresh.png\" alt=\"refresh\"/></a>");
        }

        pageContext.setAttribute("hasCaptcha", true, PageContext.REQUEST_SCOPE);
    } catch (IOException e) {
        throw new JspException(e);
    }

    return EVAL_PAGE;
}

From source file:org.jahia.taglibs.template.include.AddResourcesTag.java

/**
 * Default processing of the end tag returning EVAL_PAGE.
 *
 * @return EVAL_PAGE// w  w w . j a  v a  2s  .  c o  m
 * @throws javax.servlet.jsp.JspException if an error occurred while processing this tag
 * @see javax.servlet.jsp.tagext.Tag#doEndTag
 */
@Override
public int doEndTag() throws JspException {
    org.jahia.services.render.Resource currentResource = (org.jahia.services.render.Resource) pageContext
            .getAttribute("currentResource", PageContext.REQUEST_SCOPE);

    boolean isVisible = true;

    try {
        isVisible = getRenderContext().getEditModeConfig() == null
                || getRenderContext().isVisible(currentResource.getNode());
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }
    if (isVisible) {
        addResources(getRenderContext());
    }
    resetState();
    return super.doEndTag();
}

From source file:org.jahia.taglibs.template.include.ModuleTag.java

@Override
public int doEndTag() throws JspException {

    try {/*ww  w.  ja v a 2s .  com*/

        RenderContext renderContext = (RenderContext) pageContext.getAttribute("renderContext",
                PageContext.REQUEST_SCOPE);
        builder = new StringBuilder();

        Resource currentResource = (Resource) pageContext.getAttribute("currentResource",
                PageContext.REQUEST_SCOPE);

        findNode(renderContext, currentResource);

        String resourceNodeType = null;
        if (parameters.containsKey("resourceNodeType")) {
            resourceNodeType = URLDecoder.decode(parameters.get("resourceNodeType"), "UTF-8");
        }

        if (node != null) {

            try {
                constraints = ConstraintsHelper.getConstraints(node);
            } catch (RepositoryException e) {
                logger.error("Error when getting list constraints", e);
            }

            if (templateType == null) {
                templateType = currentResource.getTemplateType();
            }

            Resource resource = new Resource(node, templateType, view, getConfiguration());

            String charset = pageContext.getResponse().getCharacterEncoding();
            for (Map.Entry<String, String> param : parameters.entrySet()) {
                resource.getModuleParams().put(URLDecoder.decode(param.getKey(), charset),
                        URLDecoder.decode(param.getValue(), charset));
            }

            if (resourceNodeType != null) {
                try {
                    resource.setResourceNodeType(NodeTypeRegistry.getInstance().getNodeType(resourceNodeType));
                } catch (NoSuchNodeTypeException e) {
                    throw new JspException(e);
                }
            }

            boolean isVisible = true;
            try {
                isVisible = renderContext.getEditModeConfig() == null || renderContext.isVisible(node);
            } catch (RepositoryException e) {
                logger.error(e.getMessage(), e);
            }

            try {

                boolean canEdit = canEdit(renderContext) && contributeAccess(renderContext, resource.getNode())
                        && !isExcluded(renderContext, resource);

                boolean nodeEditable = checkNodeEditable(renderContext, node);
                resource.getModuleParams().put("editableModule", canEdit && nodeEditable);

                if (canEdit) {

                    String type = getModuleType(renderContext);
                    List<String> contributeTypes = contributeTypes(renderContext, resource.getNode());
                    String oldNodeTypes = nodeTypes;
                    String add = "";
                    if (!nodeEditable) {
                        add = "editable=\"false\"";
                    }
                    if (contributeTypes != null) {
                        nodeTypes = StringUtils.join(contributeTypes, " ");
                        add = "editable=\"false\"";
                    }
                    if (node.isNodeType(Constants.JAHIAMIX_BOUND_COMPONENT)) {
                        add += " bindable=\"true\"";
                    }

                    Script script = null;
                    try {
                        script = RenderService.getInstance().resolveScript(resource, renderContext);
                        printModuleStart(type, node.getPath(), resource.getResolvedTemplate(), script, add);
                    } catch (TemplateNotFoundException e) {
                        printModuleStart(type, node.getPath(), resource.getResolvedTemplate(), null, add);
                    }
                    nodeTypes = oldNodeTypes;
                    currentResource.getDependencies().add(node.getCanonicalPath());
                    if (isVisible) {
                        render(renderContext, resource);
                    }
                    //Copy dependencies to parent Resource (only for include of the same node)
                    if (currentResource.getNode().getPath().equals(resource.getNode().getPath())) {
                        currentResource.getRegexpDependencies().addAll(resource.getRegexpDependencies());
                        currentResource.getDependencies().addAll(resource.getDependencies());
                    }
                    printModuleEnd();
                } else {
                    currentResource.getDependencies().add(node.getCanonicalPath());
                    if (isVisible) {
                        render(renderContext, resource);
                    } else {
                        pageContext.getOut().print("&nbsp;");
                    }
                    //Copy dependencies to parent Resource (only for include of the same node)
                    if (currentResource.getNode().getPath().equals(resource.getNode().getPath())) {
                        currentResource.getRegexpDependencies().addAll(resource.getRegexpDependencies());
                        currentResource.getDependencies().addAll(resource.getDependencies());
                    }
                }
            } catch (RepositoryException e) {
                logger.error(e.getMessage(), e);
            }
        }
    } catch (RenderException ex) {
        throw new JspException(ex.getCause());
    } catch (IOException ex) {
        throw new JspException(ex);
    } finally {
        if (var != null) {
            pageContext.setAttribute(var, builder.toString());
        }
        path = null;
        node = null;
        contextSite = null;
        nodeName = null;
        view = null;
        templateType = null;
        editable = true;
        nodeTypes = null;
        listLimit = -1;
        constraints = null;
        var = null;
        builder = null;
        parameters.clear();
        checkConstraints = true;
        showAreaButton = true;
        skipAggregation = false;
    }
    return EVAL_PAGE;
}

From source file:org.jahia.taglibs.template.include.OptionTag.java

public static void renderNodeWithViewAndTypes(JCRNodeWrapper node, String view,
        String commaConcatenatedNodeTypes, PageContext pageContext, Map<String, String> parameters)
        throws RepositoryException, IOException, RenderException {

    String charset = pageContext.getResponse().getCharacterEncoding();
    // Todo test if module is active
    RenderContext renderContext = (RenderContext) pageContext.getAttribute("renderContext",
            PageContext.REQUEST_SCOPE);
    Resource currentResource = (Resource) pageContext.getAttribute("currentResource",
            PageContext.REQUEST_SCOPE);/* ww  w .j  a v a2s  .  c  om*/
    String[] nodeTypes = StringUtils.split(commaConcatenatedNodeTypes, ",");

    if (nodeTypes.length > 0) {
        final String primaryNodeType = nodeTypes[0];

        if (node.isNodeType(primaryNodeType)) {
            ExtendedNodeType mixinNodeType = NodeTypeRegistry.getInstance().getNodeType(primaryNodeType);

            // create a resource to render the current node with the specified view
            Resource wrappedResource = new Resource(node, currentResource.getTemplateType(), view,
                    Resource.CONFIGURATION_INCLUDE);
            wrappedResource.setResourceNodeType(mixinNodeType);

            // set parameters
            for (Map.Entry<String, String> param : parameters.entrySet()) {
                wrappedResource.getModuleParams().put(URLDecoder.decode(param.getKey(), charset),
                        URLDecoder.decode(param.getValue(), charset));
            }

            // attempt to resolve script for the newly created resource
            Script script = null;
            try {
                script = RenderService.getInstance().resolveScript(wrappedResource, renderContext);
            } catch (RepositoryException e) {
                logger.error(e.getMessage(), e);
            } catch (TemplateNotFoundException e) {
                // if we didn't find a script, attempt to locate one based on secondary node type if one was specified
                if (nodeTypes.length > 1) {
                    mixinNodeType = NodeTypeRegistry.getInstance().getNodeType(nodeTypes[1]);
                    wrappedResource.setResourceNodeType(mixinNodeType);
                    script = RenderService.getInstance().resolveScript(wrappedResource, renderContext);
                }
            }

            // if we have found a script, render it
            if (script != null) {
                final ServletRequest request = pageContext.getRequest();

                //save environment
                Object currentNode = request.getAttribute("currentNode");
                Resource currentOption = (Resource) request.getAttribute("optionResource");

                // set attributes to render the newly created resource
                request.setAttribute("optionResource", currentResource);
                request.setAttribute("currentNode", node);
                request.setAttribute("currentResource", wrappedResource);
                try {
                    pageContext.getOut().write(script.execute(wrappedResource, renderContext));
                } finally {
                    // restore environment as it previously was
                    request.setAttribute("optionResource", currentOption);
                    request.setAttribute("currentNode", currentNode);
                    request.setAttribute("currentResource", currentResource);
                }
            }
        }
    }
}

From source file:org.jahia.taglibs.template.pager.InitPagerTag.java

@Override
public int doStartTag() throws JspException {
    try {/*  w w  w  . ja  v a2 s  . c om*/
        @SuppressWarnings("unchecked")
        Map<String, Object> moduleMap = (HashMap<String, Object>) pageContext.getRequest()
                .getAttribute("moduleMap");
        if (moduleMap == null) {
            moduleMap = new HashMap<String, Object>();
        }
        Object value = moduleMap.get("begin");
        if (value != null) {
            moduleMap.put("old_begin" + id, value);
        }
        value = moduleMap.get("end");
        if (value != null) {
            moduleMap.put("old_end" + id, value);
        }
        value = moduleMap.get("pageSize");
        if (value != null) {
            moduleMap.put("old_pageSize" + id, value);
        }
        value = moduleMap.get("nbPages");
        if (value != null) {
            moduleMap.put("old_nbPages" + id, value);
        }
        value = moduleMap.get("currentPage");
        if (value != null) {
            moduleMap.put("old_currentPage" + id, value);
        }
        value = moduleMap.get("paginationActive");
        if (value != null) {
            moduleMap.put("old_paginationActive" + id, value);
        }
        value = moduleMap.get("totalSize");
        if (value != null) {
            moduleMap.put("old_totalSize" + id, value);
        }
        String beginStr = StringEscapeUtils.escapeXml(pageContext.getRequest().getParameter("begin" + id));
        String endStr = StringEscapeUtils.escapeXml(pageContext.getRequest().getParameter("end" + id));

        if (pageContext.getRequest().getParameter("pagesize" + id) != null) {
            pageSize = Integer.parseInt(
                    StringEscapeUtils.escapeXml(pageContext.getRequest().getParameter("pagesize" + id)));
        }

        //To escape dividing by zero we test if the page size is equal to zero if yes we put it to a default pagesize value
        if (pageSize == 0) {
            pageSize = DEFAULT_PAGE_SIZE;
        }

        int begin = beginStr == null ? 0 : Integer.parseInt(beginStr);
        int end = endStr == null ? pageSize - 1 : Integer.parseInt(endStr);

        int currentPage = begin / pageSize + 1;

        long nbPages = totalSize / pageSize;
        if (nbPages * pageSize < totalSize) {
            nbPages++;
        }
        if (totalSize == Integer.MAX_VALUE) {
            nbPages = currentPage;// + 1;
        }

        if (totalSize < pageSize) {
            begin = 0;
        } else if (begin > totalSize) {
            begin = (int) ((nbPages - 1) * pageSize);
            end = begin + pageSize - 1;
        }

        if (currentPage > nbPages) {
            currentPage = (int) nbPages;
        }

        moduleMap.put("begin", begin);
        moduleMap.put("end", end);
        moduleMap.put("pageSize", pageSize);
        moduleMap.put("nbPages", nbPages);
        moduleMap.put("currentPage", currentPage);
        moduleMap.put("paginationActive", true);
        moduleMap.put("totalSize", totalSize);
        moduleMap.put("sizeNotExact", sizeNotExact);
        moduleMap.put("totalSizeUnknown", totalSize == Integer.MAX_VALUE);
        pageContext.setAttribute("moduleMap", moduleMap);
        pageContext.setAttribute("begin_" + id, begin, PageContext.REQUEST_SCOPE);
        pageContext.setAttribute("end_" + id, end, PageContext.REQUEST_SCOPE);

        moduleMap.put("requestAttributesToCache", Arrays.asList("begin_" + id, "end_" + id));
    } catch (Exception e) {
        throw new JspException(e);
    }
    return super.doStartTag();
}

From source file:org.jahia.taglibs.template.TokenizedFormTag.java

@Override
public int doStartTag() throws JspException {
    String id = java.util.UUID.randomUUID().toString();
    pageContext.setAttribute("currentFormId", id, PageContext.REQUEST_SCOPE);

    // Skip the aggregation in the body of the tag
    if (!AggregateFilter.skipAggregation(pageContext.getRequest())) {
        skipAggregation = true;//from   ww  w.  j a  va  2 s  . c om
        pageContext.getRequest().setAttribute(AggregateFilter.SKIP_AGGREGATION, true);
    }

    return EVAL_BODY_BUFFERED;
}

From source file:org.jahia.taglibs.template.TokenizedFormTag.java

@Override
public int doEndTag() throws JspException {
    boolean hasCaptcha = false;
    if (pageContext.findAttribute("hasCaptcha") != null) {
        hasCaptcha = (Boolean) pageContext.findAttribute("hasCaptcha");
    }/*from   w  w w.  j  a  v a  2  s  . co  m*/
    try {
        String id = (String) pageContext.findAttribute("currentFormId");

        RenderContext renderContext = (RenderContext) pageContext.findAttribute("renderContext");
        JspWriter out = pageContext.getOut();

        String bodyContent = getBodyContent().getString();
        Source source = new Source(bodyContent);

        OutputDocument outputDocument = new OutputDocument(source);

        TreeMap<String, List<String>> hiddenInputs = new TreeMap<String, List<String>>();
        List<StartTag> formTags = source.getAllStartTags("form");

        StartTag formTag = formTags.get(0);
        String action = formTag.getAttributeValue("action");

        if (!action.startsWith("/") && !action.contains("://")) {
            String requestURI = ((HttpServletRequest) pageContext.getRequest()).getRequestURI();
            if (requestURI.startsWith("/gwt/")) {
                requestURI = renderContext.getURLGenerator().buildURL(renderContext.getMainResource().getNode(),
                        renderContext.getMainResourceLocale().toString(),
                        renderContext.getMainResource().getTemplate(),
                        renderContext.getMainResource().getTemplateType());
            }
            action = StringUtils.substringBeforeLast(requestURI, "/") + "/" + action;
        }
        hiddenInputs.put("form-action", Arrays.asList(StringUtils.substringBeforeLast(action, ";")));
        hiddenInputs.put("form-method",
                Arrays.asList(StringUtils.capitalize(formTag.getAttributeValue("method"))));

        List<StartTag> inputTags = source.getAllStartTags("input");
        for (StartTag inputTag : inputTags) {
            if ("hidden".equals(inputTag.getAttributeValue("type"))) {
                String name = inputTag.getAttributeValue("name");
                List<String> strings = hiddenInputs.get(name);
                String value = inputTag.getAttributeValue("value");
                if (strings == null) {
                    strings = new LinkedList<String>();
                }
                strings.add(value);
                hiddenInputs.put(name, strings);
            }
        }

        if (hasCaptcha) {
            // Put random number here, will be replaced by the captcha servlet with the expected value
            hiddenInputs.put("jcrCaptcha", Arrays.asList(java.util.UUID.randomUUID().toString()));
        }

        hiddenInputs.put("disableXSSFiltering", Arrays.asList(String.valueOf(disableXSSFiltering)));
        hiddenInputs.put("allowsMultipleSubmits", Arrays.asList(String.valueOf(allowsMultipleSubmits)));
        outputDocument.insert(formTag.getEnd(),
                "<input type=\"hidden\" name=\"disableXSSFiltering\" value=\"" + disableXSSFiltering + "\"/>");

        outputDocument.insert(formTag.getEnd(),
                "<jahia:token-form id='" + id + "' forms-data='" + JSONUtil.toJSON(hiddenInputs) + "'/>");

        out.print(outputDocument.toString());
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

    pageContext.removeAttribute("hasCaptcha", PageContext.REQUEST_SCOPE);
    pageContext.removeAttribute("currentFormId", PageContext.REQUEST_SCOPE);

    // Restore the aggregation for the following fragments
    if (skipAggregation) {
        pageContext.getRequest().removeAttribute(AggregateFilter.SKIP_AGGREGATION);
        skipAggregation = false;
    }
    return super.doEndTag();
}

From source file:org.jboss.dashboard.ui.taglib.RegionTag.java

/**
 * @see javax.servlet.jsp.tagext.TagSupport
 *//*from w w  w  .ja  v a2  s.c o  m*/
public int doEndTag() throws JspException {
    try {
        new HibernateTxFragment() {
            protected void txFragment(Session session) throws Throwable {
                Properties displayConfiguration = (Properties) Factory
                        .lookup("org.jboss.dashboard.ui.formatters.DisplayConfiguration");
                pageContext.setAttribute(Parameters.RENDER_IDREGION, getRegion(), PageContext.REQUEST_SCOPE);

                String preview = (String) pageContext.getRequest()
                        .getAttribute("org.jboss.dashboard.ui.taglib.RegionTag.preview");
                if (preview != null && preview.trim().equalsIgnoreCase("true")) {
                    //PREVIEW
                    String layoutId = (String) pageContext.getRequest()
                            .getAttribute("org.jboss.dashboard.ui.taglib.RegionTag.layout");
                    Layout layout = (Layout) UIServices.lookup().getLayoutsManager()
                            .getAvailableElement(layoutId);
                    LayoutRegion layoutRegion = layout.getRegion(region);
                    String pageStr = "/section/render_region.jsp";

                    int dotIndex = pageStr.lastIndexOf('.');
                    pageStr = pageStr.substring(0, dotIndex) + "_preview"
                            + pageStr.substring(dotIndex, pageStr.length());
                    pageContext.getRequest().setAttribute("layoutRegion", layoutRegion);
                    pageContext.include(pageStr);
                    pageContext.getRequest().removeAttribute("layoutRegion");
                } else {
                    // NORMAL DISPLAY
                    Section section = NavigationManager.lookup().getCurrentSection();
                    if (section != null) {
                        LayoutRegion layoutRegion = section.getLayout().getRegion(getRegion());
                        if (layoutRegion != null) {
                            String pageStr = displayConfiguration.getProperty("regionRenderPage");
                            log.debug("REGION TAG: INCLUDING (" + layoutRegion.getId() + ") " + pageStr);
                            pageContext.include(pageStr);
                        }
                    }
                }
            }
        }.execute();
        return EVAL_PAGE;
    } catch (Throwable e) {
        throw new JspException(e);
    }
}

From source file:org.openmrs.module.htmlformflowsheet.web.taglibs.HtmlIncludeTag.java

public int doStartTag() throws JspException {
    log.debug("\n\n");

    // see if this is a JS or CSS file
    boolean isJs = false;
    boolean isCss = false;

    String fileExt = file.substring(file.lastIndexOf("."));

    if (this.type != null) {
        if (this.type.length() > 0) {
            if (HtmlIncludeTag.POSSIBLE_TYPES_CSS.indexOf(type) >= 0)
                isCss = true;/*from w  w  w.  j a v a2s . c o  m*/
            else if (HtmlIncludeTag.POSSIBLE_TYPES_JS.indexOf(type) >= 0)
                isJs = true;
        }
    }

    if (!isCss && !isJs && fileExt.length() > 0) {
        if (HtmlIncludeTag.POSSIBLE_TYPES_CSS.indexOf(fileExt) >= 0)
            isCss = true;
        else if (HtmlIncludeTag.POSSIBLE_TYPES_JS.indexOf(fileExt) >= 0)
            isJs = true;
    }

    if (isJs || isCss) {
        String initialRequestId = getInitialRequestUniqueId();
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        log.debug("initialRequest id: [" + initialRequestId + "]");
        log.debug("Object at pageContext." + HtmlIncludeTag.OPENMRS_HTML_INCLUDE_MAP_KEY + " is " + pageContext
                .getAttribute(HtmlIncludeTag.OPENMRS_HTML_INCLUDE_MAP_KEY, PageContext.REQUEST_SCOPE) + "");

        if (!isAlreadyUsed(file, initialRequestId)) {
            String output = "";
            String prefix = "";
            try {
                prefix = request.getContextPath();
                if (file.startsWith(prefix + "/"))
                    prefix = "";
            } catch (ClassCastException cce) {
                log.debug("Could not cast request to HttpServletRequest in HtmlIncludeTag");
            }

            // the openmrs version is inserted into the file src so that js and css files are cached across version releases
            if (isJs) {
                output = "<script src=\"" + prefix + file + "?v=" + OpenmrsConstants.OPENMRS_VERSION_SHORT
                        + "\" type=\"text/javascript\" ></script>";
            } else if (isCss) {
                output = "<link href=\"" + prefix + file + "?v=" + OpenmrsConstants.OPENMRS_VERSION_SHORT
                        + "\" type=\"text/css\" rel=\"stylesheet\" />";
            }

            log.debug("isAlreadyUsed() is FALSE - printing " + this.file + " to output.");

            try {
                pageContext.getOut().print(output);
            } catch (IOException e) {
                log.debug("Could not produce output in HtmlIncludeTag.java");
            }
        } else {
            log.debug("isAlreadyUsed() is TRUE - suppressing file print for " + this.file + "");
        }
    }

    resetValues();

    return SKIP_BODY;
}