001// Licensed under the Apache License, Version 2.0 (the "License");
002// you may not use this file except in compliance with the License.
003// You may obtain a copy of the License at
004//
005// http://www.apache.org/licenses/LICENSE-2.0
006//
007// Unless required by applicable law or agreed to in writing, software
008// distributed under the License is distributed on an "AS IS" BASIS,
009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
010// See the License for the specific language governing permissions and
011// limitations under the License.
012
013package org.apache.tapestry5.corelib.components;
014
015import org.apache.tapestry5.*;
016import org.apache.tapestry5.annotations.*;
017import org.apache.tapestry5.corelib.ClientValidation;
018import org.apache.tapestry5.corelib.internal.ComponentActionSink;
019import org.apache.tapestry5.corelib.internal.FormSupportImpl;
020import org.apache.tapestry5.corelib.internal.InternalFormSupport;
021import org.apache.tapestry5.dom.Element;
022import org.apache.tapestry5.internal.BeanValidationContext;
023import org.apache.tapestry5.internal.BeanValidationContextImpl;
024import org.apache.tapestry5.internal.InternalConstants;
025import org.apache.tapestry5.internal.services.FormControlNameManager;
026import org.apache.tapestry5.internal.services.HeartbeatImpl;
027import org.apache.tapestry5.internal.util.AutofocusValidationDecorator;
028import org.apache.tapestry5.ioc.Location;
029import org.apache.tapestry5.ioc.Messages;
030import org.apache.tapestry5.ioc.annotations.Inject;
031import org.apache.tapestry5.ioc.annotations.Symbol;
032import org.apache.tapestry5.ioc.internal.util.InternalUtils;
033import org.apache.tapestry5.ioc.internal.util.TapestryException;
034import org.apache.tapestry5.ioc.services.PropertyAccess;
035import org.apache.tapestry5.ioc.util.ExceptionUtils;
036import org.apache.tapestry5.ioc.util.IdAllocator;
037import org.apache.tapestry5.json.JSONArray;
038import org.apache.tapestry5.runtime.Component;
039import org.apache.tapestry5.services.*;
040import org.apache.tapestry5.services.compatibility.DeprecationWarning;
041import org.apache.tapestry5.services.javascript.JavaScriptSupport;
042import org.slf4j.Logger;
043
044import java.io.EOFException;
045import java.io.IOException;
046import java.io.ObjectInputStream;
047import java.io.UnsupportedEncodingException;
048import java.net.URLDecoder;
049
050/**
051 * An HTML form, which will enclose other components to render out the various
052 * types of fields.
053 *
054 * A Form triggers many notification events. When it renders, it triggers a
055 * {@link org.apache.tapestry5.EventConstants#PREPARE_FOR_RENDER} notification, followed by a
056 * {@link EventConstants#PREPARE} notification.
057 *
058 * When the form is submitted, the component triggers several notifications: first a
059 * {@link EventConstants#PREPARE_FOR_SUBMIT}, then a {@link EventConstants#PREPARE}: these allow the page to update its
060 * state as necessary to prepare for the form submission.
061 *
062 * The Form component then determines if the form was cancelled (see {@link org.apache.tapestry5.corelib.SubmitMode#CANCEL}). If so,
063 * a {@link EventConstants#CANCELED} event is triggered.
064 *
065 * Next come notifications to contained components (or more accurately, the execution of stored {@link ComponentAction}s), to allow each component to retrieve and validate
066 * submitted values, and update server-side properties.  This is based on the {@code t:formdata} query parameter,
067 * which contains serialized object data (generated when the form initially renders).
068 *
069 * Once the form data is processed, the next step is to trigger the
070 * {@link EventConstants#VALIDATE}, which allows for cross-form validation. After that, either a
071 * {@link EventConstants#SUCCESS} OR {@link EventConstants#FAILURE} event (depending on whether the
072 * {@link ValidationTracker} has recorded any errors). Lastly, a {@link EventConstants#SUBMIT} event, for any listeners
073 * that care only about form submission, regardless of success or failure.
074 *
075 * For all of these notifications, the event context is derived from the <strong>context</strong> component parameter. This
076 * context is encoded into the form's action URI (the parameter is not read when the form is submitted, instead the
077 * values encoded into the form are used).
078 *
079 *
080 * While rendering, or processing a Form submission, the Form component places a {@link FormSupport} object into the {@linkplain Environment environment},
081 * so that enclosed components can coordinate with the Form component. It also places a {@link ValidationTracker} into the environment during both render and submission.
082 * During submission it also pushes a {@link Heartbeat} into the environment, which is {@link org.apache.tapestry5.services.Heartbeat#end() ended} just before
083 * {@linkplain FormSupport#defer(Runnable) deferred FormSupport operations} are executed.
084 *
085 *
086 * @tapestrydoc
087 * @see BeanEditForm
088 * @see Errors
089 * @see FormFragment
090 * @see Label
091 */
092@Events(
093        {EventConstants.PREPARE_FOR_RENDER, EventConstants.PREPARE, EventConstants.PREPARE_FOR_SUBMIT,
094                EventConstants.VALIDATE, EventConstants.SUBMIT, EventConstants.FAILURE, EventConstants.SUCCESS, EventConstants.CANCELED})
095@SupportsInformalParameters
096public class Form implements ClientElement, FormValidationControl
097{
098    /**
099     * Query parameter name storing form data (the serialized commands needed to
100     * process a form submission).
101     */
102    public static final String FORM_DATA = "t:formdata";
103
104    /**
105     * Used by {@link Submit}, etc., to identify which particular client-side element (by element id)
106     * was responsible for the submission. An empty hidden field is created, as needed, to store this value.
107     * Starting in Tapestry 5.3, this is a JSONArray with two values: the client id followed by the client name.
108     *
109     * @since 5.2.0
110     */
111    public static final String SUBMITTING_ELEMENT_ID = "t:submit";
112
113    public static final StreamPageContent STREAM_ACTIVE_PAGE_CONTENT = new StreamPageContent().withoutActivation();
114
115    /**
116     * The context for the link (optional parameter). This list of values will
117     * be converted into strings and included in
118     * the URI. The strings will be coerced back to whatever their values are
119     * and made available to event handler
120     * methods.
121     */
122    @Parameter
123    private Object[] context;
124
125    /**
126     * The object which will record user input and validation errors. When not using
127     * the default behavior supplied by the Form component (an immediate re-render of the active
128     * page when there are form validation errors), it is necessary to bind this parameter
129     * to a persistent value that can be maintained until the active page is re-rendered. See
130     * <a href="https://issues.apache.org/jira/browse/TAP5-1808">TAP5-1801</a>.
131     */
132    @Parameter("defaultTracker")
133    protected ValidationTracker tracker;
134
135    @Inject
136    @Symbol(SymbolConstants.FORM_CLIENT_LOGIC_ENABLED)
137    private boolean clientLogicDefaultEnabled;
138
139    /**
140     * Controls when client validation occurs on the client, if at all. Defaults to {@link ClientValidation#SUBMIT}.
141     * {@link ClientValidation#BLUR} was the default, prior to Tapestry 5.4, but is no longer supported.
142     */
143    @Parameter(allowNull = false, defaultPrefix = BindingConstants.LITERAL)
144    private ClientValidation clientValidation = clientLogicDefaultEnabled ? ClientValidation.SUBMIT
145            : ClientValidation.NONE;
146
147    /**
148     * If true (the default), then the JavaScript will be added to position the
149     * cursor into the form. The field to
150     * receive focus is the first rendered field that is in error, or required,
151     * or present (in that order of priority).
152     *
153     * @see SymbolConstants#FORM_CLIENT_LOGIC_ENABLED
154     */
155    @Parameter
156    private boolean autofocus = clientLogicDefaultEnabled;
157
158    /**
159     * Binding the zone parameter will cause the form submission to be handled
160     * as an Ajax request that updates the
161     * indicated zone. Often a Form will update the same zone that contains it.
162     */
163    @Parameter(defaultPrefix = BindingConstants.LITERAL)
164    private String zone;
165
166    /**
167     * If true, then the Form's action will be secure (using an absolute URL with the HTTPs scheme) regardless
168     * of whether the containing page itself is secure or not. This parameter does nothing
169     * when {@linkplain SymbolConstants#SECURE_ENABLED security is disabled} (which is often
170     * the case in development mode). This only affects how the Form's action attribute is rendered, there is
171     * not (currently) a check that the form is actually submitted securely.
172     */
173    @Parameter
174    private boolean secure;
175
176    /**
177     * Prefix value used when searching for validation messages and constraints.
178     * The default is the Form component's
179     * id. This is overridden by {@link org.apache.tapestry5.corelib.components.BeanEditForm}.
180     *
181     * @see org.apache.tapestry5.services.FormSupport#getFormValidationId()
182     */
183    @Parameter
184    private String validationId;
185
186    /**
187     * Object to validate during the form submission process. The default is the Form component's container.
188     * This parameter should only be used in combination with the Bean Validation Library.
189     */
190    @Parameter
191    private Object validate;
192
193    /**
194     * When true, the the form will submit as an asynchronous request (via XmlHttpRequest); the event handler methods
195     * can make use of the {@link org.apache.tapestry5.services.ajax.AjaxResponseRenderer} in order to force content
196     * updates to the client.  This is used as an alternative to placing the form inside a {@link org.apache.tapestry5.corelib.components.Zone}
197     * and binding the {@code zone} parameter.
198     *
199     * @since 5.4
200     */
201    @Parameter
202    private boolean async = false;
203
204    @Inject
205    private Logger logger;
206
207    @Inject
208    private Environment environment;
209
210    @Inject
211    private ComponentResources resources;
212
213    @Inject
214    private Messages messages;
215
216    @Environmental
217    private JavaScriptSupport javascriptSupport;
218
219    @Inject
220    private Request request;
221
222    @Inject
223    private ComponentSource source;
224
225    @Inject
226    private FormControlNameManager formControlNameManager;
227
228
229    /**
230     * Starting in 5.4, this is a simple, non-persistent property, with no extra magic tricks.
231     */
232    private ValidationTracker defaultTracker;
233
234    @Inject
235    @Symbol(SymbolConstants.SECURE_ENABLED)
236    private boolean secureEnabled;
237
238    private InternalFormSupport formSupport;
239
240    private Element form;
241
242    private Element div;
243
244    // Collects a stream of component actions. Each action goes in as a UTF
245    // string (the component
246    // component id), followed by a ComponentAction
247
248    private ComponentActionSink actionSink;
249
250    @SuppressWarnings("unchecked")
251    @Environmental
252    private TrackableComponentEventCallback eventCallback;
253
254    @Inject
255    private ClientDataEncoder clientDataEncoder;
256
257    @Inject
258    private PropertyAccess propertyAccess;
259
260    @Inject
261    private DeprecationWarning deprecationWarning;
262
263    private String clientId;
264
265    @Inject
266    private ComponentSource componentSource;
267
268    String defaultValidationId()
269    {
270        return resources.getId();
271    }
272
273    Object defaultValidate()
274    {
275        return resources.getContainer();
276    }
277
278    /**
279     * Returns an instance of {@link ValidationTrackerImpl}, lazily creating it as needed. This property
280     * is the default for the <strong>tracker</strong> parameter; the property (as of Tapestry 5.4) is not
281     * persistent.
282     *
283     * @return per-request cached instance
284     */
285    public ValidationTracker getDefaultTracker()
286    {
287        if (defaultTracker == null)
288        {
289            defaultTracker = new ValidationTrackerImpl();
290        }
291
292        return defaultTracker;
293    }
294
295    /**
296     * @deprecated In 5.4; previously used only for testing
297     */
298    public void setDefaultTracker(ValidationTracker defaultTracker)
299    {
300        this.defaultTracker = defaultTracker;
301    }
302
303    void setupRender()
304    {
305        FormSupport existing = environment.peek(FormSupport.class);
306
307        if (existing != null)
308        {
309            throw new TapestryException(messages.get("core-form-nesting-not-allowed"), existing, null);
310        }
311
312        if (clientValidation == ClientValidation.BLUR)
313        {
314            deprecationWarning.componentParameterValue(resources, "clientValidation", clientValidation, "BLUR is no longer supported, starting in 5.4. Validation will occur as with SUBMIT.");
315        }
316    }
317
318    void beginRender(MarkupWriter writer)
319    {
320        Link link = resources.createFormEventLink(EventConstants.ACTION, context);
321
322        String actionURL = secure && secureEnabled ? link.toAbsoluteURI(true) : link.toURI();
323
324        actionSink = new ComponentActionSink(logger, clientDataEncoder);
325
326        clientId = javascriptSupport.allocateClientId(resources);
327
328        // Pre-register some names, to prevent client-side collisions with function names
329        // attached to the JS Form object.
330
331        IdAllocator allocator = new IdAllocator();
332
333        preallocateNames(allocator);
334
335        formSupport = createRenderTimeFormSupport(clientId, actionSink, allocator);
336
337        environment.push(FormSupport.class, formSupport);
338        environment.push(ValidationTracker.class, tracker);
339
340        if (autofocus)
341        {
342            ValidationDecorator autofocusDecorator = new AutofocusValidationDecorator(
343                    environment.peek(ValidationDecorator.class), tracker, javascriptSupport);
344            environment.push(ValidationDecorator.class, autofocusDecorator);
345        }
346
347        // Now that the environment is setup, inform the component or other
348        // listeners that the form
349        // is about to render.
350
351        resources.triggerEvent(EventConstants.PREPARE_FOR_RENDER, context, null);
352
353        resources.triggerEvent(EventConstants.PREPARE, context, null);
354
355        // Push BeanValidationContext only after the container had a chance to prepare
356        environment.push(BeanValidationContext.class, new BeanValidationContextImpl(validate));
357
358        // Save the form element for later, in case we want to write an encoding
359        // type attribute.
360
361        form = writer.element("form",
362                "id", clientId,
363                "method", "post",
364                "action", actionURL,
365                "data-update-zone", zone);
366
367        if (clientValidation != ClientValidation.NONE)
368        {
369            writer.attributes("data-validate", "submit");
370        }
371
372        if (async)
373        {
374            javascriptSupport.require("t5/core/zone");
375            writer.attributes("data-async-trigger", true);
376        }
377
378        resources.renderInformalParameters(writer);
379
380        div = writer.element("div");
381
382        for (String parameterName : link.getParameterNames())
383        {
384            String[] values = link.getParameterValues(parameterName);
385
386            for (String value : values)
387            {
388                // The parameter value is expected to be encoded,
389                // but the input value shouldn't be encoded.
390                try
391                {
392                    value = URLDecoder.decode(value, "UTF-8");
393                } catch (UnsupportedEncodingException e)
394                {
395                    logger.error("Enable to decode parameter value for parameter {} in form {}",
396                            parameterName, form.getName(), e);
397                }
398                writer.element("input", "type", "hidden", "name", parameterName, "value", value);
399                writer.end();
400            }
401        }
402
403        writer.end(); // div
404
405        environment.peek(Heartbeat.class).begin();
406    }
407
408    /**
409     * Creates an {@link org.apache.tapestry5.corelib.internal.InternalFormSupport} for
410     * this Form.
411     *
412     * This method may also be invoked as the handler for the "internalCreateRenderTimeFormSupport" event.
413     *
414     * @param clientId
415     *         the client-side id for the rendered form
416     *         element
417     * @param actionSink
418     *         used to collect component actions that will, ultimately, be
419     *         written as the t:formdata hidden
420     *         field
421     * @param allocator
422     *         used to allocate unique ids
423     * @return form support object
424     */
425    @OnEvent("internalCreateRenderTimeFormSupport")
426    InternalFormSupport createRenderTimeFormSupport(String clientId, ComponentActionSink actionSink,
427                                                    IdAllocator allocator)
428    {
429        return new FormSupportImpl(resources, clientId, actionSink,
430                clientValidation != ClientValidation.NONE, allocator, validationId);
431    }
432
433    void afterRender(MarkupWriter writer)
434    {
435        environment.peek(Heartbeat.class).end();
436
437        formSupport.executeDeferred();
438
439        String encodingType = formSupport.getEncodingType();
440
441        if (encodingType != null)
442        {
443            form.forceAttributes("enctype", encodingType);
444        }
445
446        writer.end(); // form
447
448        div.element("input", "type", "hidden", "name", FORM_DATA, "value", actionSink.getClientData());
449        div.pop();
450
451        if (autofocus)
452        {
453            environment.pop(ValidationDecorator.class);
454        }
455    }
456
457    void cleanupRender()
458    {
459        environment.pop(FormSupport.class);
460
461        formSupport = null;
462
463        environment.pop(ValidationTracker.class);
464
465        tracker.clear();
466
467        environment.pop(BeanValidationContext.class);
468    }
469
470    @SuppressWarnings(
471            {"unchecked", "InfiniteLoopStatement"})
472    Object onAction(EventContext context) throws IOException
473    {
474        beforeProcessSubmit(context);
475
476        tracker.clear();
477
478        formSupport = new FormSupportImpl(resources, validationId);
479
480        environment.push(ValidationTracker.class, tracker);
481        environment.push(FormSupport.class, formSupport);
482
483        Heartbeat heartbeat = new HeartbeatImpl();
484
485        environment.push(Heartbeat.class, heartbeat);
486
487        heartbeat.begin();
488
489        boolean didPushBeanValidationContext = false;
490
491        try
492        {
493            resources.triggerContextEvent(EventConstants.PREPARE_FOR_SUBMIT, context, eventCallback);
494
495            if (eventCallback.isAborted())
496                return true;
497
498            resources.triggerContextEvent(EventConstants.PREPARE, context, eventCallback);
499            if (eventCallback.isAborted())
500                return true;
501
502            if (isFormCancelled())
503            {
504                executeStoredActions(true);
505
506                resources.triggerContextEvent(EventConstants.CANCELED, context, eventCallback);
507                if (eventCallback.isAborted())
508                    return true;
509            }
510
511            environment.push(BeanValidationContext.class, new BeanValidationContextImpl(validate));
512
513            didPushBeanValidationContext = true;
514
515            executeStoredActions(false);
516
517            heartbeat.end();
518
519            formSupport.executeDeferred();
520
521            fireValidateEvent(EventConstants.VALIDATE, context, eventCallback);
522
523            if (eventCallback.isAborted())
524            {
525                return true;
526            }
527
528            afterValidate();
529
530            // Let the listeners know about overall success or failure. Most
531            // listeners fall into
532            // one of those two camps.
533
534            // If the tracker has no errors, then clear it of any input values
535            // as well, so that the next page render will be "clean" and show
536            // true persistent data, not value from the previous form
537            // submission.
538
539            if (!tracker.getHasErrors())
540            {
541                tracker.clear();
542            }
543
544            String eventType = tracker.getHasErrors()
545                    ? EventConstants.FAILURE
546                    : EventConstants.SUCCESS;
547
548            resources.triggerContextEvent(eventType, context, eventCallback);
549
550            if (eventCallback.isAborted())
551            {
552                return true;
553            }
554
555            // Lastly, tell anyone whose interested that the form is completely
556            // submitted.
557
558            resources.triggerContextEvent(EventConstants.SUBMIT, context, eventCallback);
559
560            afterSuccessOrFailure();
561
562            if (eventCallback.isAborted())
563            {
564                return true;
565            }
566
567            // For traditional request with no validation exceptions, re-render the
568            // current page immediately, as-is.  Prior to Tapestry 5.4, a redirect was
569            // sent that required that the tracker be persisted across requests.
570            // See https://issues.apache.org/jira/browse/TAP5-1808
571
572            if (tracker.getHasErrors() && !request.isXHR())
573            {
574                return STREAM_ACTIVE_PAGE_CONTENT;
575            }
576
577            // The event will not work its way up.
578
579            return false;
580
581        } finally
582        {
583            environment.pop(Heartbeat.class);
584            environment.pop(FormSupport.class);
585
586            environment.pop(ValidationTracker.class);
587
588            if (didPushBeanValidationContext)
589            {
590                environment.pop(BeanValidationContext.class);
591            }
592        }
593    }
594
595    /**
596     * A hook invoked from {@link #onAction(org.apache.tapestry5.EventContext)} after the
597     * {@link org.apache.tapestry5.EventConstants#SUBMIT} or {@link org.apache.tapestry5.EventConstants#FAILURE} event has been triggered.
598     *
599     * This method will be invoked regardless of whether the submit or failure event was aborted.
600     *
601     * This implementation does nothing.
602     *
603     * @since 5.4
604     */
605
606    protected void afterSuccessOrFailure()
607    {
608
609    }
610
611    /**
612     * A hook invoked from {@link #onAction(org.apache.tapestry5.EventContext)} before any other setup.
613     *
614     * This implementation does nothing.
615     *
616     * @param context
617     *         as passed to {@code onAction()}
618     * @since 5.4
619     */
620    protected void beforeProcessSubmit(EventContext context)
621    {
622
623    }
624
625    /**
626     * A hook invoked from {@link #onAction(org.apache.tapestry5.EventContext)} after the
627     * {@link org.apache.tapestry5.EventConstants#VALIDATE} event has been triggered, and
628     * before the {@link #tracker} has been {@linkplain org.apache.tapestry5.ValidationTracker#clear() cleared}.
629     *
630     * Only invoked if the valiate event did not abort (that is, the no event handler method returned a value).
631     *
632     * This implementation does nothing.
633     *
634     * @since 5.4
635     */
636    protected void afterValidate()
637    {
638
639    }
640
641    private boolean isFormCancelled()
642    {
643        // The "cancel" query parameter is reserved for this purpose; if it is present then the form was canceled on the
644        // client side.  For image submits, there will be two parameters: "cancel.x" and "cancel.y".
645
646        if (request.getParameter(InternalConstants.CANCEL_NAME) != null ||
647                request.getParameter(InternalConstants.CANCEL_NAME + ".x") != null)
648        {
649            return true;
650        }
651
652        // When JavaScript is involved, it's more complicated. In fact, this is part of HLS's desire
653        // to have all forms submit via XHR when JavaScript is present, since it would provide
654        // an opportunity to get the submitting element's value into the request properly.
655
656        String raw = request.getParameter(SUBMITTING_ELEMENT_ID);
657
658        if (InternalUtils.isNonBlank(raw) &&
659                new JSONArray(raw).getString(1).equals(InternalConstants.CANCEL_NAME))
660        {
661            return true;
662        }
663
664        return false;
665    }
666
667
668    private void fireValidateEvent(String eventName, EventContext context, TrackableComponentEventCallback callback)
669    {
670        try
671        {
672            resources.triggerContextEvent(eventName, context, callback);
673        } catch (RuntimeException ex)
674        {
675            ValidationException ve = ExceptionUtils.findCause(ex, ValidationException.class, propertyAccess);
676
677            if (ve != null)
678            {
679                ValidationTracker tracker = environment.peek(ValidationTracker.class);
680
681                tracker.recordError(ve.getMessage());
682
683                return;
684            }
685
686            throw ex;
687        }
688    }
689
690    /**
691     * Pulls the stored actions out of the request, converts them from MIME
692     * stream back to object stream and then
693     * objects, and executes them.
694     */
695    private void executeStoredActions(boolean forFormCancel)
696    {
697        String[] values = request.getParameters(FORM_DATA);
698
699        if (!request.getMethod().equals("POST") || values == null)
700            throw new RuntimeException(messages.format("core-invalid-form-request", FORM_DATA));
701
702        // Due to Ajax there may be multiple values here, so
703        // handle each one individually.
704
705        for (String clientEncodedActions : values)
706        {
707            if (InternalUtils.isBlank(clientEncodedActions))
708                continue;
709
710            logger.debug("Processing actions: {}", clientEncodedActions);
711
712            ObjectInputStream ois = null;
713
714            Component component = null;
715
716            try
717            {
718                ois = clientDataEncoder.decodeClientData(clientEncodedActions);
719
720                while (!eventCallback.isAborted())
721                {
722                    String componentId = ois.readUTF();
723                    boolean cancelAction = ois.readBoolean();
724                    ComponentAction action = (ComponentAction) ois.readObject();
725
726                    // Actions are a mix of ordinary actions and cancel actions.  Filter out one set or the other
727                    // based on whether the form was submitted or cancelled.
728                    if (forFormCancel != cancelAction)
729                    {
730                        continue;
731                    }
732
733                    component = source.getComponent(componentId);
734
735                    logger.debug("Processing: {} {}", componentId, action);
736
737                    action.execute(component);
738
739                    component = null;
740                }
741            } catch (EOFException ex)
742            {
743                // Expected
744            } catch (Exception ex)
745            {
746                Location location = component == null ? null : component.getComponentResources().getLocation();
747
748                throw new TapestryException(ex.getMessage(), location, ex);
749            } finally
750            {
751                InternalUtils.close(ois);
752            }
753        }
754    }
755
756    public void recordError(String errorMessage)
757    {
758        tracker.recordError(errorMessage);
759    }
760
761    public void recordError(Field field, String errorMessage)
762    {
763        tracker.recordError(field, errorMessage);
764    }
765
766    public boolean getHasErrors()
767    {
768        return tracker.getHasErrors();
769    }
770
771    public boolean isValid()
772    {
773        return !tracker.getHasErrors();
774    }
775
776    public void clearErrors()
777    {
778        tracker.clear();
779    }
780
781    // For testing:
782
783    void setTracker(ValidationTracker tracker)
784    {
785        this.tracker = tracker;
786    }
787
788    /**
789     * Forms use the same value for their name and their id attribute.
790     */
791    public String getClientId()
792    {
793        return clientId;
794    }
795
796    private void preallocateNames(IdAllocator idAllocator)
797    {
798        for (String name : formControlNameManager.getReservedNames())
799        {
800            idAllocator.allocateId(name);
801            // See https://issues.apache.org/jira/browse/TAP5-1632
802            javascriptSupport.allocateClientId(name);
803
804        }
805
806        Component activePage = componentSource.getActivePage();
807
808        // This is unlikely but may be possible if people override some of the standard
809        // exception reporting logic.
810
811        if (activePage == null)
812            return;
813
814        ComponentResources activePageResources = activePage.getComponentResources();
815
816        try
817        {
818
819            activePageResources.triggerEvent(EventConstants.PREALLOCATE_FORM_CONTROL_NAMES, new Object[]
820                    {idAllocator}, null);
821        } catch (RuntimeException ex)
822        {
823            logger.error(
824                    String.format("Unable to obtain form control names to preallocate: %s",
825                            ExceptionUtils.toMessage(ex)), ex);
826        }
827    }
828}