KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > autoupdate > AutoChecker


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.autoupdate;
21
22 import java.util.*;
23 import java.util.logging.Level JavaDoc;
24 import java.util.logging.Logger JavaDoc;
25
26 import org.openide.util.NbBundle;
27 import javax.swing.SwingUtilities JavaDoc;
28 import org.openide.awt.StatusDisplayer;
29 import org.openide.util.RequestProcessor;
30
31 /** This class checks for updates in given period
32  *
33  * @author Petr Hrebejk, Jiri Rechtacek
34  */

35 public class AutoChecker extends Object JavaDoc
36             implements Runnable JavaDoc, Wizard.Validator {
37
38     /** Settings of autoupdate module */
39     private Settings settings;
40
41     /** Updates build by check */
42     private Updates updates;
43  
44     /** pairs AutoupdateType, Updates */
45     private HashMap allUpdates = new HashMap();
46     
47     // ==================================================================
48
// This part is temporary
49

50     static AutoChecker autoChecker;
51     private static final Logger JavaDoc err = Logger.getLogger("org.netbeans.modules.autoupdate"); // NOI18N
52

53     private RequestProcessor.Task regularlyCheck = null;
54     static final RequestProcessor REGULARLY_CHECK_TIMER =
55         new RequestProcessor("auto-checker-reqularly-timer", 1, true); // NOI18N
56

57     private boolean canceled = false;
58     
59     static void doCheck() {
60         autoChecker.run();
61     }
62
63     // ==================================================================
64

65
66     /** Creates new AutoChecker */
67     AutoChecker() {
68         settings = Settings.getShared();
69     }
70
71     /** Installs this class into update support in NetBeans 3.0 implementation */
72     void install() {
73         Autoupdater.installUpdateChecker( this );
74
75         // ==================================================================
76
// This part is temporary
77
autoChecker = this;
78         // ==================================================================
79

80     }
81     
82     // Implementation of UpdateSupport.UpdateChecker
83

84     public void run() {
85         canceled = false;
86         
87         // not need to check UC in AWT, issue 86286
88
if (SwingUtilities.isEventDispatchThread()) {
89             RequestProcessor.getDefault ().post(this);
90             return;
91         }
92
93         if (timeToCheck ()) {
94
95             if ( settings.isAskBefore() ) {
96                 AutoCheckInfo info = new AutoCheckInfo(
97                                          NbBundle.getMessage( AutoChecker.class, "MSG_AutoCheck_Before" ),
98                                          javax.swing.JOptionPane.INFORMATION_MESSAGE
99                                      );
100                 if (!info.showDialog(true)) {
101                     return;
102                 }
103             }
104
105             // init list of UC with new content
106
final List withNewContent;
107             if (Settings.EVERY_NEVER != settings.getPeriod ()) {
108                 withNewContent = getListWithNewContent ();
109             } else {
110                 withNewContent = Collections.EMPTY_LIST;
111             }
112
113             RequestProcessor.getDefault ().post (new Runnable JavaDoc () {
114                 public void run () {
115                     runInner (withNewContent);
116                 }
117             });
118
119         }
120     }
121     
122     private static List getListWithNewContent () {
123         List newContent = new ArrayList ();
124         err.log (Level.FINER, "getListWithNewContent() entry:"); // NOI18N
125
Enumeration en = AutoupdateType.autoupdateTypes ();
126         XMLAutoupdateType ut = null;
127         while (en.hasMoreElements ()) {
128             Object JavaDoc o = en.nextElement ();;
129             if (o instanceof XMLAutoupdateType) {
130                 ut = (XMLAutoupdateType) o;
131                 if (ut.isEnabled ()) {
132                     Boolean JavaDoc hasNew = ut.hasNewContent ();
133                     err.log (Level.FINER, "Has UT " + ut.getName () + " any new content? " + hasNew);
134                     if (hasNew == null || hasNew.booleanValue ()) {
135                         newContent.add (ut);
136                     }
137                 }
138             }
139         }
140         
141         if (ut == null) {
142             err.log (Level.FINER, "Warning: No appropriate Update Center found!"); // NOI18N
143
} else {
144             err.log (Level.FINER, "getListWithNewContent() exit. " + newContent.size () + " UCs have new content."); // NOI18N
145
}
146         
147         return newContent;
148     }
149     
150     void runInner (List withNewContent) {
151         assert withNewContent != null : "List UC with new content cannot be null!";
152         
153         //Autoupdater.setRunning( true );
154
Wizard.resetErrorStore ();
155
156         StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage( AutoChecker.class, "CTL_Checking_StatusText" ) ); // NOI18N
157

158         int countOfServer = 0, countOfConnectedServer = 0;
159         Iterator it = withNewContent.listIterator ();
160         while (it.hasNext ()) {
161             AutoupdateType at = (AutoupdateType) it.next ();
162             countOfServer++;
163             updates = at.connectForUpdates();
164             updates.checkUpdates( this, at, true );
165             int res = Wizard.checkConnect(updates, at);
166             if (res == ConnectingDialog.OK && (updates.getTimeStamp () == null || at.getLastTimeStamp () == null ||
167                        at.getLastTimeStamp ().before(updates.getTimeStamp ()))) {
168                 allUpdates.put(at, updates);
169                 countOfConnectedServer++;
170             } else if (res == ConnectingDialog.SKIP && Wizard.getStoredErrorType () == Updates.NO_AVAILABLE_MODULES) {
171                 countOfConnectedServer++;
172             }
173         }
174         
175         boolean success = true;
176         
177         if ( countOfConnectedServer == 0 ) {
178             //Autoupdater.setRunning( false );
179
StatusDisplayer.getDefault().setStatusText( "" ); // NOI18N
180
canceled = true;
181             if (Wizard.isErrorStored () && Updates.NO_NETWORK == Wizard.getStoredErrorType ()) {
182                 notifyError (Updates.NO_NETWORK);
183                 success = false;
184             } else if (countOfServer == 0) {
185                 // we can ignore the NO_SERVER_ERROR, an user knows why disabled all servers => don't force to enable some
186
//notifyError (Updates.NO_SERVER_ERROR);
187
} else if (settings.isNegativeResults ()) {
188                 notifyNoUpdatesFound ();
189             }
190             return;
191         }
192         
193         reportResults (success);
194     }
195
196     void reportResults (boolean success) {
197         //Autoupdater.setRunning( false );
198

199         StatusDisplayer.getDefault().setStatusText( "" );
200         
201         if (success) {
202             settings.setLastCheck (new Date ());
203         }
204         
205         if (canceled || ! success) {
206             return;
207         }
208
209         // First af all check wether the XML has changed
210
if ( allUpdates.size() == 0 ) {
211             // Report it if necessary
212
if ( settings.isNegativeResults() ) {
213                 notifyNoUpdatesFound ();
214             }
215             return;
216         }
217
218
219         if (getAllModules () != null && getAllModules ().size () > 0) {
220             notifyUpdates ();
221         } else if ( settings.isNegativeResults() ) {
222             // No modules found and we have to report negative results
223
notifyNoUpdatesFound ();
224         }
225         
226     }
227     
228     private void notifyUpdates () {
229         // Some modules found
230
Runnable JavaDoc onMouseClick = new Runnable JavaDoc () {
231             public void run () {
232                 Wizard.go( allUpdates );
233             }
234         };
235         AvailableUpdateVisualizerProvider.UpdatesFlasher flasher = AvailableUpdateVisualizerProvider.getFlasher (onMouseClick);
236         assert flasher != null : "Updates Flasher cannot be null.";
237         flasher.setToolTipText (NbBundle.getMessage (AutoChecker.class, "MSG_AutoCheck_Found_ToolTip"));
238         flasher.startFlashing();
239     }
240     
241     private void notifyNoUpdatesFound () {
242         // Some modules found
243
Runnable JavaDoc onMouseClick = new Runnable JavaDoc () {
244             public void run () {
245                 noUpdatesFound ();
246             }
247         };
248         ProblemsVisualizerProvider.UpdatesFlasher flasher = ProblemsVisualizerProvider.getFlasher (onMouseClick);
249         assert flasher != null : "Updates Flasher cannot be null.";
250         flasher.setToolTipText (NbBundle.getMessage (AutoChecker.class, "MSG_AutoCheck_Problem"));
251         flasher.startFlashing();
252     }
253     
254     private void notifyError (final int errorType) {
255         // Some modules found
256
Runnable JavaDoc onMouseClick = new Runnable JavaDoc () {
257             public void run () {
258                 ConnectingErrorDialog.showDialog (errorType, null, true);
259             }
260         };
261         ProblemsVisualizerProvider.UpdatesFlasher flasher = ProblemsVisualizerProvider.getFlasher (onMouseClick);
262         assert flasher != null : "Updates Flasher cannot be null.";
263         flasher.setToolTipText (NbBundle.getMessage (AutoChecker.class, "MSG_AutoCheck_Problem"));
264         flasher.startFlashing();
265     }
266     
267     private void noUpdatesFound () {
268         AutoCheckInfo info = new AutoCheckInfo(
269                                  NbBundle.getMessage( AutoChecker.class, "MSG_AutoCheck_NotFound" ),
270                                  javax.swing.JOptionPane.INFORMATION_MESSAGE
271                              );
272         info.showDialog(false);
273     }
274
275     private Collection getAllModules() {
276         Set ret = new HashSet();
277         Iterator it = allUpdates.values().iterator();
278         while (it.hasNext()) {
279             Collection c = ((Updates)it.next()).getModules();
280             if ( c != null )
281                 ret.addAll( c );
282         }
283         return ret;
284     }
285     
286     // Implementation of Wizard.Validator
287

288     /** This method gets the notification that the updates is ready */
289
290     public void setValid(boolean valid) {
291     }
292
293     // Utility methods --------------------------------------------------------
294

295     /** This method decides whether to perform the check or not
296     */

297     private boolean timeToCheck() {
298         if (getReqularlyTimerTask () != null) {
299             // if time is off then is time to check
300
if (getReqularlyTimerTask ().getDelay () <= 0 && getWaitPeriod () > 0) {
301                 // schedule next check
302
getReqularlyTimerTask ().schedule (getWaitPeriod ());
303                 return true;
304             }
305         }
306         
307         // If this is the first time always check
308
if ( settings.getLastCheck() == null ) {
309             return true;
310         }
311         
312         switch ( settings.getPeriod() ) {
313         case Settings.EVERY_STARTUP:
314             return true;
315         case Settings.EVERY_NEVER:
316             return false;
317         default:
318             Date lastCheck = settings.getLastCheck();
319             GregorianCalendar calendar = new GregorianCalendar();
320             calendar.setTime( lastCheck );
321
322             calendar.set( Calendar.HOUR, 0 );
323             calendar.set( Calendar.AM_PM, 0 );
324             calendar.set( Calendar.MINUTE, 0 );
325             calendar.set( Calendar.SECOND, 0 );
326             calendar.set( Calendar.MILLISECOND, 0 );
327             
328             switch ( settings.getPeriod() ) {
329             case Settings.EVERY_DAY:
330                 calendar.add( GregorianCalendar.DATE, 1 );
331                 break;
332             case Settings.EVERY_WEEK:
333                 calendar.add( GregorianCalendar.WEEK_OF_YEAR, 1 );
334                 break;
335             case Settings.EVERY_2WEEKS:
336                 calendar.add( GregorianCalendar.WEEK_OF_YEAR, 2 );
337                 break;
338             case Settings.EVERY_MONTH:
339                 calendar.add( GregorianCalendar.MONTH, 1 );
340                 break;
341             }
342             
343             return calendar.getTime().before( new Date() );
344
345         }
346     }
347     
348     private RequestProcessor.Task getReqularlyTimerTask () {
349         if (regularlyCheck == null) {
350             // only for ordinary periods
351
if (getWaitPeriod () > 0) {
352                 int waitPeriod = getWaitPeriod ();
353                 int restTime = waitPeriod;
354                 // calculate rest time to check
355
if (settings.getLastCheck () != null) {
356                     restTime = waitPeriod - (int)(System.currentTimeMillis () - settings.getLastCheck ().getTime ());
357                 }
358                 
359                 // if restTime < 0 then schedule next round by given period
360
if (restTime <= 0) {
361                     restTime = waitPeriod;
362                 }
363                 
364                 regularlyCheck = REGULARLY_CHECK_TIMER.post (this, restTime, Thread.MIN_PRIORITY);
365                 
366             }
367         }
368         return regularlyCheck;
369     }
370
371     private int getWaitPeriod () {
372         switch (settings.getPeriod ()) {
373             case Settings.EVERY_NEVER:
374                 return 0;
375             case Settings.EVERY_STARTUP:
376                 return 0;
377             case Settings.EVERY_DAY:
378                 return 1000 * 3600 * 24;
379             case Settings.EVERY_WEEK:
380                 return 1000 * 3600 * 24 * 7;
381             case Settings.EVERY_2WEEKS:
382                 return 1000 * 3600 * 24 * 14;
383             case Settings.EVERY_MONTH:
384                 return Integer.MAX_VALUE; // 1000 * 3600 * 24 * 28 is close but too big
385
default:
386                 return 0;
387         }
388     }
389     
390 }
391
Popular Tags