Search in sources :

Example 16 with Parameter

use of org.apache.tapestry5.annotations.Parameter in project tapestry-5 by apache.

the class ActivationRequestParameterWorker method decorateLinks.

@SuppressWarnings("all")
private static void decorateLinks(TransformationSupport support, String fieldName, final FieldHandle handle, final String parameterName, final ValueEncoder encoder, final URLEncoder urlEncoder) {
    ComponentEventHandler handler = new ComponentEventHandler() {

        public void handleEvent(Component instance, ComponentEvent event) {
            Object value = handle.get(instance);
            if (value == null) {
                return;
            }
            Link link = event.getEventContext().get(Link.class, 0);
            String clientValue = encoder.toClient(value);
            // TAP5-1768: escape special characters
            clientValue = urlEncoder.encode(clientValue);
            link.addParameter(parameterName, clientValue);
        }
    };
    support.addEventHandler(EventConstants.DECORATE_COMPONENT_EVENT_LINK, 0, String.format("ActivationRequestParameterWorker decorate component event link event handler for field %s as query parameter '%s'", fieldName, parameterName), handler);
    support.addEventHandler(EventConstants.DECORATE_PAGE_RENDER_LINK, 0, String.format("ActivationRequestParameterWorker decorate page render link event handler for field %s as query parameter '%s'", fieldName, parameterName), handler);
}
Also used : ComponentEventHandler(org.apache.tapestry5.services.ComponentEventHandler) ComponentEvent(org.apache.tapestry5.runtime.ComponentEvent) Component(org.apache.tapestry5.runtime.Component) Link(org.apache.tapestry5.http.Link)

Example 17 with Parameter

use of org.apache.tapestry5.annotations.Parameter in project tapestry-5 by apache.

the class ActivationRequestParameterWorker method setValueFromInitializeEventHandler.

@SuppressWarnings("all")
private void setValueFromInitializeEventHandler(final TransformationSupport support, final String fieldName, final boolean required, final FieldHandle handle, final String parameterName, final ValueEncoder encoder, final URLEncoder urlEncoder) {
    ComponentEventHandler handler = new ComponentEventHandler() {

        public void handleEvent(Component instance, ComponentEvent event) {
            String clientValue = request.getParameter(parameterName);
            if (clientValue == null) {
                if (required) {
                    throw new TapestryException(String.format("Activation request parameter field %s is marked as required, but query parameter '%s' is null.", fieldName, parameterName), null);
                }
                return;
            }
            // TAP5-1768: unescape encoded value
            clientValue = urlEncoder.decode(clientValue);
            Object value = encoder.toValue(clientValue);
            handle.set(instance, value);
        }
    };
    support.addEventHandler(EventConstants.ACTIVATE, 0, String.format("Restoring field %s from query parameter '%s'", fieldName, parameterName), handler);
}
Also used : ComponentEventHandler(org.apache.tapestry5.services.ComponentEventHandler) ComponentEvent(org.apache.tapestry5.runtime.ComponentEvent) Component(org.apache.tapestry5.runtime.Component) TapestryException(org.apache.tapestry5.commons.internal.util.TapestryException)

Example 18 with Parameter

use of org.apache.tapestry5.annotations.Parameter in project tapestry-5 by apache.

the class ServiceAdvisorImpl method advise.

/**
 * Invokes the configured method, passing the builder. The method will always take, as a parameter, a
 * MethodAdvisor.
 */
@Override
public void advise(MethodAdviceReceiver methodAdviceReceiver) {
    Map<Class, Object> resources = CollectionFactory.newMap(this.resourcesDefaults);
    resources.put(MethodAdviceReceiver.class, methodAdviceReceiver);
    InjectionResources injectionResources = new MapInjectionResources(resources);
    // By design, advise methods return void, so we know that the return value is null.
    invoke(injectionResources);
}
Also used : InjectionResources(org.apache.tapestry5.ioc.internal.util.InjectionResources) MapInjectionResources(org.apache.tapestry5.ioc.internal.util.MapInjectionResources) MapInjectionResources(org.apache.tapestry5.ioc.internal.util.MapInjectionResources)

Example 19 with Parameter

use of org.apache.tapestry5.annotations.Parameter in project tapestry-5 by apache.

the class ExceptionReportWriterImpl method writeReport.

@Override
public void writeReport(final PrintWriter writer, ExceptionAnalysis analysis) {
    writer.printf("EXCEPTION STACK:%n%n");
    // Figure out what all the property names are so that we can set the width of the column that lists
    // property names.
    Flow<String> propertyNames = F.flow(analysis.getExceptionInfos()).mapcat(EXCEPTION_INFO_TO_PROPERTY_NAMES).append("Exception", "Message");
    PropertyWriter pw = newPropertyWriter(writer, propertyNames);
    boolean first = true;
    for (ExceptionInfo info : analysis.getExceptionInfos()) {
        if (first) {
            writer.println();
            first = false;
        }
        pw.write("Exception", info.getClassName());
        pw.write("Message", info.getMessage());
        for (String name : info.getPropertyNames()) {
            pw.write(name, info.getProperty(name));
        }
        if (!info.getStackTrace().isEmpty()) {
            writer.printf("%n  Stack trace:%n%n");
            for (StackTraceElement e : info.getStackTrace()) {
                writer.printf("  - %s%n", e.toString());
            }
        }
        writer.println();
    }
    Request request = requestGlobals.getRequest();
    if (request != null) {
        // New PropertyWriter based on the lengths of parameter names and header names, and a sample of
        // the literal keys.
        pw = newPropertyWriter(writer, F.flow(request.getParameterNames()).concat(request.getHeaderNames()).append("serverName", "removeHost"));
        writer.printf("REQUEST:%n%nBasic Information:%n%n");
        List<String> flags = CollectionFactory.newList();
        if (request.isXHR()) {
            flags.add("XHR");
        }
        if (request.isRequestedSessionIdValid()) {
            flags.add("requestedSessionIdValid");
        }
        if (request.isSecure()) {
            flags.add("secure");
        }
        pw.write("contextPath", contextPath);
        if (!flags.isEmpty()) {
            pw.write("flags", InternalUtils.joinSorted(flags));
        }
        pw.write("method", request.getMethod());
        pw.write("path", request.getPath());
        pw.write("locale", request.getLocale());
        pw.write("serverName", request.getServerName());
        pw.write("remoteHost", request.getRemoteHost());
        writer.printf("%nHeaders:%n%n");
        for (String name : request.getHeaderNames()) {
            pw.write(name, request.getHeader(name));
        }
        if (!request.getParameterNames().isEmpty()) {
            writer.printf("%nParameters:%n");
            for (String name : request.getParameterNames()) {
                // TODO: Support multi-value parameters
                pw.write(name, request.getParameters(name));
            }
        }
        Session session = request.getSession(false);
        if (session != null) {
            pw = newPropertyWriter(writer, session.getAttributeNames());
            writer.printf("%nSESSION:%n%n");
            for (String name : session.getAttributeNames()) {
                pw.write(name, session.getAttribute(name));
            }
        }
    }
    writer.printf("%nSYSTEM INFORMATION:");
    Runtime runtime = Runtime.getRuntime();
    writer.printf("%n%nMemory:%n  %,15d bytes free%n  %,15d bytes total%n  %,15d bytes max%n", runtime.freeMemory(), runtime.totalMemory(), runtime.maxMemory());
    Thread[] threads = TapestryInternalUtils.getAllThreads();
    int maxThreadNameLength = 0;
    for (Thread t : threads) {
        maxThreadNameLength = Math.max(maxThreadNameLength, t.getName().length());
    }
    String format = "%n%s %" + maxThreadNameLength + "s %s";
    writer.printf("%n%,d Threads:", threads.length);
    for (Thread t : threads) {
        writer.printf(format, Thread.currentThread() == t ? "*" : " ", t.getName(), t.getState().name());
        if (t.isDaemon()) {
            writer.write(", daemon");
        }
        if (!t.isAlive()) {
            writer.write(", NOT alive");
        }
        if (t.isInterrupted()) {
            writer.write(", interrupted");
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            writer.printf(", priority %d", t.getPriority());
        }
    }
    // Finish the final line.
    writer.println();
}
Also used : Request(org.apache.tapestry5.http.services.Request) ExceptionInfo(org.apache.tapestry5.ioc.services.ExceptionInfo) Session(org.apache.tapestry5.http.services.Session)

Example 20 with Parameter

use of org.apache.tapestry5.annotations.Parameter in project tapestry-5 by apache.

the class Form method beginRender.

void beginRender(MarkupWriter writer) {
    Link link = resources.createFormEventLink(EventConstants.ACTION, context);
    String actionURL = secure && secureEnabled ? link.toAbsoluteURI(true) : link.toURI();
    actionSink = new ComponentActionSink(logger, clientDataEncoder);
    clientId = javascriptSupport.allocateClientId(resources);
    // Pre-register some names, to prevent client-side collisions with function names
    // attached to the JS Form object.
    IdAllocator allocator = new IdAllocator();
    preallocateNames(allocator);
    formSupport = createRenderTimeFormSupport(clientId, actionSink, allocator);
    environment.push(FormSupport.class, formSupport);
    environment.push(ValidationTracker.class, tracker);
    if (autofocus) {
        ValidationDecorator autofocusDecorator = new AutofocusValidationDecorator(environment.peek(ValidationDecorator.class), tracker, javascriptSupport);
        environment.push(ValidationDecorator.class, autofocusDecorator);
    }
    // Now that the environment is setup, inform the component or other
    // listeners that the form
    // is about to render.
    resources.triggerEvent(EventConstants.PREPARE_FOR_RENDER, context, null);
    resources.triggerEvent(EventConstants.PREPARE, context, null);
    // Push BeanValidationContext only after the container had a chance to prepare
    environment.push(BeanValidationContext.class, new BeanValidationContextImpl(validate));
    // Save the form element for later, in case we want to write an encoding
    // type attribute.
    form = writer.element("form", "id", clientId, "method", "post", "action", actionURL, "data-update-zone", zone, DATA_ATTRIBUTE, DATA_ATTRIBUTE_VALUE);
    if (clientValidation != ClientValidation.NONE) {
        writer.attributes("data-validate", "submit");
    }
    if (async) {
        javascriptSupport.require("t5/core/zone");
        writer.attributes("data-async-trigger", true);
    }
    resources.renderInformalParameters(writer);
    div = writer.element("div");
    for (String parameterName : link.getParameterNames()) {
        String[] values = link.getParameterValues(parameterName);
        for (String value : values) {
            // but the input value shouldn't be encoded.
            try {
                value = URLDecoder.decode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("Enable to decode parameter value for parameter {} in form {}", parameterName, form.getName(), e);
            }
            writer.element("input", "type", "hidden", "name", parameterName, "value", value);
            writer.end();
        }
    }
    // div
    writer.end();
    environment.peek(Heartbeat.class).begin();
}
Also used : ComponentActionSink(org.apache.tapestry5.corelib.internal.ComponentActionSink) IdAllocator(org.apache.tapestry5.ioc.util.IdAllocator) AutofocusValidationDecorator(org.apache.tapestry5.internal.util.AutofocusValidationDecorator) Heartbeat(org.apache.tapestry5.services.Heartbeat) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AutofocusValidationDecorator(org.apache.tapestry5.internal.util.AutofocusValidationDecorator) Link(org.apache.tapestry5.http.Link) BeanValidationContextImpl(org.apache.tapestry5.internal.BeanValidationContextImpl)

Aggregations

TapestryException (org.apache.tapestry5.commons.internal.util.TapestryException)12 UnknownValueException (org.apache.tapestry5.commons.util.UnknownValueException)6 MutableComponentModel (org.apache.tapestry5.model.MutableComponentModel)6 RequestParameter (org.apache.tapestry5.annotations.RequestParameter)5 JSONObject (org.apache.tapestry5.json.JSONObject)5 ComponentEvent (org.apache.tapestry5.runtime.ComponentEvent)5 InternalComponentResources (org.apache.tapestry5.internal.InternalComponentResources)4 Test (org.testng.annotations.Test)4 Binding (org.apache.tapestry5.Binding)3 ComponentResources (org.apache.tapestry5.ComponentResources)3 ActivationContextParameter (org.apache.tapestry5.annotations.ActivationContextParameter)3 Location (org.apache.tapestry5.commons.Location)3 Resource (org.apache.tapestry5.commons.Resource)3 AvailableValues (org.apache.tapestry5.commons.util.AvailableValues)3 LiteralBinding (org.apache.tapestry5.internal.bindings.LiteralBinding)3 Logger (org.slf4j.Logger)3 Method (java.lang.reflect.Method)2 Parameter (java.lang.reflect.Parameter)2 EventContext (org.apache.tapestry5.EventContext)2 ValueEncoder (org.apache.tapestry5.ValueEncoder)2