net.openchrom.chromatogram.msd.process.supplier.jython.ui.Activator.java Source code

Java tutorial

Introduction

Here is the source code for net.openchrom.chromatogram.msd.process.supplier.jython.ui.Activator.java

Source

/*******************************************************************************
 * Copyright (c) 2015, 2017 Lablicate GmbH.
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 * Dr. Philip Wenig - initial API and implementation
 *******************************************************************************/
package net.openchrom.chromatogram.msd.process.supplier.jython.ui;

import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipFile;

import org.eclipse.chemclipse.support.ui.activator.AbstractActivatorUI;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.swt.widgets.Shell;
import org.osgi.framework.BundleContext;
import org.python.copiedfromeclipsesrc.JDTNotAvailableException;
import org.python.pydev.core.IInterpreterManager;
import org.python.pydev.plugin.PydevPlugin;
import org.python.pydev.runners.SimpleJythonRunner;
import org.python.pydev.shared_core.string.StringUtils;
import org.python.pydev.shared_core.structure.Tuple;
import org.python.pydev.shared_ui.utils.AsynchronousProgressMonitorDialog;
import org.python.pydev.ui.dialogs.PyDialogHelpers;
import org.python.pydev.ui.filetypes.FileTypesPreferencesPage;
import org.python.pydev.ui.pythonpathconf.ObtainInterpreterInfoOperation;

import net.openchrom.chromatogram.msd.process.supplier.jython.preferences.PreferenceSupplier;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractActivatorUI {

    public static final String ERMSG_NOLIBS = "The interpreter's standard libraries (typically in a Lib/ folder) are missing: ";
    public static final String CHECK_PREFERRED_PYDEV_SETTINGS = "CHECK_PREFERRED_PYDEV_SETTINGS";
    /*
     * Instance
     */
    private static Activator plugin;

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
     */
    public void start(BundleContext context) throws Exception {

        super.start(context);
        plugin = this;
        setSettingsForPyDev();
        initializePreferenceStore(PreferenceSupplier.INSTANCE());
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
     */
    public void stop(BundleContext context) throws Exception {

        plugin = null;
        super.stop(context);
    }

    private void setSettingsForPyDev() {

        // check in org.python.pydev.plugin.preferences.CheckDefaultPreferencesDialog whether other stuff also needs to be changed
        // check stuff around org.python.pydev.ui.pythonpathconf.JythonInterpreterEditor and org.python.pydev.ui.pythonpathconf.JythonInterpreterProviderFactory
        System.setProperty("pydev.funding.hide", "1");
        PydevPlugin.getDefault().getPreferenceStore().setValue(CHECK_PREFERRED_PYDEV_SETTINGS, false);
        // to test this part, comment it out for a release
        // String jythonPath = net.openchrom.thirdpartylibraries.jython.Activator.getJythonPath();
        // Tuple<String, String> jythonPathTuple = new Tuple<String, String>("Integrated Jython interpreter", jythonPath);
        // CharArrayWriter charWriter = new CharArrayWriter();
        // PrintWriter logger = new PrintWriter(charWriter);
        // try {
        // IInterpreterManager interpreterManager = new JythonEclipseInterpreterManager();
        // Shell shell = new Shell();
        // ObtainInterpreterInfoOperation operation = tryInterpreter(jythonPathTuple, interpreterManager, true, true, logger, shell);
        // } catch(Exception e) {
        // e.printStackTrace(logger);
        // }
    }

    @SuppressWarnings("unused")
    private ObtainInterpreterInfoOperation tryInterpreter(Tuple<String, String> interpreterNameAndExecutable,
            IInterpreterManager interpreterManager, boolean autoSelectFolders, boolean displayErrors,
            PrintWriter logger, Shell shell) throws Exception {

        String executable = interpreterNameAndExecutable.o2;
        logger.println("- Ok, file is non-null. Getting info on:" + executable);
        ProgressMonitorDialog monitorDialog = new AsynchronousProgressMonitorDialog(shell);
        monitorDialog.setBlockOnOpen(false);
        ObtainInterpreterInfoOperation operation;
        while (true) {
            operation = new ObtainInterpreterInfoOperation(interpreterNameAndExecutable.o2, logger,
                    interpreterManager, autoSelectFolders);
            monitorDialog.run(true, false, operation);
            if (operation.e != null) {
                logger.println("- Some error happened while getting info on the interpreter:");
                operation.e.printStackTrace(logger);
                String errorTitle = "Unable to get info on the interpreter: " + executable;
                if (operation.e instanceof SimpleJythonRunner.JavaNotConfiguredException) {
                    SimpleJythonRunner.JavaNotConfiguredException javaNotConfiguredException = (SimpleJythonRunner.JavaNotConfiguredException) operation.e;
                    if (displayErrors) {
                        ErrorDialog.openError(shell, errorTitle, javaNotConfiguredException.getMessage(),
                                PydevPlugin.makeStatus(IStatus.ERROR, "Java vm not configured.\n",
                                        javaNotConfiguredException));
                    }
                    throw new Exception(javaNotConfiguredException);
                } else if (operation.e instanceof JDTNotAvailableException) {
                    JDTNotAvailableException noJdtException = (JDTNotAvailableException) operation.e;
                    if (displayErrors) {
                        ErrorDialog.openError(shell, errorTitle, noJdtException.getMessage(),
                                PydevPlugin.makeStatus(IStatus.ERROR, "JDT not available.\n", noJdtException));
                    }
                    throw new Exception(noJdtException);
                } else {
                    if (displayErrors) {
                        // show the user a message (so that it does not fail silently)...
                        String errorMsg = "Unable to get info on the interpreter: " + executable + "\n\n"
                                + "Common reasons include:\n\n" + "- Using an unsupported version\n"
                                + "  (Python and Jython require at least version 2.1 and IronPython 2.6).\n" + "\n"
                                + "- Specifying an invalid interpreter\n"
                                + "  (usually a link to the actual interpreter on Mac or Linux)" + "";
                        ErrorDialog.openError(shell, errorTitle, errorMsg,
                                PydevPlugin.makeStatus(IStatus.ERROR, "See error log for details.", operation.e));
                    }
                    throw new Exception(operation.e);
                }
            } else if (operation.result == null) {
                // Folder selection was canceled, exit
                return null;
            }
            // Ok, we got the result, so, let's check if things are correct (i.e.: do we have threading.py, traceback.py?)
            HashSet<String> hashSet = new HashSet<String>();
            hashSet.add("threading");
            hashSet.add("traceback");
            String[] validSourceFiles = FileTypesPreferencesPage.getValidSourceFiles();
            Set<String> extensions = new HashSet<String>(Arrays.asList(validSourceFiles));
            for (String s : operation.result.libs) {
                File file = new File(s);
                if (file.isDirectory()) {
                    String[] directoryFiles = file.list();
                    if (directoryFiles != null) {
                        for (String found : directoryFiles) {
                            List<String> split = StringUtils.split(found, '.');
                            if (split.size() == 2) {
                                if (extensions.contains(split.get(1))) {
                                    hashSet.remove(split.get(0));
                                }
                            }
                        }
                    } else {
                        logger.append("Warning: unable to get contents of directory: " + file
                                + " (permission not available, it's not a dir or dir does not exist).");
                    }
                } else if (file.isFile()) {
                    // Zip file?
                    try {
                        try (ZipFile zipFile = new ZipFile(file)) {
                            for (String extension : validSourceFiles) {
                                if (zipFile.getEntry("threading." + extension) != null) {
                                    hashSet.remove("threading");
                                }
                                if (zipFile.getEntry("traceback." + extension) != null) {
                                    hashSet.remove("traceback");
                                }
                            }
                        }
                    } catch (Exception e) {
                        // ignore (not zip file)
                    }
                }
            }
            if (hashSet.size() > 0) {
                if (displayErrors) {
                    // The /Lib folder wasn't there (or at least threading.py and traceback.py weren't found)
                    int choice = PyDialogHelpers.openCriticalWithChoices(
                            "Error: Python stdlib source files not found.",
                            "Error: Python stdlib not found or stdlib found without .py files.\n" + "\n"
                                    + "It seems that the Python /Lib folder (which contains the standard library) "
                                    + "was not found/selected during the install process or the stdlib does not contain "
                                    + "the required .py files (i.e.: only has .pyc files).\n" + "\n"
                                    + "This folder (which contains files such as threading.py and traceback.py) is "
                                    + "required for PyDev to function properly, and it must contain the actual source files, not "
                                    + "only .pyc files. if you don't have the .py files in your install, please use an install from "
                                    + "python.org or grab the standard library for your install from there.\n"
                                    + "\n"
                                    + "If this is a virtualenv install, the /Lib folder from the base install needs to be selected "
                                    + "(unlike the site-packages which is optional).\n" + "\n"
                                    + "What do you want to do?\n\n"
                                    + "Note: if you choose to proceed, the /Lib with the standard library .py source files must "
                                    + "be added later on, otherwise PyDev may not function properly.",
                            new String[] { "Re-select folders", "Cancel", "Proceed anyways" });
                    if (choice == 0) {
                        // Keep on with outer while(true)
                        continue;
                    }
                    if (choice == 1) {
                        // Return nothing and exit quietly on a cancel
                        return null;
                    }
                } else {
                    // Don't allow auto-selection of an interpreter missing these folders
                    logger.println("- Could not find /Lib folder, exiting with error.");
                    throw new Exception(ERMSG_NOLIBS + executable);
                }
            }
            operation.result.setName(interpreterNameAndExecutable.o1);
            logger.println("- Success getting the info. Result:" + operation.result);
            return operation;
        }
    }

    /**
     * Returns the shared instance
     * 
     * @return the shared instance
     */
    public static AbstractActivatorUI getDefault() {

        return plugin;
    }
}