Example usage for javax.el MethodExpression invoke

List of usage examples for javax.el MethodExpression invoke

Introduction

In this page you can find the example usage for javax.el MethodExpression invoke.

Prototype

public abstract Object invoke(ELContext context, Object[] params);

Source Link

Usage

From source file:org.apache.myfaces.custom.ajaxchildcombobox.HtmlAjaxChildComboBoxRenderer.java

public void encodeAjax(FacesContext context, UIComponent uiComponent) throws IOException {

    String parentValue = (String) context.getExternalContext().getRequestParameterMap().get("parentValue");

    ServletResponse response = (ServletResponse) context.getExternalContext().getResponse();
    PrintWriter writer = response.getWriter();

    StringBuffer xml = new StringBuffer();

    MethodExpression mb = ((AjaxChildComboBox) uiComponent).getAjaxSelectItemsMethod();
    SelectItem[] options = (SelectItem[]) mb.invoke(context.getELContext(), new Object[] { parentValue });

    xml.append("<?xml version=\"1.0\"?>\n");
    xml.append("<response>\n");
    for (int i = 0; i < options.length; i++) {
        xml.append(BEGIN_OPTION);// w w  w  .  ja v a  2s  .co m
        xml.append(BEGIN_OPTION_TEXT).append(options[i].getLabel()).append(END_OPTION_TEXT);
        xml.append(BEGIN_OPTION_VALUE).append(options[i].getValue()).append(END_OPTION_VALUE);
        xml.append(END_OPTION);
    }
    xml.append("</response>");

    writer.write(xml.toString());

}

From source file:org.nuxeo.ecm.platform.ui.web.rest.RestfulPhaseListener.java

/**
 * Hack trigger of a Seam component that will trigger reset of most Seam components caches, only if dev mode is
 * enabled//from  w w  w  .j  a v  a 2  s .  com
 * <p>
 * This is handled here to be done very early, before response is constructed.
 *
 * @since 5.6
 * @see Framework#isDevModeSet()
 */
protected void resetHotReloadContext(FacesContext facesContext) {
    if (Framework.isDevModeSet()) {
        try {
            ExpressionFactory ef = facesContext.getApplication().getExpressionFactory();
            ELContext context = facesContext.getELContext();
            String actionBinding = SEAM_HOTRELOAD_TRIGGER_ACTION;
            MethodExpression action = ef.createMethodExpression(context, actionBinding, String.class,
                    new Class[] { DocumentView.class });
            action.invoke(context, new Object[0]);
        } catch (ELException | NullPointerException e) {
            String msg = "Error while trying to flush seam context after a reload, executing method expression '"
                    + SEAM_HOTRELOAD_TRIGGER_ACTION + "'";
            log.error(msg, e);
        }
    }
}

From source file:org.ajax4jsf.bean.TemplateBean.java

/**
 * Invokes reset method of appropriate backing bean
 * //from   w  w  w . j av a2 s.c  o  m
 * @param actionEvent
 */
public void reset(ActionEvent actionEvent) {
    FacesContext context = FacesContext.getCurrentInstance();
    if (context != null) {
        if (methodName != null && methodName.trim().length() > 0 && !"null".equals(methodName)) {
            ExpressionFactory factory = context.getApplication().getExpressionFactory();
            if (factory != null) {
                MethodExpression methodExpression = factory.createMethodExpression(context.getELContext(),
                        methodName, Void.class, new Class[] {});
                methodExpression.invoke(context.getELContext(), new Object[] {});
            }
        }
    }

}

From source file:org.nuxeo.ecm.platform.ui.web.binding.MetaMethodExpression.java

@Override
public Object invoke(ELContext context, Object[] params) {
    Object res = null;/*ww  w .j a va 2 s .  co m*/
    if (originalMethodExpression != null) {
        res = originalMethodExpression.invoke(context, params);
        if (res instanceof String) {
            String expression = (String) res;
            if (ComponentTagUtils.isValueReference(expression)) {
                FacesContext faces = FacesContext.getCurrentInstance();
                Application app = faces.getApplication();
                ExpressionFactory factory = app.getExpressionFactory();
                MethodExpression newMeth = factory.createMethodExpression(context, expression, Object.class,
                        new Class[0]);
                try {
                    res = newMeth.invoke(context, null);
                } catch (Throwable t) {
                    if (t instanceof InvocationTargetException) {
                        // respect the javadoc contract of the overridden
                        // method
                        throw new ELException(t.getCause());
                    } else {
                        throw new ELException(t);
                    }
                }
            } else {
                res = expression;
            }
        }
    }
    return res;
}

From source file:org.ajax4jsf.component.AjaxRegionBrige.java

/**
 * <p>//from ww w  .  ja  v  a 2s. c o  m
 * In addition to to the default {@link UIComponent#broadcast}processing,
 * pass the {@link AjaxEvent}being broadcast to the method referenced by
 * <code>AjaxListener</code> (if any), and to the default
 * {@link AjaxListener}registered on the {@link Application}.
 * </p>
 * 
 * @param event
 *            {@link FacesEvent}to be broadcast
 * 
 * @exception AbortProcessingException
 *                Signal the JavaServer Faces implementation that no further
 *                processing on the current event should be performed
 * @exception IllegalArgumentException
 *                if the implementation class of this {@link FacesEvent}is
 *                not supported by this component
 * @exception NullPointerException
 *                if <code>event</code> is <code>null</code>
 */
public void broadcast(FacesEvent event) throws AbortProcessingException {

    // Perform standard superclass processing
    // component.broadcast(event);

    if (event instanceof AjaxEvent) {
        if (log.isDebugEnabled()) {
            log.debug(Messages.getMessage(Messages.SEND_EVENT_TO_AJAX_LISTENER, component.getId()));
        }

        // Notify the specified action listener method (if any)
        MethodExpression mb = getAjaxListener();
        if (mb != null) {
            FacesContext context = FacesContext.getCurrentInstance();
            ELContext elContext = context.getELContext();
            mb.invoke(elContext, new Object[] { event });
        }
    }
}

From source file:org.apache.myfaces.custom.suggestajax.inputsuggestajax.InputSuggestAjaxRenderer.java

public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
    RendererUtils.checkParamValidity(context, component, InputSuggestAjax.class);

    InputSuggestAjax inputSuggestAjax = (InputSuggestAjax) component;

    encodeJavascript(context, component);

    String clientId = component.getClientId(context);
    String actionURL = getActionUrl(context);

    String charset = (inputSuggestAjax.getCharset() != null ? inputSuggestAjax.getCharset() : "");

    String ajaxUrl = context.getExternalContext().encodeActionURL(addQueryString(actionURL,
            "affectedAjaxComponent=" + clientId + "&charset=" + charset + "&" + clientId + "=%{searchString}"));

    ResponseWriter out = context.getResponseWriter();

    String label = null;//from  w  w w  .  j a  v  a2s  .  co  m
    String hiddenInputValue = null;
    boolean hasLabelMethod = false;

    String mainComponentRenderedValue = null;

    /* check if the user supplied a label method */
    if (inputSuggestAjax.getItemLabelMethod() == null) {
        mainComponentRenderedValue = RendererUtils.getStringValue(context, inputSuggestAjax);
    } else {
        MethodExpression labelMethod = inputSuggestAjax.getItemLabelMethod();

        if (labelMethod != null) {
            hasLabelMethod = true;

            Object valueObject = inputSuggestAjax.getValue();

            Converter converter = getRequiredConverter(context, inputSuggestAjax);

            label = (String) labelMethod.invoke(context.getELContext(), new Object[] { valueObject });

            hiddenInputValue = converter.getAsString(context, inputSuggestAjax, valueObject);
            mainComponentRenderedValue = hiddenInputValue;
        }
    }

    String placeHolderId = context.getViewRoot().createUniqueId();
    out.startElement(HTML.DIV_ELEM, component);
    out.writeAttribute(HTML.ID_ATTR, placeHolderId, null);
    if (inputSuggestAjax.getStyle() != null) {
        out.writeAttribute(HTML.STYLE_ATTR, inputSuggestAjax.getStyle(), null);
    }
    if (inputSuggestAjax.getStyleClass() != null) {
        out.writeAttribute(HTML.CLASS_ATTR, inputSuggestAjax.getStyleClass(), null);
    }
    out.endElement(HTML.DIV_ELEM);

    String textInputId = inputSuggestAjax.getClientId(context);
    if (label != null) {
        // whe have a label method and thus a hidden input field holding the real value
        // now fake the component id to have the rendered input component use another id
        // than the one we render later for the real value
        String oriId = inputSuggestAjax.getId();
        try {
            // fake the label
            inputSuggestAjax.setId(oriId + "_fake");

            textInputId = inputSuggestAjax.getClientId(context);

            // fake a submitted value so we have it rendered
            inputSuggestAjax.setSubmittedValue(label);

            super.encodeEnd(context, inputSuggestAjax);
        } finally {
            inputSuggestAjax.setSubmittedValue(null);
            inputSuggestAjax.setId(oriId);
        }
    } else {
        super.encodeEnd(context, inputSuggestAjax);
    }

    String inputSuggestComponentVar = DojoUtils.calculateWidgetVarName(placeHolderId);

    Map attributes = new HashedMap();

    attributes.put("dataUrl", ajaxUrl);
    attributes.put("mode", "remote");
    attributes.put("textInputId", textInputId);

    String autoComplete = inputSuggestAjax.getAutoComplete().booleanValue() ? "true" : "false";
    attributes.put("autoComplete", autoComplete);

    if (label != null) {
        mainComponentRenderedValue = label;
    } else if (mainComponentRenderedValue != null) {
        mainComponentRenderedValue = escapeQuotes(mainComponentRenderedValue);
    }

    DojoUtils.renderWidgetInitializationCode(context.getResponseWriter(), component,
            "extensions:InputSuggestAjax", attributes, placeHolderId.toString(), true);

    out.startElement(HTML.SCRIPT_ELEM, null);
    out.writeAttribute(HTML.TYPE_ATTR, HTML.SCRIPT_TYPE_TEXT_JAVASCRIPT, null);

    StringBuffer buffer = new StringBuffer();

    buffer.append("dojo.addOnLoad(function() {\n").append(inputSuggestComponentVar)
            .append(".comboBoxValue.value = \"").append(mainComponentRenderedValue).append("\";\n")
            .append(inputSuggestComponentVar).append(".onResize();\n").append("});\n");

    out.write(buffer.toString());

    out.endElement(HTML.SCRIPT_ELEM);

    if (hasLabelMethod) {
        out.startElement(HTML.INPUT_ELEM, inputSuggestAjax);
        out.writeAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_HIDDEN, null);
        out.writeAttribute(HTML.ID_ATTR, clientId, null);
        out.writeAttribute(HTML.NAME_ATTR, clientId, null);
        out.writeAttribute(HTML.VALUE_ATTR, hiddenInputValue != null ? hiddenInputValue : "", null);
        out.endElement(HTML.INPUT_ELEM);

        out.startElement(HTML.SCRIPT_ELEM, null);
        out.writeAttribute(HTML.TYPE_ATTR, HTML.SCRIPT_TYPE_TEXT_JAVASCRIPT, null);

        StringBuffer script = new StringBuffer();

        script.append("dojo.event.connect(" + inputSuggestComponentVar
                + ", \"_selectOption\", function(evt) { \n" + "dojo.byId('" + clientId + "').value = ")
                .append(inputSuggestComponentVar).append(".comboBoxSelectionValue.value; });\n");

        out.write(script.toString());

        out.endElement(HTML.SCRIPT_ELEM);
    }
}

From source file:org.apache.myfaces.custom.suggestajax.inputsuggestajax.InputSuggestAjaxRenderer.java

public void encodeAjax(FacesContext context, UIComponent uiComponent) throws IOException {
    // we are not sending html, xml or json, so notify the system about that else any filter
    // trying to parse the result as html (e.g. richfaces) will fail
    ServletResponse response = (ServletResponse) context.getExternalContext().getResponse();
    response.setContentType("text/plain");

    InputSuggestAjax inputSuggestAjax = (InputSuggestAjax) uiComponent;

    Collection suggesteds = getSuggestedItems(context, uiComponent);

    MethodExpression labelMethod = inputSuggestAjax.getItemLabelMethod();

    StringBuffer buf = new StringBuffer();

    buf.append("[");

    if (labelMethod != null) {
        Converter converter = getRequiredConverter(context, inputSuggestAjax);

        for (Iterator iterator = suggesteds.iterator(); iterator.hasNext();) {
            Object suggestedItemObject = iterator.next();

            String label = (String) labelMethod.invoke(context.getELContext(),
                    new Object[] { suggestedItemObject });
            String value = converter.getAsString(context, inputSuggestAjax, suggestedItemObject);

            buf.append("[\"").append(label).append("\",\"").append(value).append("\"],");
        }//w  w w. j a  va2 s . com
    } else {
        //writing the suggested list
        for (Iterator suggestedItem = suggesteds.iterator(); suggestedItem.hasNext();) {
            Object item = suggestedItem.next();

            String prefix = escapeQuotes(encodeSuggestString(item.toString()).substring(0, 1)).toUpperCase();

            buf.append("[\"").append(encodeSuggestString(escapeQuotes(item.toString()))).append("\",\"")
                    .append(prefix).append("\"],");
        }
    }

    buf.append("]");

    context.getResponseWriter().write(buf.toString());
}

From source file:org.richfaces.component.UIDatascroller.java

public void broadcast(FacesEvent event) throws AbortProcessingException {
    super.broadcast(event);
    if (event instanceof DataScrollerEvent) {
        DataScrollerEvent dataScrollerEvent = (DataScrollerEvent) event;

        updateModel(dataScrollerEvent.getPage());

        FacesContext context = getFacesContext();

        MethodExpression scrollerListener = getScrollerListener();
        if (scrollerListener != null) {
            scrollerListener.invoke(context.getELContext(), new Object[] { event });
        }//  w w  w  .j  av  a 2  s.  co  m
    } else if (event instanceof AjaxEvent) {
        FacesContext context = getFacesContext();

        AjaxRendererUtils.addRegionByName(context, this, this.getId());
        AjaxRendererUtils.addRegionByName(context, this, this.getFor());

        setupReRender(context);
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.rest.services.URLPolicyServiceImpl.java

@Override
public String navigate(FacesContext facesContext) {
    HttpServletRequest httpRequest = (HttpServletRequest) facesContext.getExternalContext().getRequest();

    URLPatternDescriptor pattern = getURLPatternDescriptor(httpRequest);
    if (pattern == null) {
        return null;
    }/*from   ww w.  ja  v a 2  s.c  om*/

    DocumentView docView = getDocumentViewFromRequest(pattern.getName(), httpRequest);
    ExpressionFactory ef = facesContext.getApplication().getExpressionFactory();
    ELContext context = facesContext.getELContext();
    String actionBinding = pattern.getActionBinding();

    if (actionBinding != null && !"".equals(actionBinding)
            && httpRequest.getAttribute(URLPolicyService.DISABLE_ACTION_BINDING_KEY) == null) {
        MethodExpression action = ef.createMethodExpression(context, actionBinding, String.class,
                new Class[] { DocumentView.class });
        return (String) action.invoke(context, new Object[] { docView });
    }
    return null;
}

From source file:com.jsmartframework.web.manager.ExpressionHandler.java

String handleSubmitExpression(String expr, String jParam) throws ServletException, IOException {
    Object response = null;/* w ww  .  j  a v  a2 s .  com*/
    Matcher matcher = EL_PATTERN.matcher(expr);
    if (matcher.find()) {

        String beanMethod = matcher.group(1);
        String[] methodSign = beanMethod.split(Constants.EL_SEPARATOR);
        HttpServletRequest request = WebContext.getRequest();

        if (methodSign.length > 0 && WebContext.containsAttribute(methodSign[0])) {
            Object bean = getExpressionBean(methodSign[0]);
            String elBeanMethod = String.format(Constants.JSP_EL, beanMethod);

            // Check authorization to execute method
            if (!HANDLER.checkExecuteAuthorization(bean, elBeanMethod, request)) {
                return null;
            }

            // Call mapped method with @PreSubmit / @PreAction annotation for specific action
            boolean preActionValidated = HANDLER.executePreSubmit(bean, methodSign[methodSign.length - 1]);
            preActionValidated &= HANDLER.executePreAction(bean, methodSign[methodSign.length - 1]);

            if (preActionValidated) {
                Object[] arguments = null;
                String[] paramArgs = request.getParameterValues(TagHandler.J_SBMT_ARGS + jParam);

                AnnotatedFunction function = HANDLER.beanMethodFunctions.get(beanMethod);

                if (paramArgs != null) {
                    arguments = new Object[paramArgs.length];
                    boolean unescape = HANDLER.containsUnescapeMethod(methodSign);

                    for (int i = 0; i < paramArgs.length; i++) {
                        if (function != null) {
                            Class<?> argClass = function.getArgumentType(i);

                            if (argClass != null && !Primitives.isPrimitive(argClass)
                                    && !argClass.equals(String.class)) {
                                arguments[i] = GSON.fromJson(paramArgs[i], argClass);
                                continue;
                            }
                        }
                        arguments[i] = unescape ? paramArgs[i] : escapeValue(paramArgs[i]);
                    }
                }

                // Call submit method
                ELContext context = WebContext.getPageContext().getELContext();

                MethodExpression methodExpr = WebContext.getExpressionFactory().createMethodExpression(context,
                        elBeanMethod, null,
                        arguments != null ? new Class<?>[arguments.length] : new Class<?>[] {});

                response = methodExpr.invoke(context, arguments);

                if (function != null && function.hasProduces()) {
                    switch (function.getProduces()) {
                    case JSON:
                        WebContext.writeResponseAsJson(response);
                        break;
                    case XML:
                        WebContext.writeResponseAsXmlQuietly(response);
                        break;
                    case STRING:
                        WebContext.writeResponseAsString(response.toString());
                        break;
                    }
                    // Reset response to be passed to path analysis
                    response = null;
                }

                // Call mapped method with @PostSubmit / @PostAction annotation for specific action
                HANDLER.executePostSubmit(bean, methodSign[methodSign.length - 1]);
                HANDLER.executePostAction(bean, methodSign[methodSign.length - 1]);
            }
        }
    }
    return response != null ? response.toString() : null;
}