Search in sources :

Example 1 with JSONFunction

use of org.apache.wicket.ajax.json.JSONFunction in project wicket by apache.

the class ModalWindow method getWindowOpenJavaScript.

/**
 * Returns the javascript used to open the window. Subclass
 * {@link #postProcessSettings(AppendingStringBuffer)} to modify the JavaScript if needed.
 *
 * See WICKET-12
 *
 * @return javascript that opens the window
 */
protected final String getWindowOpenJavaScript() {
    JSONObject settings = new JSONObject();
    settings.put("minWidth", getMinimalWidth());
    settings.put("minHeight", getMinimalHeight());
    settings.put("className", getCssClassName());
    settings.put("width", getInitialWidth());
    if ((isUseInitialHeight() == true) || (isCustomComponent() == false)) {
        settings.put("height", getInitialHeight());
    } else {
        settings.put("height", (Object) null);
    }
    settings.put("resizable", isResizable());
    if (isResizable() == false) {
        settings.put("widthUnit", getWidthUnit());
        settings.put("heightUnit", getHeightUnit());
    }
    if (isCustomComponent() == false) {
        Page page = createPage();
        if (page == null) {
            throw new WicketRuntimeException("Error creating page for modal dialog.");
        }
        CharSequence pageUrl;
        RequestCycle requestCycle = RequestCycle.get();
        page.getSession().getPageManager().touchPage(page);
        if (page.isPageStateless()) {
            pageUrl = requestCycle.urlFor(page.getClass(), page.getPageParameters());
        } else {
            IRequestHandler handler = new RenderPageRequestHandler(new PageProvider(page));
            pageUrl = requestCycle.urlFor(handler);
        }
        settings.put("src", pageUrl);
    } else {
        settings.put("element", new JSONFunction("document.getElementById(\"" + getContentMarkupId() + "\")"));
    }
    if (getCookieName() != null) {
        settings.put("cookieId", getCookieName());
    }
    String title = getTitle() != null ? getTitle().getObject() : null;
    if (title != null) {
        settings.put("title", getDefaultModelObjectAsString(title));
    }
    if (getMaskType() == MaskType.TRANSPARENT) {
        settings.put("mask", "transparent");
    } else if (getMaskType() == MaskType.SEMI_TRANSPARENT) {
        settings.put("mask", "semi-transparent");
    }
    settings.put("autoSize", autoSize);
    settings.put("unloadConfirmation", showUnloadConfirmation());
    // set true if we set a windowclosedcallback
    boolean haveCloseCallback = false;
    // notification request
    if (windowClosedCallback != null) {
        WindowClosedBehavior behavior = getBehaviors(WindowClosedBehavior.class).get(0);
        settings.put("onClose", new JSONFunction("function() { " + behavior.getCallbackScript() + " }"));
        haveCloseCallback = true;
    }
    // close window property (thus cleaning the shown flag)
    if ((closeButtonCallback != null) || (haveCloseCallback == false)) {
        CloseButtonBehavior behavior = getBehaviors(CloseButtonBehavior.class).get(0);
        settings.put("onCloseButton", new JSONFunction("function() { " + behavior.getCallbackScript() + "; return false; }"));
    }
    postProcessSettings(settings);
    AppendingStringBuffer buffer = new AppendingStringBuffer(500);
    buffer.append("var settings = ");
    buffer.append(settings.toString());
    buffer.append(";");
    buffer.append(getShowJavaScript());
    return buffer.toString();
}
Also used : AppendingStringBuffer(org.apache.wicket.util.string.AppendingStringBuffer) IRequestHandler(org.apache.wicket.request.IRequestHandler) RenderPageRequestHandler(org.apache.wicket.core.request.handler.RenderPageRequestHandler) RequestCycle(org.apache.wicket.request.cycle.RequestCycle) WicketRuntimeException(org.apache.wicket.WicketRuntimeException) Page(org.apache.wicket.Page) JSONFunction(org.apache.wicket.ajax.json.JSONFunction) JSONObject(com.github.openjson.JSONObject) PageProvider(org.apache.wicket.core.request.handler.PageProvider)

Example 2 with JSONFunction

use of org.apache.wicket.ajax.json.JSONFunction in project wicket by apache.

the class AbstractDefaultAjaxBehavior method appendListenerHandler.

private void appendListenerHandler(final CharSequence handler, final JSONObject attributesJson, final String propertyName, final String functionTemplate) throws JSONException {
    if (Strings.isEmpty(handler) == false) {
        final JSONFunction function;
        if (handler instanceof JSONFunction) {
            function = (JSONFunction) handler;
        } else {
            String func = String.format(functionTemplate, handler);
            function = new JSONFunction(func);
        }
        attributesJson.append(propertyName, function);
    }
}
Also used : JSONFunction(org.apache.wicket.ajax.json.JSONFunction)

Example 3 with JSONFunction

use of org.apache.wicket.ajax.json.JSONFunction in project wicket by apache.

the class AjaxDownloadBehavior method initiate.

/**
 * Call this method to initiate the download.
 *
 * @param target
 *            the initiating Ajax target
 */
public void initiate(AjaxRequestTarget target) {
    if (getComponent() == null) {
        throw new WicketRuntimeException("not bound to a component");
    }
    ((WebResponse) RequestCycle.get().getResponse()).clearCookie(cookie(getName()));
    CharSequence url;
    if (resourceBehavior == null) {
        if (resourceReference.canBeRegistered()) {
            getComponent().getApplication().getResourceReferenceRegistry().registerResourceReference(resourceReference);
        }
        PageParameters parameters = new PageParameters();
        if (resourceParameters != null) {
            parameters.mergeWith(resourceParameters);
        }
        parameters.set(RESOURCE_PARAMETER_NAME, getName());
        url = getComponent().getRequestCycle().urlFor(new ResourceReferenceRequestHandler(resourceReference, parameters));
    } else {
        url = resourceBehavior.getUrl();
    }
    JSONObject settings = new JSONObject();
    settings.put("attributes", new JSONFunction(renderAjaxAttributes(getComponent())));
    settings.put("name", getName());
    settings.put("downloadUrl", url);
    settings.put("method", getLocation().name().toLowerCase(Locale.ENGLISH));
    target.appendJavaScript(String.format("Wicket.AjaxDownload.initiate(%s);", settings));
    onBeforeDownload(target);
}
Also used : ResourceReferenceRequestHandler(org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler) WebResponse(org.apache.wicket.request.http.WebResponse) JSONObject(com.github.openjson.JSONObject) WicketRuntimeException(org.apache.wicket.WicketRuntimeException) PageParameters(org.apache.wicket.request.mapper.parameter.PageParameters) JSONFunction(org.apache.wicket.ajax.json.JSONFunction)

Example 4 with JSONFunction

use of org.apache.wicket.ajax.json.JSONFunction in project wicket by apache.

the class AbstractDefaultAjaxBehavior method getCallbackFunctionBody.

/**
 * Generates the body the {@linkplain #getCallbackFunction(CallbackParameter...) callback
 * function}. To embed this code directly into a piece of javascript, make sure any context
 * parameters are available as local variables, global variables or within the closure.
 *
 * @param extraParameters
 * @return The body of the {@linkplain #getCallbackFunction(CallbackParameter...) callback
 *         function}.
 */
public CharSequence getCallbackFunctionBody(CallbackParameter... extraParameters) {
    AjaxRequestAttributes attributes = getAttributes();
    attributes.setEventNames();
    CharSequence attrsJson = renderAjaxAttributes(getComponent(), attributes);
    StringBuilder sb = new StringBuilder();
    sb.append("var attrs = ");
    sb.append(attrsJson);
    sb.append(";\n");
    JSONArray jsonArray = new JSONArray();
    for (CallbackParameter curExtraParameter : extraParameters) {
        if (curExtraParameter.getAjaxParameterName() != null) {
            try {
                JSONObject object = new JSONObject();
                object.put("name", curExtraParameter.getAjaxParameterName());
                object.put("value", new JSONFunction(curExtraParameter.getAjaxParameterCode()));
                jsonArray.put(object);
            } catch (JSONException e) {
                throw new WicketRuntimeException(e);
            }
        }
    }
    sb.append("var params = ").append(jsonArray).append(";\n");
    sb.append("attrs.").append(AjaxAttributeName.EXTRA_PARAMETERS).append(" = params.concat(attrs.").append(AjaxAttributeName.EXTRA_PARAMETERS).append(" || []);\n");
    sb.append("Wicket.Ajax.ajax(attrs);\n");
    return sb;
}
Also used : AjaxRequestAttributes(org.apache.wicket.ajax.attributes.AjaxRequestAttributes) JSONObject(com.github.openjson.JSONObject) WicketRuntimeException(org.apache.wicket.WicketRuntimeException) JSONArray(com.github.openjson.JSONArray) JSONException(com.github.openjson.JSONException) CallbackParameter(org.apache.wicket.ajax.attributes.CallbackParameter) JSONFunction(org.apache.wicket.ajax.json.JSONFunction)

Example 5 with JSONFunction

use of org.apache.wicket.ajax.json.JSONFunction in project wicket by apache.

the class AbstractDefaultAjaxBehavior method renderAjaxAttributes.

/**
 * @param component
 * @param attributes
 * @return the attributes as string in JSON format
 */
protected final CharSequence renderAjaxAttributes(final Component component, AjaxRequestAttributes attributes) {
    JSONObject attributesJson = new JSONObject();
    try {
        attributesJson.put(AjaxAttributeName.URL.jsonName(), getCallbackUrl());
        Method method = attributes.getMethod();
        if (Method.POST == method) {
            attributesJson.put(AjaxAttributeName.METHOD.jsonName(), method);
        }
        if (component instanceof Page == false) {
            String componentId = component.getMarkupId();
            attributesJson.put(AjaxAttributeName.MARKUP_ID.jsonName(), componentId);
        }
        String formId = attributes.getFormId();
        if (Strings.isEmpty(formId) == false) {
            attributesJson.put(AjaxAttributeName.FORM_ID.jsonName(), formId);
        }
        if (attributes.isMultipart()) {
            attributesJson.put(AjaxAttributeName.IS_MULTIPART.jsonName(), true);
        }
        String submittingComponentId = attributes.getSubmittingComponentName();
        if (Strings.isEmpty(submittingComponentId) == false) {
            attributesJson.put(AjaxAttributeName.SUBMITTING_COMPONENT_NAME.jsonName(), submittingComponentId);
        }
        CharSequence childSelector = attributes.getChildSelector();
        if (Strings.isEmpty(childSelector) == false) {
            attributesJson.put(AjaxAttributeName.CHILD_SELECTOR.jsonName(), childSelector);
        }
        if (attributes.isSerializeRecursively()) {
            attributesJson.put(AjaxAttributeName.SERIALIZE_RECURSIVELY.jsonName(), true);
        }
        String indicatorId = findIndicatorId();
        if (Strings.isEmpty(indicatorId) == false) {
            attributesJson.put(AjaxAttributeName.INDICATOR_ID.jsonName(), indicatorId);
        }
        for (IAjaxCallListener ajaxCallListener : attributes.getAjaxCallListeners()) {
            if (ajaxCallListener != null) {
                CharSequence initHandler = ajaxCallListener.getInitHandler(component);
                appendListenerHandler(initHandler, attributesJson, AjaxAttributeName.INIT_HANDLER.jsonName(), INIT_HANDLER_FUNCTION_TEMPLATE);
                CharSequence beforeHandler = ajaxCallListener.getBeforeHandler(component);
                appendListenerHandler(beforeHandler, attributesJson, AjaxAttributeName.BEFORE_HANDLER.jsonName(), BEFORE_HANDLER_FUNCTION_TEMPLATE);
                CharSequence beforeSendHandler = ajaxCallListener.getBeforeSendHandler(component);
                appendListenerHandler(beforeSendHandler, attributesJson, AjaxAttributeName.BEFORE_SEND_HANDLER.jsonName(), BEFORE_SEND_HANDLER_FUNCTION_TEMPLATE);
                CharSequence afterHandler = ajaxCallListener.getAfterHandler(component);
                appendListenerHandler(afterHandler, attributesJson, AjaxAttributeName.AFTER_HANDLER.jsonName(), AFTER_HANDLER_FUNCTION_TEMPLATE);
                CharSequence successHandler = ajaxCallListener.getSuccessHandler(component);
                appendListenerHandler(successHandler, attributesJson, AjaxAttributeName.SUCCESS_HANDLER.jsonName(), SUCCESS_HANDLER_FUNCTION_TEMPLATE);
                CharSequence failureHandler = ajaxCallListener.getFailureHandler(component);
                appendListenerHandler(failureHandler, attributesJson, AjaxAttributeName.FAILURE_HANDLER.jsonName(), FAILURE_HANDLER_FUNCTION_TEMPLATE);
                CharSequence completeHandler = ajaxCallListener.getCompleteHandler(component);
                appendListenerHandler(completeHandler, attributesJson, AjaxAttributeName.COMPLETE_HANDLER.jsonName(), COMPLETE_HANDLER_FUNCTION_TEMPLATE);
                CharSequence precondition = ajaxCallListener.getPrecondition(component);
                appendListenerHandler(precondition, attributesJson, AjaxAttributeName.PRECONDITION.jsonName(), PRECONDITION_FUNCTION_TEMPLATE);
                CharSequence doneHandler = ajaxCallListener.getDoneHandler(component);
                appendListenerHandler(doneHandler, attributesJson, AjaxAttributeName.DONE_HANDLER.jsonName(), DONE_HANDLER_FUNCTION_TEMPLATE);
            }
        }
        JSONArray extraParameters = JsonUtils.asArray(attributes.getExtraParameters());
        if (extraParameters.length() > 0) {
            attributesJson.put(AjaxAttributeName.EXTRA_PARAMETERS.jsonName(), extraParameters);
        }
        List<CharSequence> dynamicExtraParameters = attributes.getDynamicExtraParameters();
        if (dynamicExtraParameters != null) {
            for (CharSequence dynamicExtraParameter : dynamicExtraParameters) {
                String func = String.format(DYNAMIC_PARAMETER_FUNCTION_TEMPLATE, dynamicExtraParameter);
                JSONFunction function = new JSONFunction(func);
                attributesJson.append(AjaxAttributeName.DYNAMIC_PARAMETER_FUNCTION.jsonName(), function);
            }
        }
        if (attributes.isAsynchronous() == false) {
            attributesJson.put(AjaxAttributeName.IS_ASYNC.jsonName(), false);
        }
        String[] eventNames = attributes.getEventNames();
        if (eventNames.length == 1) {
            attributesJson.put(AjaxAttributeName.EVENT_NAME.jsonName(), eventNames[0]);
        } else {
            for (String eventName : eventNames) {
                attributesJson.append(AjaxAttributeName.EVENT_NAME.jsonName(), eventName);
            }
        }
        AjaxChannel channel = attributes.getChannel();
        if (channel != null && channel.equals(AjaxChannel.DEFAULT) == false) {
            attributesJson.put(AjaxAttributeName.CHANNEL.jsonName(), channel);
        }
        if (attributes.isPreventDefault()) {
            attributesJson.put(AjaxAttributeName.IS_PREVENT_DEFAULT.jsonName(), true);
        }
        if (AjaxRequestAttributes.EventPropagation.STOP.equals(attributes.getEventPropagation())) {
            attributesJson.put(AjaxAttributeName.EVENT_PROPAGATION.jsonName(), "stop");
        } else if (AjaxRequestAttributes.EventPropagation.STOP_IMMEDIATE.equals(attributes.getEventPropagation())) {
            attributesJson.put(AjaxAttributeName.EVENT_PROPAGATION.jsonName(), "stopImmediate");
        }
        Duration requestTimeout = attributes.getRequestTimeout();
        if (requestTimeout != null) {
            attributesJson.put(AjaxAttributeName.REQUEST_TIMEOUT.jsonName(), requestTimeout.getMilliseconds());
        }
        boolean wicketAjaxResponse = attributes.isWicketAjaxResponse();
        if (wicketAjaxResponse == false) {
            attributesJson.put(AjaxAttributeName.IS_WICKET_AJAX_RESPONSE.jsonName(), false);
        }
        String dataType = attributes.getDataType();
        if (AjaxRequestAttributes.XML_DATA_TYPE.equals(dataType) == false) {
            attributesJson.put(AjaxAttributeName.DATATYPE.jsonName(), dataType);
        }
        ThrottlingSettings throttlingSettings = attributes.getThrottlingSettings();
        if (throttlingSettings != null) {
            JSONObject throttlingSettingsJson = new JSONObject();
            String throttleId = throttlingSettings.getId();
            if (throttleId == null) {
                throttleId = component.getMarkupId();
            }
            throttlingSettingsJson.put(AjaxAttributeName.THROTTLING_ID.jsonName(), throttleId);
            throttlingSettingsJson.put(AjaxAttributeName.THROTTLING_DELAY.jsonName(), throttlingSettings.getDelay().getMilliseconds());
            if (throttlingSettings.getPostponeTimerOnUpdate()) {
                throttlingSettingsJson.put(AjaxAttributeName.THROTTLING_POSTPONE_ON_UPDATE.jsonName(), true);
            }
            attributesJson.put(AjaxAttributeName.THROTTLING.jsonName(), throttlingSettingsJson);
        }
        postprocessConfiguration(attributesJson, component);
    } catch (JSONException e) {
        throw new WicketRuntimeException(e);
    }
    String attributesAsJson = attributesJson.toString();
    return attributesAsJson;
}
Also used : ThrottlingSettings(org.apache.wicket.ajax.attributes.ThrottlingSettings) IAjaxCallListener(org.apache.wicket.ajax.attributes.IAjaxCallListener) WicketRuntimeException(org.apache.wicket.WicketRuntimeException) JSONArray(com.github.openjson.JSONArray) JSONException(com.github.openjson.JSONException) Page(org.apache.wicket.Page) Duration(org.apache.wicket.util.time.Duration) Method(org.apache.wicket.ajax.attributes.AjaxRequestAttributes.Method) JSONFunction(org.apache.wicket.ajax.json.JSONFunction) JSONObject(com.github.openjson.JSONObject)

Aggregations

JSONFunction (org.apache.wicket.ajax.json.JSONFunction)5 JSONObject (com.github.openjson.JSONObject)4 WicketRuntimeException (org.apache.wicket.WicketRuntimeException)4 JSONArray (com.github.openjson.JSONArray)2 JSONException (com.github.openjson.JSONException)2 Page (org.apache.wicket.Page)2 AjaxRequestAttributes (org.apache.wicket.ajax.attributes.AjaxRequestAttributes)1 Method (org.apache.wicket.ajax.attributes.AjaxRequestAttributes.Method)1 CallbackParameter (org.apache.wicket.ajax.attributes.CallbackParameter)1 IAjaxCallListener (org.apache.wicket.ajax.attributes.IAjaxCallListener)1 ThrottlingSettings (org.apache.wicket.ajax.attributes.ThrottlingSettings)1 PageProvider (org.apache.wicket.core.request.handler.PageProvider)1 RenderPageRequestHandler (org.apache.wicket.core.request.handler.RenderPageRequestHandler)1 IRequestHandler (org.apache.wicket.request.IRequestHandler)1 RequestCycle (org.apache.wicket.request.cycle.RequestCycle)1 ResourceReferenceRequestHandler (org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler)1 WebResponse (org.apache.wicket.request.http.WebResponse)1 PageParameters (org.apache.wicket.request.mapper.parameter.PageParameters)1 AppendingStringBuffer (org.apache.wicket.util.string.AppendingStringBuffer)1 Duration (org.apache.wicket.util.time.Duration)1