001// Copyright 2008, 2009, 2011 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.corelib.components;
016
017import org.apache.tapestry5.ComponentAction;
018import org.apache.tapestry5.ComponentResources;
019import org.apache.tapestry5.annotations.Environmental;
020import org.apache.tapestry5.annotations.Events;
021import org.apache.tapestry5.ioc.annotations.Inject;
022import org.apache.tapestry5.services.FormSupport;
023
024/**
025 * A non visual component used to provide notifications to its container during a form submission. Records actions into
026 * the form on {@link org.apache.tapestry5.annotations.BeginRender} and {@link org.apache.tapestry5.annotations.AfterRender}
027 * that (during the form submission) triggers "BeginSubmit" and "AfterSubmit" events.  The container can receive these
028 * events to perform setup before a group of components process their submission, and perform cleanup afterwards.
029 * 
030 * @tapestrydoc
031 */
032@Events({ SubmitNotifier.BEGIN_SUBMIT_EVENT, SubmitNotifier.AFTER_SUBMIT_EVENT })
033public class SubmitNotifier
034{
035
036    public static final String BEGIN_SUBMIT_EVENT = "BeginSubmit";
037    public static final String AFTER_SUBMIT_EVENT = "AfterSubmit";
038
039    private static final class TriggerEvent implements ComponentAction<SubmitNotifier>
040    {
041        private final String eventType;
042
043        public TriggerEvent(String eventType)
044        {
045            this.eventType = eventType;
046        }
047
048        public void execute(SubmitNotifier component)
049        {
050            component.trigger(eventType);
051        }
052
053        @Override
054        public String toString()
055        {
056            return String.format("SubmitNotifier.TriggerEvent[%s]", eventType);
057        }
058    }
059
060
061    @Inject
062    private ComponentResources resources;
063
064    @Environmental
065    private FormSupport formSupport;
066
067    void beginRender()
068    {
069        formSupport.store(this, new TriggerEvent(BEGIN_SUBMIT_EVENT));
070    }
071
072    void afterRender()
073    {
074        formSupport.store(this, new TriggerEvent(AFTER_SUBMIT_EVENT));
075    }
076
077    private void trigger(String eventType)
078    {
079        resources.triggerEvent(eventType, null, null);
080    }
081}