org.pegadi.client.ApplicationLauncher.java Source code

Java tutorial

Introduction

Here is the source code for org.pegadi.client.ApplicationLauncher.java

Source

/**
 * Copyright 1999-2009 The Pegadi Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.pegadi.client;

import no.dusken.common.model.Person;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.pegadi.games.tetris.Tetris;
import org.pegadi.lister.Lister;
import org.pegadi.maildialog.MailDialog;
import org.pegadi.model.LoginContext;
import org.pegadi.permissions.GlobalPermissions;
import org.pegadi.publicationcontrol.PublicationControl;
import org.pegadi.server.NoAccessException;
import org.pegadi.sources.Sources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.rmi.RMISecurityManager;
import java.security.*;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * Pegadi ApplicationLauncher. This is the first window the user sees, it
 * serves as a desktop and a portal.<br>
 * By default this class will log errors to ${user.home}/pegadi.log.
 *
 * @author Christian Waale Hansen <chrishan@stud.ntnu.no>
 */

public class ApplicationLauncher extends JFrame {

    protected static String PREF_DOMAIN = "General";

    protected static String PREF_LOCALE = "Locale";

    protected static String PREF_THEME = "Theme";

    private File logFile;

    // hardcoded default RMI hostname
    final static String hostString = "localhost";

    // hardcoded default RMI servername
    final static String nameString = "PegadiServer";

    // the actual name and host used for this setup
    static String usedHost;

    static String usedName;

    static String servername;

    static String host;

    BorderLayout borderLayout1 = new BorderLayout();

    JPanel jPanel1 = new JPanel();

    FlowLayout flowLayout1 = new FlowLayout();

    JButton listerButton = new JButton();

    JButton publicationButton = new JButton();

    JButton tetrisButton = new JButton();

    JButton sourcesButton = new JButton();

    static ResourceBundle str;

    // The application parameters fetched from file
    static ResourceBundle appStrings;

    JPanel jPanel2 = new JPanel();

    JButton logoutButton = new JButton();

    JButton quitButton = new JButton();

    JLabel usrlabel = new JLabel();

    Lister lis;

    PublicationControl pub;

    Tetris tet;

    Sources sources;

    protected JMenuBar menuBar = new JMenuBar();

    protected JMenu fileMenu = new JMenu();

    protected JMenu editMenu = new JMenu();

    protected JMenu helpMenu = new JMenu();

    protected JMenuItem prefsMenuItem = new JMenuItem();

    protected JMenuItem logoutMenuItem = new JMenuItem();

    protected JMenuItem quitMenuItem = new JMenuItem();

    protected JMenuItem listerMenuItem = new JMenuItem();

    protected JMenuItem tetrisMenuItem = new JMenuItem();

    protected JMenuItem sourcesMenuItem = new JMenuItem();

    AbstractAction reportBugAction;

    /**
     * User preferences.
     */
    protected Properties prefs;

    private final Logger log = LoggerFactory.getLogger(getClass());

    private LoginDialog loginDialog = new LoginDialog(this);
    private static String version;

    public ApplicationLauncher() {
        log.debug("Inside applicationlauncher constructor");
        try {
            str = ResourceBundle.getBundle("org.pegadi.client.ClientStrings");
            appStrings = ResourceBundle.getBundle("org.pegadi.client.ClientApp");

            ClientContext.includeUnstable = Boolean.valueOf(appStrings.getString("pegadi.includeunstable"));
            log.debug("UNSTABLE:" + ClientContext.includeUnstable);
            jbInit();
            setLocale("no_NO");

        } catch (Exception e) {
            log.error("Error initialising strings", e);
        }
        version = str.getString("version");
        setTitle(str.getString("app_title") + " " + version);

        registerOSXApplicationMenu();
    }

    /**
     * This method registers a listener for the Quit-menuitem on OS X application menu.
     * To avoid platform dependent compilation, reflection is utilized.
     * <p/>
     * Basically what happens, is this:
     * <p/>
     * Application app = Application.getApplication();
     * app.addApplicationListener(new ApplicationAdapter() {
     * public void handleQuit(ApplicationEvent e) {
     * e.setHandled(false);
     * conditionalExit();
     * }
     * });
     */
    private void registerOSXApplicationMenu() {

        try {
            ClassLoader cl = getClass().getClassLoader();

            // Create class-objects for the classes and interfaces we need
            final Class comAppleEawtApplicationClass = cl.loadClass("com.apple.eawt.Application");
            final Class comAppleEawtApplicationListenerInterface = cl
                    .loadClass("com.apple.eawt.ApplicationListener");
            final Class comAppleEawtApplicationEventClass = cl.loadClass("com.apple.eawt.ApplicationEvent");
            final Method applicationEventSetHandledMethod = comAppleEawtApplicationEventClass
                    .getMethod("setHandled", new Class[] { boolean.class });

            // Set up invocationhandler-object to recieve events from OS X application menu
            InvocationHandler handler = new InvocationHandler() {

                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("handleQuit")) {
                        applicationEventSetHandledMethod.invoke(args[0], new Object[] { Boolean.FALSE });
                        conditionalExit();
                    }
                    return null;
                }
            };

            // Create applicationlistener proxy
            Object applicationListenerProxy = Proxy.newProxyInstance(cl,
                    new Class[] { comAppleEawtApplicationListenerInterface }, handler);

            // Get a real Application-object
            Method applicationGetApplicationMethod = comAppleEawtApplicationClass.getMethod("getApplication",
                    new Class[0]);
            Object theApplicationObject = applicationGetApplicationMethod.invoke(null, new Object[0]);

            // Add the proxy application object as listener
            Method addApplicationListenerMethod = comAppleEawtApplicationClass.getMethod("addApplicationListener",
                    new Class[] { comAppleEawtApplicationListenerInterface });
            addApplicationListenerMethod.invoke(theApplicationObject, new Object[] { applicationListenerProxy });

        } catch (Exception e) {
            log.info("we are not on OSX");
        }
    }

    public static void main(String[] args) {
        com.sun.net.ssl.internal.ssl.Provider provider = new com.sun.net.ssl.internal.ssl.Provider();
        java.security.Security.addProvider(provider);
        setAllPermissions();
        /**
         * If we are on Apples operating system, we would like to use the screen
         * menu bar It is the first property we set in our main method. This is
         * to make sure that the property is set before awt is loaded.
         */
        if (System.getProperty("os.name").toLowerCase().startsWith("mac os x")) {
            System.setProperty("apple.laf.useScreenMenuBar", "true");
        }
        Logger log = LoggerFactory.getLogger(ApplicationLauncher.class);
        /**
         * Making sure default L&F is System
         */
        if (!UIManager.getLookAndFeel().getName().equals(UIManager.getSystemLookAndFeelClassName())) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                log.warn("Unable to change L&F to System", e);
            }
        }

        long start = System.currentTimeMillis();

        // Splash
        Splash splash = new Splash("/images/splash.png");
        splash.setVisible(true);

        splash.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "org/pegadi/client/client-context.xml");
        closeContextOnShutdown(context);

        long timeToLogin = System.currentTimeMillis() - start;
        log.info("Connected OK after {} ms", timeToLogin);
        log.info("Java Version {}", System.getProperty("java.version"));

        splash.dispose();
    }

    private static void closeContextOnShutdown(final ClassPathXmlApplicationContext context) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                context.close();
            }
        });
    }

    private static void setAllPermissions() {
        // give all permissions. needed when run from java web start, because
        // the rmi classloaders don't heed the security settings in the .jnlp
        // file.
        try {
            Policy.setPolicy(new Policy() {
                public PermissionCollection getPermissions(CodeSource codesource) {
                    Permissions perms = new Permissions();
                    perms.add(new AllPermission());
                    return (perms);
                }

                public void refresh() {
                }
            });
        } catch (Exception wse) {
            LoggerFactory.getLogger(ApplicationLauncher.class).error("Error setting policies", wse);
            System.exit(-1);
        }
    }

    private void jbInit() {
        ImageIcon icon = new ImageIcon(getClass().getResource("/images/pegadi.gif"));
        setIconImage(icon.getImage());

        this.getContentPane().setLayout(borderLayout1);
        jPanel1.setLayout(flowLayout1);
        listerButton.setEnabled(false);
        publicationButton.setEnabled(false);
        tetrisButton.setEnabled(false);

        // ImageIcon reportBugIcon = new
        // ImageIcon(getClass().getResource(appStrings.getString("icon_open")));

        reportBugAction = new AbstractAction(str.getString("menu_help_report")) {
            public void actionPerformed(ActionEvent e) {
                reportBug_actionPerformed(e);
            }
        };

        prefsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                prefsMenuItem_actionPerformed(e);
            }
        });

        listerMenuItem
                .setAccelerator(javax.swing.KeyStroke.getKeyStroke(76, java.awt.event.KeyEvent.CTRL_MASK, false));
        listerMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                listerButton_actionPerformed(e);
            }
        });

        sourcesMenuItem
                .setAccelerator(javax.swing.KeyStroke.getKeyStroke(73, java.awt.event.KeyEvent.CTRL_MASK, false));
        sourcesMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sourcesButton_actionPerformed();
            }
        });

        tetrisMenuItem
                .setAccelerator(javax.swing.KeyStroke.getKeyStroke(84, java.awt.event.KeyEvent.CTRL_MASK, false));
        tetrisMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tetrisButton_actionPerformed(e);
            }
        });

        logoutMenuItem
                .setAccelerator(javax.swing.KeyStroke.getKeyStroke(87, java.awt.event.KeyEvent.CTRL_MASK, false));
        logoutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                logoutMenuItem_actionPerformed(e);
            }
        });

        quitMenuItem
                .setAccelerator(javax.swing.KeyStroke.getKeyStroke(81, java.awt.event.KeyEvent.CTRL_MASK, false));
        quitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                quitMenuItem_actionPerformed(e);
            }
        });

        this.getContentPane().add(jPanel1, BorderLayout.NORTH);
        jPanel1.add(listerButton, null);

        listerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                listerButton_actionPerformed(e);
            }
        });

        publicationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                publicationButton_actionPerformed(e);
            }
        });

        sourcesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sourcesButton_actionPerformed();
            }
        });

        tetrisButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tetrisButton_actionPerformed(e);
            }
        });

        logoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                logoutButton_actionPerformed(e);
            }
        });

        quitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                quitButton_actionPerformed(e);
            }
        });

        jPanel1.add(publicationButton, null);
        jPanel1.add(sourcesButton, null);
        jPanel1.add(tetrisButton, null);
        this.getContentPane().add(jPanel2, BorderLayout.EAST);
        jPanel2.add(usrlabel, null);
        jPanel2.add(logoutButton, null);
        jPanel2.add(quitButton, null);
        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        menuBar.add(helpMenu);
        editMenu.add(prefsMenuItem);
        fileMenu.add(listerMenuItem);
        fileMenu.add(sourcesMenuItem);
        fileMenu.add(tetrisMenuItem);
        fileMenu.add(logoutMenuItem);
        fileMenu.add(quitMenuItem);
        helpMenu.add(reportBugAction);
        this.setJMenuBar(menuBar);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                conditionalExit();
            }
        });
        this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

    }

    /**
     * Load preferences from server and apply them.
     */
    protected void loadPrefs() {
        LoggerFactory.getLogger(getClass()).debug("Loading preferences");
        try {
            prefs = LoginContext.server.getPreferences(PREF_DOMAIN, LoginContext.sessionKey);
        } catch (Exception e) {
            log.warn("Exception getting preferences for domain {}", PREF_DOMAIN, e);
            prefs = new Properties();
        }

        String locale = prefs.getProperty(PREF_LOCALE);
        if (locale == null) {
            locale = "no_NO";
            prefs.put(PREF_LOCALE, locale);
        }

        setLocale(locale);

        String theme = prefs.getProperty(PREF_THEME);
        if (theme == null) {
            theme = "system";
            prefs.put(PREF_THEME, theme);
        }

        setTheme(theme);
    }

    protected void setLocale(String locale) {
        if (locale.equals("no_NO")) {
            Locale.setDefault(new Locale("no", "NO"));
        } else if (locale.equals("no_NO_NY")) {
            Locale.setDefault(new Locale("no", "NO", "NY"));
        } else if (locale.equals("en")) {
            Locale.setDefault(new Locale("en", "GB"));
        } else if (locale.equals("le")) {
            Locale.setDefault(new Locale("le", "XX"));
        } else {
            throw new IllegalArgumentException("'" + locale + "' is not a supported locale");
        }
        // TODO make resourcebundle read as utf-8 http://pegadi.underdusken.no/ticket/4           
        str = ResourceBundle.getBundle("org.pegadi.client.ClientStrings");

        listerButton.setText(str.getString("lister_button"));
        listerButton.setToolTipText(str.getString("tip_lister_button"));
        listerButton.setMnemonic(str.getString("lister_button").charAt(0));

        publicationButton.setText(str.getString("publication_button"));
        publicationButton.setToolTipText(str.getString("tip_publication_button"));

        sourcesButton.setText(str.getString("sources_button"));
        sourcesButton.setToolTipText(str.getString("tip_sources_button"));
        sourcesButton.setMnemonic(str.getString("sources_button").charAt(0));

        tetrisButton.setText(str.getString("tetris_button"));
        tetrisButton.setToolTipText(str.getString("tip_tetris_button"));
        tetrisButton.setMnemonic(str.getString("tetris_button").charAt(0));

        logoutButton.setText(str.getString("logout_button"));
        logoutButton.setToolTipText(str.getString("tip_logout_button"));

        quitButton.setText(str.getString("quit_button"));
        quitButton.setToolTipText(str.getString("tip_quit_button"));

        fileMenu.setMnemonic(str.getString("menu_program_mnem").charAt(0));
        fileMenu.setText(str.getString("menu_program"));

        editMenu.setMnemonic(str.getString("menu_edit_mnem").charAt(0));
        editMenu.setText(str.getString("menu_edit"));

        helpMenu.setMnemonic(str.getString("menu_help_mnem").charAt(0));
        helpMenu.setText(str.getString("menu_help"));

        prefsMenuItem.setText(str.getString("menu_edit_pref"));
        prefsMenuItem.setMnemonic(str.getString("menu_edit_pref_mnem").charAt(0));

        logoutMenuItem.setText(str.getString("menu_program_logout"));
        logoutMenuItem.setMnemonic(str.getString("menu_program_logout_mnem").charAt(0));

        quitMenuItem.setMnemonic(str.getString("menu_program_quit_mnem").charAt(0));
        quitMenuItem.setText(str.getString("menu_program_quit"));

        listerMenuItem.setText(str.getString("lister_button"));
        listerMenuItem.setMnemonic(str.getString("lister_button").charAt(0));
        tetrisMenuItem.setText(str.getString("tetris_button"));
        tetrisMenuItem.setMnemonic(str.getString("tetris_button").charAt(0));
        sourcesMenuItem.setText(str.getString("sources_button"));
        sourcesMenuItem.setMnemonic(str.getString("sources_button").charAt(0));

        reportBugAction.putValue(AbstractAction.NAME, str.getString("menu_help_report"));

        if (LoginContext.server != null) {
            try {

                setLoggedinUserLabel();
            } catch (Exception le) {
                log.error("Error getting real user name", le);
            }
        }

    }

    private void setLoggedinUserLabel() throws NoAccessException {
        String name = LoginContext.server
                .getUser(LoginContext.server.getUserID(LoginContext.sessionKey), LoginContext.sessionKey).getName();
        String userLabelText = String.format("%s : %s", str.getString("isLoggedOn"), name);
        usrlabel.setText(userLabelText);
    }

    protected void setTheme(String theme) {
        //TODO: fix nullpointerexception
        log.debug("theme: {}", theme);
        String lfTheme;
        if (theme.equalsIgnoreCase("system")) {
            lfTheme = UIManager.getSystemLookAndFeelClassName();
        } else if (theme.equalsIgnoreCase("swing")) {
            lfTheme = UIManager.getCrossPlatformLookAndFeelClassName();
            lfTheme = UIManager.getSystemLookAndFeelClassName();
        } else if (theme.equalsIgnoreCase("gtk")) {
            lfTheme = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
            //DEBUG
            lfTheme = UIManager.getSystemLookAndFeelClassName();
        } else {
            log.error("Invalid L&F theme");
            throw new IllegalArgumentException("'" + theme + "' is not a supported L&F");
        }

        if (!lfTheme.equals(UIManager.getLookAndFeel().getName())) {
            try {
                UIManager.setLookAndFeel(lfTheme);
            } catch (Exception e) {
                log.warn("Unable to set selected L&F, swapping to a default L&F");
                UIManager.LookAndFeelInfo[] installedLF = UIManager.getInstalledLookAndFeels();
                try {
                    UIManager.setLookAndFeel(installedLF[0].getClassName());
                } catch (Exception e2) {
                    log.error("Unable to load any L&F, exiting", e2);
                    System.exit(-1);
                }
            }
            try {
                log.debug("attempting to update componenttreeui");
                SwingUtilities.updateComponentTreeUI(this.getContentPane());
            } catch (Exception swe) {
                log.error("Unable to update component tree", swe);
            }
        }
        pack();
        //Might be the cause of occasional NullpointEx due to system
        //not being able to locate LookAndFeel
    }

    void sourcesButton_actionPerformed() {
        if (sources == null) {
            sources = new Sources();
        }
        sources.setLocationRelativeTo(this);
        sources.setVisible(true);

    }

    void listerButton_actionPerformed(ActionEvent e) {
        if (lis == null) {

            this.setCursor(new Cursor(Cursor.WAIT_CURSOR));

            lis = new Lister();

            lis.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    lis = null;
                }

                public void windowClosed(WindowEvent e) {
                    lis = null;
                }
            });

            // Set a reasonable size and center the window
            Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
            int x = Math.min(((size.width / 5) * 4), 810);
            int y = Math.min(((size.height / 5) * 4), 600);

            lis.setSize(x, y);
            lis.setLocation((size.width - x) / 2, (size.height - y) / 2);

            this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

            lis.setLocationRelativeTo(this);
        }
        lis.setVisible(true);
    }

    void publicationButton_actionPerformed(ActionEvent e) {
        if (pub == null) {

            this.setCursor(new Cursor(Cursor.WAIT_CURSOR));

            pub = new PublicationControl();

            pub.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    pub = null;
                }

                public void windowClosed(WindowEvent e) {
                    pub = null;
                }
            });

            pub.pack();

            this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

            pub.setLocationRelativeTo(this);
        }
        pub.setVisible(true);
    }

    void tetrisButton_actionPerformed(ActionEvent e) {
        if (tet == null) {

            this.setCursor(new Cursor(Cursor.WAIT_CURSOR));

            tet = new Tetris();

            tet.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    tet = null;
                }

                public void windowClosed(WindowEvent e) {
                    tet = null;
                }
            });

            tet.setSize(750, 550);
            tet.setLocationRelativeTo(this);

            this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
        tet.setVisible(true);
    }

    void logoutButton_actionPerformed(ActionEvent e) {
        relogin();
    }

    void quitButton_actionPerformed(ActionEvent e) {
        conditionalExit();
    }

    /**
     * Logs out the current user, and redies the system for a new user.
     */
    protected void relogin() {
        if (lis != null || pub != null || tet != null) {

            boolean choice = displayWarning();

            if (choice) {

                if (lis != null) {
                    lis.closeAllArtis();
                    lis.dispose();
                    lis = null;
                }
                if (pub != null) {
                    pub.dispose();
                    pub = null;
                }
                if (tet != null) {
                    tet.dispose();
                    tet = null;
                }

                try {
                    LoginContext.server.logout(LoginContext.sessionKey);
                } catch (Exception exc) {
                    log.error("Error logging out!", exc);
                }
                listerButton.setEnabled(false);
                tetrisButton.setEnabled(false);
                publicationButton.setEnabled(false);

                this.login();

            } // end choice-if
        } else {
            try {
                LoginContext.server.logout(LoginContext.sessionKey);
            } catch (Exception exc) {
                log.error("Error logging out!", exc);
            }

            this.hide();
            listerButton.setEnabled(false);
            tetrisButton.setEnabled(false);
            publicationButton.setEnabled(false);
            this.login();
        }
    }

    /**
     * Needs to be set public so that it can be called by OSX application
     * events.
     */
    public void conditionalExit() {
        if (lis != null || pub != null || tet != null) {
            boolean chump = displayWarning();

            if (chump) {
                if (lis != null)
                    lis.closeAllArtis();
                dispose();
            } else {
                // Cancel exit
                return;
            }
        }

        // Exit confirmed, log user out
        try {
            if (LoginContext.sessionKey != null) {
                LoginContext.server.logout(LoginContext.sessionKey);
            }
        } catch (Exception e) {
            log.error("Exception when logging out in preparation for exit.", e);
        }
        System.exit(0);
    }

    protected void login() {

        usrlabel.setText("");

        //LoginDialog loginDialog = new LoginDialog(this);
        String user = null;
        String pass = null;
        LoginContext.sessionKey = null;
        this.requestFocus();

        try {
            do {
                loginDialog.pack();
                loginDialog.requestFocus();
                Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
                Dimension dialog = loginDialog.getSize();
                loginDialog.setLocation((screen.width - dialog.width) / 2, (screen.height - dialog.height) / 2);
                loginDialog.setVisible(true);
                user = loginDialog.getUserName();
                pass = loginDialog.getPassword();
                loginDialog.deletePassword();
                LoginContext.server = loginDialog.getServer();

                log.info("Trying to log in...");
                LoginContext.sessionKey = LoginContext.server.login(user, pass);
                log.info("Got sessionkey {}", LoginContext.sessionKey);
            } while (LoginContext.sessionKey == null);

            loginDialog.loginSuccessful();

        } catch (Exception ce) {
            JOptionPane.showMessageDialog(this, str.getString("server_down_text"),
                    str.getString("server_down_title"), JOptionPane.WARNING_MESSAGE);
            log.error("Cannot connect to server", ce);
            System.exit(-1);
        }

        boolean isGod = false;
        try {
            log.debug("Checking isGod?");
            isGod = LoginContext.server.hasGlobalPermission(LoginContext.server.getUserID(LoginContext.sessionKey),
                    GlobalPermissions.LEGACY_IS_GOD, LoginContext.sessionKey);

            log.debug("Is God? {}", isGod);
        } catch (Exception e) {
            log.error("error checking users privileges", e);
        }

        // running developer mode?
        isGod |= "true".equals(System.getProperty("developerMode"));

        listerButton.setEnabled(true);
        if (isGod) {
            publicationButton.setEnabled(true);
        } else {
            publicationButton.setEnabled(false);
        }
        tetrisButton.setEnabled(true);
        try {
            setLoggedinUserLabel();
        } catch (Exception le) {
            log.error("Error getting real name for user", le);
        }

        this.setVisible(true);

        loadPrefs();
        String url = null;

        try {
            url = LoginContext.server.getWebBase(LoginContext.sessionKey);
        } catch (Exception e) {
            log.error("Error getting webbase", e);
        }

        log.info("Webxml is: " + url);
        webLogin(url, user, pass);

        try {
            GetMethod get = new GetMethod(url + "/protected/");

            LoginContext.httpClient.executeMethod(get);
            log.info("HTTP Status for /protected is: " + get.getStatusCode());
        } catch (Exception e) {
            log.error("Error loggin in on web", e);
        }
    }

    public boolean webLogin(String url, String user, String pass) {
        log.info("Weblogin with url {}", url);
        PostMethod post = new PostMethod(url + "j_security_check");
        post.addParameter(new NameValuePair("j_username", user));
        post.addParameter(new NameValuePair("j_password", pass));

        try {
            LoginContext.httpClient.executeMethod(post);

        } catch (IOException e) {
            log.error("Error executing method for weblogin", e);
            return false;
        }

        return true;
    }

    protected boolean displayWarning() {
        // JOptionPane warning = new JoptionPane();
        int warning = JOptionPane.showConfirmDialog(this, str.getString("want_to_exit"),
                str.getString("running_applications"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);

        if (warning == JOptionPane.YES_OPTION) {
            return true;
        } else {
            log.info("logout/quit cancelled by user");
            return false;
        } // end if

    }

    void logoutMenuItem_actionPerformed(ActionEvent e) {
        relogin();
    }

    void quitMenuItem_actionPerformed(ActionEvent e) {
        conditionalExit();
    }

    void prefsMenuItem_actionPerformed(ActionEvent e) {
        PreferencesDialog d = new PreferencesDialog(this, prefs);
        d.setLocationRelativeTo(this);
        d.setVisible(true);
        if (d.okResult()) {
            Properties changed = d.getChangedPreferences();

            Enumeration en = changed.keys();
            while (en.hasMoreElements()) {
                String pkey = en.nextElement().toString();
                String pvalue = changed.getProperty(pkey);
                prefs.put(pkey, pvalue);
                try {
                    LoginContext.server.savePreference(PREF_DOMAIN, pkey, pvalue, LoginContext.sessionKey);
                } catch (Exception ex) {
                    log.error("Can't save preference '{}' with value '{}'", new Object[] { pkey, pvalue, ex });
                }

                if (pkey.equals(PREF_LOCALE)) {
                    setLocale(pvalue);
                    pack();
                } else if (pkey.equals(PREF_THEME)) {
                    setTheme(pvalue);
                }
            }
        }
    }

    public void reportBug_actionPerformed(ActionEvent e) {

        String[] replaceWith = new String[12];

        try {
            Person u = LoginContext.server.getSessionUser(LoginContext.sessionKey);

            replaceWith[0] = u.getName();
            replaceWith[1] = u.getEmailAddress();
        } catch (java.rmi.RemoteException re) {
            log.error("Could not get user data from server");
        }

        try {
            replaceWith[2] = java.net.InetAddress.getLocalHost().getHostName();
            replaceWith[3] = java.net.InetAddress.getLocalHost().getHostAddress();
        } catch (java.net.UnknownHostException uhe) {
            log.error("Could not get local hostname", uhe);
            replaceWith[2] = "Unknown host";
            replaceWith[3] = "Unknown host address";
        } catch (java.lang.SecurityException se) {
            log.error("Could not connect to server", se);
            replaceWith[2] = "Unknown host";
            replaceWith[3] = "Unknown host address";
        }

        Properties p;

        try {
            p = System.getProperties();
        } catch (SecurityException se) {
            p = null;
        }

        if (p == null) {
            for (int i = 4; i <= 9; i++)
                replaceWith[i] = "Not disclosed";
        } else {
            replaceWith[4] = p.getProperty("os.name");
            replaceWith[5] = p.getProperty("os.arch");
            replaceWith[6] = p.getProperty("os.version");
            replaceWith[7] = p.getProperty("java.vm.name");
            replaceWith[8] = p.getProperty("java.vm.vendor");
            replaceWith[9] = p.getProperty("java.vm.version");
            replaceWith[10] = ApplicationLauncher.getVersion();
        }

        replaceWith[11] = getLog();

        String url;

        try {
            url = LoginContext.server.getWebXMLRoot(LoginContext.sessionKey);
            url += "/templates/bugreport.template";
        } catch (java.rmi.RemoteException re) {
            log.error("Error getting webxmlroot", re);
            return;
        }

        MailDialog dialog = new MailDialog(this, "", false);
        dialog.loadTemplate(url, replaceWith);
        dialog.setFromFieldEditable(false);
        dialog.setToFieldEditable(false);

        dialog.setTitle(str.getString("menu_help_report"));
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }

    private String getLog() {
        if (logFile == null) {
            log.error("No log file set");
            return "";
        }
        try {
            return IOUtils.toString(new FileReader(logFile));
        } catch (IOException e) {
            log.error("Failed reading log file");
            return "No log file";
        }
    }

    /**
     * @param loginDialog The loginDialog to set.
     */
    public void setLoginDialog(LoginDialog loginDialog) {
        this.loginDialog = loginDialog;
    }

    public static String getVersion() {
        return version;
    }

    public void setLogFile(File logFile) {
        this.logFile = logFile;
    }
}