001: /*
002: ItsNat Java Web Application Framework
003: Copyright (C) 2007 Innowhere Software Services S.L., Spanish Company
004: Author: Jose Maria Arranz Santamaria
005:
006: This program is free software: you can redistribute it and/or modify
007: it under the terms of the GNU Affero General Public License as published by
008: the Free Software Foundation, either version 3 of the License, or
009: (at your option) any later version. See the GNU Affero General Public
010: License for more details. See the copy of the GNU Affero General Public License
011: included in this program. If not, see <http://www.gnu.org/licenses/>.
012: */
013:
014: package org.itsnat.impl.core.listener.domext;
015:
016: import org.itsnat.core.ItsNatException;
017: import org.itsnat.core.ItsNatTimer;
018: import org.itsnat.core.event.ParamTransport;
019: import org.itsnat.core.event.TimerHandle;
020: import org.itsnat.impl.core.ItsNatTimerImpl;
021: import org.itsnat.impl.core.event.client2serv.*;
022: import org.itsnat.impl.core.event.client2serv.domext.TimerEventImpl;
023: import org.itsnat.impl.core.js.listener.TimerEventListenerJSRenderImpl;
024: import org.itsnat.impl.core.util.UserDataImpl;
025: import org.w3c.dom.events.EventListener;
026: import org.w3c.dom.events.EventTarget;
027:
028: /**
029: *
030: * @author jmarranz
031: */
032: public class TimerEventListenerWrapperImpl extends
033: DOMExtensionEventListenerWrapperImpl implements TimerHandle {
034: private static final int SCHEDULED = 1;
035: private static final int EXECUTED = 2;
036: private static final int CANCELLED = 3;
037:
038: protected long time; // incluye el delay de la primera vez (si existe)
039: protected long period;
040: protected long nextExecutionTime;
041: protected boolean fixedRate = false;
042: protected ItsNatTimerImpl timer;
043: protected int state = SCHEDULED;
044: protected UserDataImpl userData;
045:
046: /**
047: * Creates a new instance of TimerEventListenerWrapperImpl
048: */
049: public TimerEventListenerWrapperImpl(EventTarget target,
050: EventListener listener, long time, long period,
051: boolean fixedRate, int syncMode,
052: ParamTransport[] extraParams, String preSendCode,
053: long ajaxTimeout, ItsNatTimerImpl timer) {
054: super (timer.getItsNatDocumentImpl(), target, listener,
055: syncMode, extraParams, preSendCode, ajaxTimeout);
056:
057: this .time = time;
058: this .period = period;
059: this .fixedRate = fixedRate;
060: this .timer = timer;
061:
062: this .nextExecutionTime = time;
063: }
064:
065: public long getFirstTime() {
066: return time;
067: }
068:
069: public long getDelayFirstTime() {
070: long delay = getFirstTime() - System.currentTimeMillis(); // El tiempo que ha de esperar hasta que le toque ejecutarse por primera vez
071: if (delay < 0)
072: delay = 0; // YA (ya vamos con retraso, ocurre cuando time es el instante "actual" pero hasta llegar aquí puede haber pasado un milisegundo), si time es una fecha del pasado ejecutamos de todas formas tal y como se documenta java.util.Timer
073: return delay;
074: }
075:
076: public long getPeriod() {
077: return period;
078: }
079:
080: public ItsNatTimer getItsNatTimer() {
081: return timer;
082: }
083:
084: public ItsNatTimerImpl getItsNatTimerImpl() {
085: return timer;
086: }
087:
088: public boolean cancel() {
089: boolean res = (state == SCHEDULED);
090: this .state = CANCELLED;
091: timer.removeListener(this ); // Si ya fue eliminado no pasa nada
092: return res;
093: }
094:
095: public long scheduledExecutionTime() {
096: // Este método si es llamado durante el proceso del evento
097: // representa el instante teórico en el que le tocaría ejecutarse (que puede diferir con el momento actual si hay retraso)
098: // Si es llamado después del proceso del evento representa la siguiente ejecución prevista.
099: return nextExecutionTime;
100: }
101:
102: public void handleEvent(NormalEventImpl event) {
103: long computedPeriod = handleEvent((TimerEventImpl) event);
104:
105: if (computedPeriod != -1) // Sigue ejecutándose (status en EXECUTED y period > 0)
106: {
107: TimerEventListenerJSRenderImpl
108: .updateTimerEventListenerCode(this , computedPeriod);
109: }
110: }
111:
112: public long handleEvent(TimerEventImpl event) {
113: if (state != CANCELLED) // En algún momento ha sido cancelado pero el evento desde el cliente ha sido enviado (no ha dado tiempo de que llegue la orden al cliente), es posible que esto no ocurra nunca pero por si acaso
114: {
115: this .state = EXECUTED;
116: getEventListener().handleEvent(event);
117:
118: if (state == CANCELLED) {
119: // timer periódico cancelado en el handleEvent del usuario, no se ejecutará más
120: // Ya está desregistrado (cancel() ya lo hace)
121: return -1;
122: } else if (period == 0) {
123: // Ya se ha ejecutado y no se ejecutará más, lo eliminamos de la lista
124: // state queda en EXECUTED
125: timer.removeListener(this );
126: return -1;
127: } else {
128: // EXECUTED y period > 0
129: long computedPeriod;
130: if (!fixedRate) {
131: this .nextExecutionTime = System.currentTimeMillis()
132: + period;
133: computedPeriod = period;
134: } else {
135: this .nextExecutionTime = nextExecutionTime + period;
136: if (System.currentTimeMillis() >= nextExecutionTime) // Estamos ejecutando un evento cuando el siguiente debería de haberse ya producido, por tanto el siguiente se hará cuanto antes
137: computedPeriod = 0;
138: else
139: computedPeriod = period; // Vamos bien
140: }
141: return computedPeriod;
142: }
143: } else {
144: // timer periódico cancelado, no se ejecutará más
145: timer.removeListener(this );
146: return -1;
147: }
148: }
149:
150: public static String getTypeStatic() {
151: return "itsnat:timer";
152: }
153:
154: public String getType() {
155: return getTypeStatic();
156: }
157:
158: public UserDataImpl getUserData() {
159: if (userData == null)
160: this .userData = new UserDataImpl(); // Para ahorrar memoria si no se usa. No es necesario sincronizar pues el evento es manejado por un unico hilo
161: return userData;
162: }
163:
164: public boolean containsUserValueName(String name) {
165: return getUserData().containsName(name);
166: }
167:
168: public String[] getUserValueNames() {
169: return getUserData().getUserDataNames();
170: }
171:
172: public Object getUserValue(String name) {
173: return getUserData().getUserData(name);
174: }
175:
176: public Object setUserValue(String name, Object value) {
177: return getUserData().setUserData(name, value);
178: }
179:
180: public Object removeUserValue(String name) {
181: return getUserData().removeUserData(name);
182: }
183: }
|