Example usage for org.eclipse.jface.window Window setExceptionHandler

List of usage examples for org.eclipse.jface.window Window setExceptionHandler

Introduction

In this page you can find the example usage for org.eclipse.jface.window Window setExceptionHandler.

Prototype

public static void setExceptionHandler(IExceptionHandler handler) 

Source Link

Document

Sets the exception handler for this application.

Usage

From source file:com.AddressBookNew.java

License:Open Source License

public Shell open(Display display) throws Exception {
    prepareDataProvider();/*from ww  w.  j ava2 s  . c o m*/

    Window.setExceptionHandler(new Window.IExceptionHandler() {
        public void handleException(Throwable error) {
            MessageDialog.openError(null, "Error", "Error: Global Error Handler " + error.getMessage());
            LogClass.logger.error("error", error);
        }
    });

    shell = new Shell(display);
    FillLayout layout = new FillLayout();
    layout.type = SWT.VERTICAL;
    shell.setLayout(layout);

    if (checkLogin())
        shell.setText(Util.getString("firm.name") + "-"
                + Util.getString("welcome.message", loginUser.getNameSurname()));
    else {
        shell.dispose();
        return shell;
    }

    Composite cContent = new Composite(shell, SWT.NONE);
    cContent.setLayout(new GridLayout(1, false));

    Composite cMenu = new Composite(cContent, SWT.NONE);
    cMenu.setLayout(new FillLayout());
    cMenu.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    createToolBar(cMenu);
    cMenu.pack();
    this.getLoginUser();
    createMenuBar();

    cTabFolder = new BasicCTabFolder(cContent, SWT.BORDER);
    cTabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));

    cTabFolder.setSimple(false);
    cTabFolder.setUnselectedImageVisible(false);
    cTabFolder.setUnselectedCloseVisible(false);

    tabItemSearch = new SearchTabItem(cTabFolder, Util.getString("general.search"));
    tabItemBus = new BusTabItem(cTabFolder, Util.getString("bus.list"));
    tabItemDriver = new DriverTabItem(cTabFolder, Util.getString("driver.list"));
    tabItemHost = new HostTabItem(cTabFolder, Util.getString("host.list"));
    tabItemBusOwner = new BusOwnerTabItem(cTabFolder, Util.getString("busOwner.list"));
    tabItemMuavin = new MuavinTabItem(cTabFolder, Util.getString("muavin.list"));
    tabItemOutOffice = new OutOfficeTabItem(cTabFolder, Util.getString("outOffice.list"));
    tabItemServiceArea = new ServiceAreaTabItem(cTabFolder, Util.getString("serviceArea.list"));
    if (Util.isAdmin())
        tabItemUser = new UserTabItem(cTabFolder, Util.getString("user.list"));

    cTabFolder.forceFocus();
    cTabFolder.refreshAllTabItems();
    shell.open();
    return shell;
}

From source file:com.application.areca.launcher.gui.Application.java

License:Open Source License

public Application() {
    Window.setExceptionHandler(this);
}

From source file:de.uniluebeck.itm.spyglass.PluginSpyGlass2iShell.java

License:Open Source License

@Override
public int[] init() {
    // iShell init (called on each plug-in start)

    final CTabItem tabItem = getTabItem(getName());
    tabItem.setImage(IconTheme.lookup("system-search"));

    final Composite container = this.getTabContainer(true);
    container.setLayout(new FillLayout());

    try {//from  w w w .jav  a2 s  .co  m
        // create Model
        SpyglassEnvironment.setIShellPlugin(true);
        spyglass = new Spyglass();

        connectPacketBroker();

        // create view
        appWindow = new AppWindow(spyglass, container);

        // create Control
        UIController.connect(spyglass, appWindow);

        // add tooltip icons
        toolbarStuff = new ToolbarHandler(getCoolBar(), spyglass, appWindow);

        // Start Spyglass
        spyglass.start();

        factory = new PacketFactory(spyglass);

        // Set an exception handler which will handle uncaught exceptions
        Window.setExceptionHandler(new SpyglassExceptionHandler());

    } catch (final Exception e) {
        log.error("Could not initialize plugin \"Spyglass\" because of an very early error.", e);

        // remove spyglass tab
        this.removeTabItem();
        this.shutdown();
        return new int[] {};
    }

    log.info("Spyglass ready.");

    return new int[] { SPYGLASS_PACKET_TYPE };

}

From source file:de.uniluebeck.itm.spyglass.SpyglassApp.java

License:Open Source License

/**
 * The stand-alone application's entry point
 *
 * @param args an array of arguments/*from www .  jav a2 s  . co m*/
 */
public static void main(final String[] args) {

    tryToSetLoggingDefaults();

    log.debug("java.library.path=" + System.getProperty("java.library.path"));
    log.debug("java.class.path=" + System.getProperty("java.class.path"));

    // Set an exception handler which will handle uncaught exceptions
    Window.setExceptionHandler(new SpyglassExceptionHandler());

    if (ENABLE_SLEAK) {

        // create a customized Device. Since a Device is a singleton object
        // (at least with currently...) we don't have to save it. Newly created
        // Shells will use it automatically.
        final DeviceData data = new DeviceData();
        data.tracking = true;
        data.debug = true;
        new Display(data);

        // Open sleak
        final Sleak sleak = new Sleak();
        sleak.open();

    }

    SpyglassApp app = null;
    try {
        app = new SpyglassApp();
        app.addToolBar(SWT.None);
        app.addMenuBar();

        app.open();

    } catch (final Exception e) {
        log.error(e, e);
    } finally {
        if (app != null) {
            app.shutdown();
        }
    }

}

From source file:org.eclipse.buckminster.jnlp.Application.java

License:Open Source License

public Object start(IApplicationContext context) throws Exception {
    Object runArgs = context.getArguments().get(IApplicationContext.APPLICATION_ARGS);
    String errorCode = null;//from ww w  . j a v a  2  s . com

    try {
        String configUrl = null;
        Long popupAfter = null;

        if (runArgs instanceof String[]) {
            String[] args = (String[]) runArgs;
            for (int idx = 0; idx < args.length; ++idx) {
                String arg = args[idx];

                if ("-configURL".equals(arg)) //$NON-NLS-1$
                {
                    if (++idx < args.length) {
                        configUrl = args[idx];
                        if (configUrl != null) {
                            configUrl = configUrl.trim();
                            if (configUrl.length() == 0)
                                configUrl = null;
                        }
                    }
                } else if ("-syncString".equals(arg)) //$NON-NLS-1$
                {
                    if (++idx < args.length) {
                        m_syncString = args[idx];
                        if (m_syncString != null) {
                            m_syncString = m_syncString.trim();
                            if (m_syncString.length() == 0)
                                m_syncString = null;
                        }
                    }
                } else if ("-popupAfter".equals(arg)) //$NON-NLS-1$
                {
                    if (++idx < args.length) {
                        try {
                            popupAfter = Long.valueOf(args[idx]);
                        } catch (NumberFormatException e) {
                            // popupAfter remains null
                        }
                    }
                } else if (arg.startsWith("-") //$NON-NLS-1$
                        && (arg.endsWith(".proxyHost") || arg.endsWith(".proxyPort") || arg //$NON-NLS-1$ //$NON-NLS-2$
                                .endsWith(".nonProxyHosts"))) //$NON-NLS-1$
                {
                    if (++idx < args.length)
                        System.setProperty(arg.substring(1), args[idx]);
                }
            }
        }

        // We need to create a display first thing since many mechanisms
        // depend on its presence.
        //
        Display.setAppName("Materializer"); //$NON-NLS-1$
        Display display = Display.getDefault();

        HelpLinkErrorDialog.setSyncString(m_syncString);

        if (!Platform.getInstanceLocation().lock()) {
            errorCode = MaterializationConstants.ERROR_CODE_ALREADY_RUNNING_EXCEPTION;
            throw BuckminsterException.fromMessage(Messages.materializer_is_already_running);
        }

        BuckminsterPreferences.setLogLevelConsole(Logger.SILENT);
        BuckminsterPreferences.setLogLevelEclipseLogger(Logger.DEBUG);

        if (configUrl == null) {
            errorCode = ERROR_CODE_MISSING_ARGUMENT_EXCEPTION;
            throw BuckminsterException
                    .fromMessage(Messages.missing_required_argument_configURL_URL_to_config_properties);
        }

        Map<String, String> properties = new HashMap<String, String>();
        InputStream propStream = null;
        try {
            URL propertiesURL = new URL(configUrl);
            propStream = new BufferedInputStream(propertiesURL.openStream());
            Map<String, String> allProperties = new BMProperties(propStream);

            // Get rid of empty properties
            for (Map.Entry<String, String> entry : allProperties.entrySet()) {
                String value = entry.getValue();
                if (!(value == null || value.trim().length() == 0))
                    properties.put(entry.getKey(), value);
            }
        } catch (IOException e) {
            errorCode = ERROR_CODE_REMOTE_IO_EXCEPTION;
            throw BuckminsterException.fromMessage(e, Messages.can_not_read_materialization_information);
        } finally {
            IOUtils.close(propStream);
        }

        m_errorURL = properties.get(MaterializationConstants.PROP_ERROR_URL);
        if (m_errorURL == null)
            m_errorURL = MaterializationConstants.ERROR_HELP_URL;

        String errorMessage = properties.get(MaterializationConstants.PROP_ERROR_MESSAGE);

        if (errorMessage != null) {
            errorCode = MaterializationConstants.ERROR_CODE_404_EXCEPTION;
            throw BuckminsterException
                    .fromMessage(new String(Base64.decodeBase64(errorMessage.getBytes()), "UTF-8")); //$NON-NLS-1$
        }

        try {
            // Create the wizard dialog and resize it.
            //
            final InstallWizard installWizard = new InstallWizard(properties);
            m_errorURL = installWizard.getErrorURL();

            AdvancedWizardDialog dialog = new AdvancedWizardDialog(installWizard, ~SWT.APPLICATION_MODAL);
            dialog.create();

            // General exception handler
            Window.setExceptionHandler(new IExceptionHandler() {

                public void handleException(Throwable t) {
                    if (t instanceof ThreadDeath) {
                        // Don't catch ThreadDeath as this is a normal occurrence when
                        // the thread dies
                        throw (ThreadDeath) t;
                    }

                    IStatus status = BuckminsterException.wrap(t.getCause() != null ? t.getCause() : t)
                            .getStatus();
                    CorePlugin.logWarningsAndErrors(status);

                    if (t instanceof JNLPException) {
                        JNLPException je = (JNLPException) t;

                        HelpLinkErrorDialog.openError(null, installWizard.getWindowImage(),
                                MaterializationConstants.ERROR_WINDOW_TITLE, je.getMessage(),
                                MaterializationConstants.ERROR_HELP_TITLE, m_errorURL, je.getErrorCode(),
                                status);
                    } else {
                        HelpLinkErrorDialog.openError(null, installWizard.getWindowImage(),
                                MaterializationConstants.ERROR_WINDOW_TITLE, Messages.materializator_error,
                                MaterializationConstants.ERROR_HELP_TITLE, m_errorURL,
                                ERROR_CODE_RUNTIME_EXCEPTION, status);
                    }

                    // Try to keep running.
                }
            });

            final Shell shell = dialog.getShell();
            shell.setSize(Math.min(Math.max(WIZARD_MIN_WIDTH, shell.getSize().x), WIZARD_MAX_WIDTH),
                    Math.min(Math.max(WIZARD_MIN_HEIGHT, shell.getSize().y), WIZARD_MAX_HEIGHT));

            // when the shell is not started "ON TOP", it starts blinking
            shell.addShellListener(new ShellAdapter() {
                private int m_cnt = 0;

                @Override
                public void shellActivated(ShellEvent e) {
                    if (m_cnt == 0) {
                        Display.getDefault().asyncExec(new Runnable() {
                            public void run() {
                                shell.forceActive();
                            }
                        });

                        m_cnt++;
                    }
                }
            });

            try {
                if (popupAfter != null) {
                    long popupDelay = popupAfter.longValue() - (new Date()).getTime();
                    if (popupDelay > 0)
                        Thread.sleep(popupDelay);
                }

                synchronizeWithBootstrap();

                long popupDelay = DEFAULT_POPUP_DELAY;
                String popupDelayString = properties.get(MaterializationConstants.PROP_POPUP_DELAY);

                if (popupDelayString != null) {
                    try {
                        popupDelay = new Long(popupDelayString).longValue();
                    } catch (Throwable e) {
                        popupDelay = DEFAULT_POPUP_DELAY;
                    }
                }

                // need to wait a while until applet finishes
                Thread.sleep(popupDelay);

                dialog.open();
                return OK_EXIT_CODE;
            } catch (Throwable e) {
                errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
                final String finalErrorCode = errorCode;
                final IStatus status = BuckminsterException.wrap(e).getStatus();
                CorePlugin.logWarningsAndErrors(status);
                Display.getDefault().syncExec(new Runnable() {
                    public void run() {
                        HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE,
                                Messages.materialization_wizard_failed,
                                MaterializationConstants.ERROR_HELP_TITLE, m_errorURL, finalErrorCode, status);
                    }
                });
                return ERROR_EXIT_CODE;
            }
        } finally {
            display.dispose();
        }
    } catch (Throwable e) {
        e.printStackTrace();
        if (errorCode == null) {
            errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
        }
        final String finalErrorCode = errorCode;
        final IStatus status = BuckminsterException.wrap(e).getStatus();
        CorePlugin.logWarningsAndErrors(status);
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE,
                        Messages.materialization_cannot_be_started, MaterializationConstants.ERROR_HELP_TITLE,
                        m_errorURL, finalErrorCode, status);
            }
        });
        return ERROR_EXIT_CODE;
    }
}

From source file:org.eclipse.buckminster.jnlp.ide.IDEApplication.java

License:Open Source License

public void start(final String configUrl) throws Exception {

    try {/*from   www. jav a 2 s  .co  m*/
        if (configUrl == null || configUrl.length() < 1) {
            m_errorCode = ERROR_CODE_MISSING_ARGUMENT_EXCEPTION;
            throw BuckminsterException
                    .fromMessage(Messages.missing_required_argument_configUrl_URL_to_config_properties);
        }

        final Map<String, String> properties = new HashMap<String, String>();
        InputStream propStream = null;
        try {
            URL propertiesURL = new URL(configUrl);
            propStream = new BufferedInputStream(propertiesURL.openStream());
            Map<String, String> allProperties = new BMProperties(propStream);

            // Get rid of empty properties
            for (Map.Entry<String, String> entry : allProperties.entrySet()) {
                String value = entry.getValue();
                if (!(value == null || value.trim().length() == 0))
                    properties.put(entry.getKey(), value);
            }
        } catch (IOException e) {
            m_errorCode = ERROR_CODE_REMOTE_IO_EXCEPTION;
            setState(State.FAILED);
            throw BuckminsterException.fromMessage(e, Messages.can_not_read_materialization_information);
        } finally {
            IOUtils.close(propStream);
        }
        try {
            // Create the wizard dialog and resize it.
            //
            final InstallWizard installWizard = new InstallWizard(properties, true);
            m_errorURL = installWizard.getErrorURL();

            // The original started with a mask of SWT.APPLICATION_MODAL - and this changed the icon of
            // Eclipse to the icon of the dialog = a cloud. Looks much better if icon is unchanged.
            //
            AdvancedWizardDialog dialog = new AdvancedWizardDialog(installWizard, ~0); // SWT.APPLICATION_MODAL);
            dialog.create();

            // General exception handler
            Window.setExceptionHandler(new IExceptionHandler() {

                public void handleException(Throwable t) {
                    if (t instanceof ThreadDeath) {
                        // Don't catch ThreadDeath as this is a normal occurrence when
                        // the thread dies
                        throw (ThreadDeath) t;
                    }

                    IStatus status = BuckminsterException.wrap(t.getCause() != null ? t.getCause() : t)
                            .getStatus();
                    CorePlugin.logWarningsAndErrors(status);

                    if (t instanceof JNLPException) {
                        JNLPException je = (JNLPException) t;

                        HelpLinkErrorDialog.openError(null, installWizard.getWindowImage(),
                                MaterializationConstants.ERROR_WINDOW_TITLE, je.getMessage(),
                                MaterializationConstants.ERROR_HELP_TITLE, m_errorURL, je.getErrorCode(),
                                status);
                    } else {
                        HelpLinkErrorDialog.openError(null, installWizard.getWindowImage(),
                                MaterializationConstants.ERROR_WINDOW_TITLE, Messages.materializator_error,
                                MaterializationConstants.ERROR_HELP_TITLE, m_errorURL,
                                ERROR_CODE_RUNTIME_EXCEPTION, status);
                    }

                    // Try to keep running.
                }
            });

            final Shell shell = dialog.getShell();
            shell.setSize(Math.min(Math.max(WIZARD_MIN_WIDTH, shell.getSize().x), WIZARD_MAX_WIDTH),
                    Math.min(Math.max(WIZARD_MIN_HEIGHT, shell.getSize().y), WIZARD_MAX_HEIGHT));

            // when the shell is not started "ON TOP", it starts blinking
            shell.addShellListener(new ShellAdapter() {
                private int m_cnt = 0;

                @Override
                public void shellActivated(ShellEvent e) {
                    if (m_cnt == 0) {
                        Display.getDefault().asyncExec(new Runnable() {
                            public void run() {
                                shell.forceActive();
                            }
                        });

                        m_cnt++;
                    }
                }
            });

            try {
                setState(State.STARTED);
                dialog.open();
                return;
            } catch (Throwable e) {
                m_errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
                final String finalErrorCode = m_errorCode;
                final IStatus status = BuckminsterException.wrap(e).getStatus();
                CorePlugin.logWarningsAndErrors(status);
                Display.getDefault().syncExec(new Runnable() {
                    public void run() {
                        HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE,
                                Messages.materialization_wizard_failed,
                                MaterializationConstants.ERROR_HELP_TITLE, m_errorURL, finalErrorCode, status);
                    }
                });
                return;
            }
        } finally {
        }
        // }});

    } catch (Throwable e) {
        e.printStackTrace();
        if (m_errorCode == null) {
            m_errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
        }
        final String finalErrorCode = m_errorCode;
        final IStatus status = BuckminsterException.wrap(e).getStatus();
        CorePlugin.logWarningsAndErrors(status);
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE,
                        Messages.materialization_cannot_be_started, MaterializationConstants.ERROR_HELP_TITLE,
                        m_errorURL, finalErrorCode, status);
            }
        });
    }
}

From source file:org.eclipse.buckminster.jnlp.p2.Application.java

License:Open Source License

public Object start(IApplicationContext context) throws Exception {
    Object runArgs = context.getArguments().get(IApplicationContext.APPLICATION_ARGS);
    String errorCode = null;/*from   w  w w. j  ava 2  s .c o  m*/

    try {
        String configUrl = null;
        Long popupAfter = null;

        if (runArgs instanceof String[]) {
            String[] args = (String[]) runArgs;
            for (int idx = 0; idx < args.length; ++idx) {
                String arg = args[idx];

                if ("-configURL".equals(arg)) {
                    if (++idx < args.length) {
                        configUrl = args[idx];
                        if (configUrl != null) {
                            configUrl = configUrl.trim();
                            if (configUrl.length() == 0)
                                configUrl = null;
                        }
                    }
                } else if ("-syncString".equals(arg)) {
                    if (++idx < args.length) {
                        m_syncString = args[idx];
                        if (m_syncString != null) {
                            m_syncString = m_syncString.trim();
                            if (m_syncString.length() == 0)
                                m_syncString = null;
                        }
                    }
                } else if ("-popupAfter".equals(arg)) {
                    if (++idx < args.length) {
                        try {
                            popupAfter = Long.valueOf(args[idx]);
                        } catch (NumberFormatException e) {
                            // popupAfter remains null
                        }
                    }
                }
            }
        }

        // We need to create a display first thing since many mechanisms
        // depend on its presence.
        //
        Display.setAppName("Materializer");
        Display display = Display.getDefault();

        HelpLinkErrorDialog.setSyncString(m_syncString);

        if (!Platform.getInstanceLocation().lock()) {
            errorCode = MaterializationConstants.ERROR_CODE_ALREADY_RUNNING_EXCEPTION;
            throw BuckminsterException.fromMessage("Materializer is already running");
        }

        BuckminsterPreferences.setLogLevelConsole(Logger.SILENT);
        BuckminsterPreferences.setLogLevelEclipseLogger(Logger.DEBUG);

        if (configUrl == null) {
            errorCode = ERROR_CODE_MISSING_ARGUMENT_EXCEPTION;
            throw BuckminsterException
                    .fromMessage("Missing required argument -configURL <URL to config properties>");
        }

        Map<String, String> properties = new HashMap<String, String>();
        InputStream propStream = null;
        try {
            URL propertiesURL = new URL(configUrl);
            propStream = new BufferedInputStream(propertiesURL.openStream());
            Map<String, String> allProperties = new BMProperties(propStream);

            // Get rid of empty properties
            for (Map.Entry<String, String> entry : allProperties.entrySet()) {
                String value = entry.getValue();
                if (!(value == null || value.trim().length() == 0))
                    properties.put(entry.getKey(), value);
            }
        } catch (IOException e) {
            errorCode = ERROR_CODE_REMOTE_IO_EXCEPTION;
            throw BuckminsterException.fromMessage(e, "Can not read materialization information");
        } finally {
            IOUtils.close(propStream);
        }

        m_errorURL = properties.get(MaterializationConstants.PROP_ERROR_URL);
        if (m_errorURL == null)
            m_errorURL = MaterializationConstants.ERROR_HELP_URL;

        m_supportEmail = properties.get(MaterializationConstants.PROP_SUPPORT_EMAIL);

        String errorMessage = properties.get(MaterializationConstants.PROP_ERROR_MESSAGE);

        if (errorMessage != null) {
            errorCode = MaterializationConstants.ERROR_CODE_404_EXCEPTION;
            throw BuckminsterException
                    .fromMessage(new String(Base64.decodeBase64(errorMessage.getBytes()), "UTF-8")); //$NON-NLS-1$
        }

        try {
            // Create the wizard dialog and resize it.
            //
            final InstallWizard installWizard = new InstallWizard(properties);
            m_errorURL = installWizard.getErrorURL();

            AdvancedWizardDialog dialog = new AdvancedWizardDialog(installWizard, ~SWT.APPLICATION_MODAL);
            dialog.create();

            // General exception handler
            Window.setExceptionHandler(new IExceptionHandler() {

                public void handleException(Throwable t) {
                    if (t instanceof ThreadDeath) {
                        // Don't catch ThreadDeath as this is a normal occurrence when
                        // the thread dies
                        throw (ThreadDeath) t;
                    }

                    IStatus status = BuckminsterException.wrap(t.getCause() != null ? t.getCause() : t)
                            .getStatus();
                    CorePlugin.logWarningsAndErrors(status);

                    String localErrorCode;
                    String message;
                    boolean reportable;

                    if (t instanceof JNLPException) {
                        JNLPException e = (JNLPException) t;
                        localErrorCode = e.getErrorCode();
                        message = e.getMessage();
                        reportable = e.isReportable();
                    } else {
                        localErrorCode = ERROR_CODE_RUNTIME_EXCEPTION;
                        message = "An unexpected error occurred.\n\nThis could be because of intermittent network problems.";
                        reportable = true;
                    }

                    HelpLinkErrorDialog.openError(null, installWizard.getWindowImage(),
                            MaterializationConstants.ERROR_WINDOW_TITLE, message, status, localErrorCode,
                            reportable, m_supportEmail, "Materialization Error");
                }
            });

            final Shell shell = dialog.getShell();
            shell.setSize(Math.min(Math.max(WIZARD_MIN_WIDTH, shell.getSize().x), WIZARD_MAX_WIDTH),
                    Math.min(Math.max(WIZARD_MIN_HEIGHT, shell.getSize().y), WIZARD_MAX_HEIGHT));

            // when the shell is not started "ON TOP", it starts blinking
            shell.addShellListener(new ShellAdapter() {
                private int m_cnt = 0;

                @Override
                public void shellActivated(ShellEvent e) {
                    if (m_cnt == 0) {
                        Display.getDefault().asyncExec(new Runnable() {
                            public void run() {
                                shell.forceActive();
                            }
                        });

                        m_cnt++;
                    }
                }
            });

            try {
                if (popupAfter != null) {
                    long popupDelay = popupAfter.longValue() - (new Date()).getTime();
                    if (popupDelay > 0)
                        Thread.sleep(popupDelay);
                }

                synchronizeWithBootstrap();

                long popupDelay = DEFAULT_POPUP_DELAY;
                String popupDelayString = properties.get(MaterializationConstants.PROP_POPUP_DELAY);

                if (popupDelayString != null) {
                    try {
                        popupDelay = new Long(popupDelayString).longValue();
                    } catch (Throwable e) {
                        popupDelay = DEFAULT_POPUP_DELAY;
                    }
                }

                // need to wait a while until applet finishes
                Thread.sleep(popupDelay);

                dialog.open();
                return OK_EXIT_CODE;
            } catch (Throwable e) {
                errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
                final String finalErrorCode = errorCode;
                final IStatus status = BuckminsterException.wrap(e).getStatus();
                CorePlugin.logWarningsAndErrors(status);
                Display.getDefault().syncExec(new Runnable() {
                    public void run() {
                        HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE,
                                "Materialization wizard failed", status, finalErrorCode, true, m_supportEmail,
                                "Materialization Error");
                    }
                });
                return ERROR_EXIT_CODE;
            }
        } finally {
            display.dispose();
        }
    } catch (Throwable e) {
        e.printStackTrace();
        if (errorCode == null) {
            errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
        }
        final String finalErrorCode = errorCode;
        final IStatus status = BuckminsterException.wrap(e).getStatus();
        CorePlugin.logWarningsAndErrors(status);
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE,
                        "Materialization cannot be started", status, finalErrorCode, true, m_supportEmail,
                        "Materialization Error");
            }
        });
        return ERROR_EXIT_CODE;
    }
}

From source file:org.eclipse.buckminster.jnlp.p2.ide.IDEApplication.java

License:Open Source License

public void start(final String configUrl) throws Exception {

    try {/*  ww w . j a v a2s  . c  o  m*/
        if (configUrl == null || configUrl.length() < 1) {
            m_errorCode = ERROR_CODE_MISSING_ARGUMENT_EXCEPTION;
            throw BuckminsterException
                    .fromMessage("Missing required argument configUrl <URL to config properties>");
        }

        final Map<String, String> properties = new HashMap<String, String>();
        InputStream propStream = null;
        try {
            URL propertiesURL = new URL(configUrl);
            propStream = new BufferedInputStream(propertiesURL.openStream());
            Map<String, String> allProperties = new BMProperties(propStream);

            // Get rid of empty properties
            for (Map.Entry<String, String> entry : allProperties.entrySet()) {
                String value = entry.getValue();
                if (!(value == null || value.trim().length() == 0))
                    properties.put(entry.getKey(), value);
            }
        } catch (IOException e) {
            m_errorCode = ERROR_CODE_REMOTE_IO_EXCEPTION;
            setState(State.FAILED);
            throw BuckminsterException.fromMessage(e, "Can not read materialization information");
        } finally {
            IOUtils.close(propStream);
        }

        m_errorURL = properties.get(MaterializationConstants.PROP_ERROR_URL);
        if (m_errorURL == null)
            m_errorURL = MaterializationConstants.ERROR_HELP_URL;

        m_supportEmail = properties.get(MaterializationConstants.PROP_SUPPORT_EMAIL);

        try {
            // Create the wizard dialog and resize it.
            //
            final InstallWizard installWizard = new InstallWizard(properties, true);

            // The original started with a mask of SWT.APPLICATION_MODAL - and this changed the icon of
            // Eclipse to the icon of the dialog = a cloud. Looks much better if icon is unchanged.
            //
            AdvancedWizardDialog dialog = new AdvancedWizardDialog(installWizard, ~0); // SWT.APPLICATION_MODAL);
            dialog.create();

            // General exception handler
            Window.setExceptionHandler(new IExceptionHandler() {

                public void handleException(Throwable t) {
                    if (t instanceof ThreadDeath) {
                        // Don't catch ThreadDeath as this is a normal occurrence when
                        // the thread dies
                        throw (ThreadDeath) t;
                    }

                    IStatus status = BuckminsterException.wrap(t.getCause() != null ? t.getCause() : t)
                            .getStatus();
                    CorePlugin.logWarningsAndErrors(status);

                    String localErrorCode;
                    String message;
                    boolean reportable;

                    if (t instanceof JNLPException) {
                        JNLPException e = (JNLPException) t;
                        localErrorCode = e.getErrorCode();
                        message = e.getMessage();
                        reportable = e.isReportable();
                    } else {
                        localErrorCode = ERROR_CODE_RUNTIME_EXCEPTION;
                        message = "An unexpected error occurred.\n\nThis could be because of intermittent network problems.";
                        reportable = true;
                    }

                    HelpLinkErrorDialog.openError(null, installWizard.getWindowImage(),
                            MaterializationConstants.ERROR_WINDOW_TITLE, message, status, localErrorCode,
                            reportable, m_supportEmail, "Materialization Error");
                }
            });

            final Shell shell = dialog.getShell();
            shell.setSize(Math.min(Math.max(WIZARD_MIN_WIDTH, shell.getSize().x), WIZARD_MAX_WIDTH),
                    Math.min(Math.max(WIZARD_MIN_HEIGHT, shell.getSize().y), WIZARD_MAX_HEIGHT));

            // when the shell is not started "ON TOP", it starts blinking
            shell.addShellListener(new ShellAdapter() {
                private int m_cnt = 0;

                @Override
                public void shellActivated(ShellEvent e) {
                    if (m_cnt == 0) {
                        Display.getDefault().asyncExec(new Runnable() {
                            public void run() {
                                shell.forceActive();
                            }
                        });

                        m_cnt++;
                    }
                }
            });

            try {
                setState(State.STARTED);
                dialog.open();
                return;
            } catch (Throwable e) {
                m_errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
                final String finalErrorCode = m_errorCode;
                final IStatus status = BuckminsterException.wrap(e).getStatus();
                CorePlugin.logWarningsAndErrors(status);
                Display.getDefault().syncExec(new Runnable() {
                    public void run() {
                        HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE,
                                "Materialization wizard failed", status, finalErrorCode, true, m_supportEmail,
                                "Materialization Error");
                    }
                });
                return;
            }
        } finally {
        }
        // }});

    } catch (Throwable e) {
        e.printStackTrace();
        if (m_errorCode == null) {
            m_errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
        }
        final String finalErrorCode = m_errorCode;
        final IStatus status = BuckminsterException.wrap(e).getStatus();
        CorePlugin.logWarningsAndErrors(status);
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                HelpLinkErrorDialog.openError(null, null, MaterializationConstants.ERROR_WINDOW_TITLE,
                        "Materialization cannot be started", status, finalErrorCode, true, m_supportEmail,
                        "Materialization Error");
            }
        });
    }
}

From source file:org.eclipse.ui.internal.Workbench.java

License:Open Source License

/**
 * Internal method for running the workbench UI. This entails processing and
 * dispatching events until the workbench is closed or restarted.
 * //from w ww. j  a v a  2s.c om
 * @return return code {@link PlatformUI#RETURN_OK RETURN_OK}for normal
 *         exit; {@link PlatformUI#RETURN_RESTART RETURN_RESTART}if the
 *         workbench was terminated with a call to
 *         {@link IWorkbench#restart IWorkbench.restart};
 *         {@link PlatformUI#RETURN_UNSTARTABLE RETURN_UNSTARTABLE}if the
 *         workbench could not be started; other values reserved for future
 *         use
 * @since 3.0
 */
private int runUI() {
    UIStats.start(UIStats.START_WORKBENCH, "Workbench"); //$NON-NLS-1$

    // deadlock code
    boolean avoidDeadlock = true;

    String[] commandLineArgs = Platform.getCommandLineArgs();
    for (int i = 0; i < commandLineArgs.length; i++) {
        if (commandLineArgs[i].equalsIgnoreCase("-allowDeadlock")) { //$NON-NLS-1$
            avoidDeadlock = false;
        }
    }

    final UISynchronizer synchronizer;

    if (avoidDeadlock) {
        UILockListener uiLockListener = new UILockListener(display);
        Job.getJobManager().setLockListener(uiLockListener);
        synchronizer = new UISynchronizer(display, uiLockListener);
        display.setSynchronizer(synchronizer);
        // declare the main thread to be a startup thread.
        UISynchronizer.startupThread.set(Boolean.TRUE);
    } else
        synchronizer = null;

    // // prime the splash nice and early
    // if (createSplash)
    // createSplashWrapper();

    // ModalContext should not spin the event loop (there is no UI yet to
    // block)
    ModalContext.setAllowReadAndDispatch(false);

    // if the -debug command line argument is used and the event loop is
    // being
    // run while starting the Workbench, log a warning.
    if (WorkbenchPlugin.getDefault().isDebugging()) {
        display.asyncExec(new Runnable() {
            public void run() {
                if (isStarting()) {
                    WorkbenchPlugin.log(StatusUtil.newStatus(IStatus.WARNING,
                            "Event loop should not be run while the Workbench is starting.", //$NON-NLS-1$
                            new RuntimeException()));
                }
            }
        });
    }

    Listener closeListener = new Listener() {
        public void handleEvent(Event event) {
            event.doit = close();
        }
    };

    // Initialize an exception handler.
    Window.IExceptionHandler handler = ExceptionHandler.getInstance();

    try {
        // react to display close event by closing workbench nicely
        display.addListener(SWT.Close, closeListener);

        // install backstop to catch exceptions thrown out of event loop
        Window.setExceptionHandler(handler);

        final boolean[] initOK = new boolean[1];

        if (getSplash() != null) {

            final boolean[] initDone = new boolean[] { false };
            final Throwable[] error = new Throwable[1];
            Thread initThread = new Thread() {
                /*
                 * (non-Javadoc)
                 * 
                 * @see java.lang.Thread#run()
                 */
                public void run() {
                    try {
                        // declare us to be a startup thread so that our
                        // syncs will be executed
                        UISynchronizer.startupThread.set(Boolean.TRUE);
                        initOK[0] = Workbench.this.init();
                    } catch (Throwable e) {
                        error[0] = e;
                    } finally {
                        initDone[0] = true;
                        display.wake();
                    }
                }
            };
            initThread.start();
            while (true) {
                if (!display.readAndDispatch()) {
                    if (initDone[0])
                        break;
                    display.sleep();
                }
            }
            Throwable throwable = error[0];
            if (throwable != null) {
                if (throwable instanceof Error)
                    throw (Error) throwable;
                if (throwable instanceof Exception)
                    throw (Exception) throwable;

                // how very exotic - something that isn't playing by the
                // rules. Wrap it in an error and bail
                throw new Error(throwable);
            }
        } else {
            // initialize workbench and restore or open one window
            initOK[0] = init();

        }

        // let the advisor run its start up code
        if (initOK[0]) {
            advisor.postStartup(); // may trigger a close/restart
        }

        if (initOK[0] && runEventLoop) {
            workbenchService = WorkbenchPlugin.getDefault().getBundleContext()
                    .registerService(IWorkbench.class.getName(), this, null);
            Runnable earlyStartup = new Runnable() {
                public void run() {
                    // start eager plug-ins
                    startPlugins();
                    addStartupRegistryListener();
                }
            };
            e4Context.set(PartRenderingEngine.EARLY_STARTUP_HOOK, earlyStartup);
            // start workspace auto-save
            final int millisecondInterval = getAutoSaveJobTime();
            if (millisecondInterval > 0) {
                autoSaveJob = new WorkbenchJob("Workbench Auto-Save Job") { //$NON-NLS-1$
                    @Override
                    public IStatus runInUIThread(IProgressMonitor monitor) {
                        final int nextDelay = getAutoSaveJobTime();
                        persist(false);
                        monitor.done();
                        // repeat
                        if (nextDelay > 0) {
                            this.schedule(nextDelay);
                        }
                        return Status.OK_STATUS;
                    }
                };
                autoSaveJob.setSystem(true);
                autoSaveJob.schedule(millisecondInterval);
            }

            // WWinPluginAction.refreshActionList();

            display.asyncExec(new Runnable() {
                public void run() {
                    UIStats.end(UIStats.START_WORKBENCH, this, "Workbench"); //$NON-NLS-1$
                    UIStats.startupComplete();
                }
            });

            getWorkbenchTestable().init(display, this);

            // allow ModalContext to spin the event loop
            ModalContext.setAllowReadAndDispatch(true);
            isStarting = false;

            if (synchronizer != null)
                synchronizer.started();
            // the event loop
            // runEventLoop(handler, display);
        }
        returnCode = PlatformUI.RETURN_OK;
    } catch (final Exception e) {
        if (!display.isDisposed()) {
            handler.handleException(e);
        } else {
            String msg = "Exception in Workbench.runUI after display was disposed"; //$NON-NLS-1$
            WorkbenchPlugin.log(msg, new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, 1, msg, e));
        }
    }

    // restart or exit based on returnCode
    return returnCode;
}