alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2004 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.modules.autoupdate;

import java.util.*;
import java.text.SimpleDateFormat;

import org.openide.util.NbBundle;
import javax.swing.SwingUtilities;
import org.openide.awt.StatusDisplayer;

import org.openide.filesystems.*;
import java.io.*;

/** This class checks for updates in given period
 *
 * @author  Petr Hrebejk
 */
class AutoChecker extends Object
            implements Runnable,
    Wizard.Validator {
        
    /** Settings of autoupdate module */
    private Settings settings;

    /** Updates build by check */
    private Updates updates;

    /** pairs AutoupdateType, Updates */
    private HashMap allUpdates = new HashMap();
    
    private static final Random RANDOM = new Random ();

    // ==================================================================
    // This part is temporary

    static AutoChecker autoChecker;
    
    private boolean canceled = false;
    
    static void doCheck() {
        autoChecker.run();
    }

    // ==================================================================


    /** Creates new AutoChecker */
    AutoChecker() {
        settings = Settings.getShared();
    }

    /** Installs this class into update support in NetBeans 3.0 implementation */
    void install() {
        Autoupdater.installUpdateChecker( this );

        // ==================================================================
        // This part is temporary
        autoChecker = this;
        // ==================================================================

    }


    // Implementation of UpdateSupport.UpdateChecker

    public void run() {
        // generate ide identity if needed
        if (!(settings.getIdeIdentity () instanceof String)) {
            int id = RANDOM.nextInt ();
            if (id < 0)
                id = - (id + 1);
            String prefix = "";
            try {
                FileObject fo = Repository.getDefault().getDefaultFileSystem().findResource("/productid"); // NOI18N
                if (fo != null) {
                    InputStream is = fo.getInputStream();
                    try {
                        BufferedReader r = new BufferedReader(new InputStreamReader(is));
                        prefix = r.readLine().trim();
                    } finally {
                        is.close();
                    }
                }
            } catch (IOException ignore) {
                // IGNORE
            }            
                
            settings.setIdeIdentity (prefix + Integer.toString (id));
        }
        
        // XXX needs to be in event thread, right?
        if (! SwingUtilities.isEventDispatchThread()) {
            SwingUtilities.invokeLater(this);
            return;
        }

        if ( !timeToCheck() ) {
            return;
        }
        
        // Even if the user anwers no we did our work
        settings.setLastCheck( new Date() );
        
        if ( settings.isAskBefore() ) {
            AutoCheckInfo info = new AutoCheckInfo(
                                     NbBundle.getMessage( AutoChecker.class, "MSG_AutoCheck_Before" ),
                                     javax.swing.JOptionPane.INFORMATION_MESSAGE
                                 );
            if (!info.showDialog(true)) {
                return;
            }
        }

        Autoupdater.setRunning( true );
        Wizard.resetErrorStore ();

        StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage( AutoChecker.class, "CTL_Checking_StatusText" ) );
            
        Enumeration en = AutoupdateType.autoupdateTypes();
        int countOfServer = 0, countOfConnectedServer = 0;
        while (en.hasMoreElements()) {
            AutoupdateType at = (AutoupdateType)en.nextElement();
            if (at.isEnabled()) {
                countOfServer++;
                updates = at.connectForUpdates();
                updates.checkUpdates( this, at );
                int res = Wizard.checkConnect(updates, at);
                if ( res == ConnectingDialog.OK && 
                        (updates.getTimeStamp() == null || at.getLastTimeStamp() == null ||
                           at.getLastTimeStamp().before(updates.getTimeStamp()))) {
                    allUpdates.put(at, updates);
                    countOfConnectedServer++;
                } else if ( res == ConnectingDialog.CANCEL ) {
                    Autoupdater.setRunning( false );
                    StatusDisplayer.getDefault().setStatusText( "" );
                    return;                                
                }
            }
        }
        
        if ( countOfConnectedServer == 0 ) {
            if (Wizard.isErrorStored () && Updates.NO_NETWORK == Wizard.getStoredErrorType ()) {
                ConnectingErrorDialog.showDialog (Updates.NO_NETWORK, null);
            } else if (countOfServer == 0) {
                ConnectingErrorDialog.showDialog(Updates.NO_SERVER_ERROR, null);
            }
            canceled = true;
            Autoupdater.setRunning( false );
            StatusDisplayer.getDefault().setStatusText( "" );
            return;
        }
        
        // report results after checking
        Runnable runnable = new Runnable ( ) {
                                public void run() {
                                    reportResults();
                                }
                            };

        javax.swing.SwingUtilities.invokeLater( runnable );
        
    }

    void reportResults() {
        Autoupdater.setRunning( false );

        StatusDisplayer.getDefault().setStatusText( "" );
        
        if (canceled)
            return;

        // First af all check wether the XML has changed
        if ( allUpdates.size() == 0 ) {
            // Report it if necessary
            if ( settings.isNegativeResults() ) {
                AutoCheckInfo info = new AutoCheckInfo(
                                         NbBundle.getMessage( AutoChecker.class, "MSG_AutoCheck_NotFound" ),
                                         javax.swing.JOptionPane.INFORMATION_MESSAGE
                                     );
                info.showDialog(false);
            }
            return;
        }


        if ( getAllModules() != null &&
                getAllModules().size() > 0 ) {
                    
            // Some modules found
                    
            // by the task #39533, user has to be informed about modules found
            // Check was fully automatic inform the user about found modules
            // and ask him whether to proceed to the wizard.
            AutoCheckInfo info = new AutoCheckInfo(
                                     NbBundle.getMessage( AutoChecker.class, "MSG_AutoCheck_Found" ),
                                     javax.swing.JOptionPane.INFORMATION_MESSAGE
                                 );

            if (info.showDialog(true)) {
                Wizard.go( allUpdates );
            }
        } else if ( settings.isNegativeResults() ) {
            // No modules found and we have to report negative results
            AutoCheckInfo info = new AutoCheckInfo(
                                     NbBundle.getMessage( AutoChecker.class, "MSG_AutoCheck_NotFound" ),
                                     javax.swing.JOptionPane.INFORMATION_MESSAGE
                                 );
            info.showDialog(false);
        }

    }

    private Collection getAllModules() {
        Set ret = new HashSet();
        Iterator it = allUpdates.values().iterator();
        while (it.hasNext()) {
            Collection c = ((Updates)it.next()).getModules();
            if ( c != null )
                ret.addAll( c );
        }
        return ret;
    }
    
    // Implementation of Wizard.Validator

    /** This method gets the notification that the updates is ready */

    public void setValid(boolean valid) {
    }

    // Utility methods --------------------------------------------------------

    /** This method decides whether to perform the check or not
    */
    private boolean timeToCheck() {

        // If this is the first time always check
        if ( settings.getLastCheck() == null ) {
            settings.setLastCheck( new Date() );
            return false;
        }

        switch ( settings.getPeriod() ) {
        case Settings.EVERY_STARTUP:
            return true;
        case Settings.EVERY_NEVER:
            return false;
        default:
            Date lastCheck = settings.getLastCheck();
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime( lastCheck );

            calendar.set( Calendar.HOUR, 0 );
            calendar.set( Calendar.AM_PM, 0 );
            calendar.set( Calendar.MINUTE, 0 );
            calendar.set( Calendar.SECOND, 0 );
            calendar.set( Calendar.MILLISECOND, 0 );
            
            switch ( settings.getPeriod() ) {
            case Settings.EVERY_DAY:
                calendar.add( GregorianCalendar.DATE, 1 );
                break;
            case Settings.EVERY_WEEK:
                calendar.add( GregorianCalendar.WEEK_OF_YEAR, 1 );
                break;
            case Settings.EVERY_2WEEKS:
                calendar.add( GregorianCalendar.WEEK_OF_YEAR, 2 );
                break;
            case Settings.EVERY_MONTH:
                calendar.add( GregorianCalendar.MONTH, 1 );
                break;
            }

            SimpleDateFormat sdf = new SimpleDateFormat();

            return calendar.getTime().before( new Date() );

        }
    }
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.