Example usage for javax.swing JTextArea append

List of usage examples for javax.swing JTextArea append

Introduction

In this page you can find the example usage for javax.swing JTextArea append.

Prototype

public void append(String str) 

Source Link

Document

Appends the given text to the end of the document.

Usage

From source file:dpcs.Interface.java

public Interface() {
    setIconImage(Toolkit.getDefaultToolkit().getImage(Interface.class.getResource("/graphics/Icon.png")));
    setTitle("Droid PC Suite");
    setResizable(false);// w  w  w  .j  a v  a 2s.c  o m
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 1088, 715);
    try {
        InputStreamReader reader2 = new InputStreamReader(
                getClass().getResourceAsStream("/others/app-version.txt"));
        String tmp = IOUtils.toString(reader2);
        AppVersion = Double.parseDouble(tmp);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu mnMenu = new JMenu("Menu");
    menuBar.add(mnMenu);
    JMenuItem mntmExit = new JMenuItem("Exit");

    mntmExit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            System.exit(0);
        }
    });

    JMenu mnADBandFastbootTools = new JMenu("ADB and Fastboot tools");
    mnMenu.add(mnADBandFastbootTools);
    mnADBandFastbootTools.setToolTipText("Access various ADB and Fastboot tools");

    JMenuItem mntmDevicestate = new JMenuItem("View device state");
    mntmDevicestate.setToolTipText("Check android device state");
    mntmDevicestate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb get-state");
                p1.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
                JOptionPane.showMessageDialog(null, "State: " + reader.readLine());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    JMenuItem mntmAdbHelp = new JMenuItem("View ADB help");
    mntmAdbHelp.setToolTipText("Get help regarding ADB");
    mntmAdbHelp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            ADBHelp obj = new ADBHelp();
            obj.setVisible(true);
        }
    });

    JMenuItem mntmNoOfUsers = new JMenuItem("Max user(s) supported?");
    mntmNoOfUsers.setToolTipText("Max no. of user(s) supported by android device");
    mntmNoOfUsers.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb shell pm get-max-users");
                p1.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
                JOptionPane.showMessageDialog(null, reader.readLine());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    mnADBandFastbootTools.add(mntmNoOfUsers);
    mnADBandFastbootTools.add(mntmAdbHelp);

    JMenuItem mntmAdbVersion = new JMenuItem("View ADB version");
    mntmAdbVersion.setToolTipText("Check the version of ADB installed on your computer");
    mnADBandFastbootTools.add(mntmAdbVersion);
    mntmAdbVersion.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb version");
                p1.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
                JOptionPane.showMessageDialog(null, reader.readLine());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    JMenuItem mntmViewDeviceList = new JMenuItem("View connected device");
    mntmViewDeviceList.setToolTipText(
            "Displays connected device, it will show name and serial no. of the only connected device because of connectivity limit");
    mntmViewDeviceList.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                JTextArea Devicelistviewer = new JTextArea();
                Devicelistviewer.setEditable(false);
                Devicelistviewer.setForeground(Color.BLACK);
                Devicelistviewer.setOpaque(false);
                Process p1 = Runtime.getRuntime().exec("adb devices -l");
                p1.waitFor();
                int i = 0;
                String line;
                String[] array = new String[1024];
                BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    array[i] = line;
                    Devicelistviewer.append(line + "\n");
                }
                JOptionPane.showMessageDialog(null, Devicelistviewer);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    mnADBandFastbootTools.add(mntmViewDeviceList);
    mnADBandFastbootTools.add(mntmDevicestate);

    JMenuItem mntmViewFastbootHelp = new JMenuItem("View fastboot help");
    mntmViewFastbootHelp.setToolTipText("Get help regarding fastboot");
    mntmViewFastbootHelp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FastbootHelp obj = new FastbootHelp();
            obj.setVisible(true);
        }
    });
    mnADBandFastbootTools.add(mntmViewFastbootHelp);

    JMenuItem mntmSerialNo = new JMenuItem("View serial no.");
    mntmSerialNo.setToolTipText("Check ADB connectivity serial no. of your android device");
    mnADBandFastbootTools.add(mntmSerialNo);
    mntmSerialNo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb get-serialno");
                p1.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
                JOptionPane.showMessageDialog(null, "Serial No: " + reader.readLine());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    JMenuItem mntmWaitForDevice = new JMenuItem("Wait for device");
    mntmWaitForDevice.setToolTipText("Ask ADB to wait for your device until the device can accept commands");
    mntmWaitForDevice.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb wait-for-device");
                p1.waitFor();
                JOptionPane.showMessageDialog(null, "Waiting...");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    mnADBandFastbootTools.add(mntmWaitForDevice);

    JMenuItem mntmDeviceFeatures = new JMenuItem("Device features");
    mnMenu.add(mntmDeviceFeatures);
    mntmDeviceFeatures.setToolTipText("View list of features supported by the android device");
    mntmDeviceFeatures.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Devicefeatures obj = new Devicefeatures();
            obj.setVisible(true);
        }
    });

    JMenu mnDeviceSpecificTools = new JMenu("Device specific tools");
    mnMenu.add(mnDeviceSpecificTools);
    mnDeviceSpecificTools.setToolTipText("View tools which only work with few  or specific devices");

    JMenu mnHTC = new JMenu("HTC");
    mnDeviceSpecificTools.add(mnHTC);
    mnHTC.setToolTipText("View list of tools which only work with HTC devices");

    JMenuItem mntmGetCidNo = new JMenuItem("Get CID no.");
    mntmGetCidNo.setToolTipText("Get CID Number of the device");
    mntmGetCidNo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb reboot fastboot");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("fastboot getvar cid");
                p2.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p2.getInputStream()));
                JOptionPane.showMessageDialog(null, reader.readLine());
                Process p3 = Runtime.getRuntime().exec("fastboot reboot");
                p3.waitFor();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    JMenuItem mntmBootloaderRelatedInfo = new JMenuItem("Bootloader related info");
    mntmBootloaderRelatedInfo.setToolTipText("View CID No.,Main-ver, bootloader info Etc.");
    mntmBootloaderRelatedInfo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb reboot fastboot");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("fastboot getvar all");
                p2.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p2.getInputStream()));
                JOptionPane.showMessageDialog(null, reader.readLine() + "\n");
                Process p3 = Runtime.getRuntime().exec("fastboot reboot");
                p3.waitFor();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    mnHTC.add(mntmBootloaderRelatedInfo);
    mnHTC.add(mntmGetCidNo);

    JMenuItem mntmWriteSuperCIDNo = new JMenuItem("Write Super CID no.");
    mntmWriteSuperCIDNo.setToolTipText("Write Super CID Number to device");
    mntmWriteSuperCIDNo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                int supercidno;
                Process p1 = Runtime.getRuntime().exec("adb reboot fastboot");
                p1.waitFor();
                supercidno = Integer.parseInt(JOptionPane.showInputDialog(null,
                        "Enter the Super CID Number to be written :\nfor ex. 11111111"));
                Process p2 = Runtime.getRuntime().exec("fastboot oem writecid " + supercidno);
                p2.waitFor();
                JOptionPane.showMessageDialog(null, "Done, Click OK to reboot");
                Process p3 = Runtime.getRuntime().exec("fastboot reboot");
                p3.waitFor();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    mnHTC.add(mntmWriteSuperCIDNo);

    JMenu mnSamsung = new JMenu("Samsung");
    mnSamsung.setToolTipText("View list of tools which only work with Samsung devices");
    mnDeviceSpecificTools.add(mnSamsung);

    JMenuItem mntmDownloadMode = new JMenuItem("Download Mode");
    mntmDownloadMode.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("adb reboot download");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });
    mntmDownloadMode.setToolTipText(
            "Reboot to Download Mode for flashing firmware to samsung device using Odin or Heimdall");
    mnSamsung.add(mntmDownloadMode);

    mnMenu.add(mntmExit);
    JMenu mnHelp = new JMenu("Help");
    menuBar.add(mnHelp);

    JMenuItem mntmCommonWorkarounds = new JMenuItem("Common workarounds");
    mntmCommonWorkarounds.setToolTipText(
            "View solutions and tips to avoid the common problems while using this application");
    mntmCommonWorkarounds.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Workarounds obj = new Workarounds();
            obj.setVisible(true);
        }
    });

    JMenuItem mntmAbout = new JMenuItem("About");
    mntmAbout.setToolTipText("Information about the application");
    mntmAbout.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            About obj = new About();
            obj.setVisible(true);
        }
    });
    mnHelp.add(mntmAbout);

    JMenuItem mntmCheckForUpdates = new JMenuItem("Check for updates");
    mntmCheckForUpdates.setToolTipText("Check for the new updates of this application");
    mntmCheckForUpdates.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new Updater();
        }
    });

    JMenuItem mntmChangelog = new JMenuItem("Changelog");
    mntmChangelog.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Changelog obj = new Changelog();
            obj.setVisible(true);
        }
    });
    mntmChangelog.setToolTipText("View changes made to this application over the time");
    mnHelp.add(mntmChangelog);
    mnHelp.add(mntmCheckForUpdates);
    mnHelp.add(mntmCommonWorkarounds);

    JMenuItem mntmNeedHelp = new JMenuItem("Online help");
    mntmNeedHelp.setToolTipText("Get online help for Droid PC Suite");
    mntmNeedHelp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                JOptionPane.showMessageDialog(null, "Post your queries on XDA-Developers thread");
                Desktop.getDesktop().browse(new URL(
                        "http://forum.xda-developers.com/android/development/tool-droid-pc-suite-t3398599")
                                .toURI());
            } catch (Exception e) {
                System.err.println(e);
            }
        }
    });

    JMenuItem mntmForceConnect = new JMenuItem("Force connect");
    mnHelp.add(mntmForceConnect);
    mntmForceConnect.setToolTipText("Force connect android device to computer using ADB protocol");
    mntmForceConnect.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null,
                    "Go to developer options and turn off android debugging and turn it on again");
            JOptionPane.showMessageDialog(null,
                    "Now tap on Revoke USB debugging authorizations and confirm it by tapping OK on android device");
            JOptionPane.showMessageDialog(null, "Now disconnect your android device and reconnect it via USB");
            JOptionPane.showMessageDialog(null, "Reboot your device. After it completely boots up click OK");
            try {
                adbconnected = false;
                Process p1 = Runtime.getRuntime().exec("adb kill-server");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("adb devices");
                p2.waitFor();
                JOptionPane.showMessageDialog(null, "Check if your device asks to Allow USB debugging");
                JOptionPane.showMessageDialog(null,
                        "If yes check always allow from this computer checkbox and tap OK on your android device");
                Process p3 = Runtime.getRuntime().exec("adb shell touch /sdcard/.CheckADBConnection");
                p3.waitFor();
                Process p4 = Runtime.getRuntime().exec("adb pull /sdcard/.CheckADBConnection");
                p4.waitFor();
                Process p5 = Runtime.getRuntime().exec("adb shell rm /sdcard/.CheckADBConnection");
                p5.waitFor();
                File file = new File(".CheckADBConnection");
                if (file.exists() && !file.isDirectory()) {
                    file.delete();
                    adbconnected = true;
                    ADBConnectionLabel.setText("Device is connected");
                    JOptionPane.showMessageDialog(null, "Success!");
                } else {
                    adbconnected = false;
                    ADBConnectionLabel.setText("");
                    ADBConnectionLabel.setText("Connect your device...");
                    JOptionPane.showMessageDialog(null,
                            "Please try again or perhaps try installing your android device adb drivers on PC");
                }
            } catch (Exception e1) {
                System.err.println(e1);
            }
            try {
                File file = new File("su");
                Process p1 = Runtime.getRuntime().exec("adb pull /system/xbin/su");
                p1.waitFor();
                if (file.exists() && !file.isDirectory()) {
                    file.delete();
                    rooted = true;
                    RootStatusLabel.setText("Device is rooted");
                } else {
                    if (adbconnected == true) {
                        rooted = false;
                        RootStatusLabel.setText("Device is not rooted");
                    } else {
                        rooted = false;
                        RootStatusLabel.setText("");
                    }
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    JMenu mnLegalInformation = new JMenu("Legal information");
    mnLegalInformation.setToolTipText("Vew legal information about the application");
    mnHelp.add(mnLegalInformation);

    JMenuItem mntmDroidPcSuite = new JMenuItem("Droid PC Suite license");
    mntmDroidPcSuite.setToolTipText("View Droid PC Suite licence");
    mntmDroidPcSuite.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            GPLLicense obj = new GPLLicense();
            obj.setVisible(true);
        }
    });
    mnLegalInformation.add(mntmDroidPcSuite);

    JMenuItem mntmOpenSourceLicenses = new JMenuItem("Open source licenses");
    mntmOpenSourceLicenses
            .setToolTipText("View other open source licences for other softwares used with this application");
    mntmOpenSourceLicenses.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            ApacheLicense obj = new ApacheLicense();
            obj.setVisible(true);
        }
    });
    mnLegalInformation.add(mntmOpenSourceLicenses);
    mnHelp.add(mntmNeedHelp);
    contentPane = new JPanel();
    contentPane.setBackground(Color.WHITE);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    ApplicationStatus = new JLabel("");
    ApplicationStatus.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            if (!ApplicationStatus.getText().equals("")) {
                int dialogButton = JOptionPane.YES_NO_OPTION;
                int dialogResult = JOptionPane.showConfirmDialog(null,
                        "Do you want to clear application status?", "Application status", dialogButton);
                if (dialogResult == 0) {
                    ApplicationStatus.setText("");
                }
            }
        }
    });

    JLabel lblApplicationVersion = new JLabel("Version: " + AppVersion);
    lblApplicationVersion.setBounds(818, 150, 135, 22);
    contentPane.add(lblApplicationVersion);
    ApplicationStatus.setBounds(12, 230, 1062, 17);
    contentPane.add(ApplicationStatus);

    RootStatusLabel = new JLabel("");
    RootStatusLabel.setBounds(921, 12, 153, 17);
    RootStatusLabel.setForeground(Color.RED);
    contentPane.add(RootStatusLabel);

    ADBConnectionLabel = new JLabel("");
    ADBConnectionLabel.setBounds(900, 0, 175, 17);
    ADBConnectionLabel.setForeground(Color.GREEN);
    contentPane.add(ADBConnectionLabel);

    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    tabbedPane.setBounds(0, 255, 1075, 447);
    contentPane.add(tabbedPane);

    JPanel panel_7 = new JPanel();
    panel_7.setBackground(Color.WHITE);
    tabbedPane.addTab("General", null, panel_7, null);
    panel_7.setLayout(null);

    JButton btnADBTerminal = new JButton("ADB Terminal");
    btnADBTerminal.setToolTipText("Send commands to your android device via ADB protocol, EXPERIMENTAL!");
    btnADBTerminal.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Terminal obj = new Terminal();
            obj.setVisible(true);
        }
    });

    JButton btnBuildpropeditor = new JButton("build.prop Editor");
    btnBuildpropeditor
            .setToolTipText("Editor for editing build properties of your android device, Use with Caution!");
    btnBuildpropeditor.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Buildpropeditor obj = new Buildpropeditor();
            obj.setVisible(true);
        }
    });
    btnBuildpropeditor.setBounds(541, 27, 220, 75);
    panel_7.add(btnBuildpropeditor);
    btnADBTerminal.setBounds(25, 27, 220, 75);
    panel_7.add(btnADBTerminal);

    JLabel lblNoteInstallationTo = new JLabel("# Only for android 4.4.x and higher");
    lblNoteInstallationTo.setBounds(20, 311, 1046, 15);
    panel_7.add(lblNoteInstallationTo);

    GeneralDone = new JLabel("");
    GeneralDone.setText("");
    GeneralDone.setBounds(766, 27, 300, 220);
    panel_7.add(GeneralDone);

    JButton btnFileManager = new JButton("File Manager");
    btnFileManager.setToolTipText("Access files on your android device");
    btnFileManager.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            GeneralDone.setText("");
            filemanager.FileManager.main(null);
        }
    });
    btnFileManager.setBounds(25, 131, 220, 75);
    panel_7.add(btnFileManager);

    JLabel lblNeedsRoot = new JLabel(
            "* Needs root access, also may not work with some devices regardless of root access");
    lblNeedsRoot.setBounds(20, 326, 1046, 15);
    panel_7.add(lblNeedsRoot);

    JButton btnScreenshot = new JButton("Screenshot");
    btnScreenshot.setToolTipText("Screenshot your android device screen");
    btnScreenshot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb shell screencap -p /sdcard/screenshot.png");
                p1.waitFor();
                JFileChooser directorychooser = new JFileChooser();
                directorychooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                directorychooser.setDialogTitle("Select path to save the screenshot");
                FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG Files", "png");
                directorychooser.setFileFilter(filter);
                directorychooser.setApproveButtonText("Save");
                int returnVal = directorychooser.showOpenDialog(getParent());
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    Process p2 = Runtime.getRuntime().exec("adb pull /sdcard/screenshot.png "
                            + directorychooser.getSelectedFile().getAbsolutePath());
                    p2.waitFor();
                }
                Process p3 = Runtime.getRuntime().exec("adb shell rm /sdcard/screenshot.png");
                p3.waitFor();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    btnScreenshot.setBounds(282, 131, 220, 75);
    panel_7.add(btnScreenshot);

    JButton btnScreenRecorder = new JButton("Screen Recorder #");
    btnScreenRecorder.setToolTipText("Record android device screen");
    btnScreenRecorder.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String[] options = new String[] { "5 Sec", "30 Sec", "60 Sec", "180 Sec", "Custom" };
            int response = JOptionPane.showOptionDialog(null, "Select duration of recording", "Screen Recorder",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
            int time = 0, bitrate = 8000000;
            try {
                if (response == 0) {
                    time = 5;
                }
                if (response == 1) {
                    time = 30;
                }
                if (response == 2) {
                    time = 60;
                }
                if (response == 3) {
                    time = 180;
                }
                if (response == 4) {
                    time = Integer.parseInt(JOptionPane.showInputDialog(null,
                            "Enter the duration of recording in seconds (1 - 180): for ex. 25 for 25 Seconds"));
                    bitrate = Integer.parseInt(JOptionPane.showInputDialog(null,
                            "Enter the bitrate of recording (Default = 8000000 (8Mbps))"));
                }
                JOptionPane.showMessageDialog(null, "You will need to wait for " + time + " seconds, Click ok");
                Process p1 = Runtime.getRuntime().exec("adb shell screenrecord --bit-rate " + bitrate
                        + " --time-limit " + time + " /sdcard/videorecording.mp4");
                p1.waitFor();
                JOptionPane.showMessageDialog(null, "Recording finished, Select destination to save the file");
                JFileChooser directorychooser = new JFileChooser();
                directorychooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                directorychooser.setDialogTitle("Select path to save the recording");
                FileNameExtensionFilter filter = new FileNameExtensionFilter("MP4 Files", "mp4");
                directorychooser.setFileFilter(filter);
                directorychooser.setApproveButtonText("Save");
                int returnVal = directorychooser.showOpenDialog(getParent());
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    Process p2 = Runtime.getRuntime().exec("adb pull /sdcard/videorecording.mp4 "
                            + directorychooser.getSelectedFile().getAbsolutePath());
                    p2.waitFor();
                }
                Process p3 = Runtime.getRuntime().exec("adb shell rm /sdcard/videorecording.mp4");
                p3.waitFor();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    btnScreenRecorder.setBounds(541, 131, 220, 75);
    panel_7.add(btnScreenRecorder);

    JButton btnAppManager = new JButton("App Manager");
    btnAppManager.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            GeneralDone.setText("");
            String[] MainOptions = new String[] { "Install apps", "Uninstall apps" };
            int MainResponse = JOptionPane.showOptionDialog(null, "Select an operation", "App Manager",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, MainOptions, MainOptions[0]);
            if (MainResponse == 0) {
                try {
                    GeneralDone.setText("");
                    String[] options = new String[] { "User apps", "Priv-apps", "System apps" };
                    int response = JOptionPane.showOptionDialog(null, "Where to install the app?", "Installer",
                            JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (response == 0) {
                        try {
                            GeneralDone.setText("");
                            JFileChooser chooser = new JFileChooser();
                            FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk");
                            chooser.setFileFilter(filter);
                            int returnVal = chooser.showOpenDialog(getParent());
                            if (returnVal == JFileChooser.APPROVE_OPTION) {
                                File file = chooser.getSelectedFile();
                                String filename = chooser.getSelectedFile().getName();
                                try {
                                    ApplicationStatus.setText("Installing...");
                                    String[] commands = new String[3];
                                    commands[0] = "adb";
                                    commands[1] = "install";
                                    commands[2] = file.getAbsolutePath();
                                    ApplicationStatus.setText("Installing App...");
                                    Process p1 = Runtime.getRuntime().exec(commands, null);
                                    p1.waitFor();
                                    ApplicationStatus.setText(filename
                                            + " has been successfully installed on your android device!");
                                    GeneralDone.setIcon(
                                            new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                                } catch (Exception e1) {
                                    System.err.println(e1);
                                }
                            }
                        } catch (Exception e1) {
                        }
                    }
                    if (response == 1) {
                        GeneralDone.setText("");
                        JFileChooser chooser = new JFileChooser();
                        FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk");
                        chooser.setFileFilter(filter);
                        int returnVal = chooser.showOpenDialog(getParent());
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
                            File file = chooser.getSelectedFile();
                            try {
                                ApplicationStatus.setText("Installing...");
                                Process p1 = Runtime.getRuntime().exec("adb remount");
                                p1.waitFor();
                                String[] pushcommand = new String[4];
                                pushcommand[0] = "adb";
                                pushcommand[1] = "push";
                                pushcommand[2] = file.getAbsolutePath();
                                pushcommand[3] = "/system/priv-app/";
                                ApplicationStatus.setText("Installing App...");
                                Process p2 = Runtime.getRuntime().exec(pushcommand, null);
                                p2.waitFor();
                                ApplicationStatus.setText("Rebooting your android device");
                                Process p3 = Runtime.getRuntime().exec("adb reboot");
                                p3.waitFor();
                                ApplicationStatus.setText("");
                                GeneralDone.setIcon(
                                        new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                            } catch (Exception e1) {
                                System.err.println(e1);
                            }
                        }
                    }
                    if (response == 2) {
                        GeneralDone.setText("");
                        JFileChooser chooser = new JFileChooser();
                        FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk");
                        chooser.setFileFilter(filter);
                        int returnVal = chooser.showOpenDialog(getParent());
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
                            File file = chooser.getSelectedFile();
                            try {
                                ApplicationStatus.setText("Installing...");
                                Process p1 = Runtime.getRuntime().exec("adb remount");
                                p1.waitFor();
                                String[] pushcommand = new String[4];
                                pushcommand[0] = "adb";
                                pushcommand[1] = "push";
                                pushcommand[2] = file.getAbsolutePath();
                                pushcommand[3] = "/system/app/";
                                Process p2 = Runtime.getRuntime().exec(pushcommand, null);
                                p2.waitFor();
                                ApplicationStatus.setText("Rebooting your android device");
                                Process p3 = Runtime.getRuntime().exec("adb reboot");
                                p3.waitFor();
                                ApplicationStatus.setText("");
                                GeneralDone.setIcon(
                                        new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                            } catch (Exception e1) {
                                System.err.println(e1);
                            }
                        }
                    }
                } catch (Exception e1) {
                }
            }
            if (MainResponse == 1) {
                try {
                    GeneralDone.setText("");
                    String[] options = new String[] { "User apps", "Priv-apps", "System apps" };
                    int response = JOptionPane.showOptionDialog(null,
                            "Which kind of app you want to uninstall?", "Uninstaller",
                            JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (response == 0) {
                        try {
                            UninstallUserApps obj = new UninstallUserApps();
                            obj.setVisible(true);
                        } catch (Exception e1) {
                        }
                    }
                    if (response == 1) {
                        try {
                            UninstallPrivApps obj = new UninstallPrivApps();
                            obj.setVisible(true);
                        } catch (Exception e1) {
                        }
                    }
                    if (response == 2) {
                        try {
                            UninstallSystemApps obj = new UninstallSystemApps();
                            obj.setVisible(true);
                        } catch (Exception e1) {
                        }
                    }
                } catch (Exception e1) {
                }
            }
        }
    });
    btnAppManager.setToolTipText("Manage Apps on your android device");
    btnAppManager.setBounds(282, 27, 220, 75);
    panel_7.add(btnAppManager);

    JLabel lblInstallationAndUninstallation = new JLabel(
            "Installation and Uninstallation of apps to Priv-app is only for android 4.4 and higher, requires root and even simply may not work on your device!");
    lblInstallationAndUninstallation.setBounds(20, 356, 1046, 15);
    panel_7.add(lblInstallationAndUninstallation);

    JLabel lblInstallationAndUninstallation_1 = new JLabel(
            "Installation and Uninstallation of apps to System requires root, and may not work for your device!");
    lblInstallationAndUninstallation_1.setBounds(20, 341, 1046, 15);
    panel_7.add(lblInstallationAndUninstallation_1);

    JPanel panel_8 = new JPanel();
    panel_8.setBackground(Color.WHITE);
    tabbedPane.addTab("Advanced", null, panel_8, null);
    panel_8.setLayout(null);

    JButton btnMemoryInformation = new JButton("Memory Information");
    btnMemoryInformation.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Memoryinfo obj = new Memoryinfo();
            obj.setVisible(true);
        }
    });

    JButton btnClearBatteryStats = new JButton("Clear Battery Stats *");
    btnClearBatteryStats.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb remount");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("adb shell su -c rm -r /data/system/batterystats.bin");
                p2.waitFor();
                String[] options = new String[] { "Yes", "No" };
                int response = JOptionPane.showOptionDialog(null, "Done, would you like to reboot your device?",
                        "Reboot device? (Recommended)", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
                        null, options, options[0]);
                if (response == 0) {
                    try {
                        Process p3 = Runtime.getRuntime().exec("adb reboot");
                        p3.waitFor();
                    } catch (Exception e1) {
                    }
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    btnClearBatteryStats.setToolTipText("Clear outdated or invalid battery stats");
    btnClearBatteryStats.setBounds(25, 131, 220, 75);
    panel_8.add(btnClearBatteryStats);
    btnMemoryInformation.setToolTipText("View current memory information of android device");
    btnMemoryInformation.setBounds(25, 236, 220, 75);
    panel_8.add(btnMemoryInformation);

    JButton btnBatteryInformation = new JButton("Battery Information");
    btnBatteryInformation.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Batteryinfo obj = new Batteryinfo();
            obj.setVisible(true);
        }
    });
    btnBatteryInformation.setToolTipText("View current battery information of android device");
    btnBatteryInformation.setBounds(541, 27, 220, 75);
    panel_8.add(btnBatteryInformation);

    JButton btnCpuInformation = new JButton("CPU Information");
    btnCpuInformation.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            CPUinfo obj = new CPUinfo();
            obj.setVisible(true);
        }
    });
    btnCpuInformation.setToolTipText("View current CPU information of android device");
    btnCpuInformation.setBounds(282, 131, 220, 75);
    panel_8.add(btnCpuInformation);

    JButton btnAppInformation = new JButton("App Information");
    btnAppInformation.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Appinfo obj = new Appinfo();
            obj.setVisible(true);
        }
    });
    btnAppInformation.setToolTipText("View current app information of android device");
    btnAppInformation.setBounds(25, 27, 220, 75);
    panel_8.add(btnAppInformation);

    JButton btnKillApps = new JButton("Kill Apps");
    btnKillApps.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String[] options = new String[] { "Enter package name", "Kill all apps" };
            int response = JOptionPane.showOptionDialog(null, "Which app(s) should be killed?", "Kill Apps",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
            if (response == 0) {
                try {
                    JOptionPane.showMessageDialog(null,
                            "You can find an app package name from App Packages List");
                    String selectedapp = (JOptionPane.showInputDialog(null, "Enter app's package name:"));
                    Process p1 = Runtime.getRuntime().exec("adb shell am force-stop " + selectedapp);
                    p1.waitFor();
                    JOptionPane.showMessageDialog(null, selectedapp + " has been killed");
                } catch (Exception e1) {
                }
            }
            if (response == 1) {
                try {
                    Process p1 = Runtime.getRuntime().exec("adb shell am kill-all");
                    p1.waitFor();
                    JOptionPane.showMessageDialog(null, "All 'safe to kill' apps have been killed");
                } catch (Exception e1) {
                }
            }
        }
    });
    btnKillApps.setToolTipText("Kill any app currently running on android device");
    btnKillApps.setBounds(541, 131, 220, 75);
    panel_8.add(btnKillApps);

    JButton btnWifiInformation = new JButton("WiFi Information");
    btnWifiInformation.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Wifiinfo obj = new Wifiinfo();
            obj.setVisible(true);
        }
    });
    btnWifiInformation.setToolTipText("View current wifi information of android device");
    btnWifiInformation.setBounds(541, 236, 220, 75);
    panel_8.add(btnWifiInformation);

    JButton btnAppPackageList = new JButton("App Packages List");
    btnAppPackageList.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AppPackagesList obj = new AppPackagesList();
            obj.setVisible(true);
        }
    });
    btnAppPackageList.setToolTipText("View all installed app packages list information");
    btnAppPackageList.setBounds(282, 27, 220, 75);
    panel_8.add(btnAppPackageList);

    JLabel lblAdvancedToolsNote = new JLabel(
            "Note: All of the above tools are not supported by every device or ROM");
    lblAdvancedToolsNote.setBounds(25, 345, 736, 15);
    panel_8.add(lblAdvancedToolsNote);

    JButton btnUnroot = new JButton("Unroot Device");
    btnUnroot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                File file1 = new File(".events");
                if (!file1.exists()) {
                    List<String> lines = Arrays.asList("Unroot_Warning_Shown = True");
                    Path file = Paths.get(".events");
                    Files.write(file, lines, Charset.forName("UTF-8"));
                    JOptionPane.showMessageDialog(null,
                            "Only the SU Binary will get removed since there are lot of different root management\napplications for android available, I can't regularly search for them and add their\nsupport to this application. If you think this concerns you, you can help me by sending\nme a list of root management applicationsfor android like supersu, kingroot, kingoroot,\netc. But I can't promise that I will add support for each of them. Cheers! :)");
                }
                JOptionPane.showMessageDialog(null, "Unrooting work only on non-production builds of android");
                Process p1 = Runtime.getRuntime().exec("adb pull /system/xbin/su");
                p1.waitFor();
                File file2 = new File("su");
                if (file2.exists() && !file2.isDirectory()) {
                    file2.delete();
                    Process p2 = Runtime.getRuntime().exec("adb remount");
                    p2.waitFor();
                    Process p3 = Runtime.getRuntime().exec("adb shell su -c rm -r /system/xbin/su");
                    p3.waitFor();
                    JOptionPane.showMessageDialog(null, "Operation completed");
                } else {
                    JOptionPane.showMessageDialog(null, "This device is not rooted");
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    btnUnroot.setToolTipText("Unroot device by removing SU binary from the device");
    btnUnroot.setBounds(282, 236, 220, 75);
    panel_8.add(btnUnroot);

    JLabel lblNewLabel_1 = new JLabel(
            "* Needs root access, also may not work with some devices regardless of root access");
    lblNewLabel_1.setBounds(25, 372, 736, 15);
    panel_8.add(lblNewLabel_1);

    JPanel panel_10 = new JPanel();
    panel_10.setBackground(Color.WHITE);
    tabbedPane.addTab("Developer", null, panel_10, null);
    panel_10.setLayout(null);

    JButton btnUnpackAPKs = new JButton("Unpack APKs");
    btnUnpackAPKs.addActionListener(new ActionListener() {
        private Component parentFrame;

        public void actionPerformed(ActionEvent e) {
            File path = null;
            JFileChooser chooser1 = new JFileChooser();
            chooser1.setDialogTitle("Select an APK file to extract");
            FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk");
            chooser1.setCurrentDirectory(new java.io.File("."));
            chooser1.setFileFilter(filter);
            int returnVal = chooser1.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser1.getSelectedFile();
                String filename = chooser1.getSelectedFile().getName();
                JFileChooser chooser2 = new JFileChooser();
                chooser2.setDialogTitle("Extract APK file to");
                chooser2.setCurrentDirectory(new java.io.File("."));
                chooser2.setAcceptAllFileFilterUsed(false);
                chooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int userSelection = chooser2.showSaveDialog(parentFrame);
                if (userSelection == JFileChooser.APPROVE_OPTION) {
                    path = chooser2.getSelectedFile();
                }
                String outputDir = path.getAbsolutePath();
                java.util.zip.ZipFile zipFile = null;
                try {
                    zipFile = new ZipFile(file);
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        File entryDestination = new File(outputDir, entry.getName());
                        if (entry.isDirectory()) {
                            entryDestination.mkdirs();
                        } else {
                            entryDestination.getParentFile().mkdirs();
                            InputStream in = zipFile.getInputStream(entry);
                            OutputStream out = null;
                            out = new FileOutputStream(entryDestination);
                            IOUtils.copy(in, out);
                            IOUtils.closeQuietly(in);
                            out.close();
                        }
                    }
                    zipFile.close();
                    JOptionPane.showMessageDialog(null, filename + " has been successfully extracted");
                } catch (Exception e1) {
                    e1.printStackTrace();
                    JOptionPane.showMessageDialog(null, "An error occured");
                }
            }
        }
    });
    btnUnpackAPKs.setToolTipText("Unpack APKs stored on disk");
    btnUnpackAPKs.setBounds(541, 27, 220, 75);
    panel_10.add(btnUnpackAPKs);

    JButton btnRepackAPKs = new JButton("Repack APKs");
    btnRepackAPKs.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new Repacker();
        }
    });
    btnRepackAPKs.setToolTipText("Repack previously unpacked APKs and save to them to disk");
    btnRepackAPKs.setBounds(25, 27, 220, 75);
    panel_10.add(btnRepackAPKs);

    JButton btnStartAnActivity = new JButton("Start an activity *");
    btnStartAnActivity.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                String packagename = JOptionPane.showInputDialog(null, "Enter the package name of the app",
                        "com.package.name");
                String activityname = JOptionPane.showInputDialog(null, "Enter the activity name of the app",
                        "MainActivity");
                Process p1 = Runtime.getRuntime().exec("adb shell am start -n " + packagename + "/"
                        + packagename + "com.package.name." + activityname);
                p1.waitFor();
            } catch (Exception e1) {
                e1.printStackTrace();
            }

        }
    });
    btnStartAnActivity.setToolTipText("Start an actvity of an android app on your android device");
    btnStartAnActivity.setBounds(282, 27, 220, 75);
    panel_10.add(btnStartAnActivity);

    JLabel lblActivityWill = new JLabel(
            "* An activity will not start if you enter wrong package name or activity name");
    lblActivityWill.setBounds(25, 381, 736, 15);
    panel_10.add(lblActivityWill);

    JPanel panel_5 = new JPanel();
    panel_5.setBackground(Color.WHITE);
    tabbedPane.addTab("Backup & Restore", null, panel_5, null);
    panel_5.setLayout(null);

    BackupAndRestoreDone = new JLabel("");
    BackupAndRestoreDone.setText("");
    BackupAndRestoreDone.setBounds(758, 70, 300, 220);
    panel_5.add(BackupAndRestoreDone);

    JLabel lblRestoreOperations = new JLabel("Restore Operations");
    lblRestoreOperations.setBounds(541, 12, 142, 36);
    panel_5.add(lblRestoreOperations);

    final JButton btnRestoreFromCustomLocationBackup = new JButton("From Custom Location");
    btnRestoreFromCustomLocationBackup
            .setToolTipText("Restore data to android device from the backup stored somewhere on the computer");
    btnRestoreFromCustomLocationBackup.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Android Backup Files", "ab");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
                    ApplicationStatus.setText("Restoring may take upto several minutes, please be patient...");
                    JOptionPane.showMessageDialog(null,
                            "Unlock your device and confirm the restore operation when asked");
                    String[] commands = new String[3];
                    commands[0] = "adb";
                    commands[1] = "restore";
                    commands[2] = file.getAbsolutePath();
                    ApplicationStatus.setText("Restoring...");
                    Process p1 = Runtime.getRuntime().exec(commands, null);
                    p1.waitFor();
                    ApplicationStatus.setText("Restore completed successfully!");
                    BackupAndRestoreDone
                            .setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnRestoreFromCustomLocationBackup.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnRestoreFromCustomLocationBackup.setBounds(510, 70, 220, 75);
    panel_5.add(btnRestoreFromCustomLocationBackup);

    JLabel lblBackup = new JLabel("Backup Operations");
    lblBackup.setBounds(192, 12, 142, 36);
    panel_5.add(lblBackup);

    final JButton btnBackupInternelStorage = new JButton("Internel Storage");
    btnBackupInternelStorage.setToolTipText("Backup android device internal storage");
    btnBackupInternelStorage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                ApplicationStatus.setText("Backup can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the backup operation when asked");
                String[] commands = new String[3];
                commands[0] = "adb";
                commands[1] = "backup";
                commands[2] = "-shared";
                ApplicationStatus.setText("Performing backup...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Backup completed successfully!");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnBackupInternelStorage.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnBackupInternelStorage.setBounds(270, 70, 220, 75);
    panel_5.add(btnBackupInternelStorage);

    final JButton btnBackupSingleApp = new JButton("Single App");
    btnBackupSingleApp.setToolTipText("Backup a single app from android device");
    btnBackupSingleApp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                String message = JOptionPane.showInputDialog(null, "Please specify a package name to backup");
                ApplicationStatus.setText("Backup can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the backup operation when asked");
                String[] commands = new String[3];
                commands[0] = "adb";
                commands[1] = "backup";
                commands[2] = message;
                ApplicationStatus.setText("Performing backup...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Backup completed successfully!");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnBackupSingleApp.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnBackupSingleApp.setBounds(25, 184, 220, 75);
    panel_5.add(btnBackupSingleApp);

    final JButton btnBackupAppAndAppData = new JButton("App and App Data");
    btnBackupAppAndAppData.setToolTipText("Backup app and it's data from android device");
    btnBackupAppAndAppData.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                ApplicationStatus.setText("Backup can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the backup operation when asked");
                String[] commands = new String[3];
                commands[0] = "adb";
                commands[1] = "backup";
                commands[2] = "-all";
                ApplicationStatus.setText("Performing backup...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Backup completed successfully!");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnBackupAppAndAppData.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnBackupAppAndAppData.setBounds(25, 70, 220, 75);
    panel_5.add(btnBackupAppAndAppData);

    final JButton btnBackupWholeDevice = new JButton("Whole Device");
    btnBackupWholeDevice.setToolTipText("Backup whole android device");
    btnBackupWholeDevice.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                ApplicationStatus.setText("Backup can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the backup operation when asked");
                String[] commands = new String[6];
                commands[0] = "adb";
                commands[1] = "backup";
                commands[2] = "-all";
                commands[3] = "-apk";
                commands[4] = "-shared";
                commands[5] = "-system";
                ApplicationStatus.setText("Performing backup...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Backup completed successfully");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnBackupWholeDevice.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnBackupWholeDevice.setBounds(25, 303, 220, 75);
    panel_5.add(btnBackupWholeDevice);

    final JButton btnRestorePreviousBackup = new JButton("Previous Backup");
    btnRestorePreviousBackup.setToolTipText("Restore data to android device from the previous backup");
    btnRestorePreviousBackup.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                ApplicationStatus.setText("Restoring can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the restore operation when asked");
                String[] commands = new String[3];
                commands[0] = "adb";
                commands[1] = "restore";
                commands[2] = "backup.ab";
                ApplicationStatus.setText("Restoring...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Restore completed successfully!");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnRestorePreviousBackup.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRestorePreviousBackup.setBounds(510, 184, 220, 75);
    panel_5.add(btnRestorePreviousBackup);

    final JButton btnBackupSystem = new JButton("System");
    btnBackupSystem.setToolTipText("Backup android device system");
    btnBackupSystem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                ApplicationStatus.setText("Backup can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the backup operation when asked");
                String[] commands = new String[3];
                commands[0] = "adb";
                commands[1] = "backup";
                commands[2] = "-system";
                ApplicationStatus.setText("Performing backup...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Backup completed successfully!");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnBackupSystem.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnBackupSystem.setBounds(270, 184, 220, 75);
    panel_5.add(btnBackupSystem);

    JPanel panel_2 = new JPanel();
    panel_2.setBackground(Color.WHITE);
    tabbedPane.addTab("Rebooter", null, panel_2, null);
    panel_2.setLayout(null);

    JLabel lblRebootFrom = new JLabel("Reboot from :");
    lblRebootFrom.setBounds(25, 180, 220, 15);
    panel_2.add(lblRebootFrom);

    JLabel lblRebootTo = new JLabel("Reboot to :");
    lblRebootTo.setBounds(25, 12, 220, 15);
    panel_2.add(lblRebootTo);

    JLabel lblNotFor = new JLabel("# Not for Samsung devices");
    lblNotFor.setBounds(514, 359, 238, 19);
    panel_2.add(lblNotFor);

    JLabel lblDeviceMust_1 = new JLabel("Device must be in fastboot mode (Except for Reboot System)");
    lblDeviceMust_1.setBounds(25, 332, 479, 19);
    panel_2.add(lblDeviceMust_1);

    JLabel lblYouMust_1 = new JLabel("* You must have a bootloader that supports fastboot commands");
    lblYouMust_1.setBounds(25, 359, 470, 19);
    panel_2.add(lblYouMust_1);

    JButton btnRebootFromFastboot = new JButton("Fastboot *");
    btnRebootFromFastboot.setToolTipText("Reboot android device from fastboot mode to normal");
    btnRebootFromFastboot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("fastboot reboot");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootFromFastboot.setBounds(28, 232, 220, 75);
    panel_2.add(btnRebootFromFastboot);

    JButton btnRebootToBootloaderFromFastboot = new JButton("Fastboot to Bootloader *");
    btnRebootToBootloaderFromFastboot.setToolTipText("Reboot to Bootloader mode while accessing fastboot mode");
    btnRebootToBootloaderFromFastboot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("fasboot reboot-bootloader");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootToBootloaderFromFastboot.setBounds(281, 232, 220, 75);
    panel_2.add(btnRebootToBootloaderFromFastboot);

    JButton btnRebootToFastboot = new JButton("Fastboot");
    btnRebootToFastboot.setToolTipText("Reboot android device to fastboot mode");
    btnRebootToFastboot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("adb reboot fastboot");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootToFastboot.setBounds(281, 55, 220, 75);
    panel_2.add(btnRebootToFastboot);

    JButton btnRebootToBootloader = new JButton("Bootloader #");
    btnRebootToBootloader.setToolTipText("Reboot android device to bootloader mode");
    btnRebootToBootloader.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("adb reboot bootloader");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootToBootloader.setBounds(28, 55, 220, 75);
    panel_2.add(btnRebootToBootloader);

    JButton btnRebootToRecovery = new JButton("Recovery");
    btnRebootToRecovery.setToolTipText("Reboot android device to recovery mode");
    btnRebootToRecovery.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("adb reboot recovery");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootToRecovery.setBounds(532, 55, 220, 75);
    panel_2.add(btnRebootToRecovery);

    JButton btnRebootSystem = new JButton("System");
    btnRebootSystem.setToolTipText("Reboot android device normally");
    btnRebootSystem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("adb reboot");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootSystem.setBounds(785, 55, 220, 75);
    panel_2.add(btnRebootSystem);

    JPanel panel_9 = new JPanel();
    panel_9.setBackground(Color.WHITE);
    tabbedPane.addTab("Bypass Security", null, panel_9, null);
    panel_9.setLayout(null);

    JLabel lblRootOperationsexperimental = new JLabel(
            "Method #1 : Root Operations (Recommended) [EXPERIMENTAL] :");
    lblRootOperationsexperimental.setBounds(12, 12, 507, 15);
    panel_9.add(lblRootOperationsexperimental);

    JButton btnPattern = new JButton("Pattern #");
    btnPattern.setToolTipText("Remove pattern security from android device (Experimental)");
    btnPattern.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                ApplicationStatus.setText("Trying to break into security...");
                Process p1 = Runtime.getRuntime().exec("adb shell su -c rm /data/system/gesture.key");
                p1.waitFor();
                ApplicationStatus.setText(
                        "Done, now try to unlock the device with a random pattern then change security manually from settings");
            } catch (Exception e1) {
            }
        }
    });

    btnPattern.setBounds(220, 75, 220, 75);
    panel_9.add(btnPattern);

    JButton btnPasswordPin = new JButton("Password/ PIN #");
    btnPasswordPin.setToolTipText("Remove password or pin security from android device (Experimental)");
    btnPasswordPin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                ApplicationStatus.setText("Trying to break into security...");
                Process p1 = Runtime.getRuntime().exec("adb shell su -c rm /data/system/password.key");
                p1.waitFor();
                ApplicationStatus.setText("Done, check your device...");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnPasswordPin.setBounds(630, 75, 220, 75);
    panel_9.add(btnPasswordPin);

    JLabel lblMayNot = new JLabel("# Works on Android 4.4.x and lower");
    lblMayNot.setBounds(630, 250, 366, 15);
    panel_9.add(lblMayNot);

    JLabel lblNonRoot = new JLabel("Method # 2 : Non - Root/ Root Operations [EXPERIMENTAL] :");
    lblNonRoot.setBounds(12, 191, 507, 15);
    panel_9.add(lblNonRoot);

    JButton btnJellyBeanPatternPinPassword = new JButton("Pattern/ PIN/ Password *");
    btnJellyBeanPatternPinPassword
            .setToolTipText("Remove pattern, pin or password security from android device (Experimental)");
    btnJellyBeanPatternPinPassword.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                ApplicationStatus.setText("Trying to break into security...");
                Process p1 = Runtime.getRuntime().exec(
                        "adb shell am start -n com.android.settings/com.android.settings.ChooseLockGeneric --ez confirm_credentials false --ei lockscreen.password_type 0 --activity-clear-task");
                p1.waitFor();
                ApplicationStatus.setText("Rebooting...");
                Process p2 = Runtime.getRuntime().exec("adb reboot");
                p2.waitFor();
                ApplicationStatus.setText("Done, check your device...");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnJellyBeanPatternPinPassword.setBounds(220, 250, 220, 75);
    panel_9.add(btnJellyBeanPatternPinPassword);

    JLabel lblWorksWell = new JLabel("* Works well on Jelly Bean Devices but may or");
    lblWorksWell.setBounds(630, 273, 366, 15);
    panel_9.add(lblWorksWell);

    JLabel lblNewLabel = new JLabel("may not work for older/ newer android versions");
    lblNewLabel.setBounds(640, 293, 356, 15);
    panel_9.add(lblNewLabel);

    JPanel panel_4 = new JPanel();
    panel_4.setBackground(Color.WHITE);
    tabbedPane.addTab("Logger", null, panel_4, null);
    panel_4.setLayout(null);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(0, 72, 1072, 285);
    panel_4.add(scrollPane);

    LogViewer = new JTextArea();
    LogViewer.setEditable(false);
    scrollPane.setViewportView(LogViewer);

    JButton btnSaveAsTextFile = new JButton("Save as a text file");
    btnSaveAsTextFile.setToolTipText("Save printed logcat as a text file on computer");
    btnSaveAsTextFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if (LogViewer.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "No log found, please click view log");
            } else {
                ApplicationStatus.setText("");
                JFrame parentFrame = new JFrame();
                JFileChooser fileChooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
                fileChooser.setFileFilter(filter);
                fileChooser.setDialogTitle("Save as a text file");
                int userSelection = fileChooser.showSaveDialog(parentFrame);
                if (userSelection == JFileChooser.APPROVE_OPTION) {
                    File fileToSave = fileChooser.getSelectedFile();
                    FileWriter write = null;
                    try {
                        write = new FileWriter(fileToSave.getAbsolutePath() + ".txt");
                        LogViewer.write(write);
                        ApplicationStatus.setText("Logcat saved");
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (write != null)
                            try {
                                write.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                    }
                }
            }
        }
    });

    btnSaveAsTextFile.setBounds(420, 13, 220, 47);
    panel_4.add(btnSaveAsTextFile);

    JButton btnClearLogcat = new JButton("Clear");
    btnClearLogcat.setToolTipText("Clean the printed logcat from the screen");
    btnClearLogcat.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            LogViewer.setText("");
            File file = new File(".logcat.txt");
            if (file.exists() && !file.isDirectory()) {
                file.delete();
            }
            ApplicationStatus.setText("Logcat cleared");
        }
    });
    btnClearLogcat.setBounds(12, 13, 220, 48);
    panel_4.add(btnClearLogcat);

    JButton btnViewLogcat = new JButton("View Logcat");
    btnViewLogcat.setToolTipText("Print android device logcat on screen");
    btnViewLogcat.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            ApplicationStatus.setText("Generating logcat, please wait a moment...");
            try {
                Process p1 = Runtime.getRuntime().exec("adb logcat -d > /sdcard/.logcat.txt");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("adb logcat -c");
                p2.waitFor();
                Process p3 = Runtime.getRuntime().exec("adb pull /sdcard/.logcat.txt");
                p3.waitFor();
                Process p4 = Runtime.getRuntime().exec("adb shell rm /sdcard/.logcat.txt");
                p4.waitFor();
                try {
                    Reader reader = new FileReader(new File(".logcat.txt"));
                    LogViewer.read(reader, "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                File file = new File(".logcat.txt");
                if (file.exists() && !file.isDirectory()) {
                    file.delete();
                }
                ApplicationStatus.setText("");
            } catch (Exception e) {
                System.err.println(e);
            }
        }
    });

    btnViewLogcat.setBounds(838, 13, 220, 47);
    panel_4.add(btnViewLogcat);

    JLabel lblNoteLogcatG = new JLabel(
            "Note: Logcat generation takes some time, program may not respond for a few moments");
    lblNoteLogcatG.setBounds(12, 364, 1046, 15);
    panel_4.add(lblNoteLogcatG);

    JPanel panel = new JPanel();
    panel.setBackground(Color.WHITE);
    tabbedPane.addTab("Flasher", null, panel, null);
    panel.setLayout(null);

    final JButton btnFlashSystem = new JButton("System");
    btnFlashSystem.setToolTipText("Flash system partition");
    btnFlashSystem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase system");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "system";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashSystem.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    final JButton btnFlashData = new JButton("Data");
    btnFlashData.setToolTipText("Flash data partition");
    btnFlashData.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase data");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "data";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashData.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    final JButton btnFlashViaRecovery = new JButton("Flash via Recovery");
    btnFlashViaRecovery.setToolTipText("Flash a zip archive using recovery");
    btnFlashViaRecovery.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("zip Files", "zip");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
                    JOptionPane.showMessageDialog(null,
                            "Select Update via ADB from recovery menu using physical keys on your device");
                    String[] commands = new String[3];
                    commands[0] = "adb";
                    commands[1] = "sideload";
                    commands[2] = file.getAbsolutePath();
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec(commands, null);
                    p1.waitFor();
                    ApplicationStatus.setText("Sideloaded...");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashViaRecovery.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    FlasherDone = new JLabel("");
    FlasherDone.setText("");
    FlasherDone.setBounds(760, 29, 300, 220);
    panel.add(FlasherDone);
    btnFlashViaRecovery.setBounds(25, 131, 220, 75);
    panel.add(btnFlashViaRecovery);
    btnFlashData.setBounds(541, 27, 220, 75);
    panel.add(btnFlashData);
    btnFlashSystem.setBounds(282, 236, 220, 75);
    panel.add(btnFlashSystem);

    final JButton btnFlashCache = new JButton("Cache");
    btnFlashCache.setToolTipText("Flash cache partition");
    btnFlashCache.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase cache");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "cache";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashCache.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnFlashCache.setBounds(282, 27, 220, 75);
    panel.add(btnFlashCache);

    final JButton btnBootImage = new JButton("Boot");
    btnBootImage.setToolTipText("Flash boot partition");
    btnBootImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase boot");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "boot";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnBootImage.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnBootImage.setBounds(25, 27, 220, 75);
    panel.add(btnBootImage);

    final JButton btnFlashZipArchive = new JButton("Zip Archive");
    btnFlashZipArchive.setToolTipText("Flash a zip archive");
    btnFlashZipArchive.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("zip Files", "zip");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    String[] commands = new String[3];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = file.getAbsolutePath();
                    Process p1 = Runtime.getRuntime().exec(commands, null);
                    p1.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashZipArchive.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnFlashZipArchive.setBounds(541, 236, 220, 75);
    panel.add(btnFlashZipArchive);

    final JButton btnFlashRecovery = new JButton("Recovery");
    btnFlashRecovery.setToolTipText("Flash recovery partition");
    btnFlashRecovery.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase recovery");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "recovery";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashRecovery.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnFlashRecovery.setBounds(541, 131, 220, 75);
    panel.add(btnFlashRecovery);

    JLabel lblYouMust = new JLabel(
            "Note: Your device's bootloader must support fastboot commands and should be in fastboot mode");
    lblYouMust.setBounds(25, 356, 835, 19);
    panel.add(lblYouMust);

    final JButton btnFlashSplash = new JButton("Splash");
    btnFlashSplash.setToolTipText("Flash splash partition");
    btnFlashSplash.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase splash");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "splash";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashSplash.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnFlashSplash.setBounds(25, 236, 220, 75);
    panel.add(btnFlashSplash);

    JButton btnFlashRadio = new JButton("Radio");
    btnFlashRadio.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase radio");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "radio";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashSplash.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });
    btnFlashRadio.setToolTipText("Flash radio partition");
    btnFlashRadio.setBounds(282, 131, 220, 75);
    panel.add(btnFlashRadio);

    JPanel panel_1 = new JPanel();
    panel_1.setBackground(Color.WHITE);
    tabbedPane.addTab("Wiper", null, panel_1, null);
    panel_1.setLayout(null);

    WiperDone = new JLabel("");
    WiperDone.setText("");
    WiperDone.setBounds(758, 26, 300, 220);
    panel_1.add(WiperDone);

    JLabel label_13 = new JLabel("** Device must be rooted");
    label_13.setBounds(25, 336, 252, 19);
    panel_1.add(label_13);

    JButton btnWipeRecovery = new JButton("Recovery");
    btnWipeRecovery.setToolTipText("Wipe recovery partition");
    btnWipeRecovery.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase cache");
                p1.waitFor();
                ApplicationStatus.setText("Recovery has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeRecovery.setBounds(541, 131, 220, 75);
    panel_1.add(btnWipeRecovery);

    JButton btnWipeBoot = new JButton("Boot");
    btnWipeBoot.setToolTipText("Flash boot partition");
    btnWipeBoot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase boot");
                p1.waitFor();
                ApplicationStatus.setText("Boot has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeBoot.setBounds(25, 27, 220, 75);
    panel_1.add(btnWipeBoot);

    JButton btnWipeSystem = new JButton("System");
    btnWipeSystem.setToolTipText("Wipe system partition");
    btnWipeSystem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase system");
                p1.waitFor();
                ApplicationStatus.setText("System has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeSystem.setBounds(282, 236, 220, 75);
    panel_1.add(btnWipeSystem);

    JButton btnWipeSplash = new JButton("Splash");
    btnWipeSplash.setToolTipText("Wipe splash partition");
    btnWipeSplash.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase splash");
                p1.waitFor();
                ApplicationStatus.setText("Splash has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeSplash.setBounds(25, 236, 220, 75);
    panel_1.add(btnWipeSplash);

    JButton btnWipeData = new JButton("Data");
    btnWipeData.setToolTipText("Wipe data partition");
    btnWipeData.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase data");
                p1.waitFor();
                ApplicationStatus.setText("Data has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeData.setBounds(25, 131, 220, 75);
    panel_1.add(btnWipeData);

    JButton btnFlashDalvikCache = new JButton("Dalvik Cache **");
    btnFlashDalvikCache.setToolTipText("Wipe dalvik cache");
    btnFlashDalvikCache.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("adb shell su -c rm * /data/dalvik-cache");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("adb shell su -c rm * /cache/dalvik-cache");
                p2.waitFor();
                ApplicationStatus.setText("Dalvik Cache has been wiped! Now rebooting device...");
                Process p3 = Runtime.getRuntime().exec("adb reboot");
                p3.waitFor();
                ApplicationStatus.setText("Done");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnFlashDalvikCache.setBounds(541, 27, 220, 75);
    panel_1.add(btnFlashDalvikCache);

    JButton btnWipeCache = new JButton("Cache");
    btnWipeCache.setToolTipText("Wipe cache partition");
    btnWipeCache.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase cache");
                p1.waitFor();
                ApplicationStatus.setText("Cache has been wiped! Now rebooting device...");
                Process p2 = Runtime.getRuntime().exec("adb reboot");
                p2.waitFor();
                ApplicationStatus.setText("Done");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeCache.setBounds(282, 27, 220, 75);
    panel_1.add(btnWipeCache);

    JButton btnWipeRadio = new JButton("Radio");
    btnWipeRadio.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase radio");
                p1.waitFor();
                ApplicationStatus.setText("Radio has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });
    btnWipeRadio.setToolTipText("Wipe radio partition");
    btnWipeRadio.setBounds(282, 131, 220, 75);
    panel_1.add(btnWipeRadio);

    JLabel lblNoteYourDevices = new JLabel(
            "Note: Your device's bootloader must support fastboot commands and should be in fastboot mode");
    lblNoteYourDevices.setBounds(25, 357, 835, 19);
    panel_1.add(lblNoteYourDevices);

    JPanel panel_3 = new JPanel();
    panel_3.setBackground(Color.WHITE);
    tabbedPane.addTab("Bootloader", null, panel_3, null);
    panel_3.setLayout(null);

    JLabel label_17 = new JLabel("Note: Don't worry if the app says to connect your device while");
    label_17.setBounds(66, 320, 600, 19);
    panel_3.add(label_17);

    JLabel label_18 = new JLabel("android is not booted ex. fastboot, bootloader, booting etc.");
    label_18.setBounds(66, 337, 600, 19);
    panel_3.add(label_18);

    JLabel lblOnlyForNexus = new JLabel(
            "Works only with specific devices ex. Nexus, Android One, FEW MTK devices etc.");
    lblOnlyForNexus.setBounds(66, 351, 600, 24);
    panel_3.add(lblOnlyForNexus);

    JButton btnUnlockBootloader = new JButton("Unlock Bootloader");
    btnUnlockBootloader.setToolTipText("Unlock android device bootloader");
    btnUnlockBootloader.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText(
                        "Unlocking bootloader will factory reset your device and may void your device warranty!");
                JOptionPane.showMessageDialog(null,
                        "You will need to re-enable USB debugging later as your device will get factory reset");
                Process p1 = Runtime.getRuntime().exec("adb reboot bootloader");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("fastboot oem unlock");
                p2.waitFor();
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnUnlockBootloader.setBounds(282, 27, 220, 75);
    panel_3.add(btnUnlockBootloader);

    JButton btnLockBootloader = new JButton("Lock Bootloader");
    btnLockBootloader.setToolTipText("Lock android device bootloader");
    btnLockBootloader.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb reboot bootloader");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("fastboot oem lock");
                p2.waitFor();
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnLockBootloader.setBounds(25, 27, 220, 75);
    panel_3.add(btnLockBootloader);

    JPanel panel_6 = new JPanel();
    panel_6.setBackground(Color.WHITE);
    tabbedPane.addTab("Crypto", null, panel_6, null);
    panel_6.setLayout(null);

    JButton btnSHA512 = new JButton("SHA-512");
    btnSHA512.setToolTipText("Calculate SHA-512 sum of a file");
    btnSHA512.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = new File("");
                ApplicationStatus.setText("Calculating...");
                CalculatedCrypto.setText(DigestUtils.sha512Hex(file.getAbsolutePath()));
                ApplicationStatus.setText("");
            }
        }
    });

    btnSHA512.setBounds(541, 131, 220, 75);
    panel_6.add(btnSHA512);

    JScrollPane scrollPane_2 = new JScrollPane();
    scrollPane_2.setBounds(12, 332, 900, 25);
    panel_6.add(scrollPane_2);

    InputCrypto = new JTextArea();
    InputCrypto.setToolTipText("Input sum to be compared with calculated sum");
    scrollPane_2.setViewportView(InputCrypto);

    JLabel lblLabelCalculatedSum = new JLabel("Calculated Sum :");
    lblLabelCalculatedSum.setBounds(12, 240, 235, 17);
    panel_6.add(lblLabelCalculatedSum);

    JScrollPane scrollPane_1 = new JScrollPane();
    scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scrollPane_1.setBounds(12, 268, 900, 28);
    panel_6.add(scrollPane_1);

    CalculatedCrypto = new JTextArea();
    CalculatedCrypto.setToolTipText("Calclated sum");
    scrollPane_1.setViewportView(CalculatedCrypto);
    CalculatedCrypto.setEditable(false);

    JButton btnSHA384 = new JButton("SHA-384");
    btnSHA384.setToolTipText("Calculate SHA-384 sum of a file");
    btnSHA384.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = new File("");
                ApplicationStatus.setText("Calculating...");
                CalculatedCrypto.setText(DigestUtils.sha384Hex(file.getAbsolutePath()));
                ApplicationStatus.setText("");
            }
        }
    });

    btnSHA384.setBounds(282, 131, 220, 75);
    panel_6.add(btnSHA384);

    JButton btnSHA256 = new JButton("SHA-256");
    btnSHA256.setToolTipText("Calculate SHA-256 sum of a file");
    btnSHA256.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = new File("");
                ApplicationStatus.setText("Calculating...");
                CalculatedCrypto.setText(DigestUtils.sha256Hex(file.getAbsolutePath()));
                ApplicationStatus.setText("");
            }
        }
    });

    btnSHA256.setBounds(25, 131, 220, 75);
    panel_6.add(btnSHA256);

    JButton btnSHA1 = new JButton("SHA-1");
    btnSHA1.setToolTipText("Calculate SHA-1 sum of a file");
    btnSHA1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = new File("");
                ApplicationStatus.setText("Calculating...");
                CalculatedCrypto.setText(DigestUtils.sha1Hex(file.getAbsolutePath()));
                ApplicationStatus.setText("");
            }
        }
    });

    btnSHA1.setBounds(541, 27, 220, 75);
    panel_6.add(btnSHA1);

    JButton btnMD5 = new JButton("MD5");
    btnMD5.setToolTipText("Calculate MD5 sum of a file");
    btnMD5.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = new File("");
                ApplicationStatus.setText("Calculating...");
                CalculatedCrypto.setText(DigestUtils.md5Hex(file.getAbsolutePath()));
                ApplicationStatus.setText("");
            }
        }
    });

    btnMD5.setBounds(282, 27, 220, 75);
    panel_6.add(btnMD5);

    JLabel lblInputSumTo = new JLabel("Input Sum to be compared :");
    lblInputSumTo.setBounds(12, 308, 235, 15);
    panel_6.add(lblInputSumTo);

    JButton btnCompare = new JButton("Compare");
    btnCompare.setToolTipText("Click to compare calculated sum and input sum");
    btnCompare.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (InputCrypto.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "Please select algorithm and a file");
            }
            if (CalculatedCrypto.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "Please input a sum to be compared");
            } else {
                if (InputCrypto.getText().equalsIgnoreCase(CalculatedCrypto.getText())) {
                    JOptionPane.showMessageDialog(null, "Both sums are matched");
                } else {
                    JOptionPane.showMessageDialog(null, "Sums are not matched!");
                }
            }
        }
    });
    btnCompare.setBounds(924, 268, 134, 89);
    panel_6.add(btnCompare);

    JButton btnClearCalculatedCrypto = new JButton("Clear");
    btnClearCalculatedCrypto.setToolTipText("Clear the calculated sum");
    btnClearCalculatedCrypto.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            CalculatedCrypto.setText("");
            InputCrypto.setText("");
        }
    });
    btnClearCalculatedCrypto.setBounds(25, 27, 220, 75);
    panel_6.add(btnClearCalculatedCrypto);

    JLabel label_2 = new JLabel("");
    label_2.setBounds(50, 0, 1038, 256);
    label_2.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Interface_logo.png")));
    contentPane.add(label_2);

    new Updater();

    Thread t = new Thread(r); // Background services
    t.start();

    Runtime.getRuntime().addShutdownHook(new Thread() { // Exit sequence
        public void run() {
            try {
                System.out.println("Killing ADB instance...");
                Process p1 = Runtime.getRuntime().exec("adb kill-server");
                p1.waitFor();
                System.out.println("Cleaning cache...");
                File file2 = new File(".CheckADBConnection");
                if (file2.exists() && !file2.isDirectory()) {
                    file2.delete();
                }
                File file3 = new File("su");
                if (file3.exists() && !file3.isDirectory()) {
                    file3.delete();
                }
                File file4 = new File(".logcat.txt");
                if (file4.exists() && !file4.isDirectory()) {
                    file4.delete();
                }
                File file5 = new File(".userapps.txt");
                if (file5.exists() && !file5.isDirectory()) {
                    file5.delete();
                }
                File file6 = new File(".privapps.txt");
                if (file6.exists() && !file6.isDirectory()) {
                    file6.delete();
                }
                File file7 = new File(".systemapps.txt");
                if (file7.exists() && !file7.isDirectory()) {
                    file4.delete();
                }
                System.out.println("Droid PC Suite terminated");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
}

From source file:com.smanempat.controller.ControllerEvaluation.java

public void proccessMining(JTable tableDataSetModel, JTable tableDataSetTesting, JTextField txtNumberOfK,
        JLabel labelPesanError, JTabbedPane jTabbedPane1, JTable tableResult, JTable tableConfMatrix,
        JTable tableTahunTesting, JLabel totalAccuracy, JPanel panelChart, JPanel panelChart1,
        JPanel panelChart2, JRadioButton singleTesting, JRadioButton multiTesting, JTextArea txtArea)
        throws SQLException {
    Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
    modelEvaluation = new ModelEvaluation();
    int rowCountModel = tableDataSetModel.getRowCount();
    int rowCountTest = tableDataSetTesting.getRowCount();
    int[] tempK;//w w w.j  ava2s  .  c o m
    double[][] tempEval;
    double[][] evalValue;
    boolean valid = false;

    /*Validasi Dataset Model dan Dataset Uji*/
    if (rowCountModel == 0) {
        JOptionPane.showMessageDialog(null, "Pilih dataset model terlebih dahulu!", "Error",
                JOptionPane.INFORMATION_MESSAGE,
                new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
        txtNumberOfK.requestFocus();
    } else if (rowCountTest == 0) {
        JOptionPane.showMessageDialog(null, "Pilih dataset uji terlebih dahulu!", "Error",
                JOptionPane.INFORMATION_MESSAGE,
                new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
        txtNumberOfK.requestFocus();
    } else {
        valid = true;
    }
    /*Validasi Dataset Model dan Dataset Uji*/

    if (valid == true) {
        if (multiTesting.isSelected()) {
            String iterasi = JOptionPane.showInputDialog("Input Jumlah Iterasi Pengujian :");
            boolean validMulti = false;

            if (iterasi != null) {

                /*Validasi Jumlah Iterasi*/
                if (Pattern.matches("[0-9]+", iterasi) == false && iterasi.length() > 0) {
                    JOptionPane.showMessageDialog(null, "Nilai iterasi tidak valid!", "Error",
                            JOptionPane.INFORMATION_MESSAGE,
                            new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                } else if (iterasi.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "Nilai iterasi tidak boleh kosong!", "Error",
                            JOptionPane.INFORMATION_MESSAGE,
                            new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                } else if (iterasi.length() == 9) {
                    JOptionPane.showMessageDialog(null, "Nilai iterasi terlalu panjang!", "Error",
                            JOptionPane.INFORMATION_MESSAGE,
                            new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                } else if (rowCountTest > rowCountModel) {

                    JOptionPane.showMessageDialog(null, "Data Uji tidak boleh lebih besar daripada data Model!",
                            "Error", JOptionPane.INFORMATION_MESSAGE,
                            new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                } else {
                    validMulti = true;
                    System.out.println("valiMulti = " + validMulti + " Kok");
                }
                /*Validasi Jumlah Iterasi*/
            }

            if (validMulti == true) {
                tempK = new int[Integer.parseInt(iterasi)];
                evalValue = new double[3][tempK.length];
                for (int i = 0; i < Integer.parseInt(iterasi); i++) {
                    validMulti = false;
                    String k = JOptionPane
                            .showInputDialog("Input Nilai Nearest Neighbor (k) ke " + (i + 1) + " :");
                    if (k != null) {
                        /*Validasi Nilai K Tiap Iterasi*/
                        if (Pattern.matches("[0-9]+", k) == false && k.length() > 0) {
                            JOptionPane.showMessageDialog(null, "Nilai nearest neighbor (k) tidak valid!",
                                    "Error", JOptionPane.INFORMATION_MESSAGE,
                                    new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                        } else if (k.isEmpty()) {
                            JOptionPane.showMessageDialog(null,
                                    "Nilai nearest neighbor (k) tidak boleh kosong!", "Error",
                                    JOptionPane.INFORMATION_MESSAGE,
                                    new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                        } else if (k.length() == 9) {
                            JOptionPane.showMessageDialog(null, "Nilai nearest neighbor (k) terlalu panjang!",
                                    "Error", JOptionPane.INFORMATION_MESSAGE,
                                    new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                        } else {
                            validMulti = true;
                        }
                        /*Validasi Nilai K Tiap Iterasi*/
                    }

                    if (validMulti == true) {
                        tempK[i] = Integer.parseInt(k);
                        System.out.println(tempK[i]);
                    } else {
                        break;
                    }
                }

                if (validMulti == true) {
                    for (int i = 0; i < tempK.length; i++) {
                        int kValue = tempK[i];
                        String[][] modelValue = getModelValue(rowCountModel, tableDataSetModel);
                        double[][] testValue = getTestvalue(rowCountTest, tableDataSetTesting);
                        String[] knnValue = getKNNValue(rowCountModel, rowCountTest, modelValue, testValue,
                                kValue);
                        tempEval = evaluationModel(tableResult, tableConfMatrix, totalAccuracy,
                                tableTahunTesting, tableDataSetTesting, knnValue, i, tempK, panelChart);
                        //Menampung nilai Accuracy
                        evalValue[0][i] = tempEval[0][i];
                        //Menampung nilai Recall
                        evalValue[1][i] = tempEval[1][i];
                        //Menampung nilai Precision
                        evalValue[2][i] = tempEval[2][i];
                        jTabbedPane1.setSelectedIndex(1);
                        txtArea.append(
                                "Tingkat Keberhasilan Sistem dengan Nilai Number of Nearest Neighbor (K) = "
                                        + tempK[i] + "\n");
                        txtArea.append("Akurasi\t\t: " + evalValue[0][i] * 100 + " %\n");
                        txtArea.append("Recall\t\t: " + evalValue[1][i] * 100 + " %\n");
                        txtArea.append("Precision\t: " + evalValue[2][i] * 100 + " %\n");
                        txtArea.append(
                                "=============================================================================\n");
                    }
                    showChart(tempK, evalValue, panelChart, panelChart1, panelChart2);
                }
            }
        } else if (singleTesting.isSelected()) {
            boolean validSingle = false;
            String k = txtNumberOfK.getText();
            int nilaiK = 0;
            evalValue = new double[3][1];

            /*Validasi Nilai Number of Nearest Neighbor*/
            if (Pattern.matches("[0-9]+", k) == false && k.length() > 0) {
                labelPesanError.setText("Number of Nearest Neighbor tidak valid");
                JOptionPane.showMessageDialog(null, "Number of Nearest Neighbor tidak valid!", "Error",
                        JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                txtNumberOfK.requestFocus();
            } else if (k.isEmpty()) {
                JOptionPane.showMessageDialog(null, "Number of Nearest Neighbor tidak boleh kosong!", "Error",
                        JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                labelPesanError.setText("Number of Nearest Neighbor tidak boleh kosong");
                txtNumberOfK.requestFocus();
            } else if (rowCountModel == 0 && Integer.parseInt(k) >= rowCountModel) {
                JOptionPane.showMessageDialog(null, "Pilih dataset model terlebih dahulu!", "Error",
                        JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                txtNumberOfK.requestFocus();
            } else if (rowCountTest == 0 && Integer.parseInt(k) >= rowCountTest) {
                JOptionPane.showMessageDialog(null, "Pilih dataset uji terlebih dahulu!", "Error",
                        JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                txtNumberOfK.requestFocus();
            } else if (Integer.parseInt(k) >= rowCountModel) {
                JOptionPane.showMessageDialog(null,
                        "Number of Nearest Neighbor tidak boleh lebih dari " + rowCountModel + " !", "Error",
                        JOptionPane.INFORMATION_MESSAGE,
                        new ImageIcon(getClass().getResource("/com/smanempat/image/fail.png")));
                txtNumberOfK.requestFocus();
            } else {
                validSingle = true;
                nilaiK = Integer.parseInt(k);
            }
            /*Validasi Nilai Number of Nearest Neighbor*/

            if (validSingle == true) {
                int confirm;
                int i = 0;
                confirm = JOptionPane.showOptionDialog(null, "Yakin ingin memproses data?",
                        "Proses Klasifikasi", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                        null, null);
                if (confirm == JOptionPane.OK_OPTION) {

                    int kValue = Integer.parseInt(txtNumberOfK.getText());
                    String[][] modelValue = getModelValue(rowCountModel, tableDataSetModel);
                    double[][] testValue = getTestvalue(rowCountTest, tableDataSetTesting);
                    String[] knnValue = getKNNValue(rowCountModel, rowCountTest, modelValue, testValue, kValue);
                    tempEval = evaluationModel(tableResult, tableConfMatrix, totalAccuracy, tableTahunTesting,
                            tableDataSetTesting, knnValue, nilaiK, panelChart);
                    evalValue[0][i] = tempEval[0][0];
                    evalValue[1][i] = tempEval[1][0];
                    evalValue[2][i] = tempEval[2][0];
                    jTabbedPane1.setSelectedIndex(1);
                }
                System.out.println("com.smanempat.controller.ControllerEvaluation.proccessMining()OKOKOK");
                showChart(nilaiK, evalValue, panelChart, panelChart1, panelChart2);
                Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
            }
        }
    }

}

From source file:org.olivier.ihm.FramePUMLCleanerControler.java

/**
 * Filtre le fichier PUML stock dans le textArea  partir du filtre contenu
 * dans le JTree/*from   ww  w.j  av a  2s .co m*/
 *
 * @param jTextAreaFichier
 * @param jTreeFiltre
 */
private void filtrerFichier(JTextArea jTextAreaFichier, JTree jTreeFiltre) {
    jTextAreaFichier.setText("");
    // Liste des noeuds  supprimer
    final DefaultMutableTreeNode nodeToDelete = getNodeToDelete(
            (DefaultMutableTreeNode) jTreeFiltre.getModel().getRoot(),
            checkTreeManager.getSelectionModel().getSelectionPaths());

    // traitement des lignes
    for (String line : lines) {
        if (isLinePrintable(line, nodeToDelete)) {
            jTextAreaFichier.append(line + "\n");
        }
    }
    jTextAreaFichier.requestFocus();
}

From source file:org.openscience.jmol.app.Jmol.java

public static void main(String[] args) {

    Dialog.setupUIManager();/*from w w  w.  j  a  v  a2s  . co  m*/

    Jmol jmol = null;

    String modelFilename = null;
    String scriptFilename = null;

    Options options = new Options();
    options.addOption("b", "backgroundtransparent", false, GT._("transparent background"));
    options.addOption("h", "help", false, GT._("give this help page"));
    options.addOption("n", "nodisplay", false, GT._("no display (and also exit when done)"));
    options.addOption("c", "check", false, GT._("check script syntax only"));
    options.addOption("i", "silent", false, GT._("silent startup operation"));
    options.addOption("l", "list", false, GT._("list commands during script execution"));
    options.addOption("o", "noconsole", false, GT._("no console -- all output to sysout"));
    options.addOption("t", "threaded", false, GT._("independent commmand thread"));
    options.addOption("x", "exit", false, GT._("exit after script (implicit with -n)"));

    OptionBuilder.withLongOpt("script");
    OptionBuilder.withDescription("script file to execute");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("s"));

    OptionBuilder.withLongOpt("menu");
    OptionBuilder.withDescription("menu file to use");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("m"));

    OptionBuilder.withArgName(GT._("property=value"));
    OptionBuilder.hasArg();
    OptionBuilder.withValueSeparator();
    OptionBuilder.withDescription(GT._("supported options are given below"));
    options.addOption(OptionBuilder.create("D"));

    OptionBuilder.withLongOpt("geometry");
    // OptionBuilder.withDescription(GT._("overall window width x height, e.g. {0}", "-g512x616"));
    OptionBuilder.withDescription(GT._("window width x height, e.g. {0}", "-g500x500"));
    OptionBuilder.withValueSeparator();
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("g"));

    OptionBuilder.withLongOpt("quality");
    // OptionBuilder.withDescription(GT._("overall window width x height, e.g. {0}", "-g512x616"));
    OptionBuilder.withDescription(GT._(
            "JPG image quality (1-100; default 75) or PNG image compression (0-9; default 2, maximum compression 9)"));
    OptionBuilder.withValueSeparator();
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("q"));

    OptionBuilder.withLongOpt("write");
    OptionBuilder
            .withDescription(GT._("{0} or {1}:filename", new Object[] { "CLIP", "GIF|JPG|JPG64|PNG|PPM" }));
    OptionBuilder.withValueSeparator();
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("w"));

    int startupWidth = 0, startupHeight = 0;

    CommandLine line = null;
    try {
        CommandLineParser parser = new PosixParser();
        line = parser.parse(options, args);
    } catch (ParseException exception) {
        System.err.println("Unexpected exception: " + exception.toString());
    }

    if (line.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jmol", options);

        // now report on the -D options
        System.out.println();
        System.out.println(GT._("For example:"));
        System.out.println();
        System.out.println("Jmol -ions myscript.spt -w JPEG:myfile.jpg > output.txt");
        System.out.println();
        System.out.println(GT._("The -D options are as follows (defaults in parenthesis):"));
        System.out.println();
        System.out.println("  cdk.debugging=[true|false] (false)");
        System.out.println("  cdk.debug.stdout=[true|false] (false)");
        System.out.println("  display.speed=[fps|ms] (ms)");
        System.out.println("  JmolConsole=[true|false] (true)");
        System.out.println("  jmol.logger.debug=[true|false] (false)");
        System.out.println("  jmol.logger.error=[true|false] (true)");
        System.out.println("  jmol.logger.fatal=[true|false] (true)");
        System.out.println("  jmol.logger.info=[true|false] (true)");
        System.out.println("  jmol.logger.logLevel=[true|false] (false)");
        System.out.println("  jmol.logger.warn=[true|false] (true)");
        System.out.println("  plugin.dir (unset)");
        System.out.println("  user.language=[CA|CS|DE|EN|ES|FR|NL|PT|TR] (EN)");

        System.exit(0);
    }

    args = line.getArgs();
    if (args.length > 0) {
        modelFilename = args[0];
    }

    // Process more command line arguments
    // these are also passed to viewer

    String commandOptions = "";

    //silent startup
    if (line.hasOption("i")) {
        commandOptions += "-i";
        isSilent = Boolean.TRUE;
    }

    // transparent background
    if (line.hasOption("b")) {
        commandOptions += "-b";
    }

    // independent command thread
    if (line.hasOption("t")) {
        commandOptions += "-t";
    }

    //list commands during script operation
    if (line.hasOption("l")) {
        commandOptions += "-l";
    }

    //output to sysout
    if (line.hasOption("o")) {
        commandOptions += "-o";
        haveConsole = Boolean.FALSE;
    }

    //no display (and exit)
    if (line.hasOption("n")) {
        // this ensures that noDisplay also exits
        commandOptions += "-n-x";
        haveDisplay = Boolean.FALSE;
    }

    //check script only
    if (line.hasOption("c")) {
        commandOptions += "-c";
    }

    //run script
    if (line.hasOption("s")) {
        commandOptions += "-s";
        scriptFilename = line.getOptionValue("s");
    }

    //menu file
    if (line.hasOption("m")) {
        menuFile = line.getOptionValue("m");
    }

    //exit when script completes (or file is read)
    if (line.hasOption("x")) {
        commandOptions += "-x";
    }
    String imageType_name = null;
    //write image to clipboard or image file  
    if (line.hasOption("w")) {
        imageType_name = line.getOptionValue("w");
    }

    Dimension size;
    try {
        String vers = System.getProperty("java.version");
        if (vers.compareTo("1.1.2") < 0) {
            System.out.println("!!!WARNING: Swing components require a " + "1.1.2 or higher version VM!!!");
        }

        size = historyFile.getWindowSize(JMOL_WINDOW_NAME);
        if (size != null && haveDisplay.booleanValue()) {
            startupWidth = size.width;
            startupHeight = size.height;
        }

        //OUTER window dimensions
        /*
         if (line.hasOption("g") && haveDisplay.booleanValue()) {
         String geometry = line.getOptionValue("g");
         int indexX = geometry.indexOf('x');
         if (indexX > 0) {
         startupWidth = parseInt(geometry.substring(0, indexX));
         startupHeight = parseInt(geometry.substring(indexX + 1));
         }
         }
         */

        Point b = historyFile.getWindowBorder(JMOL_WINDOW_NAME);
        //first one is just approximate, but this is set in doClose()
        //so it will reset properly -- still, not perfect
        //since it is always one step behind.
        if (b == null)
            border = new Point(12, 116);
        else
            border = new Point(b.x, b.y);
        //note -- the first time this is run after changes it will not work
        //because there is a bootstrap problem.

        int width = -1;
        int height = -1;
        int quality = 75;
        //INNER frame dimensions
        if (line.hasOption("g")) {
            String geometry = line.getOptionValue("g");
            int indexX = geometry.indexOf('x');
            if (indexX > 0) {
                width = Parser.parseInt(geometry.substring(0, indexX));
                height = Parser.parseInt(geometry.substring(indexX + 1));
                //System.out.println("setting geometry to " + geometry + " " + border + " " + startupWidth + startupHeight);
            }
            if (haveDisplay.booleanValue()) {
                startupWidth = width + border.x;
                startupHeight = height + border.y;
            }
        }

        if (line.hasOption("q"))
            quality = Parser.parseInt(line.getOptionValue("q"));

        if (imageType_name != null)
            commandOptions += "-w\1" + imageType_name + "\t" + width + "\t" + height + "\t" + quality + "\1";

        if (startupWidth <= 0 || startupHeight <= 0) {
            startupWidth = 500 + border.x;
            startupHeight = 500 + border.y;
        }
        JFrame jmolFrame = new JFrame();
        Point jmolPosition = historyFile.getWindowPosition(JMOL_WINDOW_NAME);
        if (jmolPosition != null) {
            jmolFrame.setLocation(jmolPosition);
        }

        //now pass these to viewer
        jmol = getJmol(jmolFrame, startupWidth, startupHeight, commandOptions);

        // Open a file if one is given as an argument -- note, this CAN be a script file
        if (modelFilename != null) {
            jmol.viewer.openFile(modelFilename);
            jmol.viewer.getOpenFileError();
        }

        // OK, by now it is time to execute the script
        if (scriptFilename != null) {
            report("Executing script: " + scriptFilename);
            if (haveDisplay.booleanValue())
                jmol.splash.showStatus(GT._("Executing script..."));
            jmol.viewer.evalFile(scriptFilename);
        }
    } catch (Throwable t) {
        System.out.println("uncaught exception: " + t);
        t.printStackTrace();
    }

    if (haveConsole.booleanValue()) {
        Point location = jmol.frame.getLocation();
        size = jmol.frame.getSize();
        // Adding console frame to grab System.out & System.err
        consoleframe = new JFrame(GT._("Jmol Java Console"));
        consoleframe.setIconImage(jmol.frame.getIconImage());
        try {
            final ConsoleTextArea consoleTextArea = new ConsoleTextArea();
            consoleTextArea.setFont(java.awt.Font.decode("monospaced"));
            consoleframe.getContentPane().add(new JScrollPane(consoleTextArea), java.awt.BorderLayout.CENTER);
            if (Boolean.getBoolean("clearConsoleButton")) {
                JButton buttonClear = new JButton(GT._("Clear"));
                buttonClear.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        consoleTextArea.setText("");
                    }
                });
                consoleframe.getContentPane().add(buttonClear, java.awt.BorderLayout.SOUTH);
            }
        } catch (IOException e) {
            JTextArea errorTextArea = new JTextArea();
            errorTextArea.setFont(java.awt.Font.decode("monospaced"));
            consoleframe.getContentPane().add(new JScrollPane(errorTextArea), java.awt.BorderLayout.CENTER);
            errorTextArea.append(GT._("Could not create ConsoleTextArea: ") + e);
        }

        Dimension consoleSize = historyFile.getWindowSize(CONSOLE_WINDOW_NAME);
        Point consolePosition = historyFile.getWindowPosition(CONSOLE_WINDOW_NAME);
        if ((consoleSize != null) && (consolePosition != null)) {
            consoleframe.setBounds(consolePosition.x, consolePosition.y, consoleSize.width, consoleSize.height);
        } else {
            consoleframe.setBounds(location.x, location.y + size.height, size.width, 200);
        }

        Boolean consoleVisible = historyFile.getWindowVisibility(CONSOLE_WINDOW_NAME);
        if ((consoleVisible != null) && (consoleVisible.equals(Boolean.TRUE))) {
            consoleframe.show();
        }
    }
}

From source file:org.shaman.rpg.editor.dbviewer.TreeTableModelFactory.java

private static void showErrors(ErrorCollector collector) {
    JTextArea area = new JTextArea();
    for (Map.Entry<String, Integer> e : collector.entries.entrySet()) {
        area.append(e.getValue().toString());
        area.append("x: ");
        area.append(e.getKey());//from  ww  w .  j ava  2 s . co m
        area.append("\n");
    }
    JScrollPane pane = new JScrollPane(area);
    pane.setMinimumSize(new Dimension(200, 50));
    DialogDisplayer.getDefault()
            .notifyLater(new NotifyDescriptor.Message(pane, NotifyDescriptor.ERROR_MESSAGE));
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public void doBlastn(final String fasta, final String evaluestr, final boolean ids, final RunnableResult rr,
        boolean show) {
    /*File blastn;/*from w ww  .j a  v  a  2s.c o m*/
    File blastp;
    File makeblastdb;
    File blastx = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastx.exe" );
    if( !blastx.exists() ) {
       blastx = new File( "/opt/ncbi-blast-2.2.29+/bin/blastx" );
       if( !blastx.exists() ) {
    blastx = new File( "/usr/local/ncbi/blast/bin/blastx" );
    blastn = new File( "/usr/local/ncbi/blast/bin/blastn" );
    blastp = new File( "/usr/local/ncbi/blast/bin/blastp" );
            
    makeblastdb = new File( "/usr/local/ncbi/blast/bin/makeblastdb" );
       } else {
    blastn = new File( "/opt/ncbi-blast-2.2.29+/bin/blastn" );
    blastp = new File( "/opt/ncbi-blast-2.2.29+/bin/blastp" );
            
    makeblastdb = new File( "/opt/ncbi-blast-2.2.29+/bin/makeblastdb" );
       }
    } else {
       blastn = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastn.exe" );
       blastp = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastp.exe" );
               
       makeblastdb = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\makeblastdb.exe" );
    }*/

    int procs = Runtime.getRuntime().availableProcessors();
    String[] mcmds = { "makeblastdb", "-dbtype", "nucl", "-title", "tmp", "-out", "tmp" };
    List<String> lcmd = new ArrayList<String>(Arrays.asList(mcmds));

    final ProcessBuilder mpb = new ProcessBuilder(lcmd);
    mpb.redirectErrorStream(true);
    try {
        final Process mp = mpb.start();

        new Thread() {
            public void run() {
                try {
                    OutputStream pos = mp.getOutputStream();
                    for (String cname : geneset.contigmap.keySet()) {
                        Sequence c = geneset.contigmap.get(cname);
                        if (ids)
                            pos.write((">" + c.id + "\n").getBytes());
                        else {
                            pos.write((">" + c.getName() + "\n").getBytes());
                        }
                        StringBuilder sb = c.getStringBuilder();
                        for (int i = 0; i < sb.length(); i += 70) {
                            pos.write(sb.substring(i, Math.min(sb.length(), i + 70)).getBytes());
                        }
                        pos.write('\n');
                    }
                    pos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            public void run() {
                try {
                    InputStream pin = mp.getInputStream();
                    InputStreamReader rdr = new InputStreamReader(pin);
                    //FileReader fr = new FileReader( new File("c:/dot.blastout") );
                    BufferedReader br = new BufferedReader(rdr);
                    String line = br.readLine();
                    while (line != null) {
                        System.out.println(line);
                        line = br.readLine();
                    }
                    pin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.run();

        //File blastFile = blastn; //dbType.equals("prot") ? type.equals("prot") ? blastp : blastx : blastn;

        String[] cmds1 = { "blastn", "-dust", "no", "-perc_identity", "99", "-word_size", "21", "-query", "-",
                "-db", "tmp", "-evalue", evaluestr, "-num_threads", Integer.toString(procs) };
        String[] cmds2 = { "blastn", "-query", "-", "-db", "tmp", "-evalue", evaluestr, "-num_threads",
                Integer.toString(procs) };
        String[] cmds = show ? cmds2 : cmds1;

        lcmd = new ArrayList<String>(Arrays.asList(cmds));
        //String[] exts = extrapar.trim().split("[\t ]+");

        ProcessBuilder pb = new ProcessBuilder(lcmd);
        pb.redirectErrorStream(true);
        final Process p = pb.start();

        final Thread t = new Thread() {
            public void run() {
                try {
                    OutputStream pos = p.getOutputStream();
                    pos.write(fasta.getBytes());
                    pos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();

        Map<String, Set<String>> tph = new HashMap<String, Set<String>>();
        Map<String, Map<String, String>> tvp = new HashMap<String, Map<String, String>>();
        Map<String, Map<String, String>> tmr = new HashMap<String, Map<String, String>>();

        Map<String, Integer> specindex = new LinkedHashMap<String, Integer>();
        Map<String, Integer> phindex = new LinkedHashMap<String, Integer>();

        /*final Thread t2 = new Thread() {
           public void run() {*/
        try {
            System.err.println("WHY NOT");
            InputStreamReader rdr = new InputStreamReader(p.getInputStream());
            //FileReader fr = new FileReader( new File("c:/dot.blastout") );

            String qspec = null;
            String query = null;
            String ctype = null;
            Annotation at = new Annotation();
            int o = 0;
            StringBuilder res = new StringBuilder();
            BufferedReader br = new BufferedReader(rdr);
            String line = br.readLine();
            res.append(line + "\n");
            while (line != null) {
                if (line.startsWith("Query= ")) {
                    query = line.substring(7, line.length());
                    int e = query.indexOf("CRISPR") - 1;
                    if (e > 0) {
                        qspec = query.substring(0, e);
                        qspec = Sequence.getSpec(qspec);
                        String rest = query.substring(e + 8);
                        int ri = rest.lastIndexOf('-');
                        if (ri != -1)
                            ctype = rest.substring(ri + 1);
                    } else {
                        System.err.println();
                    }

                    line = br.readLine();
                    res.append(line + "\n");
                    while (!line.startsWith("Length")) {
                        line = br.readLine();
                        res.append(line + "\n");
                    }
                    o = Integer.parseInt(line.substring(7));
                } else if (line.startsWith("> ")) {
                    String contname = line.substring(1).trim();
                    //line = br.readLine();
                    //res.append( line+"\n" );
                    //int o = Integer.parseInt( line.substring(7) );

                    Sequence cont = geneset.contigmap.get(contname);

                    if (cont != null) {
                        int start = -1;
                        int stop = 0;
                        line = br.readLine();
                        res.append(line + "\n");
                        String lastmatch = null;
                        while (line != null && !line.startsWith(">")
                                && !line.startsWith("Query=") /*&& !line.contains("Expect =")*/ ) {
                            if (line.startsWith("Sbjct")) {
                                String[] split = line.split("[\t ]+");
                                int k = Integer.parseInt(split[1]);
                                int m = Integer.parseInt(split[3]);
                                lastmatch = split[2];

                                if (start == -1)
                                    start = k;
                                stop = m;
                            }
                            line = br.readLine();
                            res.append(line + "\n");
                        }

                        if (start > stop) {
                            int tmp = start;
                            start = stop;
                            stop = tmp;
                        }

                        at.start = start;
                        at.stop = stop;

                        //if( stop - start < o*2 ) {
                        List<Annotation> lann = cont.getAnnotations();
                        if (lann != null) {
                            int k = Collections.binarySearch(lann, at);

                            //System.err.println( "kkk  " + k + "   " + lann.size() );

                            if (k < 0)
                                k = -(k + 1) - 1;

                            Annotation ann = lann.get(Math.max(0, k));

                            boolean yes = true;
                            if (ann.type != null && ann.type.contains("ummer")) {
                                yes = false;
                            }

                            int u = k - 1;
                            Annotation nann = null;
                            if (u >= 0 && u < lann.size())
                                nann = lann.get(u);

                            u = k + 1;
                            Annotation rann = null;
                            if (u >= 0 && u < lann.size())
                                rann = lann.get(u);

                            if (nann != null && nann.type != null && nann.type.contains("ummer")) {
                                yes = false;
                            }

                            if (rann != null && rann.type != null && rann.type.contains("ummer")) {
                                yes = false;
                            }

                            if (!yes) {
                                //System.err.println();
                            }

                            Gene g = ann.getGene();
                            String desig = ann.designation;

                            if (yes && g != null) { //ann.stop > at.start && ann.start < at.stop ) {
                                GeneGroup gg = g.getGeneGroup();
                                if (desig != null && desig.contains("phage")) {
                                    if (!phindex.containsKey(desig))
                                        phindex.put(desig, phindex.size());

                                    Map<String, String> tvps;
                                    String specname = qspec;//Sequence.nameFix(qspec, true);
                                    if (!specindex.containsKey(specname))
                                        specindex.put(specname, specindex.size());

                                    if (tvp.containsKey(specname)) {
                                        tvps = tvp.get(specname);
                                    } else {
                                        tvps = new HashMap<String, String>();
                                        tvp.put(specname, tvps);
                                    }
                                    tvps.put(desig, ctype);

                                    String contspec = cont.getSpec();
                                    System.err.println(query + " asdf " + contspec + " " + lastmatch + "  "
                                            + at.start + " " + at.stop + "  " + ann.start + " " + ann.stop
                                            + " rann " + (rann != null ? rann.start + "  " + rann.stop : "")
                                            + " nann " + (nann != null ? nann.start + "  " + nann.stop : ""));
                                    if (qspec.equals(contspec)) {
                                        if (tmr.containsKey(specname)) {
                                            tvps = tmr.get(specname);
                                        } else {
                                            tvps = new HashMap<String, String>();
                                            tmr.put(specname, tvps);
                                        }
                                        tvps.put(desig, ctype);
                                    }

                                    /*if( specname.contains("brockianus_MAT_338") ) {
                                       System.err.println();
                                    }*/
                                }

                                Platform.runLater(() -> {
                                    if (!isGeneview()) {
                                        /*int ggindex = geneset.allgenegroups.indexOf( gg );
                                        int i = table.convertRowIndexToView( ggindex );
                                        if( i != -1 ) table.addRowSelectionInterval(i, i);*/

                                        table.getSelectionModel().select(gg);
                                    } else {
                                        /*int gindex = geneset.genelist.indexOf( g );
                                        int i = table.convertRowIndexToView( gindex );
                                        table.addRowSelectionInterval(i, i);*/

                                        gtable.getSelectionModel().select(g);
                                    }
                                });
                            }

                            /*for( Annotation ann : lann ) {
                               if( ann.stop > start && ann.start < stop ) {
                            Gene g = ann.getGene();
                            if( g != null ) {
                               if( table.getModel() == groupModel ) {
                                  GeneGroup gg = g.getGeneGroup();
                                          
                                  int ggindex = allgenegroups.indexOf( gg );
                                  int i = table.convertRowIndexToView( ggindex );
                                  table.addRowSelectionInterval(i, i);
                               } else if( table.getModel() == defaultModel ) {
                                  int gindex = geneset.genelist.indexOf( g );
                                  int i = table.convertRowIndexToView( gindex );
                                  table.addRowSelectionInterval(i, i);
                               }
                            }
                               }
                            }*/
                        }
                        //}
                        continue;
                    }
                }

                /*int i = line.indexOf(' ', 2);
                if( i == -1 ) i = line.length();
                String id = line.substring(2, i);
                        
                Gene g = genemap.get( id );
                if( g != null ) {
                   if( table.getModel() == groupModel ) {
                      i = allgenegroups.indexOf( g.getGeneGroup() );
                      if( i != -1 && i < table.getRowCount() ) {
                         int r = table.convertRowIndexToView( i );
                         table.addRowSelectionInterval(r, r);
                      }
                   } else {
                      i = geneset.genelist.indexOf( g );
                      if( i != -1 && i < table.getRowCount() ) {
                         int r = table.convertRowIndexToView( i );
                         table.addRowSelectionInterval(r, r);
                      }
                   }
                }
                        
                String stuff = line+"\n";
                line = br.readLine();
                while( line != null && !line.startsWith("Query=") && !line.startsWith("> ") ) {
                   stuff += line+"\n";
                   line = br.readLine();
                }
                if( rr != null ) {
                   rr.run( stuff );
                   //res += line+"\n";
                }
                } //else*/
                line = br.readLine();
                res.append(line + "\n");
            }
            br.close();
            p.destroy();

            for (String specname : geneset.speccontigMap.keySet()) {
                List<Sequence> lseq = geneset.speccontigMap.get(specname);
                for (Sequence seq : lseq) {
                    List<Annotation> lann = seq.getAnnotations();
                    if (lann != null) {
                        for (Annotation a : lann) {
                            String desig = a.designation;
                            if (desig != null && desig.contains("phage") && phindex.containsKey(desig)) {
                                if (!specindex.containsKey(specname))
                                    specindex.put(specname, specindex.size());

                                Set<String> tvps;
                                if (tph.containsKey(specname)) {
                                    tvps = tph.get(specname);
                                } else {
                                    tvps = new HashSet<String>();
                                    tph.put(specname, tvps);
                                }
                                tvps.add(desig);
                            }
                        }
                    }
                }
            }

            int k = 0;
            int u = 0;
            Workbook wb = new XSSFWorkbook();
            Sheet sh = wb.createSheet("Phage");
            Row rw = sh.createRow(u++);
            //res = new StringBuilder();
            for (String ph : phindex.keySet()) {
                res.append("\t" + ph);
                rw.createCell(++k).setCellValue(ph);
            }
            res.append("\n");
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);
                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Map<String, String> set = tvp.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.containsKey(ph)) {
                            String type = set.get(ph);
                            if (type == null || type.length() == 0)
                                type = "yes";
                            res.append("\t" + type);
                            rw.createCell(k).setCellValue(type);
                        } else {
                            res.append("\t");
                        }

                        k++;
                    }
                }
                res.append("\n");
            }

            for (String ph : phindex.keySet()) {
                res.append("\t" + ph);
            }
            res.append("\n");

            u++;
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);

                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Map<String, String> set = tmr.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.containsKey(ph)) {
                            String type = set.get(ph);
                            if (type == null || type.length() == 0)
                                type = "yes";
                            res.append("\t" + type);
                            rw.createCell(k).setCellValue(type);
                        } else
                            res.append("\t");

                        k++;
                    }
                }
                res.append("\n");
            }

            u++;
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);

                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Set<String> set = tph.get(rspec);
                Map<String, String> setvp = tvp.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.contains(ph)) {
                            if (setvp != null && setvp.containsKey(ph)) {
                                res.append("\tyes wspacer");
                                rw.createCell(k).setCellValue("yes wspacer");
                            } else {
                                res.append("\tyes");
                                rw.createCell(k).setCellValue("yes");
                            }
                        } else
                            res.append("\t");

                        k++;
                    }
                }
                res.append("\n");
            }

            File file = new File("/Users/sigmar/phage.xlsx");
            FileOutputStream fos = new FileOutputStream(file);
            wb.write(fos);
            fos.close();

            Desktop.getDesktop().open(file);

            //if( !show ) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(800, 600);

            JTextArea ta = new JTextArea();
            ta.setFont(new Font("monospaced", Font.PLAIN, 12));
            ta.append(res.toString());
            JScrollPane sp = new JScrollPane(ta);
            frame.add(sp);

            frame.setVisible(true);

            FileWriter fw = new FileWriter("/Users/sigmar/file.txt");
            fw.write(res.toString());
            fw.close();

            if (rr != null)
                rr.run("close");
            //}

            /*if( rr != null ) {
             rr.run( res );
            }*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*   }
        };
        t2.start();*/
        //fr.close();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public void init(final Stage primaryStage, final Container comp, final SplitPane splitpane,
        final TableView<Gene> genetable, final TableView<Function> upper, final TableView<GeneGroup> lower,
        final MenuBar menubar, final ToolBar toolbar, final ToolBar btoolbar) {
    geneset.user = System.getProperty("user.name");
    JavaFasta.user = geneset.user;/*from   w  ww  .j  ava  2s . c  o  m*/
    this.splitpane = splitpane;
    this.primaryStage = primaryStage;

    table = lower;
    gtable = genetable;
    //SerifyApplet.user = user;

    /*try {
       UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    } catch (ClassNotFoundException e) {
       e.printStackTrace();
    } catch (InstantiationException e) {
       e.printStackTrace();
    } catch (IllegalAccessException e) {
       e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
       e.printStackTrace();
    }*/

    String userhome = System.getProperty("user.home");
    boolean windows = false;
    try {
        InputStream isk = GeneSet.class.getClassLoader().getResourceAsStream("org/simmi/genesetkey");
        //Path gkey = Paths.get( url.toURI() );
        InputStream iskp = GeneSet.class.getClassLoader().getResourceAsStream("org/simmi/genesetkey.pub");
        //Path gkeypub = Paths.get( url.toURI() );

        Path gkeyssh = Paths.get(userhome);
        //Path gkeyssh = userpath.resolve(".ssh");
        if (!Files.exists(gkeyssh))
            Files.createDirectory(gkeyssh);
        Path gkeylocal = gkeyssh.resolve("org/simmi/genesetkey");
        Path gkeylocalpub = gkeyssh.resolve("org/simmi/genesetkey.pub");
        if (!Files.exists(gkeylocal) && isk != null) {
            Files.copy(isk, gkeylocal, StandardCopyOption.REPLACE_EXISTING);
        }
        if (!Files.exists(gkeylocalpub) && iskp != null) {
            Files.copy(iskp, gkeylocalpub);
        }

        Set<PosixFilePermission> poset = new HashSet<PosixFilePermission>();
        poset.add(PosixFilePermission.OWNER_READ);
        poset.add(PosixFilePermission.OWNER_WRITE);
        if (Files.exists(gkeylocal))
            Files.setPosixFilePermissions(gkeylocal, poset);
        if (Files.exists(gkeylocalpub))
            Files.setPosixFilePermissions(gkeylocalpub, poset);
    } catch (IOException e1) {
        e1.printStackTrace();
    } catch (UnsupportedOperationException e2) {
        windows = true;
        e2.printStackTrace();
    }

    if (windows) {
        File f = new File(userhome + "\\genesetkey");
        f.setExecutable(false, false);
        f.setWritable(false, false);
        f.setReadable(false, false);

        f.setWritable(true, true);
        f.setReadable(true, true);
    }

    this.comp = comp;
    selcomb = new ComboBox<>();
    searchcolcomb = new ComboBox<>();
    syncolorcomb = new ComboBox<>();

    searchcolcomb.getItems().add("Name");
    searchcolcomb.getItems().add("Symbol");
    searchcolcomb.getSelectionModel().select(0);

    setColors();

    JMenuBar jmenubar = new JMenuBar();
    Menu file = new Menu("File");

    MenuItem newitem = new MenuItem("New");
    newitem.setOnAction(actionEvent -> newFile());
    file.getItems().add(newitem);

    MenuItem openitem = new MenuItem("Open");
    openitem.setOnAction(actionEvent -> {
        try {
            importStuff();
        } catch (IOException e3) {
            e3.printStackTrace();
        } catch (UnavailableServiceException e3) {
            e3.printStackTrace();
        }
    });
    file.getItems().add(openitem);
    file.getItems().add(new SeparatorMenuItem());

    MenuItem importitem = new MenuItem("Import genomes");
    importitem.setOnAction(actionEvent -> fetchGenomes());
    file.getItems().add(importitem);

    MenuItem exportitem = new MenuItem("Export genomes");
    exportitem.setOnAction(actionEvent -> exportGenomes(geneset.speccontigMap));
    file.getItems().add(exportitem);

    file.getItems().add(new SeparatorMenuItem());

    MenuItem exportproteinitem = new MenuItem("Export protein sequences");
    exportproteinitem.setOnAction(actionEvent -> exportProteinSequences(geneset.genelist));
    file.getItems().add(exportproteinitem);

    MenuItem exportgeneitem = new MenuItem("Export gene clusters");
    exportgeneitem.setOnAction(actionEvent -> exportGeneClusters(geneset.allgenegroups));
    file.getItems().add(exportgeneitem);

    file.getItems().add(new SeparatorMenuItem());

    MenuItem quititem = new MenuItem("Quit");
    quititem.setOnAction(actionEvent -> System.exit(0));
    file.getItems().add(quititem);

    Menu edit = new Menu("Edit");
    MenuItem clustergenes = new MenuItem("Cluster genes");
    clustergenes.setOnAction(actionEvent -> {
        //fxpanel.setScene( null );
        /*Platform.runLater(new Runnable() {
              @Override
              public void run() {
          Label label1 = new Label("Id:");
              tb1 = new TextField("0.5");
              Label label2 = new Label("Len:");
              tb2 = new TextField("0.5");
                      
              VBox vbox = new VBox();
              HBox hbox1 = new HBox();
              hbox1.getChildren().addAll( label1, tb1 );
              HBox hbox2 = new HBox();
              hbox2.getChildren().addAll( label2, tb2 );
                      
              epar = new TextField();
              vbox.getChildren().add( epar );
                      
              vbox.getChildren().addAll( hbox1, hbox2 );
              if( fxs == null ) fxs = new Scene( vbox );
              fxs.setRoot( vbox );
                      
              fxpanel.setScene( fxs );
              }
        });*/

        JPanel panel = new JPanel();
        GridBagLayout grid = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        panel.setLayout(grid);

        /*JLabel label1 = new JLabel("Id:");
        JTextField tb1 = new JTextField("0.5");
        JLabel label2 = new JLabel("Len:");
        JTextField tb2 = new JTextField("0.5");
                
        Dimension d = new Dimension( 300, 30 );
        JTextField epar = new JTextField();
        epar.setSize( d );
        epar.setPreferredSize( d );
                
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridwidth = 1;
        c.gridheight = 1;
                
        c.gridx = 0;
        c.gridy = 0;
        panel.add( label1, c );
        c.gridx = 1;
        c.gridy = 0;
        panel.add( tb1, c );
        c.gridx = 0;
        c.gridy = 1;
        panel.add( label2, c );
        c.gridx = 1;
        c.gridy = 1;
        panel.add( tb2, c );
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 2;
        panel.add( epar, c );
                
        JOptionPane.showMessageDialog(comp, new Object[] {panel}, "Clustering parameters", JOptionPane.PLAIN_MESSAGE );*/

        /*if( tb1 != null ) {
           float id = Float.parseFloat( tb1.getText() );
           float len = Float.parseFloat( tb2.getText() );
           String expar = epar.getText();
                   
           tb1 = null;
           tb2 = null;
           epar = null;*/

        Set<String> species = getSelspec(null, geneset.getSpecies(), null);
        geneset.clusterGenes(species, false);
        //}
    });
    MenuItem alignclusters = new MenuItem("Align clusters");
    alignclusters.setOnAction(actionEvent -> {
        try {
            String OS = System.getProperty("os.name").toLowerCase();

            Map<String, String> env = new HashMap<String, String>();
            env.put("create", "true");
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr);
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
            //s.makeBlastCluster(zipfilesystem.getPath("/"), p, 1);
            Path aldir = geneset.zipfilesystem.getPath("aligned");
            final Path aligneddir = Files.exists(aldir) ? aldir : Files.createDirectory(aldir);

            Runnable run = new Runnable() {
                @Override
                public void run() {
                    try {
                        geneset.zipfilesystem.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            NativeRun nrun = new NativeRun(run);
            //ExecutorService es = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors() );

            Object[] cont = new Object[3];

            Collection<GeneGroup> ggset;
            ObservableList<GeneGroup> ogg = table.getSelectionModel().getSelectedItems();
            ggset = new HashSet<GeneGroup>();
            if (ogg.size() == 0) {
                for (GeneGroup gg : geneset.allgenegroups) {
                    //GeneGroup gg = allgenegroups.get(table.convertRowIndexToModel(r));
                    //gg.getCommonTag()
                    if (gg != null && gg.getCommonTag() == null && gg.size() > 1)
                        ggset.add(gg);
                }
            } else {
                for (GeneGroup gg : ogg) {
                    //GeneGroup gg = geneset.allgenegroups.get(table.convertRowIndexToModel(r));
                    //gg.getCommonTag()
                    if (gg != null && gg.getCommonTag() == null && gg.size() > 1)
                        ggset.add(gg);
                }
            }

            //int i = 0;
            List commandsList = new ArrayList();
            for (GeneGroup gg : ggset) {
                String fasta = gg.getFasta(true);
                String[] cmds = new String[] {
                        OS.indexOf("mac") >= 0 ? "/usr/local/bin/mafft" : "/usr/bin/mafft", "-" };
                Object[] paths = new Object[] { fasta.getBytes(), aligneddir.resolve(gg.getCommonId() + ".aa"),
                        null };
                commandsList.add(paths);
                commandsList.add(Arrays.asList(cmds));

                //if( i++ > 5000 ) break;
            }
            nrun.runProcessBuilder("Running mafft", commandsList, cont, true, run, false);
        } catch (IOException e1) {
            if (geneset.zipfilesystem != null) {
                try {
                    geneset.zipfilesystem.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
            e1.printStackTrace();
        }
    });

    MenuItem sharenumaction = new MenuItem("Update share numbers");
    sharenumaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        Set<String> specs = getSelspec(GeneSetHead.this, geneset.specList, null);
        geneset.updateShareNum(specs);
    }));

    MenuItem importgeneclusteringaction = new MenuItem("Import gene clustering");
    importgeneclusteringaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        JPanel panel = new JPanel();
        GridBagLayout grid = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        panel.setLayout(grid);

        JLabel label1 = new JLabel("Id:");
        JTextField tb11 = new JTextField("0.5");
        JLabel label2 = new JLabel("Len:");
        JTextField tb21 = new JTextField("0.5");

        Dimension d = new Dimension(300, 30);
        JTextField epar1 = new JTextField();
        epar1.setSize(d);
        epar1.setPreferredSize(d);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridwidth = 1;
        c.gridheight = 1;

        c.gridx = 0;
        c.gridy = 0;
        panel.add(label1, c);
        c.gridx = 1;
        c.gridy = 0;
        panel.add(tb11, c);
        c.gridx = 0;
        c.gridy = 1;
        panel.add(label2, c);
        c.gridx = 1;
        c.gridy = 1;
        panel.add(tb21, c);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 2;
        panel.add(epar1, c);

        JOptionPane.showMessageDialog(comp, new Object[] { panel }, "Clustering parameters",
                JOptionPane.PLAIN_MESSAGE);

        float id = Float.parseFloat(tb11.getText());
        float len = Float.parseFloat(tb21.getText());

        //JFileChooser fc = new JFileChooser();
        //if( fc.showOpenDialog( GeneSetHead.this ) == JFileChooser.APPROVE_OPTION ) {
        Serifier s = new Serifier();
        //s.mseq = aas;
        for (String gk : geneset.refmap.keySet()) {
            Gene g = geneset.refmap.get(gk);
            if (g.tegeval.getAlignedSequence() != null)
                System.err.println(g.tegeval.getAlignedSequence().getName());
            s.mseq.put(gk, g.tegeval.getAlignedSequence());
        }

        Map<String, String> idspec = new HashMap<String, String>();
        for (String idstr : geneset.refmap.keySet()) {
            if (idstr.contains(" ")) {
                System.err.println("coooonnnnnni " + idstr);
            }

            Gene gene = geneset.refmap.get(idstr);
            idspec.put(idstr, gene.getSpecies());
        }
        //Sequences seqs = new Sequences(user, name, type, path, nseq)
        try {
            Map<String, String> env = new HashMap<String, String>();
            env.put("create", "true");
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr);
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

            Path root = geneset.zipfilesystem.getPath("/");
            Path p = geneset.zipfilesystem.getPath("cluster.blastout"); //root.resolve("culster.blastout");

            List<Set<String>> cluster = geneset.uclusterlist == null ? new ArrayList<>()
                    : new ArrayList<>(geneset.uclusterlist);
            s.makeBlastCluster(root, p, 1, id, len, idspec, cluster, geneset.refmap);

            System.err.println(cluster.get(0));
            if (geneset.uclusterlist != null)
                System.err.println(geneset.uclusterlist.get(0));

            geneset.zipfilesystem.close();
        } catch (IOException e1) {
            if (geneset.zipfilesystem != null) {
                try {
                    geneset.zipfilesystem.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
            e1.printStackTrace();
        }
    }));
    MenuItem importgenesymbolaction = new MenuItem("Import gene symbols");
    importgenesymbolaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        JFileChooser fc = new JFileChooser();
        if (fc.showOpenDialog(GeneSetHead.this) == JFileChooser.APPROVE_OPTION) {
            try {
                Map<String, String> env = new HashMap<>();
                env.put("create", "true");
                //Path path = zipfile.toPath();
                String uristr = "jar:" + geneset.zippath.toUri();
                geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

                Path nf = geneset.zipfilesystem.getPath("/smap_short.txt");
                BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE);

                File f = fc.getSelectedFile();
                InputStream is = new FileInputStream(f);
                if (f.getName().endsWith(".gz"))
                    is = new GZIPInputStream(is);
                geneset.uni2symbol(new InputStreamReader(is), bw, geneset.unimap);

                bw.close();
                //long bl = Files.copy( new ByteArrayInputStream( baos.toByteArray() ), nf, StandardCopyOption.REPLACE_EXISTING );
                geneset.zipfilesystem.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }));

    MenuItem importcazyaction = new MenuItem("Import Cazy");
    importcazyaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        JFileChooser fc = new JFileChooser();
        if (fc.showOpenDialog(GeneSetHead.this) == JFileChooser.APPROVE_OPTION) {
            try {
                BufferedReader rd = Files.newBufferedReader(fc.getSelectedFile().toPath());
                geneset.loadcazymap(geneset.cazymap, rd);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }));

    MenuItem gene2refseqaction = new MenuItem("Gene 2 refseq");
    gene2refseqaction.setOnAction(actionEvent -> {
        try {
            TextField tf = new TextField();
            tf.setText("ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2refseq.gz");
            Dialog<Path> dialog = new Dialog();
            dialog.getDialogPane().setContent(tf);
            dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
            dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
            dialog.setResultConverter(param -> param.getButtonData().isCancelButton() ? null
                    : Paths.get(URI.create(tf.getText())));
            Optional<Path> opath = dialog.showAndWait();

            if (opath.isPresent()) {
                Map<String, String> env = new HashMap<>();
                env.put("create", "true");
                //Path path = zipfile.toPath();
                String uristr = "jar:" + geneset.zippath.toUri();
                geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/);
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

                Path path = opath.get();
                InputStream is = path.toUri().toURL().openStream();
                if (path.getFileName().toString().endsWith(".gz")) {
                    is = new GZIPInputStream(is);
                }
                Path nf = geneset.zipfilesystem.getPath("/org/simmi/gene2refseq_short.txt");
                BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
                geneset.idMapping(new InputStreamReader(is), bw, 5, 1, geneset.refmap, null, geneset.gimap);
                bw.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                geneset.zipfilesystem.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    MenuItem functionmappingaction = new MenuItem("Function mapping");
    functionmappingaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        final JTextField tf = new JTextField();
        JButton btn = new JButton("File");
        JComponent comp2 = new JComponent() {
        };
        comp2.setLayout(new BorderLayout());
        comp2.add(tf);
        comp2.add(btn, BorderLayout.EAST);
        tf.setText("http://130.208.252.239/data/sp2go.txt.gz");

        final File[] file2 = new File[1];
        btn.addActionListener(e -> {
            JFileChooser fc = new JFileChooser();
            if (fc.showOpenDialog(GeneSetHead.this) == JFileChooser.APPROVE_OPTION) {
                file2[0] = fc.getSelectedFile();
                try {
                    tf.setText(fc.getSelectedFile().toURI().toURL().toString());
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }
            }
        });

        try {
            Map<String, String> env = new HashMap<>();
            env.put("create", "true");
            //Path path = zipfile.toPath();
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

            Path nf = geneset.zipfilesystem.getPath("/org/simmi/sp2go_short.txt");
            BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);

            JOptionPane.showMessageDialog(GeneSetHead.this, comp2);

            final JDialog dialog = new JDialog();
            dialog.setTitle("Function mapping");
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setSize(400, 300);

            comp2 = new JComponent() {
            };
            comp2.setLayout(new BorderLayout());

            final JTextArea ta = new JTextArea();
            /*final InputStream fis;
            if( file[0] != null ) fis = new FileInputStream( file[0] );
            else {
            JTextField host = new JTextField("localhost");
            JOptionPane.showMessageDialog(null, host);
                    
            String username = System.getProperty("user.name");
            String hostname = host.getText();
                    
            List<String> commandsList = Arrays.asList( new String[] {"ssh",username+"@"+hostname,"cat",tf.getText()} );
            ProcessBuilder pb = new ProcessBuilder( commandsList );
            Process p = pb.start();
                    
            for( Object commands : commandsList ) {
                if( commands instanceof List ) {
                    for( Object cmd : (List)commands ) {
                        ta.append(cmd+" ");
                    }
                    ta.append("\n");
                } else {
                    ta.append(commands+" ");
                }
            }
            ta.append("\n");
                    
            fis = p.getInputStream();
            }*/

            final JProgressBar pbar = new JProgressBar();
            final Thread t = new Thread() {
                public void run() {
                    try {
                        URL url = new URL(tf.getText());
                        InputStream fis = url.openStream();

                        BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(fis)));
                        //if( unimap != null ) unimap.clear();
                        //unimap = idMapping(new InputStreamReader(is), bw, 2, 0, refmap, genmap, gimap);
                        geneset.funcMappingUni(br, geneset.unimap, bw);

                        fis.close();
                        bw.close();

                        try {
                            geneset.zipfilesystem.close();
                        } catch (Exception e2) {
                            e2.printStackTrace();
                        }
                        ;

                        pbar.setIndeterminate(false);
                        pbar.setEnabled(false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            ta.setEditable(false);
            final JScrollPane sp = new JScrollPane(ta);

            dialog.add(comp2);
            comp2.add(pbar, BorderLayout.NORTH);
            comp2.add(sp, BorderLayout.CENTER);
            pbar.setIndeterminate(true);

            t.start();
            /*okokdialog.addWindowListener( new WindowListener() {
                    
            @Override
            public void windowOpened(WindowEvent e) {}
                    
            @Override
            public void windowIconified(WindowEvent e) {}
                    
            @Override
            public void windowDeiconified(WindowEvent e) {}
                    
            @Override
            public void windowDeactivated(WindowEvent e) {}
                    
            @Override
            public void windowClosing(WindowEvent e) {}
                    
            @Override
            public void windowClosed(WindowEvent e) {
                if( pbar.isEnabled() ) {
                    pbar.setIndeterminate( false );
                    pbar.setEnabled( false );
                }
            }
                    
            @Override
            public void windowActivated(WindowEvent e) {}
            });*/
            dialog.setVisible(true);
            //long bl = Files.copy( new ByteArrayInputStream( baos.toByteArray() ), nf, StandardCopyOption.REPLACE_EXISTING );
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }));
    MenuItem importidmappingaction = new MenuItem("Import idmapping");
    importidmappingaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        final JTextField tf = new JTextField();
        JButton btn = new JButton("File");
        JComponent comp2 = new JComponent() {
        };
        comp2.setLayout(new BorderLayout());
        comp2.add(tf);
        comp2.add(btn, BorderLayout.EAST);
        tf.setText(
                "ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/idmapping/idmapping.dat.gz");

        final File[] file2 = new File[1];
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                if (fc.showOpenDialog(GeneSetHead.this) == JFileChooser.APPROVE_OPTION) {
                    file2[0] = fc.getSelectedFile();
                    try {
                        tf.setText(fc.getSelectedFile().toURI().toURL().toString());
                    } catch (MalformedURLException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        });

        JOptionPane.showMessageDialog(GeneSetHead.this, comp2);

        //Thread t = new Thread() {
        //   public void run() {
        try {
            Map<String, String> env = new HashMap<String, String>();
            env.put("create", "true");
            //Path path = zipfile.toPath();
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

            Path nf = geneset.zipfilesystem.getPath("/org/simmi/idmapping_short.dat");
            final BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE,
                    StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

            final JDialog dialog = new JDialog();
            dialog.setTitle("Id mapping");
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setSize(400, 300);

            comp2 = new JComponent() {
            };
            comp2.setLayout(new BorderLayout());

            final JTextArea ta = new JTextArea();

            /*final InputStream fis;
            if( file[0] != null ) fis = new FileInputStream( file[0] );
            else {
            /*Object[] cont = new Object[3];
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        bw.close();
                        geneset.zipfilesystem.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };*
                    
            JTextField host = new JTextField("localhost");
            JOptionPane.showMessageDialog(null, host);
                    
            String username = System.getProperty("user.name");
            String hostname = host.getText();
                    
            List<String> commandsList = Arrays.asList( new String[] {"ssh",username+"@"+hostname,"cat",tf.getText()} );
            ProcessBuilder pb = new ProcessBuilder( commandsList );
            Process p = pb.start();
                    
            for( Object commands : commandsList ) {
                if( commands instanceof List ) {
                    for( Object cmd : (List)commands ) {
                        ta.append(cmd+" ");
                    }
                    ta.append("\n");
                } else {
                    ta.append(commands+" ");
                }
            }
            ta.append("\n");
                    
            fis = p.getInputStream();
            }*/

            final JProgressBar pbar = new JProgressBar();
            final Thread t = new Thread() {
                public void run() {
                    try {
                        URL url = new URL(tf.getText());
                        InputStream fis = url.openStream();
                        InputStream is = new GZIPInputStream(fis);
                        if (geneset.unimap != null)
                            geneset.unimap.clear();
                        geneset.unimap = geneset.idMapping(new InputStreamReader(is), bw, 2, 0, geneset.refmap,
                                geneset.genmap, geneset.gimap);
                        is.close();
                        fis.close();
                        bw.close();

                        try {
                            geneset.zipfilesystem.close();
                        } catch (Exception ep) {
                            ep.printStackTrace();
                        }
                        ;

                        pbar.setIndeterminate(false);
                        pbar.setEnabled(false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            ta.setEditable(false);
            final JScrollPane sp = new JScrollPane(ta);

            dialog.add(comp2);
            comp2.add(pbar, BorderLayout.NORTH);
            comp2.add(sp, BorderLayout.CENTER);
            pbar.setIndeterminate(true);

            t.start();

            /*System.err.println( "about to run" );
            for( Object commands : commandsList ) {
                if( commands instanceof List ) {
                    for( Object c : (List)commands ) {
                        System.err.print( c+" " );
                    }
                    System.err.println();
                } else {
                    System.err.print( commands+" " );
                }
            }
            System.err.println();*/

            /*okokdialog.addWindowListener( new WindowListener() {
                    
            @Override
            public void windowOpened(WindowEvent e) {}
                    
            @Override
            public void windowIconified(WindowEvent e) {}
                    
            @Override
            public void windowDeiconified(WindowEvent e) {}
                    
            @Override
            public void windowDeactivated(WindowEvent e) {}
                    
            @Override
            public void windowClosing(WindowEvent e) {}
                    
            @Override
            public void windowClosed(WindowEvent e) {
                if( pbar.isEnabled() ) {
                    /*String result = ta.getText().trim();
                    if( run != null ) {
                        cont[0] = null;
                        cont[1] = result;
                        cont[2] = new Date( System.currentTimeMillis() ).toString();
                        run.run();
                    }*
                    
                    pbar.setIndeterminate( false );
                    pbar.setEnabled( false );
                }
            }
                    
            @Override
            public void windowActivated(WindowEvent e) {}
            });*/
            dialog.setVisible(true);

            /*NativeRun nrun = new NativeRun();
            nrun.runProcessBuilder("Idmapping", Arrays.asList( tf.getText().split(" ") ), run, cont, false);
            ProcessBuilder pb = new ProcessBuilder( tf.getText().split(" ") );
            Process p = pb.start();
            fis = p.getInputStream();
            }*/

            //long bl = Files.copy( new ByteArrayInputStream( baos.toByteArray() ), nf, StandardCopyOption.REPLACE_EXISTING );
        } catch (IOException e1) {
            e1.printStackTrace();
            try {
                geneset.zipfilesystem.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            ;
        }
        //   }
        //};
        //t.start();
        //}
    }));
    MenuItem cogblastaction = new MenuItem("Cog blast");
    cogblastaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        Set<String> species = getSelspec(null, geneset.getSpecies(), null);

        if (species != null && species.size() > 0)
            Platform.runLater(() -> cogBlastDlg(species));
    }));
    MenuItem unresolvedblastaction = new MenuItem("Unresolved blast");
    unresolvedblastaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        try {
            Set<String> species = getSelspec(null, geneset.getSpecies(), null);

            StringWriter sb = new StringWriter();
            Path dbPath = Paths.get("/data/nr");
            ObservableList<Gene> genes = gtable.getSelectionModel().getSelectedItems();
            if (genes.size() > 0) {
                if (isGeneview()) {
                    for (Gene g : gtable.getSelectionModel().getSelectedItems()) {
                        //int i = table.convertRowIndexToModel(r);
                        //Gene g = geneset.genelist.get(i);
                        Sequence gs = g.tegeval.getProteinSequence();
                        gs.setName(g.id);
                        gs.writeSequence(sb);
                    }
                } else {
                    for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                        //int i = table.convertRowIndexToModel(r);
                        //GeneGroup gg = geneset.allgenegroups.get(i);
                        Gene g = null;
                        for (Gene gene : gg.genes) {
                            g = gene;
                            break;
                        }
                        Sequence gs = g.tegeval.getProteinSequence();
                        gs.setName(g.id);
                        gs.writeSequence(sb);
                    }
                }
            } else {
                for (Gene g : geneset.genelist) {
                    if (g.getTag() == null || g.getTag().equalsIgnoreCase("gene")) {
                        if (species.contains(g.getSpecies())) {
                            Sequence gs = g.tegeval.getProteinSequence();
                            gs.setName(g.id);
                            gs.writeSequence(sb);

                            /*sb.append(">" + g.id + "\n");
                            for (int i = 0; i < gs.length(); i += 70) {
                            sb.append( gs.substring(i, Math.min( i + 70, gs.length() )) + "\n");
                            }*/
                        }
                    }
                }
            }

            Map<String, String> env = new HashMap<>();
            env.put("create", "true");
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
            Path resPath = geneset.zipfilesystem.getPath("/unresolved.blastout");

            NativeRun nrun = new NativeRun();
            SerifyApplet.blastpRun(nrun, sb.getBuffer(), dbPath, resPath, "-evalue 0.00001", null, true,
                    geneset.zipfilesystem, geneset.user, primaryStage);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }));

    MenuItem importbiosystemsaction = new MenuItem("Import biosystems");
    importbiosystemsaction.setOnAction(actionEvent -> {
        Dialog<Map<String, Set<String>>> dialog = new Dialog();

        TextField gene = new TextField();
        TextField biosys = new TextField();

        gene.setText("ftp://ftp.ncbi.nlm.nih.gov/pub/biosystems/biosystems.20160519/biosystems_gene_all.gz");
        biosys.setText("ftp://ftp.ncbi.nlm.nih.gov/pub/biosystems/biosystems.20160519/bsid2info.gz");

        VBox duo = new VBox();
        duo.getChildren().add(gene);
        duo.getChildren().add(biosys);

        dialog.getDialogPane().setContent(duo);
        dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
        dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
        dialog.setResultConverter(param -> {
            if (!param.getButtonData().isCancelButton()) {
                Map<String, Set<String>> result = null;
                Set<String> geneidset = geneset.genelist.stream().map(g -> g.genid).collect(Collectors.toSet());
                try {
                    InputStream p = new URI(gene.getText()).toURL().openStream();
                    InputStream b = new URI(biosys.getText()).toURL().openStream();

                    if (gene.getText().endsWith(".gz"))
                        p = new GZIPInputStream(p);
                    if (biosys.getText().endsWith(".gz"))
                        b = new GZIPInputStream(b);

                    Map<String, List<String[]>> group = new BufferedReader(new InputStreamReader(p)).lines()
                            .map(l -> l.split("\t")).filter(s -> geneidset.contains(s[1]))
                            .collect(Collectors.groupingBy(s -> s[1]));
                    Set<String> bsids = group.entrySet().stream().flatMap(e -> e.getValue().stream())
                            .map(s -> s[0]).collect(Collectors.toSet());
                    Map<String, String> bsid2name = new BufferedReader(new InputStreamReader(b)).lines()
                            .map(s -> s.split("\t")).filter(s -> bsids.contains(s[0]))
                            .collect(Collectors.toMap(s -> s[0], s -> s[2] + ":" + s[3]));
                    result = group.entrySet().stream()
                            .collect(Collectors.toMap(s -> s.getKey(), s -> s.getValue().stream()
                                    .map(sub -> bsid2name.get(sub[0])).collect(Collectors.toSet())));
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                //Path p = Paths.get(gene.getText());
                //Path b = Paths.get(biosys.getText());
                return result;
            }
            return null;
        });
        Optional<Map<String, Set<String>>> od = dialog.showAndWait();

        if (od.isPresent()) {
            geneset.biosystemsmap = od.get();
            Map<String, String> env = new HashMap<>();
            env.put("create", "true");
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            try {
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                Path resPath = geneset.zipfilesystem.getPath("/biosystems.txt");
                BufferedWriter bw = Files.newBufferedWriter(resPath, StandardOpenOption.TRUNCATE_EXISTING);
                geneset.biosystemsmap.entrySet().stream().forEach(e -> {
                    try {
                        bw.write(e.getKey() + "\t" + e.getValue().stream().collect(Collectors.joining(";"))
                                + "\n");
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                });
                bw.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    geneset.zipfilesystem.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    MenuItem importkeggpathwayaction = new MenuItem("Import kegg pathways");
    importkeggpathwayaction.setOnAction(actionEvent -> {
        Set<String> keggids = new HashSet<>();
        for (Gene g : geneset.genelist) {
            if (g.keggid != null) {
                int i = g.keggid.indexOf(':');
                if (i > 0) {
                    keggids.add(g.keggid.substring(0, i));
                }
            }
        }
        System.err.println(keggids);

        JTextField tf = new JTextField("http://130.208.252.239/organisms/");
        JOptionPane.showMessageDialog(null, tf);

        Map<String, String> env = new HashMap<>();
        env.put("create", "true");

        Path rootp = null;
        try {
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
        } catch (Exception ee) {
            ee.printStackTrace();
        }

        for (Path root : geneset.zipfilesystem.getRootDirectories()) {
            rootp = root;
            break;
        }

        for (String kegg : keggids) {
            try {
                URL url = new URL(tf.getText() + kegg + ".tar.gz");
                InputStream is = url.openStream();
                GZIPInputStream gz = new GZIPInputStream(is);

                TarArchiveInputStream tar = new TarArchiveInputStream(gz);
                TarArchiveEntry tae = (TarArchiveEntry) tar.getNextEntry();
                while (tae != null) {
                    geneset.traverseTar(tar, tae, rootp);

                    tae = (TarArchiveEntry) tar.getNextEntry();
                }

                is.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        try {
            geneset.zipfilesystem.close();
        } catch (Exception ee) {
            ee.printStackTrace();
        }
        ;
    });

    edit.getItems().add(clustergenes);
    edit.getItems().add(alignclusters);
    edit.getItems().add(new SeparatorMenuItem());
    edit.getItems().add(sharenumaction);
    edit.getItems().add(importgeneclusteringaction);
    edit.getItems().add(importgenesymbolaction);
    edit.getItems().add(importcazyaction);
    edit.getItems().add(functionmappingaction);
    edit.getItems().add(importidmappingaction);
    edit.getItems().add(gene2refseqaction);
    edit.getItems().add(importbiosystemsaction);
    edit.getItems().add(importkeggpathwayaction);
    edit.getItems().add(new SeparatorMenuItem());
    edit.getItems().add(cogblastaction);
    edit.getItems().add(unresolvedblastaction);

    Menu view = new Menu("View");
    gb = new RadioMenuItem("Genes");
    gb.setOnAction(actionEvent -> {
        splitpane.getItems().remove(table);
        splitpane.getItems().add(0, gtable);
        //table.setModel( defaultModel );
    });
    view.getItems().add(gb);
    ggb = new RadioMenuItem("Gene groups");
    ggb.setOnAction(actionEvent -> {
        splitpane.getItems().remove(gtable);
        splitpane.getItems().add(0, table);
        //table.setModel( groupModel );
    });

    ToggleGroup bg = new ToggleGroup();
    gb.setToggleGroup(bg);
    ggb.setToggleGroup(bg);
    //ButtonGroup   bg = new ButtonGroup();
    //bg.add( gb );
    //bg.add( ggb );

    ggb.setSelected(true);
    view.getItems().add(ggb);
    ActionCollection.addAll(view, geneset.clusterMap, GeneSetHead.this, geneset.speccontigMap, table, comp,
            geneset.cs);

    Menu help = new Menu("Help");
    MenuItem about = new MenuItem("About");
    about.setOnAction(actionEvent -> SwingUtilities
            .invokeLater(() -> JOptionPane.showMessageDialog(comp, "CompGen 1.0")));
    help.getItems().add(about);

    MenuItem test = new MenuItem("Test");
    test.setOnAction(actionEvent -> {
        /*for( Gene g : geneset.genelist ) {
           Sequence seq = g.tegeval.getContig();
           if( seq == null ) {
          System.err.println();
           }
        }*/

        for (String spec : geneset.speccontigMap.keySet()) {
            if (spec.contains("RAST")) {
                List<Sequence> lseq = geneset.speccontigMap.get(spec);
                for (Sequence seq : lseq) {
                    for (Annotation a : seq.getAnnotations()) {
                        System.err.println(a.getGene().getGeneGroup().species);
                        /*Sequence tseq = a.getContig();
                        if( tseq == null ) {
                           System.err.println();
                        }*/
                    }
                }
            }
        }

        /*for( GeneGroup gg : allgenegroups ) {
           if( gg.species.size() > 1 ) {
          System.err.println( gg.species );
           }
        }*/
    });
    help.getItems().add(test);
    help.getItems().add(new SeparatorMenuItem());
    MenuItem runserver = new MenuItem("Run server");
    runserver.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JSpinner spin = new JSpinner();
                JOptionPane.showMessageDialog(GeneSetHead.this, spin, "Port", JOptionPane.QUESTION_MESSAGE);
                try {
                    geneset.cs = WSServer.startServer(GeneSetHead.this, (Integer) spin.getValue());
                } catch (UnknownHostException e1) {
                    e1.printStackTrace();
                }
            }

        });
    });
    help.getItems().add(runserver);
    help.getItems().add(new SeparatorMenuItem());

    CheckMenuItem cbmi = new CheckMenuItem("Use geneset user");
    help.getItems().add(cbmi);

    cbmi.setOnAction(actionEvent -> {
        if (cbmi.isSelected()) {
            geneset.user = "geneset";
        } else
            geneset.user = System.getProperty("user.name");

        JavaFasta.user = geneset.user;
        if (geneset.currentSerify != null)
            geneset.currentSerify.user = geneset.user;
    });

    help.getItems().add(new SeparatorMenuItem());
    MenuItem helptut = new MenuItem("Help & Tutorial");
    helptut.setOnAction(actionEvent -> {
        try {
            Desktop.getDesktop().browse(new URI("http://thermusgenes.appspot.com/pancore.html"));
        } catch (IOException | URISyntaxException e1) {
            e1.printStackTrace();
        }
    });
    help.getItems().add(helptut);

    Menu sequencemenu = new Menu("Sequence");
    MenuItem showgroupseq = new MenuItem("Show group sequences");
    showgroupseq.setOnAction(actionEvent -> {
        //JTextArea textarea = new JTextArea();
        //JScrollPane scrollpane = new JScrollPane(textarea);

        /*try {
           if (clipboardService == null)
          clipboardService = (ClipboardService) ServiceManager.lookup("javax.jnlp.ClipboardService");
           Action action = new CopyAction("Copy", null, "Copy data", new Integer(KeyEvent.VK_CONTROL + KeyEvent.VK_C));
           textarea.getActionMap().put("copy", action);
           grabFocus = true;
        } catch (Exception ee) {
           ee.printStackTrace();
           System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        }
                
        textarea.setDragEnabled(true);*/

        JFrame frame = null;
        if (geneset.currentSerify == null) {
            frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            frame.setSize(400, 300);

            Map<String, String> env = new HashMap<String, String>();
            //Path path = zipfile.toPath();
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            try {
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            SerifyApplet sa = new SerifyApplet(geneset.zipfilesystem);
            sa.init(frame, null, geneset.user);
            //frame.add( )
            geneset.currentSerify = sa;
        } /* else frame = (JFrame)currentSerify.cnt;*/

        String[] farr = new String[] { "o.profundus", "mt.silvanus", "mt.ruber", "m.hydrothermalis",
                "t.thermophilus_SG0_5JP17_16", "t.thermophilusJL18", "t.thermophilusHB8", "t.thermophilusHB27",
                "t.scotoductusSA01", "t.scotoductus4063", "t.scotoductus1572", "t.scotoductus2101",
                "t.scotoductus2127", "t.scotoductus346", "t.scotoductus252", "t.antranikiani", "t.kawarayensis",
                "t.brockianus", "t.igniterrae", "t.eggertsoni", "t.RLM", "t.oshimai_JL2", "t.oshimai",
                "t.filiformis", "t.arciformis", "t.islandicus", "t.aquaticus", "t.spCCB" };

        Map<Integer, String> ups = new HashMap<Integer, String>();
        Set<Integer> stuck = new HashSet<Integer>();
        Map<Integer, List<Tegeval>> ups2 = new HashMap<Integer, List<Tegeval>>();
        //int[] rr = table.getSelectedRows();
        for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
            //int cr = table.convertRowIndexToModel(r);
            //Gene gg = geneset.genelist.get(cr);
            if (gg.getSpecies() != null) {
                if (gg.genid != null && gg.genid.length() > 0) {
                    ups.put(gg.getGroupIndex(), gg.name);
                    stuck.add(gg.getGroupIndex());
                }
                if (!stuck.contains(gg.getGroupIndex())) {
                    if (!ups.containsKey(gg.getGroupIndex())
                            || !(gg.name.contains("unnamed") || gg.name.contains("hypot")))
                        ups.put(gg.getGroupIndex(), gg.name);
                }

                List<Tegeval> tlist;
                if (ups2.containsKey(gg.getGroupIndex()))
                    tlist = ups2.get(gg.getGroupIndex());
                else {
                    tlist = new ArrayList<Tegeval>();
                    ups2.put(gg.getGroupIndex(), tlist);
                }

                //Set<String>    specs = new HashSet<String>();
                //textarea.append(gg.name + ":\n");
                //for (String sp : gg.species.keySet()) {
                int count = 0;
                for (String sp : farr) {
                    //Teginfo stv = gg.species.equals(sp) ? gg.teginfo : null;

                    if (gg.getSpecies().equals(sp))
                        tlist.add(gg.tegeval);
                    /*for( String key : gg.species.keySet() ) {
                       if( key.contains("JL2") ) {
                          System.err.println( " erm " + key );
                       }
                    }*/
                    /*if( stv == null && gg.species.size() == 28 ) {
                       System.err.println( gg.species );
                       System.err.println( sp );
                    }*/
                    //System.err.println( gg.species.keySet() );
                    /*if( stv == null ) {
                       //System.err.println( sp );
                    } else {
                       count++;
                       //specs.add( sp );
                       for (Tegeval tv : stv.tset) {
                          tlist.add( tv );
                          /*textarea.append(">" + tv.cont + " " + tv.teg + " " + tv.eval + "\n");
                          if (tv.dna != null) {
                      for (int i = 0; i < tv.dna.length(); i += 70) {
                         textarea.append(tv.dna.gg.speciessubstring(i, Math.min(i + 70, tv.dna.length())) + "\n");
                      }
                          }*
                       }
                    }*/
                }
                //if( count < gg.species.size() ) {
                //   System.err.println( gg.species );
                //   System.err.println();
                //}
                //if( specs.size() < 28 ) System.err.println("mu " + specs);
            }
        }

        try {
            StringWriter sb = new StringWriter();
            for (int gi : ups.keySet()) {
                String name = ups.get(gi);
                List<Tegeval> tlist = ups2.get(gi);

                sb.append(name.replace('/', '-') + ":\n");
                if (tlist.size() < 28) {
                    for (Tegeval tv : tlist) {
                        System.err.println(tv.name);
                    }
                    System.err.println();
                }
                for (Tegeval tv : tlist) {
                    Sequence ps = tv.getProteinSequence();
                    ps.setName(tv.name.substring(0, tv.name.indexOf('_')));
                    ps.writeSequence(sb);
                    /*sb.append(">" + tv.name.substring(0, tv.name.indexOf('_')) + "\n");
                    for (int i = 0; i < ps.length(); i += 70) {
                       sb.append( ps.substring(i, Math.min(i + 70, tv.getProteinLength() )) + "\n");
                    }*/
                }
            }

            geneset.currentSerify.addSequences("uh", new StringReader(sb.toString()), Paths.get("/"), null);
        } catch (URISyntaxException | IOException e1) {
            e1.printStackTrace();
        }
        frame.setVisible(true);
    });
    sequencemenu.getItems().add(showgroupseq);

    MenuItem showgroupdnaseq = new MenuItem("Show group DNA sequences");
    showgroupdnaseq.setOnAction(actionEvent -> {
        final JTextArea textarea = new JTextArea();
        JScrollPane scrollpane = new JScrollPane(textarea);

        try {
            if (clipboardService == null)
                clipboardService = (ClipboardService) ServiceManager.lookup("javax.jnlp.ClipboardService");
            Action action = new CopyAction("Copy", null, "Copy data",
                    new Integer(KeyEvent.VK_CONTROL + KeyEvent.VK_C));
            textarea.getActionMap().put("copy", action);
            grabFocus = true;
        } catch (Exception ee) {
            ee.printStackTrace();
            System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        }

        textarea.setDragEnabled(true);

        try {
            final DataFlavor df = new DataFlavor("text/plain;charset=utf-8");
            TransferHandler th = new TransferHandler() {
                /**
                 * 
                 */
                private static final long serialVersionUID = 1L;

                public int getSourceActions(JComponent c) {
                    return TransferHandler.COPY_OR_MOVE;
                }

                public boolean canImport(TransferHandler.TransferSupport support) {
                    return false;
                }

                protected Transferable createTransferable(JComponent c) {
                    return new Transferable() {
                        @Override
                        public Object getTransferData(DataFlavor arg0)
                                throws UnsupportedFlavorException, IOException {
                            if (arg0.equals(df)) {
                                return new ByteArrayInputStream(textarea.getText().getBytes());
                            } else {
                                return textarea.getText();
                            }
                        }

                        @Override
                        public DataFlavor[] getTransferDataFlavors() {
                            return new DataFlavor[] { df, DataFlavor.stringFlavor };
                        }

                        @Override
                        public boolean isDataFlavorSupported(DataFlavor arg0) {
                            if (arg0.equals(df) || arg0.equals(DataFlavor.stringFlavor)) {
                                return true;
                            }
                            return false;
                        }
                    };
                }

                public boolean importData(TransferHandler.TransferSupport support) {
                    return false;
                }
            };
            textarea.setTransferHandler(th);
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }

        Map<Integer, String> ups = new HashMap<Integer, String>();
        Set<Integer> stuck = new HashSet<Integer>();
        Map<Integer, List<Tegeval>> ups2 = new HashMap<Integer, List<Tegeval>>();
        //int[] rr = table.getSelectedRows();
        for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
            //int cr = table.convertRowIndexToModel(r);
            //Gene gg = geneset.genelist.get(cr);
            if (gg.getSpecies() != null) {
                if (gg.genid != null && gg.genid.length() > 0) {
                    ups.put(gg.getGroupIndex(), gg.name);
                    stuck.add(gg.getGroupIndex());
                }
                if (!stuck.contains(gg.getGroupIndex())) {
                    if (!ups.containsKey(gg.getGroupIndex())
                            || !(gg.name.contains("unnamed") || gg.name.contains("hypot")))
                        ups.put(gg.getGroupIndex(), gg.name);
                }

                List<Tegeval> tlist;
                if (ups2.containsKey(gg.getGroupIndex()))
                    tlist = ups2.get(gg.getGroupIndex());
                else {
                    tlist = new ArrayList<Tegeval>();
                    ups2.put(gg.getGroupIndex(), tlist);
                }

                //textarea.append(gg.name + ":\n");
                tlist.add(gg.tegeval);
                /*textarea.append(">" + tv.cont + " " + tv.teg + " " + tv.eval + "\n");
                if (tv.dna != null) {
                   for (int i = 0; i < tv.dna.length(); i += 70) {
                      textarea.append(tv.dna.substring(i, Math.min(i + 70, tv.dna.length())) + "\n");
                   }
                }*/
            }
        }

        for (int gi : ups.keySet()) {
            String name = ups.get(gi);
            List<Tegeval> tlist = ups2.get(gi);

            textarea.append(name.replace('/', '-') + ":\n");
            for (Tegeval tv : tlist) {
                textarea.append(">" + tv.name.substring(0, tv.name.indexOf('_')) + "\n");
                for (int i = 0; i < tv.getLength(); i += 70) {
                    textarea.append(tv.getSubstring(i, Math.min(i + 70, tv.getLength())) + "\n");
                }
            }
        }

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);
    });
    sequencemenu.getItems().add(showgroupdnaseq);
    sequencemenu.getItems().add(new SeparatorMenuItem());

    MenuItem showallseq = new MenuItem("Show all sequences");
    showallseq.setOnAction(actionEvent -> {
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Serifier serifier = new Serifier();
        JavaFasta jf = new JavaFasta((comp instanceof JApplet) ? (JApplet) comp : null, serifier, geneset.cs);
        jf.initGui(frame);

        Map<String, Sequence> contset = new HashMap<String, Sequence>();
        //int[] rr = table.getSelectedRows();
        for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
            //int cr = table.convertRowIndexToModel(r);
            //Gene gg = geneset.genelist.get(cr);
            Tegeval tv = gg.tegeval;
            String contig = tv.getContshort().getName();
            Sequence seq = tv.getProteinSequence();
            seq.setName(contig);
            serifier.mseq.put(seq.getName(), seq);
            //Sequence seq = new Sequence( contig, aa, serifier.mseq );
            serifier.addSequence(seq);
        }
        jf.updateView();

        frame.setVisible(true);
    });
    sequencemenu.getItems().add(showallseq);

    MenuItem showseq = new MenuItem("Show sequences");
    showseq.setOnAction(actionEvent -> {
        Set<GeneGroup> genegroups = new HashSet<GeneGroup>();
        //int[] rr = table.getSelectedRows();
        if (!isGeneview()) {
            for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                //int cr = table.convertRowIndexToModel(r);
                //GeneGroup gg = geneset.allgenegroups.get(cr);
                genegroups.add(gg);
            }
        } else {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                //int cr = table.convertRowIndexToModel(r);
                //Gene gg = geneset.genelist.get(cr);
                genegroups.add(gg.getGeneGroup());
            }
        }
        Platform.runLater(() -> {
            Set<String> specs = null;
            if (table.getItems().size() > 1)
                specs = getSelspec(comp, geneset.specList, null);
            showSequences(comp, genegroups, false, specs);
        });
    });
    sequencemenu.getItems().add(showseq);

    MenuItem showseqwgenenames = new MenuItem("Show sequences w/genenames");
    showseqwgenenames.setOnAction(actionEvent -> {
        Set<GeneGroup> genegroups = new HashSet<GeneGroup>();
        //int[] rr = table.getSelectedRows();
        if (!isGeneview()) {
            for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                //int cr = table.convertRowIndexToModel(r);
                //GeneGroup gg = geneset.allgenegroups.get(cr);
                genegroups.add(gg);
            }
        } else {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                //int cr = table.convertRowIndexToModel(r);
                //Gene gg = geneset.genelist.get(cr);
                genegroups.add(gg.getGeneGroup());
            }
        }
        //Set<String>   specs = null;
        //if( rr.length > 1 ) specs = getSelspec(comp, specList, null);
        showSequences(comp, genegroups, false, null, true);
    });
    sequencemenu.getItems().add(showseqwgenenames);

    MenuItem showalignseq = new MenuItem("Show aligned sequences");
    showalignseq.setOnAction(actionEvent -> {
        Set<GeneGroup> genegroups = new HashSet<GeneGroup>();
        //int[] rr = table.getSelectedRows();
        if (!isGeneview()) {
            for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                genegroups.add(gg);
            }
        } else {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                genegroups.add(gg.getGeneGroup());
            }
        }

        Serifier serifier = new Serifier();
        for (GeneGroup ggroup : genegroups) {
            for (Tegeval tv : ggroup.getTegevals()) {
                String selspec = tv.getContshort().getSpec();//tv.getContig();
                String spec = geneset.nameFix(selspec);
                /*if( selspec.contains("hermus") ) spec = selspec;
                else {
                   Matcher m = Pattern.compile("\\d").matcher(selspec); 
                   int firstDigitLocation = m.find() ? m.start() : 0;
                   if( firstDigitLocation == 0 ) spec = "Thermus_" + selspec;
                   else spec = "Thermus_" + selspec.substring(0,firstDigitLocation) + "_" + selspec.substring(firstDigitLocation);
                }*/

                Sequence seq = tv.getAlignedSequence();
                //System.err.println( "seqlen " + seq.length() );
                if (seq != null) {
                    seq.setName(spec);
                    //Sequence seq = new Sequence( contig, seqstr, null );
                    serifier.addSequence(seq);
                } else {
                    Sequence sb = tv.getProteinSequence();
                    sb.setName(spec);
                    //Sequence sseq = new Sequence( spec, sb, serifier.mseq );
                    serifier.addSequence(sb);
                }
            }
        }
        showAlignedSequences(comp, serifier);
    });
    sequencemenu.getItems().add(showalignseq);

    MenuItem splitseq = new MenuItem("Split/Show sequences");
    splitseq.setOnAction(actionEvent -> {
        try {
            StringBuffer sb = getSelectedASeqs(table, geneset.genelist, GeneSetHead.this, geneset.specList);
            if (geneset.currentSerify == null) {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                frame.setSize(800, 600);

                SerifyApplet sa = new SerifyApplet(geneset.zipfilesystem);
                sa.init(frame, null, geneset.user);
                geneset.currentSerify = sa;

                frame.setVisible(true);
            }
            geneset.currentSerify.addSequences("uh", new StringReader(sb.toString()), Paths.get("/"), null);
        } catch (URISyntaxException | IOException e1) {
            e1.printStackTrace();
        }

        //JTextArea textarea = new JTextArea();
        //textarea.append( sb.toString() );

        /*try {
           if (clipboardService == null)
          clipboardService = (ClipboardService) ServiceManager.lookup("javax.jnlp.ClipboardService");
           Action action = new CopyAction("Copy", null, "Copy data", new Integer(KeyEvent.VK_CONTROL + KeyEvent.VK_C));
           textarea.getActionMap().put("copy", action);
           grabFocus = true;
        } catch (Exception ee) {
           ee.printStackTrace();
           System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        }
                
        *
         * final DataFlavor df =
         * DataFlavor.getTextPlainUnicodeFlavor();//new
         * DataFlavor("text/plain;charset=utf-8"); final String charset
         * = df.getParameter("charset"); final Transferable transferable
         * = new Transferable() {
         * 
         * @Override public Object getTransferData(DataFlavor arg0)
         * throws UnsupportedFlavorException, IOException { String ret =
         * makeCopyString( detailTable ); return new
         * ByteArrayInputStream( ret.getBytes( charset ) ); }
         * 
         * @Override public DataFlavor[] getTransferDataFlavors() {
         * return new DataFlavor[] { df }; }
         * 
         * @Override public boolean isDataFlavorSupported(DataFlavor
         * arg0) { if( arg0.equals(df) ) { return true; } return false;
         * } };
         * 
         * TransferHandler th = new TransferHandler() { private static
         * final long serialVersionUID = 1L;
         * 
         * public int getSourceActions(JComponent c) { return
         * TransferHandler.COPY_OR_MOVE; }
         * 
         * public boolean canImport(TransferHandler.TransferSupport
         * support) { return false; }
         * 
         * protected Transferable createTransferable(JComponent c) {
         * return transferable; }
         * 
         * public boolean importData(TransferHandler.TransferSupport
         * support) { /*try { Object obj =
         * support.getTransferable().getTransferData( df ); InputStream
         * is = (InputStream)obj;
         * 
         * byte[] bb = new byte[2048]; int r = is.read(bb);
         * 
         * //importFromText( new String(bb,0,r) ); } catch
         * (UnsupportedFlavorException e) { e.printStackTrace(); } catch
         * (IOException e) { e.printStackTrace(); }* return false; } };
         * textarea.setTransferHandler( th );
         *
        textarea.setDragEnabled(true);
                
        JScrollPane scrollpane = new JScrollPane(textarea);
                
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);*/
    });
    sequencemenu.getItems().add(splitseq);

    MenuItem showdnaseq = new MenuItem("Show DNA sequences");
    showdnaseq.setOnAction(actionEvent -> {
        Set<GeneGroup> genegroups = new HashSet<GeneGroup>();
        int rr = 0;
        if (!isGeneview()) {
            ObservableList<GeneGroup> lgg = table.getSelectionModel().getSelectedItems();
            genegroups.addAll(lgg);
            rr = lgg.size();
        } else {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                genegroups.add(gg.getGeneGroup());
                rr++;
            }
        }
        Set<String> specs = null;
        if (rr > 1)
            specs = getSelspec(comp, geneset.specList, null);
        showSequences(comp, genegroups, true, specs);

        /*StringBuilder sb = getSelectedSeqs( table, genelist );
                
        if( currentSerify == null ) {
           JFrame frame = new JFrame();
           frame.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE );
           frame.setSize(800, 600);
                   
           SerifyApplet sa = new SerifyApplet();
           sa.init( frame );
                   
           try {
          sa.addSequences("uh", new StringReader( sb.toString() ), "/");
           } catch (URISyntaxException | IOException e1) {
          e1.printStackTrace();
           }
                   
           frame.setVisible( true );
        }
                
        JTextArea textarea = new JTextArea();
        JScrollPane scrollpane = new JScrollPane(textarea);
                
        try {
           if (clipboardService == null)
          clipboardService = (ClipboardService) ServiceManager.lookup("javax.jnlp.ClipboardService");
           Action action = new CopyAction("Copy", null, "Copy data", new Integer(KeyEvent.VK_CONTROL + KeyEvent.VK_C));
           textarea.getActionMap().put("copy", action);
           grabFocus = true;
        } catch (Exception ee) {
           ee.printStackTrace();
           System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        }
                
        textarea.setDragEnabled(true);
        textarea.append( sb.toString() );
                
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);*/
    });
    sequencemenu.getItems().add(showdnaseq);

    MenuItem expalldna = new MenuItem("Export all DNA sequences");
    expalldna.setOnAction(actionEvent -> {
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        try {
            Map<Integer, FileWriter> lfw = new HashMap<Integer, FileWriter>();
            if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                File f = jfc.getSelectedFile();
                for (Gene gg : getGeneTable().getSelectionModel().getSelectedItems()) {
                    FileWriter fw = null;
                    if (lfw.containsKey(gg.getGroupIndex())) {
                        fw = lfw.get(gg.getGroupIndex());
                    } else {
                        fw = new FileWriter(new File(f, "group_" + gg.getGroupIndex() + ".fasta"));
                        lfw.put(gg.getGroupIndex(), fw);
                    }

                    Tegeval tv = gg.tegeval;
                    fw.append(">" + tv.name + " " + tv.teg + " " + tv.eval + "\n");
                    for (int i = 0; i < tv.getLength(); i += 70) {
                        fw.append(tv.getSubstring(i, Math.min(i + 70, tv.getLength())) + "\n");
                    }
                }
            }
            for (int gi : lfw.keySet()) {
                lfw.get(gi).close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    sequencemenu.getItems().add(expalldna);

    MenuItem exprelcont = new MenuItem("Export relevant contigs");
    exprelcont.setOnAction(actionEvent -> {
        JFileChooser jfc = new JFileChooser();

        try {
            Map<Integer, FileWriter> lfw = new HashMap<Integer, FileWriter>();
            if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                File f = jfc.getSelectedFile();

                Set<Sequence> contset = new HashSet<Sequence>();
                for (Gene gg : getGeneTable().getSelectionModel().getSelectedItems()) {
                    Tegeval tv = gg.tegeval;
                    contset.add(tv.getContshort());
                }

                FileWriter fw = new FileWriter(f);
                for (Sequence contig : contset) {
                    fw.append(">" + contig + "\n");
                    if (geneset.contigmap.containsKey(contig)) {
                        StringBuilder dna = geneset.contigmap.get(contig).getStringBuilder();
                        for (int i = 0; i < dna.length(); i += 70) {
                            fw.append(dna.substring(i, Math.min(i + 70, dna.length())) + "\n");
                        }
                    }
                }
                fw.close();
            }
            for (int gi : lfw.keySet()) {
                lfw.get(gi).close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    sequencemenu.getItems().add(exprelcont);
    sequencemenu.getItems().add(new SeparatorMenuItem());

    MenuItem viewselrange = new MenuItem("View selected range");
    viewselrange.setOnAction(actionEvent -> {
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Serifier serifier = new Serifier();
        JavaFasta jf = new JavaFasta((comp instanceof JApplet) ? (JApplet) comp : null, serifier, geneset.cs);
        jf.initGui(frame);

        Set<Sequence> contset = new HashSet<Sequence>();
        Set<Tegeval> tvset = new HashSet<>();
        if (isGeneview()) {
            for (Gene gg : getGeneTable().getSelectionModel().getSelectedItems()) {
                Tegeval tv = gg.tegeval;
                tvset.add(tv);
                //serifier.addAnnotation( tv );
                contset.add(tv.getContshort());
            }
        } else {
            for (GeneGroup gg : getGeneGroupTable().getSelectionModel().getSelectedItems()) {
                for (Tegeval tv : gg.getTegevals()) {
                    tv.color = Color.red;
                    tvset.add(tv);
                    Sequence contig = tv.getContshort();
                    contset.add(contig);
                    //serifier.addAnnotation( tv );
                }
            }
        }
        /*Sequence seq;
        Sequence contig = tv.getContshort();
        /*if (contset.containsKey(contig)) {
          seq = contset.get(contig);
        } else {
          if( contigmap.containsKey(contig) ) {
             StringBuilder dna = contigmap.get(contig).getStringBuilder();
             seq = new Sequence(contig.getName(), dna, serifier.mseq);
          } else
             seq = new Sequence(contig.getName(), serifier.mseq);
          contset.put(contig, seq);
        }
                
        Annotation a = new Annotation(contig, contig.getName(), Color.green, serifier.mann);
        a.setStart(tv.start);
        a.setStop(tv.stop);
        a.setOri(tv.ori);
        a.setGroup(gg.name);
        a.setType("gene");*/
        // seq.addAnnotation( new Annotation( seq, ) );

        for (Sequence contig : contset) {
            int start = Integer.MAX_VALUE;
            int stop = Integer.MIN_VALUE;
            for (Tegeval tv : tvset) {
                if (contig == tv.seq) {
                    start = Math.min(start, tv.start);
                    stop = Math.max(stop, tv.stop);
                }
            }

            int rstart = 0;
            int rstop = contig.length();
            if (contig.annset != null)
                for (Annotation tv : contig.annset) {
                    if (contig == tv.seq) {
                        if (tv.stop < start && tv.stop > rstart) {
                            rstart = tv.stop;
                        }
                        if (tv.start > stop && tv.start < rstop) {
                            rstop = tv.start;
                        }
                    }
                }

            start = rstart;
            stop = rstop;

            Sequence newseq = new Sequence(contig.getName(),
                    new StringBuilder(contig.getSubstring(start, stop, 1)), serifier.mseq);
            /*if( contig.isReverse() ) {
               newseq.reverse();
               newseq.complement();
            }*/

            serifier.addSequence(newseq);
            for (Tegeval tv : tvset) {
                Annotation newann = new Annotation(newseq, tv.start - start, tv.stop - start, tv.ori, tv.name);
                if (contig == tv.seq) {
                    newseq.addAnnotation(newann);
                }
                serifier.addAnnotation(newann);
            }
            /*for( Annotation ann : contig.getAnnotations() ) {
               serifier.addAnnotation( ann );
            }*/
            /*if (seq.getAnnotations() != null)
               Collections.sort(seq.getAnnotations());*/
        }
        jf.updateView();

        frame.setVisible(true);
    });
    sequencemenu.getItems().add(viewselrange);

    MenuItem viewwhole = new MenuItem("View whole contigs for selection");
    viewwhole.setOnAction(actionEvent -> {
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Serifier serifier = new Serifier();
        JavaFasta jf = new JavaFasta((comp instanceof JApplet) ? (JApplet) comp : null, serifier, geneset.cs);
        jf.initGui(frame);

        //Map<Sequence, Sequence> contset = new HashMap<Sequence, Sequence>();
        /*int[] rr = table.getSelectedRows();
        for (int r : rr) {
           int cr = table.convertRowIndexToModel(r);
           Gene gg = geneset.genelist.get(cr);
           if (gg.species != null) {
          for (String sp : gg.species.keySet()) {
             Teginfo stv = gg.species.get(sp);
             for (Tegeval tv : stv.tset) {
                Sequence seq;
                Sequence contig = tv.getContshort();
                if (contset.containsKey(contig)) {
                   seq = contset.get(contig);
                } else {
                   if( GeneSet.contigmap.containsKey(contig) ) {
                      //StringBuilder dna = GeneSet.contigmap.get(contig).seq;
                      StringBuilder dna = contig.getSequence().getStringBuilder();
                      seq = new Sequence(contig.getName(), dna, serifier.mseq);
                   } else {
                      seq = new Sequence(contig.getName(), serifier.mseq);
                   }
                
                   contset.put(contig, seq);
                }
                
                /*
                 * Annotation a = jf.new Annotation( seq,
                 * contig, Color.red ); a.setStart( tv.start );
                 * a.setStop( tv.stop ); a.setOri( tv.ori );
                 * a.setGroup( gg.name ); a.setType( "gene" );
                 * jf.addAnnotation( a );
                 *
                // seq.addAnnotation( new Annotation( seq, ) );
             }
          }
           }
        }*/

        Set<Sequence> contigs = new HashSet<Sequence>();
        if (isGeneview()) {
            for (Gene gg : getGeneTable().getSelectionModel().getSelectedItems()) {
                Tegeval tv = gg.tegeval;
                tv.color = Color.red;
                Sequence contig = tv.getContshort();
                //contig.offset = -tv.start;
                contigs.add(contig);
            }

            /*Annotation a = new Annotation(contig, contig.getName(), Color.red, serifier.mann);
            a.setStart(tv.start);
            a.setStop(tv.stop);
            a.setOri(tv.ori);
            a.setGroup(g.name);
            a.setType("gene");*/
            //serifier.addAnnotation( tv );
        } else {
            for (GeneGroup gg : getGeneGroupTable().getSelectionModel().getSelectedItems()) {
                for (Tegeval tv : gg.getTegevals()) {
                    tv.color = Color.red;
                    Sequence contig = tv.getContshort();
                    //contig.offset = -tv.start;
                    contigs.add(contig);

                    /*Annotation a = new Annotation(contig, contig.getName(), Color.red, serifier.mann);
                    a.setStart(tv.start);
                    a.setStop(tv.stop);
                    a.setOri(tv.ori);
                    a.setGroup(gg.getCommonName());
                    a.setType("gene");*/
                    //serifier.addAnnotation( tv );
                }
            }
        }
        //Gene gg = geneset.genelist.get(cr);
        //for (Gene g : geneset.genelist) {
        //if (g.species != null) {
        //for (String sp : g.species.keySet()) {

        for (Sequence contig : contigs) {
            for (Annotation ann : contig.getAnnotations()) {
                serifier.addAnnotation(ann);
            }

            serifier.addSequence(contig);
            serifier.mseq.put(contig.getName(), contig);
            //if(contig.getAnnotations() != null)
            //   Collections.sort(contig.getAnnotations());
        }
        jf.updateView();

        frame.setVisible(true);
    });
    sequencemenu.getItems().add(viewwhole);
    sequencemenu.getItems().add(new SeparatorMenuItem());

    MenuItem viewspecseq = new MenuItem("View species sequence");
    viewspecseq.setOnAction(actionEvent -> {
        Set<String> selspec = getSelspec(GeneSetHead.this, geneset.specList);

        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Serifier serifier = new Serifier();
        JavaFasta jf = new JavaFasta((comp instanceof JApplet) ? (JApplet) comp : null, serifier, geneset.cs);
        jf.initGui(frame);

        for (String spec : selspec) {
            List<Sequence> contigs = geneset.speccontigMap.get(spec);

            for (Sequence contig : contigs) {
                List<Annotation> lann = contig.getAnnotations();
                if (lann != null)
                    for (Annotation ann : lann) {
                        serifier.addAnnotation(ann);
                    }

                serifier.addSequence(contig);
                serifier.mseq.put(contig.getName(), contig);
            }
        }

        jf.updateView();

        frame.setVisible(true);
    });
    sequencemenu.getItems().add(viewspecseq);

    Menu windowmenu = new Menu("Tools");
    MenuItem seqviewer = new MenuItem("Sequence viewer");
    seqviewer.setOnAction(actionEvent -> {
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Serifier serifier = new Serifier();
        JavaFasta jf = new JavaFasta((comp instanceof JApplet) ? (JApplet) comp : null, serifier, geneset.cs);
        jf.initGui(frame);
        jf.updateView();

        frame.setVisible(true);
    });
    windowmenu.getItems().add(seqviewer);
    windowmenu.getItems().add(new SeparatorMenuItem());
    MenuItem genesorter = new MenuItem("Gene sorter");
    genesorter.setOnAction(actionEvent -> {
        try {
            //if( gb.isSelected() ) new GeneSorter().mynd( GeneSetHead.this, genelist, table, null, contigmap );
            //else 
            new GeneSorter().groupMynd(GeneSetHead.this, geneset.allgenegroups, geneset.specList,
                    geneset.genelist, table, geneset.contigmap, geneset.specset);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    windowmenu.getItems().add(genesorter);
    MenuItem specorderaction = new MenuItem("Order species list");
    specorderaction.setOnAction(actionEvent -> {
        TreeUtil tu = new TreeUtil();
        /*corrInd.clear();
        for( String spec : specList ) {
           corrInd.add( nameFix( spec ) );
        }*/

        Serifier serifier = getConcatenatedSequences(false, false);

        Map<String, Integer> blosumap = JavaFasta.getBlosumMap();
        double[] dmat = new double[serifier.lseq.size() * serifier.lseq.size()];
        Sequence.distanceMatrixNumeric(serifier.lseq, dmat, null, false, false, null, blosumap);

        List<String> ret = new ArrayList<String>();
        for (Sequence seqname : serifier.lseq) {
            ret.add(seqname.getName()); //.replace(' ', '_') );
        }
        //List<String>   corrInd = currentjavafasta.getNames();

        //Sequence.distanceMatrixNumeric(serifier.lseq, dmat, idxs, bootstrap, cantor, ent, blosum);
        Node n = tu.neighborJoin(dmat, ret, null, false, false);

        Comparator<Node> comp2 = (o1, o2) -> {
            int c1 = o1.countLeaves();
            int c2 = o2.countLeaves();

            if (c1 > c2)
                return 1;
            else if (c1 == c2)
                return 0;

            return -1;
        };
        tu.arrange(n, comp2);
        //corrInd.clear();
        List<String> ordInd = n.traverse();

        for (String spec : ordInd) {
            System.err.println(spec);
        }

        for (String oldspec : geneset.specList) {
            if (!ordInd.contains(oldspec)) {
                ordInd.add(oldspec);
            }
        }
        geneset.specList = ordInd;

        //TableModel model = table.getModel();
        //table.setModel( nullmodel );
        //table.setModel( model );

        //table.tableChanged( new TableModelEvent( table.getModel() ) );
        //table.getColumnModel().
        System.err.println(geneset.specList.size());
    });
    MenuItem matrixaction = new MenuItem("Relation matrix");
    matrixaction.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            JComboBox<String> descombo = new JComboBox<String>(
                    geneset.deset.toArray(new String[geneset.deset.size()]));
            JCheckBox anicheck = new JCheckBox("ANImatrix");
            JCheckBox plasmidcheck = new JCheckBox("Skip plasmids");
            descombo.insertItemAt("", 0);
            descombo.setSelectedIndex(0);
            JOptionPane.showMessageDialog(GeneSetHead.this, new Object[] { descombo, anicheck, plasmidcheck });
            String val = descombo.getSelectedItem().toString();

            Collection<GeneGroup> ss = new HashSet<>();
            /*int[] rr = table.getSelectedRows();
            for( int r : rr ) {
               ss.add( geneset.allgenegroups.get( table.convertRowIndexToModel(r) ) );
            }*/
            ss.addAll(table.getSelectionModel().getSelectedItems());
            if (ss.isEmpty())
                ss = geneset.allgenegroups;

            Set<String> species = getSelspec(GeneSetHead.this, geneset.specList);
            bimg = anicheck.isSelected()
                    ? geneset.animatrix(species, geneset.clusterMap, val, ss, plasmidcheck.isSelected())
                    : geneset.bmatrix(species, geneset.clusterMap, val);

            JFrame f = new JFrame("Relation matrix");
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setSize(500, 500);

            /*
             * { public void paintComponent( Graphics g ) {
             * super.paintComponent(g); g.drawImage(bimg, 0, 0, this); } };
             */

            try {
                final DataFlavor df = new DataFlavor("text/plain;charset=utf-8");
                final Transferable transferable = new Transferable() {
                    @Override
                    public Object getTransferData(DataFlavor arg0)
                            throws UnsupportedFlavorException, IOException {
                        StringBuilder ret = new StringBuilder();

                        int i = 0;
                        for (String spc : geneset.specList) {
                            if (++i == geneset.specList.size())
                                ret.append(spc + "\n");
                            else
                                ret.append(spc + "\t");
                        }

                        int where = 0;
                        for (String spc1 : geneset.specList) {
                            int wherex = 0;
                            for (String spc2 : geneset.specList) {
                                int spc1tot = 0;
                                int spc2tot = 0;
                                int totot = 0;

                                int spc1totwocore = 0;
                                int spc2totwocore = 0;
                                int tototwocore = 0;
                                for (Set<String> set : geneset.clusterMap.keySet()) {
                                    Set<Map<String, Set<String>>> erm = geneset.clusterMap.get(set);
                                    if (set.contains(spc1)) {
                                        if (set.size() < geneset.specList.size()) {
                                            spc1totwocore += erm.size();
                                            for (Map<String, Set<String>> sm : erm) {
                                                Set<String> hset = sm.get(spc1);
                                                tototwocore += hset.size();
                                            }

                                            if (set.contains(spc2)) {
                                                spc2totwocore += erm.size();
                                            }

                                            if (spc2totwocore > spc1totwocore)
                                                System.err.println(
                                                        "okoko " + spc1totwocore + " " + spc2totwocore);
                                        }

                                        spc1tot += erm.size();
                                        for (Map<String, Set<String>> sm : erm) {
                                            Set<String> hset = sm.get(spc1);
                                            totot += hset.size();
                                        }

                                        if (set.contains(spc2)) {
                                            spc2tot += erm.size();
                                        }
                                    }
                                }

                                if (where == wherex) {
                                    if (where == geneset.specList.size() - 1)
                                        ret.append(0 + "\n");
                                    else
                                        ret.append(0 + "\t");
                                } else {
                                    double hlut = (double) spc2totwocore / (double) spc1totwocore;
                                    double sval = hlut; // 1.0/( 1.1-hlut );
                                    double val = Math.pow(50.0, sval - 0.3) - 1.0;
                                    double dval = Math.round(100.0 * (val)) / 100.0;

                                    if (wherex == geneset.specList.size() - 1)
                                        ret.append(dval + "\n");
                                    else
                                        ret.append(dval + "\t");
                                }
                                wherex++;
                            }
                            where++;
                        }

                        return new ByteArrayInputStream(ret.toString().getBytes());
                    }

                    @Override
                    public DataFlavor[] getTransferDataFlavors() {
                        return new DataFlavor[] { df };
                    }

                    @Override
                    public boolean isDataFlavorSupported(DataFlavor arg0) {
                        if (arg0.equals(df)) {
                            return true;
                        }
                        return false;
                    }
                };
                final TransferComponent comp2 = new TransferComponent(bimg, transferable);

                TransferHandler th = new TransferHandler() {
                    private static final long serialVersionUID = 1L;

                    public int getSourceActions(JComponent c) {
                        return TransferHandler.COPY_OR_MOVE;
                    }

                    public boolean canImport(TransferSupport support) {
                        return false;
                    }

                    protected Transferable createTransferable(JComponent c) {
                        return transferable;
                    }

                    public boolean importData(TransferSupport support) {
                        return true;
                    }
                };
                comp2.setTransferHandler(th);

                comp2.setEnabled(true);
                JScrollPane fsc = new JScrollPane(comp2);
                comp2.setPreferredSize(new Dimension(bimg.getWidth(), bimg.getHeight()));

                JPopupMenu popup = new JPopupMenu();
                popup.add(new AbstractAction("Save image") {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        FileSaveService fss = null;
                        FileContents fileContents = null;

                        try {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            OutputStreamWriter osw = new OutputStreamWriter(baos);
                            ImageIO.write(bimg, "png", baos);
                            baos.close();

                            try {
                                fss = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService");
                            } catch (UnavailableServiceException e1) {
                                fss = null;
                            }

                            if (fss != null) {
                                ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
                                fileContents = fss.saveFileDialog(null, null, bais, "export.png");
                                bais.close();
                                OutputStream os = fileContents.getOutputStream(true);
                                os.write(baos.toByteArray());
                                os.close();
                            } else {
                                JFileChooser jfc = new JFileChooser();
                                if (jfc.showSaveDialog(GeneSetHead.this) == JFileChooser.APPROVE_OPTION) {
                                    File f = jfc.getSelectedFile();
                                    FileOutputStream fos = new FileOutputStream(f);
                                    fos.write(baos.toByteArray());
                                    fos.close();

                                    Desktop.getDesktop().browse(f.toURI());
                                }
                            }
                        } catch (IOException e2) {
                            e2.printStackTrace();
                        }
                    }
                });
                comp2.setComponentPopupMenu(popup);

                f.add(fsc);
                f.setVisible(true);
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            }
        });
    });
    MenuItem tniaction = new MenuItem("TNI/ANI");
    tniaction.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            Set<String> species = getSelspec(GeneSetHead.this, geneset.specList);
            String makeblastdb = "makeblastdb";
            String OS = System.getProperty("os.name").toLowerCase();
            if (OS.indexOf("mac") != -1)
                makeblastdb = "/usr/local/bin/makeblastdb";
            for (String spec : species) {
                List<Sequence> lseq = geneset.speccontigMap.get(spec);
                ProcessBuilder pb = new ProcessBuilder(makeblastdb, "-dbtype", "nucl", "-title", spec, "-out",
                        spec);
                File dir = new File(System.getProperty("user.home"));

                /*try {
                    FileWriter w = new FileWriter( new File(dir, spec+".fna") );
                    for( Sequence seq : lseq ) {
                seq.writeSequence(w);
                    }
                    w.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }*/

                pb.directory(dir);
                try {
                    Process p = pb.start();
                    Writer fw = new OutputStreamWriter(p.getOutputStream());
                    for (Sequence seq : lseq) {
                        seq.writeSequence(fw);
                    }
                    fw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            int y = 0;
            double[] matrix = new double[species.size() * species.size()];
            for (String dbspec : species) {
                int x = 0;
                for (String spec : species) {
                    //if( !spec.equals(dbspec) ) {
                    final List<Sequence> lseq = geneset.speccontigMap.get(spec);
                    String blastn = "blastn";
                    if (OS.indexOf("mac") != -1)
                        blastn = "/usr/local/bin/blastn";
                    ProcessBuilder pb = new ProcessBuilder(blastn, "-db", dbspec, "-num_threads",
                            Integer.toString(Runtime.getRuntime().availableProcessors()), "-num_alignments",
                            "1", "-num_descriptions", "1"); //,"-max_hsps","1");
                    File dir = new File(System.getProperty("user.home"));
                    pb.directory(dir);
                    try {
                        Process p = pb.start();
                        final BufferedWriter fw = new BufferedWriter(
                                new OutputStreamWriter(p.getOutputStream()));
                        Thread t = new Thread() {
                            public void run() {
                                try {
                                    for (Sequence seq : lseq) {
                                        seq.writeSplitSequence(fw);
                                        //seq.writeSequence(fw);
                                    }
                                    fw.close();
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                            }
                        };
                        t.start();
                        //Path path = Paths.get("/Users/sigmar/"+spec+"_"+dbspec+".blastout");
                        //Files.copy(p.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);

                        int tnum = 0;
                        int tdenum = 0;
                        double avg = 0.0;
                        int count = 0;

                        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        String line = br.readLine();
                        while (line != null) {
                            if (line.startsWith(" Identities")) {
                                int i = line.indexOf('(');
                                String sub = line.substring(14, i - 1);
                                String[] split = sub.split("/");
                                int num = Integer.parseInt(split[0]);
                                int denum = Integer.parseInt(split[1]);

                                avg += (double) num / (double) denum;

                                tnum += num;
                                tdenum += denum;
                                count++;
                            }
                            line = br.readLine();
                        }
                        br.close();

                        if (count > 0)
                            avg /= count;
                        double val = (double) tnum / (double) tdenum;
                        matrix[y * species.size() + x] = avg;//val;
                        System.err.println(spec + " on " + dbspec + " " + val);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    //}
                    x++;
                }
                y++;
            }

            geneset.corrInd.clear();
            for (String spec : species) {
                geneset.corrInd.add(geneset.nameFix(spec));
            }

            final BufferedImage bi = geneset.showRelation(geneset.corrInd, matrix, false);
            JFrame f = new JFrame("TNI matrix");
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setSize(500, 500);

            JComponent comp2 = new JComponent() {
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    g.drawImage(bi, 0, 0, bi.getWidth(), bi.getHeight(), 0, 0, bi.getWidth(), bi.getHeight(),
                            this);
                }
            };
            Dimension dim = new Dimension(bi.getWidth(), bi.getHeight());
            comp2.setPreferredSize(dim);
            comp2.setSize(dim);
            JScrollPane scroll = new JScrollPane(comp2);
            f.add(scroll);

            f.setVisible(true);
        });
    });
    MenuItem anitreeaction = new MenuItem("ANI tree");
    anitreeaction.setOnAction(actionEvent -> {
        Set<String> species = getSelspec(GeneSetHead.this, geneset.specList);
        List<String> speclist = new ArrayList<String>(species);

        Collection<GeneGroup> allgg = new HashSet<GeneGroup>();
        allgg.addAll(table.getSelectionModel().getSelectedItems());
        if (allgg.isEmpty())
            allgg = geneset.allgenegroups;
        Map<String, Integer> blosumap = JavaFasta.getBlosumMap();

        double[] corrarr = new double[speclist.size() * speclist.size()];
        int where = 0;
        for (String spec1 : speclist) {
            int wherex = 0;

            String spc1 = geneset.nameFix(spec1);

            //String spc1 = nameFix( spec1 );
            for (String spec2 : speclist) {
                if (where != wherex) {
                    int totalscore = 0;
                    int totaltscore = 1;
                    for (GeneGroup gg : allgg) {
                        if ( /*gg.getSpecies().size() > 40 &&*/ gg.getSpecies().contains(spec1)
                                && gg.getSpecies().contains(spec2)) {
                            Teginfo ti1 = gg.species.get(spec1);
                            Teginfo ti2 = gg.species.get(spec2);
                            //if( ti1.tset.size() == 1 && ti2.tset.size() == 1 ) {
                            //double bval = 0.0;

                            int score = 0;
                            int tscore = 1;
                            for (Tegeval tv1 : ti1.tset) {
                                for (Tegeval tv2 : ti2.tset) {
                                    Sequence seq1 = tv1.getAlignedSequence();
                                    Sequence seq2 = tv2.getAlignedSequence();
                                    if (seq1 != null && seq2 != null) {
                                        int mest = 0;
                                        int tmest = 0;

                                        int startcheck = 0;
                                        int start = -1;
                                        int stopcheck = 0;
                                        int stop = -1;
                                        for (int i = 0; i < seq1.length(); i++) {
                                            if (seq1.getCharAt(i) != '-') {
                                                startcheck |= 1;
                                            }
                                            if (seq2.getCharAt(i) != '-') {
                                                startcheck |= 2;
                                            }

                                            if (start == -1 && startcheck == 3) {
                                                start = i;
                                                break;
                                            }
                                        }

                                        for (int i = seq1.length() - 1; i >= 0; i--) {
                                            if (seq1.getCharAt(i) != '-') {
                                                stopcheck |= 1;
                                            }
                                            if (seq2.getCharAt(i) != '-') {
                                                stopcheck |= 2;
                                            }

                                            if (stop == -1 && stopcheck == 3) {
                                                stop = i + 1;
                                                break;
                                            }
                                        }
                                        //count += stop-start;

                                        for (int i = start; i < stop; i++) {
                                            char lc = seq1.getCharAt(i);
                                            char c = Character.toUpperCase(lc);
                                            //if( )
                                            String comb = c + "" + c;
                                            if (blosumap.containsKey(comb))
                                                tmest += blosumap.get(comb);
                                        }

                                        for (int i = start; i < stop; i++) {
                                            char lc = seq1.getCharAt(i);
                                            char c = Character.toUpperCase(lc);
                                            char lc2 = seq2.getCharAt(i);
                                            char c2 = Character.toUpperCase(lc2);

                                            String comb = c + "" + c2;
                                            if (blosumap.containsKey(comb))
                                                mest += blosumap.get(comb);
                                        }

                                        double tani = (double) mest / (double) tmest;
                                        if (tani > (double) score / (double) tscore) {
                                            score = mest;
                                            tscore = tmest;
                                        }
                                        //ret = (double)score/(double)tscore; //int cval = tscore == 0 ? 0 : Math.min( 192, 512-score*512/tscore );
                                        //return ret;
                                    }
                                    //if( where == 0 ) d1.add( gg.getCommonName() );
                                    //else d2.add( gg.getCommonName() );
                                }
                            }
                            totalscore += score;
                            totaltscore += tscore;

                            /*if( bval > 0 ) {
                               ani += bval;
                               count++;
                            }*/
                            //}
                        }
                    }
                    double ani = (double) (totaltscore - totalscore) / (double) totaltscore;
                    corrarr[where * speclist.size() + wherex] = ani;
                }
                wherex++;
            }
            where++;
        }
        TreeUtil tu = new TreeUtil();
        geneset.corrInd.clear();
        for (String spec : speclist) {
            geneset.corrInd.add(geneset.nameFix(spec));
        }
        Node n = tu.neighborJoin(corrarr, geneset.corrInd, null, false, false);
        System.err.println(n);
    });
    windowmenu.getItems().add(specorderaction);
    windowmenu.getItems().add(matrixaction);
    windowmenu.getItems().add(tniaction);
    windowmenu.getItems().add(anitreeaction);

    MenuItem neighbourhood = new MenuItem("Neighbourhood");
    neighbourhood.setOnAction(actionEvent -> {
        try {
            Set<GeneGroup> genset = new HashSet<>();
            if (!isGeneview()) {
                for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                    genset.add(gg);
                }
            } else {
                for (Gene gene : gtable.getSelectionModel().getSelectedItems()) {
                    genset.add(gene.getGeneGroup());
                }
            }
            new Neighbour(genset).neighbourMynd(GeneSetHead.this, comp, geneset.genelist, geneset.contigmap);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    windowmenu.getItems().add(neighbourhood);

    MenuItem synteny = new MenuItem("Synteny");
    synteny.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            //Set<String> species = speciesFromCluster( clusterMap );
            new Synteni().syntenyMynd(GeneSetHead.this, comp, geneset.genelist);
        });
    });
    windowmenu.getItems().add(synteny);
    MenuItem compareplotaction = new MenuItem("Gene atlas");
    compareplotaction.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            try {
                new GeneCompare().comparePlot(GeneSetHead.this, comp, geneset.genelist, geneset.clusterMap,
                        8192, 8192);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        });

        /*gatest("MAT4726");
                
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
        frame.setSize(800, 600);
                
        final JComponent c = new JComponent() {
           public void paintComponent( Graphics g ) {
          g.drawImage(bimg, 0, 0, frame);
           }
        };
        c.setPreferredSize( new Dimension(bimg.getWidth(), bimg.getHeight()) );
        JScrollPane   scrollpane = new JScrollPane( c );
        frame.add( scrollpane );
        frame.setVisible( true );*/
    });
    windowmenu.getItems().add(compareplotaction);

    MenuItem syntenygradientaction = new MenuItem("Synteny gradient");
    syntenygradientaction.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            Set<String> presel = new HashSet<>();
            if (isGeneview()) {
                for (Gene g : gtable.getSelectionModel().getSelectedItems()) {
                    presel.addAll(g.getGeneGroup().getSpecies());
                }
            } else {
                for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                    presel.addAll(gg.getSpecies());
                }
            }
            new SyntGrad().syntGrad(GeneSetHead.this, 4096, 4096, presel);
        });
    });
    windowmenu.getItems().add(syntenygradientaction);

    MenuItem genexyplotaction = new MenuItem("Gene XY plot");
    genexyplotaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(
            () -> new XYPlot().xyPlot(GeneSetHead.this, comp, geneset.genelist, geneset.clusterMap)));
    windowmenu.getItems().add(genexyplotaction);

    MenuItem refalignaction = new MenuItem("Reference align");
    refalignaction.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            final TableView<Gene> table12 = getGeneTable();
            final Collection<String> specset = geneset.getSpecies(); //speciesFromCluster( clusterMap );
            final List<String> species = new ArrayList<>(specset);

            TableModel model = new TableModel() {
                @Override
                public int getRowCount() {
                    return species.size();
                }

                @Override
                public int getColumnCount() {
                    return 1;
                }

                @Override
                public String getColumnName(int columnIndex) {
                    return null;
                }

                @Override
                public Class<?> getColumnClass(int columnIndex) {
                    return String.class;
                }

                @Override
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return false;
                }

                @Override
                public Object getValueAt(int rowIndex, int columnIndex) {
                    return geneset.nameFix(species.get(rowIndex));
                }

                @Override
                public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
                }

                @Override
                public void addTableModelListener(TableModelListener l) {
                }

                @Override
                public void removeTableModelListener(TableModelListener l) {
                }
            };
            JTable table1 = new JTable(model);
            JTable table2 = new JTable(model);

            table1.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table2.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

            JScrollPane scroll1 = new JScrollPane(table1);
            JScrollPane scroll2 = new JScrollPane(table2);

            FlowLayout flowlayout = new FlowLayout();
            JComponent c = new JComponent() {
            };
            c.setLayout(flowlayout);

            c.add(scroll1);
            c.add(scroll2);

            JOptionPane.showMessageDialog(comp, c);

            int r = table1.getSelectedRow();
            int i = table1.convertRowIndexToModel(r);
            String spec = i == -1 ? null : species.get(i);
            List<Sequence> lcont = geneset.speccontigMap.get(spec);

            r = table2.getSelectedRow();
            i = table2.convertRowIndexToModel(r);
            String refspec = i == -1 ? null : species.get(i);
            List<Sequence> lrefcont = geneset.speccontigMap.get(spec);

            /*ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Writer fw = new OutputStreamWriter( baos );
            try {
            List<Sequence> lcont = geneset.speccontigMap.get(spec);
            for( Sequence seq : lcont ) {
                seq.writeSequence(fw);
            }
            fw.close();
            } catch (IOException e1) {
            e1.printStackTrace();
            }
                    
            String comp = spec;
            byte[] bb = baos.toByteArray();*/

            FlxReader flx = new FlxReader();

            Map<String, String> env = new HashMap<String, String>();
            env.put("create", "true");
            //String uristr = "jar:" + geneset.zippath.toUri();
            //URI geneset.zipuri = URI.create( uristr /*.replace("file://", "file:")*/ );

            try {
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                    Path subf = root.resolve(spec + ".grp");
                    if (Files.exists(subf)) {
                        BufferedReader br = Files.newBufferedReader(subf);
                        Map<String, Map<String, String>> mm = flx.loadContigGraph(br);
                        br.close();

                        String home = System.getProperty("user.home") + "/";
                        StringBuilder sb = comp != null
                                ? flx.referenceAssembly(home, spec, refspec, lrefcont, lcont)
                                : null;
                        Sequence cseq = new Sequence(spec + "_chromosome", null);
                        if (sb != null && sb.length() > 0) {
                            br = new BufferedReader(new StringReader(sb.toString()));
                        } else {
                            Path sca = root.resolve(spec + ".csc");
                            if (!Files.exists(sca)) {
                                sca = root.resolve(spec + ".sca");
                            }
                            br = Files.newBufferedReader(sca);
                        }
                        //br = new BufferedReader( fr );

                        flx.connectContigs(br, cseq, false, new FileWriter(home + spec + "_new.fna"), spec);
                        br.close();
                    }

                    break;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    geneset.zipfilesystem.close();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
                ;
            }
        });

        //flx.start( f.getParentFile().getAbsolutePath()+"/", f.getName(), false, fw, comp, bb);
    });
    windowmenu.getItems().add(refalignaction);

    windowmenu.getItems().add(new SeparatorMenuItem());

    MenuItem runantismash = new MenuItem("Run antismash");
    runantismash.setOnAction(actionEvent -> SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                Serifier ser = new Serifier();
                Set<String> selspec = getSelspec(null, geneset.getSpecies(), null);

                JTextField host = new JTextField("localhost");
                JOptionPane.showMessageDialog(null, host);

                String username = System.getProperty("user.name");
                String hostname = host.getText();

                /*Path[] pt = null;
                JFileChooser fc = new JFileChooser();
                fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
                if( fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION ) {
                   pt = new Path[3];
                   pt[2] = fc.getSelectedFile().toPath();
                }*/

                List<Object> commands = new ArrayList<Object>();
                //commands.add(genexyplotaction)

                for (String spec : selspec) {
                    Path pp = Paths.get(userhome);
                    Path p = pp.resolve(spec + ".gbk");
                    //BufferedWriter fw = Files.newBufferedWriter( p );
                    List<Sequence> clist = geneset.speccontigMap.get(spec);

                    Map<String, List<Annotation>> mapan = new HashMap<String, List<Annotation>>();
                    Serifier serifier = new Serifier();
                    for (Sequence c : clist) {
                        serifier.addSequence(c);
                        serifier.mseq.put(c.getName(), c);

                        List<Annotation> lann = new ArrayList<Annotation>();
                        if (c.getAnnotations() != null)
                            for (Annotation ann : c.getAnnotations()) {
                                Tegeval tv = (Tegeval) ann;

                                Gene g = tv.getGene();
                                GeneGroup gg = g.getGeneGroup();
                                String name = g.getName();
                                if (gg != null && name.contains(spec)) {
                                    name = gg.getName();
                                }
                                Annotation anno = new Annotation(c, tv.start, tv.stop, tv.ori, name);
                                anno.id = tv.getGene().getId();
                                anno.type = "CDS";

                                String cazy = gg != null ? gg.getCommonCazy(geneset.cazymap) : null;
                                if (cazy != null)
                                    anno.addDbRef("CAZY:" + cazy);
                                lann.add(anno);
                            }
                        mapan.put(c.getName(), lann);
                    }
                    Sequences s = new Sequences(null, spec, "nucl", null, clist.size());
                    //serifier.addSequences(seqs);
                    serifier.writeGenebank(p, false, true, s, mapan);

                    //fw.close();

                    String apath = p.toAbsolutePath().toString();
                    if (hostname.equals("localhost")) {
                        String[] cmds = { "run_antismash", apath };
                        //commands.add( pt );
                        commands.add(Arrays.asList(cmds));
                    } else {
                        String aname = p.getFileName().toString();
                        String adir = aname.substring(0, aname.length() - 4);
                        String cyghome = NativeRun.cygPath(userhome);
                        String[] cmds = { "scp", apath, hostname + ":~", ";", "ssh", hostname, "run_antismash",
                                aname, ";", "scp", "-r", hostname + ":~/" + adir, cyghome };//userhome+"~"};
                        //commands.add( pt );
                        commands.add(Arrays.asList(cmds));
                    }
                }

                Runnable run = new Runnable() {
                    @Override
                    public void run() {
                        for (String spec : selspec) {
                            Path p = Paths.get(userhome, spec);

                            Map<String, String> env = new HashMap<String, String>();
                            env.put("create", "true");

                            String uristr = "jar:" + geneset.zippath.toUri();
                            URI zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
                            final List<Path> lbi = new ArrayList<Path>();
                            try {
                                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                                for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                                    Path specdir = root;
                                    Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
                                        @Override
                                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                                throws IOException {
                                            final Path destFile = Paths.get(specdir.toString(),
                                                    file.toString());
                                            //System.out.printf("Extracting file %s to %s\n", file, destFile);
                                            Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
                                            return FileVisitResult.CONTINUE;
                                        }

                                        @Override
                                        public FileVisitResult preVisitDirectory(Path dir,
                                                BasicFileAttributes attrs) throws IOException {
                                            String specdirstr = specdir.toString();
                                            String dirstr = dir.toString();
                                            final Path dirToCreate = specdir
                                                    .resolve(dirstr.substring(userhome.length() + 1));
                                            if (Files.notExists(dirToCreate)) {
                                                System.out.printf("Creating directory %s\n", dirToCreate);
                                                Files.createDirectory(dirToCreate);
                                            }
                                            return FileVisitResult.CONTINUE;
                                        }
                                    });
                                    break;
                                }

                                URI uri = new URI("file://" + userhome + "/" + spec + "/index.html");
                                Desktop.getDesktop().browse(uri);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            } finally {
                                try {
                                    geneset.zipfilesystem.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                ;
                            }
                        }
                    }
                };

                NativeRun nr = new NativeRun(run);
                nr.runProcessBuilder("antismash", commands, new Object[3], false, run, false);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }));
    windowmenu.getItems().add(runantismash);

    MenuItem runsignalp = new MenuItem("Run signalP");
    runsignalp.setOnAction(actionEvent -> SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                Serifier ser = new Serifier();
                Set<String> selspec = getSelspec(null, geneset.getSpecies(), null);

                JTextField host = new JTextField("localhost");
                JOptionPane.showMessageDialog(null, host);

                String username = System.getProperty("user.name");
                String hostname = host.getText();

                /*Path[] pt = null;
                JFileChooser fc = new JFileChooser();
                fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
                if( fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION ) {
                   pt = new Path[3];
                   pt[2] = fc.getSelectedFile().toPath();
                }*/

                List<Object> commands = new ArrayList<Object>();
                //commands.add(genexyplotaction)

                try {
                    Map<String, String> env = new HashMap<String, String>();
                    env.put("create", "true");

                    String uristr = "jar:" + geneset.zippath.toUri();
                    URI zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );

                    geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                    for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                        for (String spec : selspec) {
                            /*Path specdir = root.resolve(spec+".prodigal.fsa");
                            if( !Files.exists(specdir) ) {
                               if( spec.startsWith("MAT") ) {
                                  specdir = root.resolve(spec+".gbk.aa");
                               } else specdir = root.resolve("fn_"+spec+"_scaffolds.prodigal.fsa");
                            }*/
                            Stream<Gene> genestream = geneset.genelist.stream()
                                    .filter(gene -> spec.equals(gene.getSpecies())
                                            && (gene.tegeval.type == null || gene.tegeval.type.length() == 0));
                            Path sigout = root.resolve(spec + ".signalp");
                            Path[] pt = new Path[] { null, sigout, null };
                            if (hostname.equals("localhost")) {
                                String[] cmds = { "signalp", "-t", "gram-", "-" };
                                commands.add(pt);
                                commands.add(Arrays.asList(cmds));
                            } else {
                                Path p = Paths.get(spec + ".signalp");
                                BufferedWriter bw = Files.newBufferedWriter(p, StandardOpenOption.CREATE,
                                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
                                genestream.forEachOrdered(gene -> {
                                    try {
                                        gene.writeGeneIdFasta(bw);
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }
                                });
                                bw.close();

                                //Files.copy(specdir, p, StandardCopyOption.REPLACE_EXISTING);

                                String[] cmds = { "scp", spec + ".signalp", hostname + ":~", ";", "ssh",
                                        hostname, "signalp", "-t", "gram-", spec + ".signalp" };
                                //String[] cmds = {"ssh",hostname,"signalp","-t","gram-","-"};
                                commands.add(pt);
                                commands.add(Arrays.asList(cmds));
                            }
                        }

                        break;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                Runnable run = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            geneset.zipfilesystem.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        ;
                    }
                };

                NativeRun nr = new NativeRun(run);
                nr.runProcessBuilder("signalp", commands, new Object[3], false, run, false);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }));
    windowmenu.getItems().add(runsignalp);

    MenuItem runtransm = new MenuItem("Run TransM");
    runtransm.setOnAction(actionEvent -> SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                Serifier ser = new Serifier();
                Set<String> selspec = getSelspec(null, geneset.getSpecies(), null);

                JTextField host = new JTextField("localhost");
                JOptionPane.showMessageDialog(null, host);

                String username = System.getProperty("user.name");
                String hostname = host.getText();

                /*Path[] pt = null;
                JFileChooser fc = new JFileChooser();
                fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
                if( fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION ) {
                   pt = new Path[3];
                   pt[2] = fc.getSelectedFile().toPath();
                }*/

                List<Object> commands = new ArrayList<>();
                //commands.add(genexyplotaction)

                try {
                    Map<String, String> env = new HashMap<>();
                    env.put("create", "true");

                    String uristr = "jar:" + geneset.zippath.toUri();
                    URI zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );

                    geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                    for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                        for (String spec : selspec) {
                            /*Path specdir = root.resolve(spec+".prodigal.fsa");
                            if( !Files.exists(specdir) ) {
                               if( spec.startsWith("MAT") ) {
                                  specdir = root.resolve(spec+".gbk.aa");
                               } else specdir = root.resolve("fn_"+spec+"_scaffolds.prodigal.fsa");
                            }*/

                            Stream<Gene> genestream = geneset.genelist.stream()
                                    .filter(gene -> spec.equals(gene.getSpecies())
                                            && (gene.tegeval.type == null || gene.tegeval.type.length() == 0));
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(baos));
                            genestream.forEach(gene -> {
                                try {
                                    gene.writeGeneIdFasta(bw);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                            });
                            bw.close();
                            baos.close();
                            String seqs = baos.toString();
                            seqs = seqs.replace('*', 'X');
                            byte[] bb = seqs.getBytes();
                            Path sigout = root.resolve(spec + ".tm");
                            Object[] pt = new Object[] { bb, sigout, null };
                            if (hostname.equals("localhost")) {
                                String[] cmds = { "decodeanhmm", "-f", "/opt/tmhmm-2.0c/lib/TMHMM2.0.options",
                                        "-modelfile", "/opt/tmhmm-2.0c/lib/TMHMM2.0.model" };
                                commands.add(pt);
                                commands.add(Arrays.asList(cmds));
                            } else {
                                //Path p = Paths.get(spec+".tm");
                                //Files.copy(specdir, p, StandardCopyOption.REPLACE_EXISTING);

                                String[] cmds = { "ssh", hostname, "decodeanhmm", "-f",
                                        "/opt/tmhmm-2.0c/lib/TMHMM2.0.options", "-modelfile",
                                        "/opt/tmhmm-2.0c/lib/TMHMM2.0.model" };
                                commands.add(pt);
                                commands.add(Arrays.asList(cmds));
                            }
                        }

                        break;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                Runnable run = () -> {
                    try {
                        geneset.zipfilesystem.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ;
                };

                NativeRun nr = new NativeRun(run);
                nr.runProcessBuilder("transm", commands, new Object[3], false, run, false);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }));
    windowmenu.getItems().add(runtransm);

    MenuItem runtrnascan = new MenuItem("tRNAscan");
    runtrnascan.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        try {
            Serifier ser = new Serifier();
            Set<String> selspec = getSelspec(null, geneset.getSpecies(), null);

            JTextField host = new JTextField("localhost");
            JOptionPane.showMessageDialog(null, host);

            String username = System.getProperty("user.name");
            String hostname = host.getText();

            /*Path[] pt = null;
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
            if( fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION ) {
            pt = new Path[3];
            pt[2] = fc.getSelectedFile().toPath();
            }*/

            List<Object> commands = new ArrayList<>();
            //commands.add(genexyplotaction)

            try {
                Map<String, String> env = new HashMap<>();
                env.put("create", "true");

                String uristr = "jar:" + geneset.zippath.toUri();
                URI zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );

                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                    for (String spec : selspec) {
                        Path specdir = root.resolve(spec + ".fna");
                        if (!Files.exists(specdir)) {
                            if (spec.startsWith("MAT")) {
                                specdir = root.resolve(spec + ".gbk.fna");
                            } else
                                specdir = root.resolve("fn_" + spec + "_scaffolds.fastg");
                        }

                        System.err.println(Files.exists(specdir));

                        Path sigout = root.resolve("trnas.txt");
                        if (hostname.equals("localhost1")) {
                            Path[] pt = new Path[] { specdir, sigout, null };
                            String[] cmds = { "/usr/local/bin/tRNAscan-SE", "-B", "-" };
                            commands.add(pt);
                            commands.add(Arrays.asList(cmds));
                        } else {
                            Path[] pt = new Path[] { null, sigout, null };
                            Path p = Paths.get(spec + ".trnascan");
                            Files.copy(specdir, p, StandardCopyOption.REPLACE_EXISTING);

                            List<String> lcmd;
                            if (hostname.equals("localhost")) {
                                //String[] cmds = {"/usr/local/bin/trnascan-1.4", spec + ".trnascan"};
                                String[] cmds = { "/usr/local/bin/tRNAscan-SE", "-B", spec + ".trnascan" };
                                lcmd = Arrays.asList(cmds);
                            } else {
                                String[] cmds = { "scp", spec + ".trnascan", hostname + ":~", ";", "ssh",
                                        hostname, "trnascan-1.4", spec + ".trnascan" };
                                lcmd = Arrays.asList(cmds);
                                //String[] cmds = {"ssh",hostname,"tRNAscan-SE","-B","-"};
                            }

                            commands.add(pt);
                            commands.add(lcmd);
                        }
                    }

                    break;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            Runnable run = () -> {
                try {
                    geneset.zipfilesystem.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ;
            };

            NativeRun nr = new NativeRun(run);
            nr.runProcessBuilder("tRNAscan", commands, new Object[3], false, run, false);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }));
    windowmenu.getItems().add(runtrnascan);

    Menu select = new Menu("Select");
    MenuItem breakpointselAction = new MenuItem("Select breakpoints");
    breakpointselAction.setOnAction(actionEvent -> {
        String spec = syncolorcomb.getSelectionModel().getSelectedItem();

        int rr = 0;
        for (Gene g : geneset.genelist) {
            if (!spec.equals(g.getSpecies()) && g.getSpecies().contains("eggert")) {
                Tegeval tv2 = g.tegeval;
                Annotation n2 = tv2.getNext();
                Annotation p2 = tv2.getPrevious();

                GeneGroup gg = g.getGeneGroup();

                if (gg.getName().contains("rhodane")) {
                    System.err.println();
                }

                Teginfo ti = gg.getGenes(spec);
                int msimcount = 0;
                if (ti != null) {
                    for (Tegeval tv1 : ti.tset) {
                        int simcount = 0;

                        Annotation n = tv1.getNext();
                        Annotation p = tv1.getPrevious();

                        GeneGroup ggg = tv1.getGene().getGeneGroup();
                        if (n2 != null) {
                            if (ggg == n2.getGene().getGeneGroup()) {
                                simcount++;
                            }

                            Annotation nn2 = n2.getNext();
                            if (nn2 != null) {
                                if (ggg == nn2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }
                        }

                        if (p2 != null) {
                            if (ggg == p2.getGene().getGeneGroup()) {
                                simcount++;
                            }

                            Annotation pp2 = p2.getPrevious();
                            if (pp2 != null) {
                                if (ggg == pp2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }
                        }

                        if (n != null) {
                            GeneGroup ngg = n.getGene().getGeneGroup();

                            if (ngg == tv2.getGene().getGeneGroup()) {
                                simcount++;
                            }

                            if (n2 != null) {
                                if (ngg == n2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }

                            if (p2 != null) {
                                if (ngg == p2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }

                            Annotation nn = n.getNext();
                            if (nn != null) {
                                ngg = nn.getGene().getGeneGroup();

                                if (ngg == tv2.getGene().getGeneGroup()) {
                                    simcount++;
                                }

                                if (n2 != null) {
                                    if (ngg == n2.getGene().getGeneGroup()) {
                                        simcount++;
                                    }
                                }

                                if (p2 != null) {
                                    if (ngg == p2.getGene().getGeneGroup()) {
                                        simcount++;
                                    }
                                }
                            }
                        }

                        if (p != null) {
                            GeneGroup pgg = p.getGene().getGeneGroup();

                            if (pgg == tv2.getGene().getGeneGroup()) {
                                simcount++;
                            }

                            if (n2 != null) {
                                if (pgg == n2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }

                            if (p2 != null) {
                                if (pgg == p2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }

                            Annotation pp = p.getPrevious();
                            if (pp != null) {
                                pgg = pp.getGene().getGeneGroup();

                                if (pgg == tv2.getGene().getGeneGroup()) {
                                    simcount++;
                                }

                                if (n2 != null) {
                                    if (pgg == n2.getGene().getGeneGroup()) {
                                        simcount++;
                                    }
                                }

                                if (p2 != null) {
                                    if (pgg == p2.getGene().getGeneGroup()) {
                                        simcount++;
                                    }
                                }
                            }
                        }

                        //double rat = GeneCompare.invertedGradientRatio(spec, contigs, -1.0, gg, tv);
                        if (simcount >= msimcount) {
                            //tv = tv1;
                            msimcount = simcount;
                        }

                        //double ratio = GeneCompare.invertedGradientRatio(spec, contigs, -1.0, gg, tv);
                        //GeneCompare.gradientColor();
                    }

                    if (msimcount < 2) {
                        gtable.getSelectionModel().select(g);
                    }
                }
            }
            rr++;
        }
        /*List<Sequence> contigs = geneset.speccontigMap.get( spec );
        for( Sequence c : contigs ) {
           for( Annotation ann : c.annset ) {
          Tegeval tv = (Tegeval)ann;
                  
           }
        }*/
    });
    MenuItem saveselAction = new MenuItem("Save selection");
    saveselAction.setOnAction(actionEvent -> {
        /*int[] rr = table.getSelectedRows();
        if( rr.length > 0 ) {
           String val = Integer.toString( table.convertRowIndexToModel(rr[0]) );
           for( int i = 1; i < rr.length; i++ ) {
              val += ","+table.convertRowIndexToModel(rr[i]);
           }
           String selname = JOptionPane.showInputDialog("Selection name");
           if( comp instanceof Applet ) {
              try {
          ((GeneSetHead)comp).saveSel( selname, val);
              } catch (Exception e1) {
          e1.printStackTrace();
              }
           }
        }*/
    });
    select.getItems().add(breakpointselAction);
    select.getItems().add(saveselAction);
    select.getItems().add(new SeparatorMenuItem());

    MenuItem showall = new MenuItem("Show all");
    showall.setOnAction(actionEvent -> {
        genefilterset.clear();
        updateFilter(table, label);
    });
    select.getItems().add(showall);
    MenuItem croptosel = new MenuItem("Crop to selection");
    croptosel.setOnAction(actionEvent -> {
        Set<GeneGroup> selitems = new HashSet<>(table.getSelectionModel().getSelectedItems());
        filteredData.setPredicate(p -> selitems.contains(p));
    });
    select.getItems().add(croptosel);
    MenuItem croptoinvsel = new MenuItem("Crop to inverted selection");
    croptoinvsel.setOnAction(actionEvent -> {
        genefilterset.clear();
        for (int i = 0; i < table.getItems().size(); i++) {
            if (!table.getSelectionModel().isSelected(i)) {
                genefilterset.add(i);
            }
        }
        updateFilter(table, label);
    });
    select.getItems().add(croptoinvsel);
    MenuItem removesel = new MenuItem("Remove selection");
    removesel.setOnAction(actionEvent -> {
        // genefilterset.clear();
        //int[] rr = table.getSelectedRows();
        if (genefilterset.isEmpty()) {
            Set<Integer> ii = new HashSet<Integer>();
            for (int r : table.getSelectionModel().getSelectedIndices())
                ii.add(r);
            for (int i = 0; i < geneset.genelist.size(); i++) {
                if (!ii.contains(i))
                    genefilterset.add(i);
            }
        } else {
            for (int r : table.getSelectionModel().getSelectedIndices()) {
                //int mr = table.convertRowIndexToModel(r);
                genefilterset.remove(r);
            }
        }
        updateFilter(table, label);
    });
    select.getItems().add(removesel);
    MenuItem invsel = new MenuItem("Invert selection");
    invsel.setOnAction(actionEvent -> {
        ObservableList<GeneGroup> selitems = table.getSelectionModel().getSelectedItems();
        List<GeneGroup> newsel = new ArrayList<>(filteredData);
        newsel.removeAll(selitems);

        table.getSelectionModel().clearSelection();
        newsel.stream().forEach(gg -> table.getSelectionModel().select(gg));

        // genefilterset.clear();
        //int[] rr = table.getSelectedRows();
        /*Set<Integer> iset = new HashSet<>();
        for( int r : table.getSelectionModel().getSelectedIndices() ) {
           iset.add( r );
        }
        table.getSelectionModel().clearSelection();
        for (int r = 0; r < table.getItems().size(); r++) {
           if( !iset.contains(r) ) table.getSelectionModel().select(r);
           /*if (table.isRowSelected(r))
          table.removeRowSelectionInterval(r, r);
           else
          table.addRowSelectionInterval(r, r);
        }*/
    });
    select.getItems().add(invsel);
    //select.addSeparator();
    select.getItems().add(new SeparatorMenuItem());
    MenuItem selsinglemult = new MenuItem("Select single copy genes found in multiple strains");
    selsinglemult.setOnAction(actionEvent -> {
        Set<String> specset = getSelspec(GeneSetHead.this, geneset.specList);
        for (GeneGroup gg : geneset.allgenegroups) {
            Set<String> checkspec = new HashSet<String>(gg.species.keySet());
            checkspec.retainAll(specset);
            if (gg.getCommonTag() == null && checkspec.size() > 1
                    && gg.getTegevals().size() == gg.species.size()) {//gg.getTegevals(checkspec).size() == checkspec.size() ) {
                table.getSelectionModel().select(gg);
                //table.setro
            }
        }
    });
    select.getItems().add(selsinglemult);
    MenuItem selsinglemultstrain = new MenuItem(
            "Select single copy genes in accessory genome of multiple strains");
    selsinglemultstrain.setOnAction(actionEvent -> {
        Set<String> specset = getSelspec(GeneSetHead.this, geneset.specList);
        for (GeneGroup gg : geneset.allgenegroups) {
            Set<String> checkspec = new HashSet<String>(gg.species.keySet());
            checkspec.retainAll(specset);
            if (gg.getCommonTag() == null && checkspec.size() > 1 && checkspec.size() < specset.size()
                    && gg.getTegevals().size() == gg.species.size()) {//gg.getTegevals(checkspec).size() == checkspec.size() ) {
                table.getSelectionModel().select(gg);
                //table.setro
            }
        }
    });
    select.getItems().add(selsinglemultstrain);

    MenuItem selsinglecopygenes = new MenuItem("Select single copy genes");
    selsinglecopygenes.setOnAction(actionEvent -> {
        Set<String> specset = getSelspec(GeneSetHead.this, geneset.specList);
        for (GeneGroup gg : geneset.allgenegroups) {
            if (gg.getTegevals().size() == gg.species.size()) {
                table.getSelectionModel().select(gg);
                //table.setro
            }
        }
    });
    select.getItems().add(selsinglecopygenes);
    MenuItem selduplgenes = new MenuItem("Select duplicated genes");
    selduplgenes.setOnAction(actionEvent -> {
        for (GeneGroup gg : geneset.allgenegroups) {
            int cnt = 0;
            for (String spec : gg.species.keySet()) {
                Teginfo ti = gg.species.get(spec);
                if (ti.tset.size() == 2) {
                    List<Tegeval> ta = new ArrayList<Tegeval>(ti.tset);
                    if (ta.get(0).getNext() == ta.get(1) || ta.get(0).getPrevious() == ta.get(1))
                        cnt++;
                }
            }
            if ((float) cnt / (float) gg.species.size() > 0.7) {
                table.getSelectionModel().select(gg);
            }
        }
    });
    select.getItems().add(selduplgenes);
    MenuItem seltriplgenes = new MenuItem("Select triplicated genes");
    seltriplgenes.setOnAction(actionEvent -> {
        for (GeneGroup gg : geneset.allgenegroups) {
            int cnt = 0;
            for (String spec : gg.species.keySet()) {
                Teginfo ti = gg.species.get(spec);
                if (ti.tset.size() == 3) {
                    List<Tegeval> ta = new ArrayList<Tegeval>(ti.tset);
                    if ((ta.get(0).getNext() == ta.get(1) || ta.get(0).getPrevious() == ta.get(1))
                            && (ta.get(1).getNext() == ta.get(2) || ta.get(1).getPrevious() == ta.get(2)))
                        cnt++;
                }
            }
            if ((float) cnt / (float) gg.species.size() > 0.7) {
                table.getSelectionModel().select(gg);
            }
        }
    });
    select.getItems().add(seltriplgenes);

    MenuItem selplasmidgenes = new MenuItem("Select plasmid genes");
    selplasmidgenes.setOnAction(actionEvent -> {
        for (GeneGroup gg : geneset.allgenegroups) {
            if (gg.isOnAnyPlasmid()) {
                table.getSelectionModel().select(gg);
            }
            /*int cnt = 0;
            for( String spec : gg.species.keySet() ) {
               Teginfo ti = gg.species.get( spec );
               if( ti.tset.size() == 3 ) {
             List<Tegeval> ta = new ArrayList<Tegeval>( ti.tset );
             if( (ta.get(0).getNext() == ta.get(1) || ta.get(0).getPrevious() == ta.get(1)) && (ta.get(1).getNext() == ta.get(2) || ta.get(1).getPrevious() == ta.get(2))) cnt++;
               }
            }
            if( (float)cnt / (float)gg.species.size() > 0.7 ) {
               int r = table.convertRowIndexToView(gg.index);
               table.addRowSelectionInterval(r, r);
            }*/
        }
    });
    select.getItems().add(selplasmidgenes);

    MenuItem selectphagegenes = new MenuItem("Select phage genes");
    selectphagegenes.setOnAction(actionEvent -> {
        for (GeneGroup gg : geneset.allgenegroups) {
            if (gg.isInAnyPhage()) {
                table.getSelectionModel().select(gg);
            }
            /*int cnt = 0;
            for( String spec : gg.species.keySet() ) {
               Teginfo ti = gg.species.get( spec );
               if( ti.tset.size() == 3 ) {
             List<Tegeval> ta = new ArrayList<Tegeval>( ti.tset );
             if( (ta.get(0).getNext() == ta.get(1) || ta.get(0).getPrevious() == ta.get(1)) && (ta.get(1).getNext() == ta.get(2) || ta.get(1).getPrevious() == ta.get(2))) cnt++;
               }
            }
            if( (float)cnt / (float)gg.species.size() > 0.7 ) {
               int r = table.convertRowIndexToView(gg.index);
               table.addRowSelectionInterval(r, r);
            }*/
        }
    });
    select.getItems().add(selectphagegenes);
    select.getItems().add(new SeparatorMenuItem());
    MenuItem selectsharingaction = new MenuItem("Select sharing");
    selectsharingaction.setOnAction(actionEvent -> {
        RadioButton panbtn = new RadioButton("Pan");
        RadioButton corebtn = new RadioButton("Core");
        RadioButton blehbtn = new RadioButton("Only in");
        ToggleGroup tg = new ToggleGroup();
        panbtn.setToggleGroup(tg);
        corebtn.setToggleGroup(tg);
        blehbtn.setToggleGroup(tg);

        HBox sp = new HBox();
        sp.getChildren().add(panbtn);
        sp.getChildren().add(corebtn);
        sp.getChildren().add(blehbtn);
        Scene scene = new Scene(sp);

        //FlowLayout flowlayout = new FlowLayout();
        final JFXPanel c = new JFXPanel();
        c.setScene(scene);

        /*Group  root  =  new  Group();
          Scene  scene  =  new  Scene(root, javafx.scene.paint.Color.ALICEBLUE);
          root.getChildren().add(panbtn);
          root.getChildren().add(corebtn);
          root.getChildren().add(blehbtn);
        JFXPanel fxpanel = new JFXPanel();
        fxpanel.setScene( scene );*/
        //bg.add( panbtn );
        //bg.add( corebtn );
        //bg.add( blehbtn );
        corebtn.setSelected(true);
        //Object[] objs = new Object[] { panbtn, corebtn };
        //JOptionPane.showMessageDialog( geneset, objs, "Select id types", JOptionPane.PLAIN_MESSAGE );

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final List<String> species = geneset.getSpecies();
                TableModel model = new TableModel() {
                    @Override
                    public int getRowCount() {
                        return species.size();
                    }

                    @Override
                    public int getColumnCount() {
                        return 1;
                    }

                    @Override
                    public String getColumnName(int columnIndex) {
                        return null;
                    }

                    @Override
                    public Class<?> getColumnClass(int columnIndex) {
                        return String.class;
                    }

                    @Override
                    public boolean isCellEditable(int rowIndex, int columnIndex) {
                        return false;
                    }

                    @Override
                    public Object getValueAt(int rowIndex, int columnIndex) {
                        return species.get(rowIndex);
                    }

                    @Override
                    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
                    }

                    @Override
                    public void addTableModelListener(TableModelListener l) {
                    }

                    @Override
                    public void removeTableModelListener(TableModelListener l) {
                    }
                };
                JTable table = new JTable(model);
                table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
                JScrollPane scroll = new JScrollPane(table);

                Object[] objs = new Object[] { scroll, c };
                JOptionPane.showMessageDialog(comp, objs);

                final Set<String> specs = new HashSet<String>();
                int[] rr = table.getSelectedRows();
                for (int r : rr) {
                    String spec = (String) table.getValueAt(r, 0);
                    specs.add(spec);
                }

                Platform.runLater(new Runnable() {
                    public void run() {
                        for (GeneGroup gg : geneset.allgenegroups) {
                            if (blehbtn.isSelected()) {
                                Set<String> ss = new HashSet<String>(gg.species.keySet());
                                ss.removeAll(specs);
                                if (ss.size() == 0) {
                                    GeneSetHead.this.table.getSelectionModel().select(gg);
                                }
                            } else if (gg.species.keySet().containsAll(specs)
                                    && (panbtn.isSelected() || specs.size() == gg.species.size())) {
                                GeneSetHead.this.table.getSelectionModel().select(gg);
                            }
                        }
                    }
                });
            }
        });
    });
    select.getItems().add(selectsharingaction);
    MenuItem selectdirtyaction = new MenuItem("Select dirty");
    selectdirtyaction.setOnAction(actionEvent -> {
        if (!isGeneview()) {
            int i = 0;
            for (GeneGroup gg : geneset.allgenegroups) {
                if (gg.containsDirty()) {
                    table.getSelectionModel().select(gg);
                }
                i++;
            }
        }
    });
    select.getItems().add(selectdirtyaction);
    MenuItem selectdesignationaction = new MenuItem("Select designation");
    selectdesignationaction.setOnAction(actionEvent -> {
        JComboBox<String> descombo = new JComboBox<String>(
                geneset.deset.toArray(new String[geneset.deset.size()]));
        descombo.insertItemAt("", 0);
        descombo.setSelectedIndex(0);

        JOptionPane.showMessageDialog(GeneSetHead.this, descombo);
        String seldes = (String) descombo.getSelectedItem();
        if (!isGeneview()) {
            int i = 0;
            for (GeneGroup gg : geneset.allgenegroups) {
                if (gg.genes != null)
                    for (Gene g : gg.genes) {
                        if (seldes.equals(g.tegeval.designation)) {
                            table.getSelectionModel().select(gg);
                        }
                    }
                i++;
            }
        }
    });
    select.getItems().add(selectdesignationaction);

    MenuItem blastselect = new MenuItem("Blast select");
    blastselect.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> blast(false)));
    select.getItems().add(blastselect);

    MenuItem blastxselect = new MenuItem("Blastx select");
    blastxselect.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> blast(true)));
    select.getItems().add(blastxselect);

    MenuItem blastnselect = new MenuItem("Blastn select");
    blastnselect.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> blastn(true)));
    select.getItems().add(blastnselect);

    MenuItem blastsearch = new MenuItem("Blastn search");
    blastsearch.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> blastn(false)));
    select.getItems().add(blastsearch);

    menubar.getMenus().add(file);
    menubar.getMenus().add(edit);
    menubar.getMenus().add(view);
    menubar.getMenus().add(sequencemenu);
    menubar.getMenus().add(windowmenu);
    menubar.getMenus().add(select);
    menubar.getMenus().add(help);

    if (comp != null) {
        final Window window = SwingUtilities.windowForComponent(comp);
        initFSKeyListener(window);
        if (comp instanceof JFrame || window instanceof JFrame) {
            JFrame frame = (JFrame) (window == null ? comp : window);
            if (!frame.isResizable())
                frame.setResizable(true);

            frame.addKeyListener(keylistener);
            frame.setJMenuBar(jmenubar);
        }
    }

    final Button jb = new Button("Atlas");
    jb.setOnAction(event -> {
        try {
            URL url = new URL("file:///home/sigmar/workspace/distann/bin/circle.html");
            GeneSetHead.this.getAppletContext().showDocument(url, "_blank");
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
    });

    try {
        newSoft(jb, comp, genetable, upper, lower, toolbar, btoolbar, GeneSetHead.this, selcomb);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (comp != null) {
        if (comp instanceof Applet)
            try {
                ((GeneSetHead) comp).saveSel(null, null);
            } catch (NoSuchMethodError | Exception e1) {
                e1.printStackTrace();
            }
        //comp.add( cc );
    }
}

From source file:org.simmi.GeneSetHead.java

License:asdf

private void showGeneTable(
        /*final Map<String, Gene> genemap, final List<Gene> genelist, 
        final List<Function> funclist, final List<Set<String>> iclusterlist, final List<Set<String>> uclusterlist,
        final Map<Set<String>, ShareNum> specset,*/ final Map<Set<String>, ClusterInfo> clustInfoMap,
        final Button jb, final TableView<Gene> genetable, final TableView<Function> upper,
        final TableView<GeneGroup> lower, final ToolBar toolbar, final ToolBar btoolbar, final Container comp,
        final JApplet applet, final ComboBox<String> selcomblocal) throws IOException {
    //JSplitPane splitpane = new JSplitPane();
    //splitpane.setOrientation(JSplitPane.VERTICAL_SPLIT);
    //splitpane.setDividerLocation(400);
    //JScrollPane scrollpane = new JScrollPane();

    /*table = new JTable() {
       public String getToolTipText(MouseEvent me) {
    Point p = me.getPoint();/*w  w w  .  j a v  a 2  s. c  om*/
    int r = rowAtPoint(p);
    int c = columnAtPoint(p);
    if (r >= 0 && r < super.getRowCount()) {
       Object ret = super.getValueAt(r, c);
       if (ret != null) {
          return ret.toString(); // super.getToolTipText( me );
       }
    }
    return "";
       }
    };*/

    //table.setDragEnabled(true);
    try {
        final DataFlavor df = new DataFlavor("text/plain;charset=utf-8");
        // System.err.println( df.getHumanPresentableName() + " " +
        // df.getPrimaryType() + " " + df.getSubType() + " " +
        // df.getMimeType() );
        // DataFlavor df1 = DataFlavor.getTextPlainUnicodeFlavor();
        // System.err.println( df.getHumanPresentableName() + " " +
        // df.getPrimaryType() + " " + df.getSubType() + " " +
        // df.getMimeType() );
        TransferHandler th = new TransferHandler() {
            /**
             * 
             */
            private static final long serialVersionUID = 1L;

            public int getSourceActions(JComponent c) {
                return TransferHandler.COPY_OR_MOVE;
            }

            public boolean canImport(TransferHandler.TransferSupport support) {
                return true;
            }

            protected Transferable createTransferable(JComponent c) {
                return new Transferable() {
                    @Override
                    public Object getTransferData(DataFlavor arg0)
                            throws UnsupportedFlavorException, IOException {
                        Map<String, List<Tegeval>> contigs = new HashMap<>();
                        StringBuilder ret = new StringBuilder();
                        for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                            Tegeval tv = gg.tegeval;
                            if (!contigs.containsKey(tv.getContshort())) {
                                List<Tegeval> ltv = new ArrayList<>();
                                ltv.add(tv);
                                contigs.put(tv.getContshort().getName(), ltv);
                            } else {
                                List<Tegeval> ltv = contigs.get(tv.getContshort());
                                ltv.add(tv);
                            }
                            /*
                             * ret.append( ">" + tv.cont + " " +
                             * tv.teg + " " + tv.eval + "\n" );
                             * if( tv.dna != null ) { for( int i
                             * = 0; i < tv.dna.length(); i+=70 )
                             * { ret.append(tv.dna.substring( i,
                             * Math.min(i+70,tv.dna.length())
                             * )+"\n"); } }
                             */
                        }
                        for (String cont : contigs.keySet()) {
                            List<Tegeval> tv = contigs.get(cont);
                            String dna = tv.get(0).getSequence();
                            ret.append(">" + cont + "\n"); // + " " + tv.teg
                            // + " " +
                            // tv.eval +
                            // "\n" );
                            if (dna != null) {
                                for (int i = 0; i < dna.length(); i += 70) {
                                    ret.append(dna.substring(i, Math.min(i + 70, dna.length())) + "\n");
                                }
                            }
                        }
                        for (String cont : contigs.keySet()) {
                            List<Tegeval> ltv = contigs.get(cont);
                            ret.append(">" + cont + "\n"); // + " " + tv.teg
                            // + " " +
                            // tv.eval +
                            // "\n" );
                            for (Tegeval tv : ltv) {
                                ret.append("erm\t#0000ff\t" + tv.start + "\t" + tv.stop + "\n");
                            }
                        }

                        return new ByteArrayInputStream(ret.toString().getBytes());
                    }

                    @Override
                    public DataFlavor[] getTransferDataFlavors() {
                        return new DataFlavor[] { df };
                    }

                    @Override
                    public boolean isDataFlavorSupported(DataFlavor arg0) {
                        if (arg0.equals(df)) {
                            return true;
                        }
                        return false;
                    }
                };
            }

            public boolean importData(TransferHandler.TransferSupport support) {
                Object obj = null;

                System.err.println(support.getDataFlavors().length);
                int b = Arrays.binarySearch(support.getDataFlavors(), DataFlavor.javaFileListFlavor,
                        (o1, o2) -> o1 == o2 ? 1 : 0);

                try {
                    obj = support.getTransferable().getTransferData(DataFlavor.imageFlavor);
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    if (obj != null && obj instanceof File[]) {
                        // File[] ff = (File[])obj;
                        // wbStuff( ff[0].getCanonicalPath() );
                    } else if (obj instanceof Image) {

                    } else {
                        obj = support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                        System.err.println(obj);
                        URL url = null;
                        try {
                            url = new URL((String) obj);
                            Image image = ImageIO.read(url);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return true;
            }
        };
        //table.setTransferHandler(th);
    } catch (ClassNotFoundException e2) {
        e2.printStackTrace();
    }

    final Color darkgreen = new Color(0, 128, 0);
    final Color darkred = new Color(128, 0, 0);
    final Color darkblue = new Color(0, 0, 128);
    final Color darkmag = new Color(128, 0, 128);
    /*table.setDefaultRenderer(Teg.class, new DefaultTableCellRenderer() {
       @Override
       public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component label = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if( value == null ) {
       label.setBackground(Color.white);
    } else {
       cellRender();
    }
    return label;
       }
    });*/

    //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //table.setAutoCreateRowSorter(true);
    //scrollpane.setViewportView(table);

    Set<String> current = null;
    Set<String> currentko = null;
    InputStream is = GeneSet.class.getResourceAsStream("/kegg_pathways");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = br.readLine();
    while (line != null) {
        if (line.startsWith(">")) {
            current = new HashSet<>();
            currentko = new HashSet<>();
            geneset.pathwaymap.put(line.substring(1), current);
            geneset.pathwaykomap.put(line.substring(1), currentko);
        } else if (!line.startsWith("K")) {
            if (current != null) {
                String str = line.split("[\t ]+")[0];
                current.add(str);
            }
        } else {
            if (currentko != null) {
                String str = line.split("[\t ]+")[0];
                currentko.add(str);
            }
        }
        line = br.readLine();
    }
    br.close();

    //FileReader fr = new FileReader("/vg454flx/ko2go.txt");
    /*is = GeneSet.class.getResourceAsStream("/ko2go.txt");
    InputStreamReader isr = new InputStreamReader( is );
    br = new BufferedReader( isr );
    line = br.readLine();
    while (line != null) {
       String[] split = line.split(" = ");
       String[] subsplit = split[1].split(" ");
       Set<String> gos = new HashSet<String>();
       for( String go : subsplit ) {
    gos.add( go );
       }
       ko2go.put( split[0], gos );
       line = br.readLine();
    }
    br.close();*/

    final TextField textfield = new TextField();
    //JComponent topcomp = new JComponent() {};
    //topcomp.setLayout(new BorderLayout());
    //topcomp.add(scrollpane);

    textfield.setPrefSize(350, 25);

    final RadioButton search = new RadioButton("Search");
    final RadioButton filter = new RadioButton("Filter");

    ToggleGroup bgsf = new ToggleGroup();
    search.setToggleGroup(bgsf);
    filter.setToggleGroup(bgsf);
    //ButtonGroup bgsf = new ButtonGroup();
    //bgsf.add( search );
    //bgsf.add( filter );

    filter.setSelected(true);

    //ToolBar topcombo = new ToolBar();
    // topcombo.
    // topcombo.setLayout( new FlowLayout() );

    specombo = new ComboBox<>();
    combo = new ComboBox<>();

    specombo.getItems().add("Select blast species");
    combo.getItems().add("Select pathway");
    btoolbar.getItems().add(combo);
    btoolbar.getItems().add(specombo);
    //topcomp.add(topcombo, BorderLayout.SOUTH);

    //JComponent ttopcom = new JComponent() {};
    //ttopcom.setLayout(new FlowLayout());

    /*            frame.setVisible( true );
             }
          };
          AbstractAction   sharenumaction = new AbstractAction("Update share numbers") {
             @Override
             public void actionPerformed(ActionEvent e) {
    Set<String> specs = getSelspec(GeneSetHead.this, specList, null);
    updateShareNum(specs);
             }
          };
          AbstractAction   importgenesymbolaction = new AbstractAction("Import gene symbols") {
             @Override
             public void actionPerformed(ActionEvent e) {
    JFileChooser fc = new JFileChooser();
    if( fc.showOpenDialog( GeneSetHead.this ) == JFileChooser.APPROVE_OPTION ) {
       try {
          Map<String,String> env = new HashMap<String,String>();
          env.put("create", "true");
          Path path = zipfile.toPath();
          String uristr = "jar:" + path.toUri();
          geneset.zipuri = URI.create( uristr /*.replace("file://", "file:")* );
          geneset.zipfilesystem = FileSystems.newFileSystem( geneset.zipuri, env );
                  
          Path nf = geneset.zipfilesystem.getPath("/smap_short.txt");
          BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE);
                  
          InputStream is = new GZIPInputStream( new FileInputStream( fc.getSelectedFile() ) );
          uni2symbol(new InputStreamReader(is), bw, unimap);
                  
          bw.close();
          //long bl = Files.copy( new ByteArrayInputStream( baos.toByteArray() ), nf, StandardCopyOption.REPLACE_EXISTING );
          geneset.zipfilesystem.close();
       } catch (IOException e1) {
          e1.printStackTrace();
       }
    }
             }
          };
                  
          AbstractAction   importidmappingaction = new AbstractAction("Id mapping") {
             @Override
             public void actionPerformed(ActionEvent e) {
    JFileChooser fc = new JFileChooser();
    if( fc.showOpenDialog( GeneSetHead.this ) == JFileChooser.APPROVE_OPTION ) {
       try {
          Map<String,String> env = new HashMap<String,String>();
          env.put("create", "true");
          Path path = zipfile.toPath();
          String uristr = "jar:" + path.toUri();
          geneset.zipuri = URI.create( uristr /*.replace("file://", "file:")/ );
          geneset.zipfilesystem = FileSystems.newFileSystem( geneset.zipuri, env );
                  
          Path nf = geneset.zipfilesystem.getPath("/idmapping_short.dat");
          BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE);
                  
          InputStream is = new GZIPInputStream( new FileInputStream( fc.getSelectedFile() ) );
          if( unimap != null ) unimap.clear();
          unimap = idMapping(new InputStreamReader(is), bw, 2, 0, refmap, genmap, gimap);
                  
          bw.close();
          //long bl = Files.copy( new ByteArrayInputStream( baos.toByteArray() ), nf, StandardCopyOption.REPLACE_EXISTING );
          geneset.zipfilesystem.close();
       } catch (IOException e1) {
          e1.printStackTrace();
       }
    }
             }
          };
                  
          final JCheckBoxMenuItem checkbox = new JCheckBoxMenuItem();
          checkbox.setAction(new AbstractAction("Sort by location") {
             @Override
             public void actionPerformed(ActionEvent e) {
    Tegeval.locsort = checkbox.isSelected();
             }
          });
          AbstractAction saveselAction = new AbstractAction("Save selection") {
             @Override
             public void actionPerformed(ActionEvent e) {
    int[] rr = table.getSelectedRows();
    if( rr.length > 0 ) {
       String val = Integer.toString( table.convertRowIndexToModel(rr[0]) );
       for( int i = 1; i < rr.length; i++ ) {
          val += ","+table.convertRowIndexToModel(rr[i]);
       }
       String selname = JOptionPane.showInputDialog("Selection name");
       if( comp instanceof Applet ) {
          try {
             ((GeneSet)comp).saveSel( selname, val);
          } catch (Exception e1) {
             e1.printStackTrace();
          }
       }
    }
             }
          };
                  
          JMenuBar   menubar = new JMenuBar();
          JMenu      menu = new JMenu("Functions");
          menu.add( importidmappingaction );
          menu.add( functionmappingaction );
          menu.add( importgenesymbolaction );
          menu.add( fetchaction );
          menu.add( blast2action );
          menu.add( sharenumaction );
          menu.addSeparator();
          menu.add( checkbox );
          menu.add( saveselAction );
          menu.addSeparator();
          menu.add( genomestataction );
          menu.add( selectsharingaction );
          menu.add( shuffletreeaction );
          menu.add( presabsaction );
          menu.add( freqdistaction );
          menu.add( gcpaction );
          menu.add( matrixaction );
          menu.add( pancoreaction );
          menu.add( blastaction );
          menu.add( koexportaction );
          menu.add( genomesizeaction );
          menu.add( gcaction );
          menu.add( gcskewaction );
          menu.add( mltreemapaction );
          menu.add( sevenaction );
          menu.add( cogaction );
          menu.add( genexyplotaction );
          menu.add( compareplotaction );
          menu.add( syntenygradientaction );
          menu.add( codregaction );
          menu.add( fetchcoreaction );
          menu.add( loadcontiggraphaction );
          menu.add( selectflankingaction );
          menu.add( showflankingaction );
          menu.add( showcontigsaction );
          menu.add( showunresolved );
          menu.add( genephyl );
                  
          menubar.add( menu );
          ttopcom.add( menubar );
                  
          JMenu      view = new JMenu("View");
          menubar.add( view );
                  
          gb = new JRadioButtonMenuItem( new AbstractAction("Genes") {
             @Override
             public void actionPerformed(ActionEvent e) {
    table.setModel( defaultModel );
             }
          });
          view.add( gb );
          ggb = new JRadioButtonMenuItem( new AbstractAction("Gene groups") {
             @Override
             public void actionPerformed(ActionEvent e) {
    table.setModel( groupModel );
             }
                     
          });
          ButtonGroup   bg = new ButtonGroup();
          bg.add( gb );
          bg.add( ggb );
                  
          ggb.setSelected( true );
                  
          view.add( ggb );*/

    //ttopcom.add( shuffletreebutton );
    //ttopcom.add( presabsbutton );
    //ttopcom.add(freqdistbutton);
    //ttopcom.add(matrixbutton);

    toolbar.getItems().add(textfield);
    toolbar.getItems().add(search);
    toolbar.getItems().add(filter);
    toolbar.getItems().add(label);

    selcomblocal.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        String key = newValue;
        if (((GeneSetHead) comp).selectionMap.containsKey(key)) {
            Set<Integer> val = ((GeneSetHead) comp).selectionMap.get(key);
            if (val != null) {
                table.getSelectionModel().clearSelection();
                for (int i : val) {
                    //int r = table.convertRowIndexToView(i);
                    table.getSelectionModel().select(i);
                }
            } else {
                System.err.println("null " + key);
            }
        } else {
            System.err.println("no " + key);
        }
    });
    toolbar.getItems().add(selcomblocal);

    /*syncolorcomb.addItemListener( new ItemListener() {
       @Override
       public void itemStateChanged(ItemEvent e) {
    String spec = (String)syncolorcomb.getSelectedItem();
    //if( spec.length() > 0 )
       }
    });*/
    toolbar.getItems().add(searchcolcomb);
    toolbar.getItems().add(syncolorcomb);
    //topcomp.add(ttopcom, BorderLayout.NORTH);

    table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    table.getSelectionModel().selectedItemProperty().addListener(e -> {
        label.setText(table.getItems().size() + "/" + table.getSelectionModel().getSelectedItems().size());
    });

    gtable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    gtable.getSelectionModel().selectedItemProperty().addListener(e -> {
        label.setText(gtable.getItems().size() + "/" + gtable.getSelectionModel().getSelectedItems().size());
    });

    /*JButton but = new JButton(new AbstractAction("Gene sorter") {
       @Override
       public void actionPerformed(ActionEvent e) {
    try {
       GeneSorter.mynd(genelist, table, "t.scotoductusSA01", contigs);
    } catch (IOException e1) {
       e1.printStackTrace();
    }
       }
    });*/

    final TextField ftextfield = new TextField();
    btoolbar.getItems().add(ftextfield);

    ComboBox<String> scombo = new ComboBox();
    scombo.getItems().add("5S/8S");
    scombo.getItems().add("16S/18S");
    scombo.getItems().add("23S/28S");
    scombo.getSelectionModel().selectedItemProperty().addListener(e -> {
        String name = e.toString().split("/")[0];
        InputStream iss = GeneSet.class.getResourceAsStream("/all" + name + ".fsa");
        InputStreamReader isr = new InputStreamReader(iss);
        BufferedReader brr = new BufferedReader(isr);

        JTextArea textarea = new JTextArea();
        JScrollPane scrollpane = new JScrollPane(textarea);

        try {
            String ln = brr.readLine();
            while (ln != null) {
                textarea.append(ln + "\n");

                ln = brr.readLine();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);
    });
    btoolbar.getItems().add(scombo);

    Button swsearch = new Button("SW Search");
    swsearch.setOnAction(e -> {
        JComponent c = new JComponent() {
        };
        final JProgressBar pb = new JProgressBar();
        final JTextArea textarea = new JTextArea();
        JButton searchbut = new JButton(new AbstractAction("Blast") {
            @Override
            public void actionPerformed(ActionEvent e) {
                final String fasta = textarea.getText();
                final SmithWater sw = new SmithWater();
                final InputStream is = GeneSet.class.getResourceAsStream("/allthermus.aa");
                new Thread() {
                    public void run() {
                        try {
                            sw.fasta_align(new StringReader(fasta), new InputStreamReader(is), pb);
                            List<SmithWater.ALN> alns = sw.getAlignments();
                            SmithWater.ALN first = null;
                            int count = 0;
                            String result = "";
                            Set<String> regnames = new HashSet<String>();
                            for (SmithWater.ALN aln : alns) {
                                if (first == null) {
                                    first = aln;
                                } else if (aln.getScore() < 3.0f * (first.getScore() / 4.0f))
                                    break;
                                result += aln.toString();
                                regnames.add(aln.getShortDestName());

                                if (++count == 10)
                                    break;
                            }
                            textarea.setText(result);

                            for (Gene g : geneset.genelist) {
                                boolean found = false;
                                Tegeval tv = g.tegeval;
                                if (regnames.contains(tv.name)) {
                                    found = true;
                                    break;
                                }
                                if (found) {
                                    gtable.getSelectionModel().select(g);
                                    break;
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
        c.setLayout(new BorderLayout());
        JScrollPane scrollpane = new JScrollPane(textarea);
        c.add(scrollpane);
        c.add(pb, BorderLayout.NORTH);
        c.add(searchbut, BorderLayout.SOUTH);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(c);
        frame.setSize(400, 300);
        frame.setVisible(true);
    });
    btoolbar.getItems().add(swsearch);
    btoolbar.getItems().add(jb);

    TableColumn<GeneGroup, String> namedesccol = new TableColumn("Desc");
    namedesccol.setCellValueFactory(new PropertyValueFactory<>("name"));
    table.getColumns().add(namedesccol);
    TableColumn<GeneGroup, String> origincol = new TableColumn("Origin");
    origincol.setCellValueFactory(new PropertyValueFactory<>("origin"));
    table.getColumns().add(origincol);
    TableColumn<GeneGroup, String> geneidcol = new TableColumn("Genid");
    geneidcol.setCellValueFactory(new PropertyValueFactory<>("genid"));
    table.getColumns().add(geneidcol);
    TableColumn<GeneGroup, String> refidcol = new TableColumn("Refid");
    refidcol.setCellValueFactory(new PropertyValueFactory<>("refid"));
    table.getColumns().add(refidcol);
    TableColumn<GeneGroup, String> unidcol = new TableColumn("Unid");
    unidcol.setCellValueFactory(new PropertyValueFactory<>("unid"));
    table.getColumns().add(unidcol);
    TableColumn<GeneGroup, String> keggidcol = new TableColumn("Keggid");
    keggidcol.setCellValueFactory(new PropertyValueFactory<>("keggid"));
    table.getColumns().add(keggidcol);
    TableColumn<GeneGroup, String> keggpathcol = new TableColumn("Kegg pathway");
    keggpathcol.setCellValueFactory(new PropertyValueFactory<>("keggPathway"));
    table.getColumns().add(keggpathcol);
    TableColumn<GeneGroup, String> kocol = new TableColumn("KO");
    kocol.setCellValueFactory(new PropertyValueFactory<>("ko"));
    table.getColumns().add(kocol);
    TableColumn<GeneGroup, String> ksymbcol = new TableColumn("Ksymbol");
    ksymbcol.setCellValueFactory(new PropertyValueFactory<>("ksymbol"));
    table.getColumns().add(ksymbcol);
    TableColumn<GeneGroup, String> symbcol = new TableColumn("Symbol");
    symbcol.setCellValueFactory(new PropertyValueFactory<>("symbol"));
    table.getColumns().add(symbcol);
    TableColumn<GeneGroup, String> konamecol = new TableColumn("KO name");
    konamecol.setCellValueFactory(new PropertyValueFactory<>("koname"));
    table.getColumns().add(konamecol);
    TableColumn<GeneGroup, String> pbidcol = new TableColumn("Pbid");
    pbidcol.setCellValueFactory(new PropertyValueFactory<>("pbid"));
    table.getColumns().add(pbidcol);
    TableColumn<GeneGroup, String> eccol = new TableColumn("Ec");
    eccol.setCellValueFactory(new PropertyValueFactory<>("ec"));
    table.getColumns().add(eccol);
    TableColumn<GeneGroup, String> cognamecol = new TableColumn("Cog name");
    cognamecol.setCellValueFactory(new PropertyValueFactory<>("cogname"));
    table.getColumns().add(cognamecol);
    TableColumn<GeneGroup, String> cogcol = new TableColumn("Cog");
    cogcol.setCellValueFactory(new PropertyValueFactory<>("cog"));
    table.getColumns().add(cogcol);
    TableColumn<GeneGroup, String> cogannocol = new TableColumn("Cog annotation");
    cogannocol.setCellValueFactory(new PropertyValueFactory<>("coganno"));
    table.getColumns().add(cogannocol);
    TableColumn<GeneGroup, String> cogsymbcol = new TableColumn("Cog symbol");
    cogsymbcol.setCellValueFactory(new PropertyValueFactory<>("cogsymbol"));
    table.getColumns().add(cogsymbcol);
    TableColumn<GeneGroup, String> cazycol = new TableColumn("Cazy");
    cazycol.setCellValueFactory(new PropertyValueFactory<>("cazy"));
    table.getColumns().add(cazycol);
    TableColumn<GeneGroup, String> prescol = new TableColumn("Present in");
    prescol.setCellValueFactory(new PropertyValueFactory<>("presentin"));
    table.getColumns().add(prescol);

    TableColumn<GeneGroup, Integer> groupindcol = new TableColumn("Group index");
    groupindcol.setCellValueFactory(new PropertyValueFactory<GeneGroup, Integer>("groupIndex"));
    table.getColumns().add(groupindcol);
    TableColumn<GeneGroup, Integer> groupcovcol = new TableColumn("Group coverage");
    groupcovcol.setCellValueFactory(new PropertyValueFactory<GeneGroup, Integer>("groupCoverage"));
    table.getColumns().add(groupcovcol);
    TableColumn<GeneGroup, Integer> groupsizecol = new TableColumn("Group size");
    groupsizecol.setCellValueFactory(new PropertyValueFactory<GeneGroup, Integer>("groupGeneCount"));
    table.getColumns().add(groupsizecol);

    TableColumn<GeneGroup, String> locprefcol = new TableColumn("Loc pref");
    locprefcol.setCellValueFactory(new PropertyValueFactory<>("locpref"));
    table.getColumns().add(locprefcol);
    TableColumn<GeneGroup, String> avgcpcol = new TableColumn("Avg GC%");
    avgcpcol.setCellValueFactory(new PropertyValueFactory<>("avggcp"));
    table.getColumns().add(avgcpcol);
    TableColumn<GeneGroup, String> numloccol = new TableColumn("#Loc");
    numloccol.setCellValueFactory(new PropertyValueFactory<>("numloc"));
    table.getColumns().add(numloccol);
    TableColumn<GeneGroup, String> numlocgroupcol = new TableColumn("#Loc group");
    numlocgroupcol.setCellValueFactory(new PropertyValueFactory<>("numlocgroup"));
    table.getColumns().add(numlocgroupcol);

    TableColumn<GeneGroup, ShareNum> sharenumcol = new TableColumn("Sharing number");
    sharenumcol.setCellValueFactory(new PropertyValueFactory<>("sharingNumber"));
    table.getColumns().add(sharenumcol);
    TableColumn<GeneGroup, String> maxcyccol = new TableColumn("Max cyc");
    maxcyccol.setCellValueFactory(new PropertyValueFactory<>("maxCyc"));
    table.getColumns().add(maxcyccol);

    TableColumn<Gene, String> gnamedesccol = new TableColumn("Desc");
    gnamedesccol.setCellValueFactory(new PropertyValueFactory<>("name"));
    gtable.getColumns().add(gnamedesccol);
    TableColumn<Gene, String> gorigincol = new TableColumn("Origin");
    gorigincol.setCellValueFactory(new PropertyValueFactory<>("origin"));
    gtable.getColumns().add(gorigincol);
    TableColumn<Gene, String> ggeneidcol = new TableColumn("Genid");
    ggeneidcol.setCellValueFactory(new PropertyValueFactory<>("genid"));
    gtable.getColumns().add(ggeneidcol);
    TableColumn<Gene, String> grefidcol = new TableColumn("Refid");
    grefidcol.setCellValueFactory(new PropertyValueFactory<>("refid"));
    gtable.getColumns().add(grefidcol);
    TableColumn<Gene, String> gunidcol = new TableColumn("Unid");
    gunidcol.setCellValueFactory(new PropertyValueFactory<>("unid"));
    gtable.getColumns().add(gunidcol);
    TableColumn<Gene, String> gkeggidcol = new TableColumn("Keggid");
    gkeggidcol.setCellValueFactory(new PropertyValueFactory<>("keggid"));
    gtable.getColumns().add(gkeggidcol);
    TableColumn<Gene, String> gkeggpathcol = new TableColumn("Kegg pathway");
    gkeggpathcol.setCellValueFactory(new PropertyValueFactory<>("keggPathway"));
    gtable.getColumns().add(gkeggpathcol);
    TableColumn<Gene, String> gkocol = new TableColumn("KO");
    gkocol.setCellValueFactory(new PropertyValueFactory<>("ko"));
    gtable.getColumns().add(gkocol);
    TableColumn<Gene, String> gksymbcol = new TableColumn("Ksymbol");
    gksymbcol.setCellValueFactory(new PropertyValueFactory<>("ksymbol"));
    gtable.getColumns().add(gksymbcol);
    TableColumn<Gene, String> gsymbcol = new TableColumn("Symbol");
    gsymbcol.setCellValueFactory(new PropertyValueFactory<>("symbol"));
    gtable.getColumns().add(gsymbcol);
    TableColumn<Gene, String> gkonamecol = new TableColumn("KO name");
    gkonamecol.setCellValueFactory(new PropertyValueFactory<>("koname"));
    gtable.getColumns().add(gkonamecol);
    TableColumn<Gene, String> gpbidcol = new TableColumn("Pbid");
    gpbidcol.setCellValueFactory(new PropertyValueFactory<>("pbid"));
    gtable.getColumns().add(gpbidcol);
    TableColumn<Gene, String> geccol = new TableColumn("Ec");
    geccol.setCellValueFactory(new PropertyValueFactory<>("ec"));
    gtable.getColumns().add(geccol);
    TableColumn<Gene, String> gcognamecol = new TableColumn("Cog name");
    gcognamecol.setCellValueFactory(new PropertyValueFactory<>("cogname"));
    gtable.getColumns().add(gcognamecol);
    TableColumn<Gene, String> gcogcol = new TableColumn("Cog");
    gcogcol.setCellValueFactory(new PropertyValueFactory<>("cog"));
    gtable.getColumns().add(gcogcol);
    TableColumn<Gene, String> gcogannocol = new TableColumn("Cog annotation");
    gcogannocol.setCellValueFactory(new PropertyValueFactory<>("coganno"));
    gtable.getColumns().add(gcogannocol);
    TableColumn<Gene, String> gcogsymbcol = new TableColumn("Cog symbol");
    gcogsymbcol.setCellValueFactory(new PropertyValueFactory<>("cogsymbol"));
    gtable.getColumns().add(gcogsymbcol);
    TableColumn<Gene, String> gcazycol = new TableColumn("Cazy");
    gcazycol.setCellValueFactory(new PropertyValueFactory<>("cazy"));
    gtable.getColumns().add(gcazycol);
    TableColumn<Gene, String> gprescol = new TableColumn("Present in");
    gprescol.setCellValueFactory(new PropertyValueFactory<>("presentin"));
    gtable.getColumns().add(gprescol);

    TableColumn<Gene, Integer> ggroupindcol = new TableColumn("Group index");
    ggroupindcol.setCellValueFactory(new PropertyValueFactory<>("groupIndex"));
    gtable.getColumns().add(ggroupindcol);
    TableColumn<Gene, Integer> ggroupcovcol = new TableColumn("Group coverage");
    ggroupcovcol.setCellValueFactory(new PropertyValueFactory<>("groupCoverage"));
    gtable.getColumns().add(ggroupcovcol);
    TableColumn<Gene, Integer> ggroupsizecol = new TableColumn("Group size");
    ggroupsizecol.setCellValueFactory(new PropertyValueFactory<>("groupGeneCount"));
    gtable.getColumns().add(ggroupsizecol);

    TableColumn<Gene, String> glocprefcol = new TableColumn("Loc pref");
    glocprefcol.setCellValueFactory(new PropertyValueFactory<>("locpref"));
    gtable.getColumns().add(glocprefcol);
    TableColumn<Gene, String> gavgcpcol = new TableColumn("Avg GC%");
    gavgcpcol.setCellValueFactory(new PropertyValueFactory<>("avggcp"));
    gtable.getColumns().add(gavgcpcol);
    TableColumn<Gene, String> gnumloccol = new TableColumn("#Loc");
    gnumloccol.setCellValueFactory(new PropertyValueFactory<>("numloc"));
    gtable.getColumns().add(gnumloccol);
    TableColumn<Gene, String> gnumlocgroupcol = new TableColumn("#Loc group");
    gnumlocgroupcol.setCellValueFactory(new PropertyValueFactory<>("numlocgroup"));
    gtable.getColumns().add(gnumlocgroupcol);

    TableColumn<Gene, ShareNum> gsharenumcol = new TableColumn("Sharing number");
    gsharenumcol.setCellValueFactory(new PropertyValueFactory<>("sharingNumber"));
    gtable.getColumns().add(gsharenumcol);
    TableColumn<Gene, String> gmaxcyccol = new TableColumn("Max cyc");
    gmaxcyccol.setCellValueFactory(new PropertyValueFactory<>("maxCyc"));
    gtable.getColumns().add(gmaxcyccol);

    /*if( upper != null ) {
       SwingUtilities.invokeLater( new Runnable() {
    public void run() {
       //upper.setContent( botcomp );
       lower.setContent( topcomp );
    }
       });
    } else {
       splitpane.setBottomComponent(botcomp);
       splitpane.setTopComponent(topcomp);
    }
            
    groupModel = new TableModel() {
       @Override
       public int getRowCount() {
    return geneset.allgenegroups == null ? 0 : geneset.allgenegroups.size();
       }
            
       @Override
       public int getColumnCount() {
    return 32+geneset.specList.size();
       }
            
       @Override
       public String getColumnName(int columnIndex) {
    if (columnIndex == 0) {
       return "Desc";
    } else if (columnIndex == 1) {
       return "Origin";
    } else if (columnIndex == 2) {
       return "Genid";
    } else if (columnIndex == 3) {
       return "Refid";
    } else if (columnIndex == 4) {
       return "Unid";
    } else if (columnIndex == 5) {
       return "Keggid";
    } else if (columnIndex == 6) {
       return "Kegg pathway";
    } else if (columnIndex == 7) {
       return "KO";
    } else if (columnIndex == 8) {
       return "KSymbol";
    } else if (columnIndex == 9) {
       return "Symbol";
    } else if (columnIndex == 10) {
       return "KO name";
    } else if (columnIndex == 11) {
       return "Pdbid";
    } else if (columnIndex == 12) {
       return "EC";
    } else if (columnIndex == 13) {
       return "Cog name";
    } else if (columnIndex == 14) {
       return "Cog";
    } else if (columnIndex == 15) {
       return "Cog annotation";
    } else if (columnIndex == 16) {
       return "Cog symbol";
    } else if (columnIndex == 17) {
       return "Cazy";
    } else if (columnIndex == 18) {
       return "Present in";
    } else if (columnIndex == 19) {
       return "Group index";
    } else if (columnIndex == 20) {
       return "Group coverage";
    } else if (columnIndex == 21) {
       return "Group size";
    } else if (columnIndex == 22) {
       return "Locprev";
    } else if (columnIndex == 23) {
       return "Avg GC%";
    } else if (columnIndex == 24) {
       return "# of locus";
    } else if (columnIndex == 25) {
       return "# of loc in group";
    } else if (columnIndex == 26) {
       return "max length";
    } else if (columnIndex == 27) {
       return "sharing number";
    } else if (columnIndex == 28) {
       return "# Cyc";
    } else if (columnIndex == 29) {
       return "16S Corr";
    } else if (columnIndex == 30) {
       return "SingalP";
    } else if (columnIndex == 31) {
       return "TransM";
    } else {
       String spec = geneset.specList.get( columnIndex - 32 );
       if( spec != null ) {
          if( spec.toLowerCase().contains("thermus") ) {
             int i = spec.indexOf('_');
             return spec.substring(i+1, spec.length());
          } else return spec;
       }
       return "";
    }
    /* else if (columnIndex == 19) {
       return "T.tSG0";
    } else if (columnIndex == 20) {
       return "T.tJL18";
    } else if (columnIndex == 21) {
       return "T.tHB8";
    } else if (columnIndex == 22) {
       return "T.tHB27";
    } else if (columnIndex == 23) {
       return "T.scotoSA01";
    } else if (columnIndex == 24) {
       return "T.aqua";
    } else if (columnIndex == 25) {
       return "T.eggert";
    } else if (columnIndex == 26) {
       return "T.island";
    } else if (columnIndex == 27) {
       return "T.antan";
    } else if (columnIndex == 28) {
       return "T.scoto346";
    } else if (columnIndex == 29) {
       return "T.scoto1572";
    } else if (columnIndex == 30) {
       return "T.scoto252";
    } else if (columnIndex == 31) {
       return "T.scoto2101";
    } else if (columnIndex == 32) {
       return "T.scoto2127";
    } else if (columnIndex == 33) {
       return "T.scoto4063";
    } else if (columnIndex == 34) {
       return "T.oshimai";
    } else if (columnIndex == 35) {
       return "T.brockianus";
    } else if (columnIndex == 36) {
       return "T.filiformis";
    } else if (columnIndex == 37) {
       return "T.igniterrae";
    } else if (columnIndex == 38) {
       return "T.kawarayensis";
    } else if (columnIndex == 39) {
       return "T.arciformis";
    } else if (columnIndex == 40) {
       return "T.spCCB";
    } else if (columnIndex == 41) {
       return "T.spRLM";
    } else if (columnIndex == 42) {
       return "T.oshimaiJL2";
    } else if (columnIndex == 43) {
       return "MT.silvianus";
    } else if (columnIndex == 44) {
       return "MT.ruber";
    } else if (columnIndex == 45) {
       return "M.hydro";
    } else if (columnIndex == 46) {
       return "O.profu";
    }*
            
    //return "";
       }
            
       @Override
       public Class<?> getColumnClass(int columnIndex) {
    if( columnIndex == 19 || columnIndex == 20 || columnIndex == 28 )
       return Double.class;
    else if(columnIndex == 10 || (columnIndex >= 17 && columnIndex <= 28) )
       return Integer.class;
    else if (columnIndex >= 32)
       return Teg.class;
    return String.class;
       }
            
       @Override
       public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
       }
            
       @Override
       public Object getValueAt(int rowIndex, int columnIndex) {
    GeneGroup gg = geneset.allgenegroups.get(rowIndex);
    if (columnIndex == 0) {
       return gg.getCommonName();
    } else if (columnIndex == 1) {
       return gg.getCommonOrigin();
    } else if (columnIndex == 2) {
       return null;//gene.genid;
    } else if (columnIndex == 3) {
       return gg.getCommonRefId();
    } else if (columnIndex == 4) {
       return gg.getCommonUnId();
    } else if (columnIndex == 5) {
       return gg.getKeggid();
    } else if (columnIndex == 6) {
       return gg.getKeggPathway();
    } else if (columnIndex == 7) {
       return gg.getCommonKO();
    } else if (columnIndex == 8) {
       return gg.getCommonKSymbol();
    } else if (columnIndex == 9) {
       return gg.getCommonSymbol(); //ko2name != null ? ko2name.get( gg.getCommonKO() ) : null;
    } else if (columnIndex == 10) {
       String ret = geneset.ko2name != null ? geneset.ko2name.get( gg.getCommonKO() ) : null;
       if( ret == null ) {
          String symbol = gg.getCommonSymbol();
          if( symbol != null ) {
             if( symbol.length() <= 5 ) ret = symbol;
          }
       }
       return ret;
    } else if (columnIndex == 11) {
       return null;//gene.pdbid;
    } else if (columnIndex == 12) {
       return gg.getCommonEc();
    } else if (columnIndex == 13) {
       Cog cog = gg.getCommonCog( geneset.cogmap );
       if( cog != null ) {
          if( cog.name == null ) cog.name = geneset.cogidmap.get( cog.id );
          return cog.name;
       }
       return null;
    } else if (columnIndex == 14) {
       Cog cog = gg.getCommonCog( geneset.cogmap );
       return cog != null ? cog.id : null;
    } else if (columnIndex == 15) {
       Cog cog = gg.getCommonCog( geneset.cogmap );
       return cog != null ? cog.annotation : null;
    } else if (columnIndex == 16) {
       Cog cog = gg.getCommonCog( geneset.cogmap );
       return cog != null ? cog.genesymbol : null;
    } else if (columnIndex == 17) {
       return gg.getCommonCazy( geneset.cazymap );
    } else if (columnIndex == 18) {
       return gg.getSpecies().size();
    } else if (columnIndex == 19) {
       return gg.groupIndex;
    } else if (columnIndex == 20) {
       return gg.getGroupCoverage();
    } else if (columnIndex == 21) {
       return gg.getGroupGeneCount();
    } else if (columnIndex == 22) {
       return null;//gene.proximityGroupPreservation;
    } else if (columnIndex == 23) {
       return gg.getAvgGCPerc();
    } else if (columnIndex == 24) {
       return gg.genes.size();
    } else if (columnIndex == 25) {
       return gg.getGroupCount();
    } else if (columnIndex == 26) {
       return gg.getMaxLength();
    } else if (columnIndex == 27) {
       return geneset.specset.get( gg.getSpecies() );
    } else if (columnIndex == 28) {
       return gg.getMaxCyc();
    } else if (columnIndex == 29) {
       return gg.getGroupCoverage() == 39 && gg.getGroupCount() == 39 ? 0 : -1;
    } else if (columnIndex == 30) {
       return gg.getCommonSignalP();
    } else if (columnIndex == 31) {
       return gg.getCommonTransM();
    } else {
       String spec = geneset.specList.get( columnIndex - 32 );
       Teginfo ret = geneset.getGroupTes( gg, spec );
       return ret;
       //return null;
    }
    //return columnIndex >= 11 ? null : "";
       }
            
       @Override
       public void setValueAt(Object aValue, int rowIndex, int columnIndex) {}
            
       @Override
       public void addTableModelListener(TableModelListener l) {}
            
       @Override
       public void removeTableModelListener(TableModelListener l) {}
    };
    defaultModel = new TableModel() {
       @Override
       public int getRowCount() {
    int gs = geneset.genelist.size();
    return gs;
       }
            
       @Override
       public int getColumnCount() {
    return 26+geneset.specList.size();
       }
            
       @Override
       public String getColumnName(int columnIndex) {
    if (columnIndex == 0) {
       return "Desc";
    } else if (columnIndex == 1) {
       return "Origin";
    } else if (columnIndex == 2) {
       return "Genid";
    } else if (columnIndex == 3) {
       return "Refid";
    } else if (columnIndex == 4) {
       return "Unid";
    } else if (columnIndex == 5) {
       return "Keggid";
    } else if (columnIndex == 6) {
       return "KOid";
    } else if (columnIndex == 7) {
       return "KSymbol";
    } else if (columnIndex == 8) {
       return "Symbol";
    } else if (columnIndex == 9) {
       return "KOname";
    } else if (columnIndex == 10) {
       return "Pdbid";
    } else if (columnIndex == 11) {
       return "ecid";
    } else if (columnIndex == 12) {
       return "COG";
    } else if (columnIndex == 13) {
       return "COG name";
    } else if (columnIndex == 14) {
       return "Present in";
    } else if (columnIndex == 15) {
       return "Group index";
    } else if (columnIndex == 16) {
       return "Group coverage";
    } else if (columnIndex == 17) {
       return "Group size";
    } else if (columnIndex == 18) {
       return "Locprev";
    } else if (columnIndex == 19) {
       return "Avg GC%";
    } else if (columnIndex == 20) {
       return "# of locus";
    } else if (columnIndex == 21) {
       return "# of loc in group";
    } else if (columnIndex == 22) {
       return "max length";
    } else if (columnIndex == 23) {
       return "sharing number";
    } else if (columnIndex == 24) {
       return "# Cyc";
    } else if (columnIndex == 25) {
       return "16S Corr";
    } else {
       return geneset.specList.get( columnIndex - 26 );
    } /*else if (columnIndex == 19) {
       return "T.tSG0";
    } else if (columnIndex == 20) {
       return "T.tJL18";
    } else if (columnIndex == 21) {
       return "T.tHB8";
    } else if (columnIndex == 22) {
       return "T.tHB27";
    } else if (columnIndex == 23) {
       return "T.scotoSA01";
    } else if (columnIndex == 24) {
       return "T.aqua";
    } else if (columnIndex == 25) {
       return "T.eggert";
    } else if (columnIndex == 26) {
       return "T.island";
    } else if (columnIndex == 27) {
       return "T.antan";
    } else if (columnIndex == 28) {
       return "T.scoto346";
    } else if (columnIndex == 29) {
       return "T.scoto1572";
    } else if (columnIndex == 30) {
       return "T.scoto252";
    } else if (columnIndex == 31) {
       return "T.scoto2101";
    } else if (columnIndex == 32) {
       return "T.scoto2127";
    } else if (columnIndex == 33) {
       return "T.scoto4063";
    } else if (columnIndex == 34) {
       return "T.oshimai";
    } else if (columnIndex == 35) {
       return "T.brockianus";
    } else if (columnIndex == 36) {
       return "T.filiformis";
    } else if (columnIndex == 37) {
       return "T.igniterrae";
    } else if (columnIndex == 38) {
       return "T.kawarayensis";
    } else if (columnIndex == 39) {
       return "T.arciformis";
    } else if (columnIndex == 40) {
       return "T.spCCB";
    } else if (columnIndex == 41) {
       return "T.spRLM";
    } else if (columnIndex == 42) {
       return "T.oshimaiJL2";
    } else if (columnIndex == 43) {
       return "MT.silvianus";
    } else if (columnIndex == 44) {
       return "MT.ruber";
    } else if (columnIndex == 45) {
       return "M.hydro";
    } else if (columnIndex == 46) {
       return "O.profu";
    }*
       }
            
       @Override
       public Class<?> getColumnClass(int columnIndex) {
    if( columnIndex == 16 || columnIndex == 19 || columnIndex == 25 )
       return Double.class;
    else if(columnIndex >= 13 && columnIndex <= 24)
       return Integer.class;
    else if (columnIndex >= 26)
       return Teg.class;
    return String.class;
       }
            
       @Override
       public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
       }
            
       @Override
       public Object getValueAt(int rowIndex, int columnIndex) {
    Gene gene = geneset.genelist.get(rowIndex);
    if (columnIndex == 0) {
       GeneGroup gg = gene.getGeneGroup();
       return gg != null ? gene.getGeneGroup().getCommonName() : null;
    } else if (columnIndex == 1) {
       return gene.getSpecies();
    } else if (columnIndex == 2) {
       return gene.genid;
    } else if (columnIndex == 3) {
       return gene.refid;
    } else if (columnIndex == 4) {
       return gene.uniid;
    } else if (columnIndex == 5) {
       return gene.keggid;
    } else if (columnIndex == 6) {
       GeneGroup gg = gene.getGeneGroup();
       return gg != null ? gg.getCommonKO() : null;
    } else if (columnIndex == 7) {
       GeneGroup gg = gene.getGeneGroup();
       return gg != null ? gg.getCommonKSymbol() : null;
    } else if (columnIndex == 8) {
       GeneGroup gg = gene.getGeneGroup();
       return gg != null ? gg.getCommonSymbol() : null; //gene.symbol
    } else if (columnIndex == 9) {
       GeneGroup gg = gene.getGeneGroup();
       return gg != null ? gg.getCommonKOName( geneset.ko2name ) : null;
    } else if (columnIndex == 10) {
       return gene.pdbid;
    } else if (columnIndex == 11) {
       return gene.ecid;
    } else if (columnIndex == 12) {
       Cog cog = gene.getGeneGroup() != null ? gene.getGeneGroup().getCommonCog( geneset.cogmap ) : null;
       if( cog != null ) return cog.id;
       return null;
    } else if (columnIndex == 13) {
       Cog cog = gene.getGeneGroup() != null ? gene.getGeneGroup().getCommonCog( geneset.cogmap ) : null;
       if( cog != null ) return cog.name;
       return null;
    } else if (columnIndex == 14) {
       return gene.getGeneGroup().getSpecies().size();
    } else if (columnIndex == 15) {
       return gene.getGroupIndex();
    } else if (columnIndex == 16) {
       return gene.getGroupCoverage();
    } else if (columnIndex == 17) {
       return gene.getGroupGenCount();
    } else if (columnIndex == 18) {
       return gene.proximityGroupPreservation;
    } else if (columnIndex == 19) {
       return gene.getGCPerc();
    } else if (columnIndex == 20) {
       /*int val = 0;
       for (String str : gene.species.keySet()) {
          val += gene.species.get(str).tset.size();
       }*
       return 1;
    } else if (columnIndex == 21) {
       return gene.getGroupCount();
    } else if (columnIndex == 22) {
       return gene.getMaxLength();
    } else if (columnIndex == 23) {
       GeneGroup gg = gene.getGeneGroup();
       if( gg != null && gg.getSpecies() != null ) {
          return geneset.specset.get( gg.getSpecies() );
       }
       return null;
    } else if (columnIndex == 24) {
       gene.getMaxCyc();
    } else if (columnIndex == 25) {
       return gene.getGroupCoverage() == 35 && gene.getGroupCount() == 35 ? gene.corr16s : -1;
    } else {
       /*String spec = specList.get( columnIndex-26 );
       /*if( spec.contains("timidus") ) {
          System.err.println();
       }*
       //Teginfo set = gene.species.equals(spec) ? gene.teginfo : null;
       if( gene.getSpecies().equals( spec ) ) {
          return gene.tegeval;
       } else {
          return gene.getGeneGroup().species.get( spec );
       }*
               
       return null;
    }
    return columnIndex >= 17 ? null : "";
       }
            
       @Override
       public void setValueAt(Object aValue, int rowIndex, int columnIndex) {}
            
       @Override
       public void addTableModelListener(TableModelListener l) {}
            
       @Override
       public void removeTableModelListener(TableModelListener l) {}
    };
    table.setModel( groupModel );*/
    //table.setModel( defaultModel );

    /*
     * Comparator<Tegeval> wrapMe = new Comparator<Tegeval>() { public int
     * compare(Tegeval o1, Tegeval o2) { return o1.compareTo(o2); } };
     * DefaultRowSorter<TableModel, Integer> rowsorter =
     * (DefaultRowSorter<TableModel,Integer>)table.getRowSorter(); for( int
     * i = 10; i < 23; i++ ) { rowsorter.setComparator(i,
     * NullComparators.atEnd(wrapMe)); }
     */

    /*table.getRowSorter().addRowSorterListener( new RowSorterListener() {
       @Override
       public void sorterChanged(RowSorterEvent e) {
    for (String cstr : geneset.contigmap.keySet()) {
       Sequence c = geneset.contigmap.get(cstr);
       //c.count = 0;
       c.loc = 0.0;
    }
            
    if( table.getModel() == defaultModel ) {
       for (Gene g : geneset.genelist) {
          Tegeval tv = g.tegeval;
             // int first = tv.cont.indexOf('_');
             // int sec = tv.cont.indexOf('_',first+1);
          Sequence cont = tv.getContshort(); // tv.cont.substring(0,sec);
          if( cont != null && geneset.contigmap.containsKey(cont.getName()) ) {
             Sequence c = geneset.contigmap.get(cont.getName());
             //c.count++;
             int val = table.convertRowIndexToView(g.index);
             c.loc += (double) val;
          }
       }
    }
    for( JSplitPane gsplitpane : splitpaneList ) {
       gsplitpane.repaint();
    }
       }
    });*/

    ftable = upper;
    ftable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    /*ftable = new JTable() {
       public String getToolTipText(MouseEvent me) {
    Point p = me.getPoint();
    int r = rowAtPoint(p);
    int c = columnAtPoint(p);
    if (r >= 0 && r < super.getRowCount()) {
       Object ret = super.getValueAt(r, c);
       if (ret != null) {
          return ret.toString(); // super.getToolTipText( me );
       }
    }
    return "";
       }
    };*/

    ContextMenu fpopup = new ContextMenu();
    MenuItem amigo = new MenuItem("Amigo lookup");
    amigo.setOnAction(e -> {
        String go = ftable.getSelectionModel().getSelectedItem().getGo();
        try {
            // GeneSetHead.this.getAppletContext().
            Desktop.getDesktop()
                    .browse(new URI("http://amigo.geneontology.org/cgi-bin/amigo/term_details?term=" + go));
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
    });
    fpopup.getItems().add(amigo);
    MenuItem keggl = new MenuItem("KEGG lookup");
    keggl.setOnAction(e -> {
        String kegg = ftable.getSelectionModel().getSelectedItem().getKegg();
        try {
            Desktop.getDesktop().browse(new URI("http://www.genome.jp/dbget-bin/www_bget?rn:" + kegg));
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
    });
    fpopup.getItems().add(keggl);
    MenuItem ecl = new MenuItem("EC lookup");
    ecl.setOnAction(e -> {
        String ec = ftable.getSelectionModel().getSelectedItem().getEc();
        try {
            Desktop.getDesktop().browse(new URI("http://enzyme.expasy.org/EC/" + ec));
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
    });
    fpopup.getItems().add(ecl);
    fpopup.getItems().add(new SeparatorMenuItem());

    MenuItem excelreport = new MenuItem("Excel report");
    excelreport.setOnAction(e -> {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("enzyme");
        int k = 0;
        for (Function f : ftable.getSelectionModel().getSelectedItems()) {
            //String ec = (String)ftable.getValueAt(r, 1);
            //String go = (String)ftable.getValueAt(r, 0);

            //int i = ftable.getSelectionModel().convertRowIndexToModel(r);
            //Function f = geneset.funclist.get(i);
            for (GeneGroup gg : f.getGeneGroups()) {
                for (String spec : gg.getSpecies()) {
                    Teginfo ti = gg.getGenes(spec);

                    Row row = sheet.createRow(k++);
                    Cell ecell = row.createCell(0);
                    ecell.setCellValue("EC:" + f.getEc());
                    Cell ncell = row.createCell(1);
                    ncell.setCellValue(f.getName());
                    Cell spell = row.createCell(2);
                    spell.setCellValue(spec);
                    Cell seqcell = row.createCell(3);
                    seqcell.setCellValue(ti.tset.size());
                }
                /*for( Gene g :gg.genes ) {
                   Row    row = sheet.createRow(k++);
                   Cell    ecell = row.createCell(0);
                   ecell.setCellValue( "EC:"+f.ec );
                   Cell    ncell = row.createCell(1);
                   ncell.setCellValue( f.name );
                   Cell    spell = row.createCell(2);
                   spell.setCellValue( g.getSpecies() );
                   Cell    seqcell = row.createCell(3);
                   seqcell.setCellValue( g.tegeval.getAlignedSequence().toString() );
                }*/
            }
            sheet.createRow(k++);
        }

        try {
            Path tempfile = Files.createTempFile("enzyme", ".xlsx");
            OutputStream os = Files.newOutputStream(tempfile);
            workbook.write(os);
            os.close();

            Desktop.getDesktop().open(tempfile.toFile());
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    fpopup.getItems().add(excelreport);
    ftable.setContextMenu(fpopup);

    ContextMenu popup = new ContextMenu();
    MenuItem splitaction = new MenuItem("Split");
    splitaction.setOnAction(e -> {
        Dialog<Set<GeneGroup>> dialog = new Dialog<>();
        dialog.setResizable(true);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 20, 10, 10));

        TextField len = new TextField();
        len.setPromptText("0.5");
        TextField id = new TextField();
        id.setPromptText("0.5");

        grid.add(new Label("%Length:"), 0, 0);
        grid.add(len, 1, 0);
        grid.add(new Label("%Identity:"), 0, 1);
        grid.add(id, 1, 1);

        final ListView<GeneGroup> list = new ListView<>();
        list.setPrefWidth(400);
        grid.add(list, 0, 2, 2, 1);

        final GeneGroup gg = table.getSelectionModel().getSelectedItem();
        list.setItems(FXCollections.singletonObservableList(gg));

        Label groupsize = new Label("" + gg.genes.size());
        grid.add(groupsize, 0, 3, 2, 1);

        len.textProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue.equals(oldValue)) {
                double d = 0;
                try {
                    d = Double.parseDouble(newValue);
                } catch (Exception ex) {
                }

                if (d > 0) {
                    Set<GeneGroup> ggmap = new HashSet<>();
                    Map<String, Integer> blosumMap = JavaFasta.getBlosumMap(false);
                    for (Gene gene : gg.genes) {
                        if (ggmap.stream().flatMap(f -> f.genes.stream()).noneMatch(p -> gene == p)) {
                            Set<Gene> ggset = new HashSet<>();
                            Sequence seq1 = gene.tegeval.getAlignedSequence();
                            for (Gene cgene : gg.genes) {
                                Sequence seq2 = cgene.tegeval.getAlignedSequence();
                                int[] tscore = GeneCompare.blosumValue(seq1, seq1, seq2, blosumMap);
                                int sscore = GeneCompare.blosumValue(seq1, seq2, blosumMap);

                                double dval = (double) (sscore - tscore[1]) / (double) (tscore[0] - tscore[1]);
                                if (dval > d) {
                                    ggset.add(cgene);
                                }
                            }
                            System.err.println(ggset.size());

                            Set<GeneGroup> osubgg = ggmap.stream().filter(f -> {
                                Set<Gene> gs = new HashSet<>(ggset);
                                gs.retainAll(f.genes);
                                return gs.size() > 0;
                            }).collect(Collectors.toSet());
                            GeneGroup subgg;
                            if (osubgg.size() > 0) {
                                Iterator<GeneGroup> git = osubgg.iterator();
                                subgg = git.next();
                                while (git.hasNext()) {
                                    GeneGroup remgg = git.next();
                                    subgg.addGenes(remgg.genes);
                                    ggmap.remove(remgg);
                                }
                            } else {
                                subgg = new GeneGroup();
                                subgg.setCogMap(gg.getCogMap());
                                subgg.setKonameMap(gg.getKonameMap());
                                subgg.setSpecSet(gg.getSpecSet());
                                ggmap.add(subgg);
                            }
                            subgg.addGenes(ggset);
                        }
                    }
                    Set<GeneGroup> sgg = ggmap.stream().collect(Collectors.toSet());

                    List<GeneGroup> lgg = new ArrayList(sgg);
                    list.setItems(FXCollections.observableList(lgg));
                    dialog.setResultConverter(param -> sgg);
                }
            }
        });

        dialog.getDialogPane().setContent(grid);
        dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
        dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
        Optional<Set<GeneGroup>> ogg = dialog.showAndWait();

        ogg.ifPresent(c -> {
            geneset.allgenegroups.remove(gg);
            geneset.allgenegroups.addAll(c);

            Map<String, String> env = new HashMap<>();
            env.put("create", "true");
            try {
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                    Files.walk(root).filter(f -> f.toString().startsWith("/aligned"))
                            .filter(f -> f.toString().endsWith(".aa")).filter(f -> {
                                String filename = f.getFileName().toString();
                                return gg.genes.stream().anyMatch(g -> {
                                    String fnid = filename.substring(0, filename.length() - 3);
                                    return g.name.equals(fnid);
                                });
                            }).forEach(p -> {
                                try {
                                    Files.deleteIfExists(p);
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                            });
                    /*for( Gene g : gg.genes ) {
                       if( g.keggpathway != null ) {
                          String sub = g.keggpathway.substring(0,3);
                          Path subf = root.resolve(sub);
                          if( Files.exists(subf) ) {
                             String[] split = g.keggpathway.split(" ");
                             for( String s : split ) {
                      Path pimg = subf.resolve(s+".png");
                      if( Files.exists(pimg) ) {
                         showKeggPathway( sub, pimg );
                      }
                             }
                          }
                       }
                    }*/
                    final Path p = root.resolve("/aligned");
                    c.stream().forEach(fgg -> {
                        Path np = p.resolve(fgg.genes.iterator().next().getName());
                        try {
                            Writer w = Files.newBufferedWriter(np);
                            fgg.getFasta(w, false);
                            w.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    });
                    break;
                }
                geneset.zipfilesystem.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
    });
    popup.getItems().add(splitaction);
    MenuItem joinaction = new MenuItem("Join");

    popup.getItems().add(joinaction);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem showkegg = new MenuItem("Show KEGG pathway");
    showkegg.setOnAction(e -> {
        GeneGroup gg = table.getSelectionModel().getSelectedItem();

        Map<String, String> env = new HashMap<>();
        env.put("create", "true");

        /*String uristr = "jar:" + geneset.zippath.toUri();
        URI zipuri = URI.create( uristr /*.replace("file://", "file:")* );
        final List<Path>   lbi = new ArrayList<>();*/
        boolean shown = false;
        try {
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
            for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                for (Gene g : gg.genes) {
                    if (g.keggpathway != null) {
                        String sub = g.keggpathway.substring(0, 3);
                        Path subf = root.resolve(sub);
                        if (Files.exists(subf)) {
                            String[] split = g.keggpathway.split(" ");
                            for (String s : split) {
                                Path pimg = subf.resolve(s + ".png");
                                if (Files.exists(pimg)) {
                                    showKeggPathway(sub, pimg);
                                    shown = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                break;
            }
            geneset.zipfilesystem.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (!shown) {
            for (Gene g : gg.genes) {
                if (g.keggpathway != null) {
                    String[] keggsplit = g.keggpathway.split(";");
                    Arrays.stream(keggsplit).map(s -> s.split(":")[0]).findFirst().ifPresent(c -> {
                        try {
                            Desktop.getDesktop().browse(
                                    URI.create("http://www.genome.jp/dbget-bin/www_bget?map" + c.substring(2)));
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    });
                }
            }
        }
    });
    popup.getItems().add(showkegg);
    MenuItem plasmid = new MenuItem("Plasmid");
    plasmid.setOnAction(e -> {
        Gene g = gtable.getSelectionModel().getSelectedItem();
        Sequence contig = g.tegeval.getContshort();
        String contigstr = contig.toString();
        contig.plasmid = !geneset.plasmids.contains(contigstr);
        if (contig.plasmid)
            geneset.plasmids.add(contigstr);
        else
            geneset.plasmids.remove(contigstr);

        try {
            Map<String, String> env = new HashMap<>();
            env.put("create", "true");
            //Path path = zipfile.toPath();
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

            //fs = FileSystems.newFileSystem( uri, env );
            //FileSystem fs = FileSystems.newFileSystem(uri, env);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            for (String contigname : geneset.plasmids) {
                baos.write((contigname + "\n").getBytes());
            }

            Path nf = geneset.zipfilesystem.getPath("/plasmids.txt");
            long bl = Files.copy(new ByteArrayInputStream(baos.toByteArray()), nf,
                    StandardCopyOption.REPLACE_EXISTING);
            //System.err.println( "eeerm " + bl );
            geneset.zipfilesystem.close();

            /*Writer writer = Files.newBufferedWriter(nf, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
            for( String phage : phageset ) {
               writer.write( phage + "\n" );
            }
            writer.close();*/

            //writer.write("hello");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    popup.getItems().add(plasmid);
    MenuItem designate = new MenuItem("Designate");
    designate.setOnAction(e -> {
        SwingUtilities.invokeLater(() -> {
            JComboBox<String> descombo = new JComboBox<>(
                    geneset.deset.toArray(new String[geneset.deset.size()]));
            descombo.setEditable(true);
            JOptionPane.showMessageDialog(GeneSetHead.this, descombo);
            String val = descombo.getSelectedItem().toString();
            geneset.deset.add(val);
            for (Gene g : gtable.getSelectionModel().getSelectedItems()) {
                g.tegeval.designation = val;
                if (g.id != null) {
                    geneset.designations.put(g.id, val);
                } else {
                    System.err.println(g.refid);
                }
                //ta.append( g.tegeval.id + "\n" );
            }

            try {
                Map<String, String> env = new HashMap<String, String>();
                env.put("create", "true");
                //Path path = zipfile.toPath();
                String uristr = "jar:" + geneset.zippath.toUri();
                geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

                //fs = FileSystems.newFileSystem( uri, env );
                //FileSystem fs = FileSystems.newFileSystem(uri, env);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                for (String geneid : geneset.designations.keySet()) {
                    String design = geneset.designations.get(geneid);
                    baos.write((geneid + "\t" + design + "\n").getBytes());
                }

                Path nf = geneset.zipfilesystem.getPath("/designations.txt");
                long bl = Files.copy(new ByteArrayInputStream(baos.toByteArray()), nf,
                        StandardCopyOption.REPLACE_EXISTING);
                //System.err.println( "eeerm " + bl );
                geneset.zipfilesystem.close();

                /*Writer writer = Files.newBufferedWriter(nf, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
                for( String phage : phageset ) {
                    writer.write( phage + "\n" );
                }
                writer.close();*/

                //writer.write("hello");
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            /*JFrame frame = new JFrame("Ids");
            frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
            frame.setSize(800, 600);
            JTextArea   ta = new JTextArea();
            JScrollPane sp = new JScrollPane( ta );
            frame.add( sp );
                    
            frame.setVisible( true );*/
        });
    });
    popup.getItems().add(designate);
    MenuItem koname = new MenuItem("KO to name");
    koname.setOnAction(e -> {
        Set<String> koids = new HashSet<>();
        for (Gene g : geneset.genelist) {
            if (g.koid != null && g.koid.length() > 0
                    && !(geneset.ko2name != null && geneset.ko2name.containsKey(g.koid)))
                koids.add(g.koid);
        }

        try {
            Map<String, String> ko2name = new HashMap<>();
            int cnt = 0;
            for (String koid : koids) {
                URL url = new URL("http://www.kegg.jp/dbget-bin/www_bget?ko:" + koid);
                InputStream is0 = url.openStream();
                StringBuilder sb = new StringBuilder();
                BufferedReader br0 = new BufferedReader(new InputStreamReader(is0));
                String line0 = br0.readLine();
                while (line0 != null) {
                    sb.append(line0);
                    line0 = br0.readLine();
                }
                br0.close();

                int i = sb.indexOf("<nobr>Name</nobr>");
                if (i != -1) {
                    int k = sb.indexOf(":hidden\">");
                    if (k != -1) {
                        k = sb.indexOf(":hidden\">", k + 9);
                        if (k != -1) {
                            String koname0 = sb.substring(k + 9, sb.indexOf("<br>", k));
                            ko2name.put(koid, koname0);

                            System.err.println(koid + "\t" + koname0);
                        }
                    }
                }

                System.err.println(ko2name.size() + " " + koids.size());
                //if( cnt++ > 20 ) break;
            }

            FileWriter fw = new FileWriter("~ko2name.txt");
            for (String koid : ko2name.keySet()) {
                fw.write(koid + "\t" + ko2name.get(koid) + "\n");
            }
            fw.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    popup.getItems().add(koname);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem genegainloss = new MenuItem("Gene gain/loss");
    genegainloss.setOnAction(e -> {
        Map<Node, List<GeneGroup>> nodeGainMap = new HashMap<>();
        Map<Node, List<GeneGroup>> nodeLossMap = new HashMap<>();

        /*String treestr = "";
        JFileChooser fc = new JFileChooser();
        if( fc.showOpenDialog( applet ) == JFileChooser.APPROVE_OPTION ) {
           File file = fc.getSelectedFile();
           try {
              byte[] bb = Files.readAllBytes( Paths.get(file.toURI()) );
              treestr = new String( bb );
           } catch (IOException e1) {
              e1.printStackTrace();
           }
        }*/

        Serifier serifier = getConcatenatedSequences(false, true);
        String tree = serifier.getFastTree(serifier.lseq, geneset.user, false);

        TreeUtil tu = new TreeUtil();
        Node n = tu.parseTreeRecursive(tree, false);

        TableModel model = new TableModel() {
            @Override
            public int getRowCount() {
                return geneset.getSpecies().size();
            }

            @Override
            public int getColumnCount() {
                return 1;
            }

            @Override
            public String getColumnName(int columnIndex) {
                return null;
            }

            @Override
            public Class<?> getColumnClass(int columnIndex) {
                return String.class;
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }

            @Override
            public Object getValueAt(int rowIndex, int columnIndex) {
                return geneset.getSpecies().get(rowIndex);
            }

            @Override
            public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            }

            @Override
            public void addTableModelListener(TableModelListener l) {
            }

            @Override
            public void removeTableModelListener(TableModelListener l) {
            }
        };
        JTable table = new JTable(model);
        table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        JScrollPane scroll = new JScrollPane(table);
        FlowLayout flowlayout = new FlowLayout();
        JComponent c = new JComponent() {
        };
        c.setLayout(flowlayout);
        c.add(scroll);
        JOptionPane.showMessageDialog(comp, c);

        List<String> rootgroup = new ArrayList<>();
        int[] rr = table.getSelectedRows();
        for (int r : rr) {
            rootgroup.add((String) table.getValueAt(r, 0));
        }

        //String[] sobj = {"mt.ruber", "mt.silvanus", "o.profundus", "m.hydrothermalis"};
        Node newnode = tu.getParent(n, new HashSet<>(rootgroup));
        tu.rerootRecur(n, newnode);

        File f = new File("/home/sigmar/gain_list.txt");
        try {
            PrintStream ps = new PrintStream(f);
            geneset.assignGain(newnode, nodeGainMap, ps);
            ps.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        f = new File("/home/sigmar/loss_list.txt");
        try {
            PrintStream ps = new PrintStream(f);
            geneset.assignLoss(newnode, nodeLossMap, ps);
            ps.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
    });
    popup.getItems().add(genegainloss);
    MenuItem concattree = new MenuItem("Concatenate tree");
    concattree.setOnAction(e -> {
        Serifier serifier = getConcatenatedSequences(false, true);

        boolean succ = true;
        if (comp instanceof Applet) {
            try {
                JSObject win = JSObject.getWindow((Applet) comp);
                StringWriter sw = new StringWriter();
                serifier.writeFasta(serifier.lseq, sw, null);
                sw.close();
                win.call("fasttree", new Object[] { sw.toString() });
            } catch (NoSuchMethodError | Exception e1) {
                e1.printStackTrace();
                succ = false;
            }
        }

        /*if( !succ ) {
           String             tree = serifier.getFastTree();
           if( cs.connections().size() > 0 ) {
        cs.sendToAll( tree );
            } else if( Desktop.isDesktopSupported() ) {
        cs.message = tree;
        //String uristr = "http://webconnectron.appspot.com/Treedraw.html?tree="+URLEncoder.encode( tree, "UTF-8" );
        String uristr = "http://webconnectron.appspot.com/Treedraw.html?ws=127.0.0.1:8887";
              try {
          Desktop.getDesktop().browse( new URI(uristr) );
              } catch (IOException | URISyntaxException e1) {
          e1.printStackTrace();
              }
            }
           System.err.println( tree );
        }*/
        showAlignedSequences(comp, serifier);
    });
    popup.getItems().add(concattree);
    MenuItem majocons = new MenuItem("Majority rule consensus");
    majocons.setOnAction(e -> {
        Serifier serifier = new Serifier();

        Set<GeneGroup> genegroups = new HashSet<GeneGroup>();
        if (!isGeneview()) {
            genegroups.addAll(table.getSelectionModel().getSelectedItems());
        } else {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                genegroups.add(gg.getGeneGroup());
            }
        }

        TreeUtil treeutil = new TreeUtil();
        Map<Set<String>, NodeSet> nmap = new HashMap<Set<String>, NodeSet>();
        for (GeneGroup ggroup : genegroups) {
            //List<Sequence>   seqlist = new ArrayList<Sequence>();

            for (Tegeval tv : ggroup.getTegevals()) {
                String spec = tv.getContshort().getSpec();
                Sequence seq = tv.getAlignedSequence();

                //Sequence seq = new Sequence( spec, null );
                //if( seqstr != null && seqstr.length() > 0 ) seq.append( seqstr );
                serifier.addSequence(seq);
            }

            String tree = serifier.getFastTree(serifier.lseq, geneset.user, false);
            Node n = treeutil.parseTreeRecursive(tree, false);
            treeutil.setLoc(0);
            n.nodeCalcMap(nmap);
        }

        Node guidetree = null;

        /*********************************** Serifier serifier = getConcatenatedSequences();
        String tree = serifier.getFastTree();
        guidetree = treeutil.parseTreeRecursive( tree, false );*/

        Node root = DataTable.majoRuleConsensus(treeutil, nmap, guidetree, false);
        String tree = root.toString();

        if (geneset.cs.connections().size() > 0) {
            geneset.cs.sendToAll(tree);
        } else if (Desktop.isDesktopSupported()) {
            geneset.cs.message = tree;
            //String uristr = "http://webconnectron.appspot.com/Treedraw.html?tree="+URLEncoder.encode( tree, "UTF-8" );
            String uristr = "http://webconnectron.appspot.com/Treedraw.html?ws=127.0.0.1:8887";
            try {
                Desktop.getDesktop().browse(new URI(uristr));
            } catch (IOException | URISyntaxException e1) {
                e1.printStackTrace();
            }
        }
    });
    popup.getItems().add(majocons);
    MenuItem addsim = new MenuItem("Add similar");
    addsim.setOnAction(e -> {
        /*int r = table.getSelectedRow();
        int c = table.getSelectedColumn();
                
        Object o = table.getValueAt(r, c);
                
        if (c >= 18) {
           for (int i = 0; i < table.getRowCount(); i++) {
              Object no = table.getValueAt(i, c);
              if (no != null && !table.isRowSelected(i))
          table.addRowSelectionInterval(i, i);
           }
        } else {
           for (int i = 0; i < table.getRowCount(); i++) {
              Object no = table.getValueAt(i, c);
              if (o.equals(no) && !table.isRowSelected(i))
          table.addRowSelectionInterval(i, i);
           }
        }*/
    });
    popup.getItems().add(addsim);
    MenuItem selsim = new MenuItem("Select similar");
    selsim.setOnAction(e -> {
        /*int r = table.getSelectedRow();
        int c = table.getSelectedColumn();
                
        Object o = table.getValueAt(r, c);
                
        table.removeRowSelectionInterval(0, table.getRowCount() - 1);
        if (c >= 18) {
           for (int i = 0; i < table.getRowCount(); i++) {
              Object no = table.getValueAt(i, c);
              if (no != null)
          table.addRowSelectionInterval(i, i);
           }
        } else {
           for (int i = 0; i < table.getRowCount(); i++) {
              Object no = table.getValueAt(i, c);
              if (o.equals(no))
          table.addRowSelectionInterval(i, i);
           }
        }*/
    });
    popup.getItems().add(selsim);
    MenuItem tabtxt = new MenuItem("Table text");
    tabtxt.setOnAction(e -> {
        /*JTextArea ta = new JTextArea();
        ta.setDragEnabled(true);
        JScrollPane scrollpane = new JScrollPane(ta);
                
        StringBuilder sb = new StringBuilder();
        int[] rr = table.getSelectedRows();
        for (int r : rr) {
           for (int c = 0; c < table.getColumnCount() - 1; c++) {
              Object o = table.getValueAt(r, c);
              if (c > 18) {
          if (o != null) {
             String val = o.toString();
             int k = val.indexOf(' ');
             sb.append(val.substring(0, k));
             sb.append("\t" + val.substring(k + 1));
          } else
             sb.append("\t");
              } else {
          if (o != null) {
             sb.append(o.toString());
          }
              }
              sb.append("\t");
           }
           Object o = table.getValueAt(r, table.getColumnCount() - 1);
           if (o != null) {
              String val = o.toString();
              int k = val.indexOf(' ');
              sb.append(val.substring(0, k));
              sb.append("\t" + val.substring(k + 1));
           } else
              sb.append("\t");
           sb.append("\n");
        }
                
        ta.setText(sb.toString());
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);*/
    });
    popup.getItems().add(tabtxt);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem ncbil = new MenuItem("NCBI lookup");
    ncbil.setOnAction(e -> {
        /*int r = table.getSelectedRow();
        if (r >= 0) {
           String ref = (String) table.getValueAt(r, 2);
           try {
              Desktop.getDesktop().browse(new URI("http://www.ncbi.nlm.nih.gov/gene?term=" + ref));
           } catch (IOException e1) {
              e1.printStackTrace();
           } catch (URISyntaxException e1) {
              e1.printStackTrace();
           }
        }*/
    });
    popup.getItems().add(ncbil);
    table.setContextMenu(popup);
    gtable.setContextMenu(popup);

    TableColumn<Function, String> gocol = new TableColumn("GO");
    gocol.setCellValueFactory(new PropertyValueFactory<>("go"));
    ftable.getColumns().add(gocol);
    TableColumn<Function, String> ecfcol = new TableColumn("EC");
    ecfcol.setCellValueFactory(new PropertyValueFactory<>("ec"));
    ftable.getColumns().add(ecfcol);
    TableColumn<Function, String> metacyccol = new TableColumn("MetaCyc");
    metacyccol.setCellValueFactory(new PropertyValueFactory<>("metacyc"));
    ftable.getColumns().add(metacyccol);
    TableColumn<Function, String> keggcol = new TableColumn("KEGG");
    keggcol.setCellValueFactory(new PropertyValueFactory<>("kegg"));
    ftable.getColumns().add(keggcol);
    TableColumn<Function, String> funcovcol = new TableColumn("Funciton coverage");
    funcovcol.setCellValueFactory(new PropertyValueFactory<>("speciesCount"));
    ftable.getColumns().add(funcovcol);
    TableColumn<Function, String> numprotcol = new TableColumn("Number of proteins");
    numprotcol.setCellValueFactory(new PropertyValueFactory<>("groupCount"));
    ftable.getColumns().add(numprotcol);

    TableColumn<Function, String> namecol = new TableColumn("Name");
    namecol.setCellValueFactory(new PropertyValueFactory<>("name"));
    ftable.getColumns().add(namecol);
    TableColumn<Function, String> namespacecol = new TableColumn("Namespace");
    namespacecol.setCellValueFactory(new PropertyValueFactory<>("namespace"));
    ftable.getColumns().add(namespacecol);
    TableColumn<Function, String> desccol = new TableColumn("Desc");
    desccol.setCellValueFactory(new PropertyValueFactory<>("desc"));
    ftable.getColumns().add(desccol);

    ftable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    //ftable.setAutoCreateRowSorter(true);
    /*ftablemodel = new TableModel() {
       @Override
       public int getRowCount() {
    return geneset.funclist.size();
       }
            
       @Override
       public int getColumnCount() {
    return 9;
       }
            
       @Override
       public String getColumnName(int columnIndex) {
    if (columnIndex == 0)
       return "GO";
    else if (columnIndex == 1)
       return "EC";
    else if (columnIndex == 2)
       return "MetaCyc";
    else if (columnIndex == 3)
       return "KEGG";
    else if (columnIndex == 4)
       return "Function coverage";
    else if (columnIndex == 5)
       return "Number of proteins";
    else if (columnIndex == 6)
       return "Name";
    else if (columnIndex == 7)
       return "Namespace";
    else if (columnIndex == 8)
       return "Def";
    return "";
       }
            
       @Override
       public Class<?> getColumnClass(int columnIndex) {
    if( columnIndex == 4 || columnIndex == 5 )
       return Integer.class;
    return String.class;
       }
            
       @Override
       public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
       }
            
       @Override
       public Object getValueAt(int rowIndex, int columnIndex) {
    Function func = geneset.funclist.get(rowIndex);
    if( columnIndex == 0 )
       return func.go;
    else if( columnIndex == 1 )
       return func.ec;
    else if( columnIndex == 2 )
       return func.metacyc;
    else if( columnIndex == 3 )
       return func.kegg;
    else if( columnIndex == 4 )
       return func.getSpeciesCount();
    else if( columnIndex == 5 )
       return table.getModel() == groupModel ? func.getGroupSize() : func.getGeneCount();
    else if( columnIndex == 6 )
       return func.name;
    else if( columnIndex == 7 )
       return func.namespace;
    else if( columnIndex == 8 )
       return func.desc;
    return null;
       }
            
       @Override
       public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
       }
            
       @Override
       public void addTableModelListener(TableModelListener l) {
       }
            
       @Override
       public void removeTableModelListener(TableModelListener l) {
       }
    };
    ftable.setModel( ftablemodel );
    fscrollpane.setViewportView(ftable);*/

    updateFilter(ftable, null);
    updateFilter(table, label);

    combo.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        String sel = newValue;
        filterset.clear();
        if (geneset.pathwaymap.containsKey(sel)) {
            Set<String> enz = geneset.pathwaymap.get(sel);
            for (Function f : geneset.funclist) {
                if (f.getEc() != null && enz.contains(f.getEc())) {
                    filterset.add(f.index);
                }
            }
        }
        updateFilter(ftable, null);
    });

    specombo.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        String sel = newValue;
        genefilterset.clear();
        for (Gene g : geneset.genelist) {
            Tegeval tv = g.tegeval;
            if (sel.equals(tv.teg)) {
                //System.out.println(g.name + " " + sp + " " + sel + "  " + tv.eval);
                genefilterset.add(g.index);
            }
        }
        updateFilter(table, label);
    });

    MenuItem findcon = new MenuItem("Find conserved terms");
    findcon.setOnAction(e -> {
        Set<Integer> res = new HashSet<>();
        for (Function f : geneset.funclist) {
            if (f.getGeneGroups() != null) {
                Set<String> check = new HashSet<>();
                for (GeneGroup g : f.getGeneGroups()) {
                    //Gene g = genemap.get(str);
                    if (g.species != null) {
                        if (check.isEmpty())
                            check.addAll(g.species.keySet());
                        else if (!(check.size() == g.species.size() && check.containsAll(g.species.keySet()))) {
                            check.clear();
                            break;
                        }
                    }
                }
                if (!check.isEmpty())
                    res.add(f.index);
            }
        }
        filterset.clear();
        for (int i : res) {
            filterset.add(i);
        }
        updateFilter(ftable, null);
    });
    fpopup.getItems().add(findcon);
    fpopup.getItems().add(new SeparatorMenuItem());

    MenuItem showgen = new MenuItem("Show genes");
    showgen.setOnAction(e -> {
        genefilterset.clear();
        Set<GeneGroup> sset = new HashSet<>();
        for (Function f : (ObservableList<Function>) ftable.getSelectionModel().getSelectedItems()) {
            if (!isGeneview()) {
                sset.addAll(f.getGeneGroups());
                /*if( sset != null ) for (GeneGroup gg : sset) {
                   //Gene g = genemap.get(s);
                   genefilterset.add(gg.index);
                }*/
            } else {
                /*Set<Gene> sset = f.getGeneentries();
                for (Gene g : sset) {
                   //Gene g = genemap.get(s);
                   genefilterset.add(g.index);
                }*/
            }
        }

        //int[] rows = sset.stream().mapToInt( gg -> sortedData.indexOf(gg) ).toArray();
        //table.getSelectionModel().selectIndices(rows[0], rows);

        filteredData.setPredicate(genegroup -> {
            return sset.contains(genegroup);
        });
        if (label != null)
            label.setText(
                    table.getItems().size() + "/" + table.getSelectionModel().getSelectedIndices().size());
    });
    fpopup.getItems().add(showgen);

    table.getSelectionModel().selectedItemProperty().addListener(e -> {
        // table.clearSelection();
        tableisselecting = true;
        if (!ftableisselecting && filterset.isEmpty()) {
            //ftable.removeRowSelectionInterval(0, ftable.getRowCount() - 1);
            if (!isGeneview()) {
                for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                    for (Function f : gg.getFunctions()) {
                        try {
                            ftable.getSelectionModel().select(f);
                            //int rf = ftable.convertRowIndexToView(f.index);
                            //if( rf >= 0 && rf < ftable.getRowCount() ) ftable.addRowSelectionInterval(rf, rf);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            } else {
                for (Gene g : gtable.getSelectionModel().getSelectedItems()) {
                    if (g.funcentries != null) {
                        for (Function f : g.funcentries) {
                            //Function f = funcmap.get(go);
                            try {
                                ftable.getSelectionModel().select(f);
                                //int rf = ftable.convertRowIndexToView(f.index);
                                //if( rf >= 0 && rf < ftable.getRowCount() ) ftable.addRowSelectionInterval(rf, rf);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        tableisselecting = false;
    });

    ftable.setOnKeyPressed(ke -> {
        if (ke.getCode() == KeyCode.ESCAPE) {
            ffilteredData.setPredicate(null);
        }
    });

    table.setOnKeyPressed(ke -> {
        if (ke.getCode() == KeyCode.ESCAPE) {
            GeneGroup selgg = table.getSelectionModel().getSelectedItem();

            List<GeneGroup> sel = new ArrayList<>(filteredData);
            filteredData.setPredicate(null);
            int[] rows = sel.stream().mapToInt(gg -> sortedData.indexOf(gg)).toArray();
            if (rows.length > 0)
                table.getSelectionModel().selectIndices(rows[0], rows);
            if (label != null)
                label.setText(
                        table.getItems().size() + "/" + table.getSelectionModel().getSelectedIndices().size());

            table.scrollTo(selgg);
            //genefilterset.clear();
            //updateFilter(table, genefilter, label);
            //geneset.scrollToSelection( table );
        }
    });

    table.setOnMousePressed(e -> {
        tableisselecting = true;
        if (!ftableisselecting && e.getClickCount() == 2) {
            /*
             * int[] rr = ftable.getSelectedRows(); int minr =
             * ftable.getRowCount(); int maxr = 0; for( int r : rr ) {
             * if( r < minr ) minr = r; if( r > maxr ) maxr = r; }
             * ftable.removeRowSelectionInterval(minr, maxr);
             */
            // ftable.removeRowSelectionInterval(0, filterset.isEmpty()
            // ? ftable.getRowCount()-1 : filterset.size()-1 );

            Set<Function> fset = new HashSet<>();
            filterset.clear();
            if (!isGeneview()) {
                for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                    fset.addAll(gg.getFunctions());
                }
            } else {
                for (Gene g : gtable.getSelectionModel().getSelectedItems()) {
                    if (g.funcentries != null) {
                        for (Function f : g.funcentries) {
                            //Function f = funcmap.get(go);
                            // ftable.getRowSorter().convertRowIndexToView(index)
                            // int rf = ftable.convertRowIndexToView(
                            // f.index );
                            filterset.add(f.index);
                            // ftable.addRowSelectionInterval(rf, rf);
                        }
                    }
                }
            }
            ffilteredData.setPredicate(p -> fset.contains(p));
        }
        tableisselecting = false;
    });

    ftable.setOnMousePressed(e -> {
        ftableisselecting = true;
        Set<GeneGroup> ggset = new HashSet<>();
        if (!tableisselecting && e.getClickCount() == 2) {
            genefilterset.clear();
            for (Function f : (ObservableList<Function>) ftable.getSelectionModel().getSelectedItems()) {
                if (f.getGeneentries() != null) {
                    if (!isGeneview()) {
                        ggset.addAll(f.getGeneGroups());
                    } else {
                        for (Gene g : f.getGeneentries()) {
                            //Gene g = genemap.get(ref);
                            // int rf = table.convertRowIndexToView( g.index
                            // );
                            // table.addRowSelectionInterval(rf, rf);
                            genefilterset.add(g.index);
                        }
                    }
                }
            }
            filteredData.setPredicate(p -> ggset.contains(p));
        }
        ftableisselecting = false;
    });

    ftable.getSelectionModel().selectedItemProperty().addListener(e -> {
        ftableisselecting = true;
        if (!tableisselecting && genefilterset.isEmpty()) {
            table.getSelectionModel().clearSelection();
            //table.removeRowSelectionInterval(0, table.getRowCount() - 1);
            for (Function f : ftable.getSelectionModel().getSelectedItems()) {
                if (f.getGeneentries() != null) {
                    for (Gene g : f.getGeneentries()) {
                        table.getSelectionModel().select(g.getGeneGroup());

                        //Gene g = genemap.get(ref);
                        /*int i = g.getGroupIndex();
                        if( i >= 0 && i <= table.getItems().size() ) {
                           int rf = table.convertRowIndexToView(i);
                           table.addRowSelectionInterval(rf, rf);
                        }*/
                    }
                }
            }
        }
        ftableisselecting = false;
    });

    textfield.setOnKeyPressed(e -> {
        String text = textfield.getText().toLowerCase();
        if (e.getCode() == KeyCode.ENTER) {
            searchi = searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol")
                    ? searchTable(table, text, searchi, e.isAltDown(), 8, 9, 10, 16)
                    : searchTable(table, text, searchi, e.isAltDown(), 0);
        }
    });

    textfield.textProperty().addListener((observable, oldValue, newValue) -> {
        //String text = textfield.getText().toLowerCase();
        String lowerCaseFilter = newValue.toLowerCase();
        Predicate<GeneGroup> p = genegroup -> {
            if (newValue == null || newValue.isEmpty()) {
                return true;
            }

            if (searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol")) {
                if ((genegroup.getCogsymbol() != null
                        && genegroup.getCogsymbol().toLowerCase().contains(lowerCaseFilter))
                        || (genegroup.getSymbol() != null
                                && genegroup.getSymbol().toLowerCase().contains(lowerCaseFilter))
                        || (genegroup.getKoname() != null
                                && genegroup.getKoname().toLowerCase().contains(lowerCaseFilter))) {
                    return true; // Filter matches first name.
                }
            } else {
                if (genegroup.getName().toLowerCase().contains(lowerCaseFilter) || genegroup.genes.stream()
                        .anyMatch(gg -> gg.getName().toLowerCase().contains(lowerCaseFilter))) {
                    return true; // Filter matches first name.
                } /* else if (genegroup.getLastName().toLowerCase().contains(lowerCaseFilter)) {
                    return true; // Filter matches last name.
                  }*/
            }
            return false; // Does not match.
        };
        if (filter.isSelected()) {
            filteredData.setPredicate(p);
            if (label != null)
                label.setText(
                        table.getItems().size() + "/" + table.getSelectionModel().getSelectedIndices().size());
            //if( searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ) updateFilter(0, text, table, genefilter, genefilterset, label, 8, 9, 10, 16 );
            //else updateFilter(0, text, table, genefilter, genefilterset, label, 0 );
        } else {
            Optional<GeneGroup> ogg = filteredData.stream().filter(p).findFirst();
            if (ogg.isPresent()) {
                GeneGroup gg = ogg.get();
                table.getSelectionModel().select(gg);
                table.scrollTo(gg);
            }
            //searchi = searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ? searchTable( table, text, 0, false, 8, 9, 10, 16 ) : searchTable( table, text, 0, false, 0 );
        }
    });
    /*textfield.getDocument().addDocumentListener(new DocumentListener() {
       public void changedUpdate(DocumentEvent e) {
    String text = textfield.getText().toLowerCase();
    if( filter.isSelected() ) {
       if( searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ) updateFilter(0, text, table, genefilter, genefilterset, label, 8, 9, 10, 16 );
       else updateFilter(0, text, table, genefilter, genefilterset, label, 0 );
    } else {
       searchi = searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ? searchTable( table, text, 0, false, 8, 9, 10, 16 ) : searchTable( table, text, 0, false, 0 );
    }
       }
            
       public void insertUpdate(DocumentEvent e) {
    String text = textfield.getText().toLowerCase();
    if( filter.isSelected() ) {
       if( searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ) updateFilter(1, text, table, genefilter, genefilterset, label, 8, 9, 10, 16);
       else updateFilter(1, text, table, genefilter, genefilterset, label, 0);
    } else {
       searchi = searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ? searchTable( table, text, 0, false, 8, 9, 10, 16 ) : searchTable( table, text, 0, false, 0 );
    }
       }
            
       public void removeUpdate(DocumentEvent e) {
    String text = textfield.getText().toLowerCase();
    if( filter.isSelected() ) {
       if( searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ) updateFilter(2, text, table, genefilter, genefilterset, label, 8, 9, 10, 16 );
       else updateFilter(2, text, table, genefilter, genefilterset, label, 0);
    } else {
       searchi = searchTable( table, text, 0, false, searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ? 7 : 0 );
    }
       }
    });*/

    ftextfield.textProperty().addListener(new javafx.beans.value.ChangeListener<String>() {
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            //String text = textfield.getText().toLowerCase();
            if (filter.isSelected()) {
                ffilteredData.setPredicate(function -> {
                    // If filter text is empty, display all persons.
                    if (newValue == null || newValue.isEmpty()) {
                        return true;
                    }

                    // Compare first name and last name of every person with filter text.
                    String lowerCaseFilter = newValue.toLowerCase();

                    boolean desc = function.getDesc() != null
                            && function.getDesc().toLowerCase().contains(lowerCaseFilter);
                    boolean name = function.getName() != null
                            && function.getName().toLowerCase().contains(lowerCaseFilter);
                    boolean go = function.getGo() != null
                            && function.getGo().toLowerCase().contains(lowerCaseFilter);
                    boolean ec = function.getEc() != null
                            && function.getEc().toLowerCase().contains(lowerCaseFilter);

                    if (desc || name || go || ec) {
                        return true; // Filter matches first name.
                    } /* else if (genegroup.getLastName().toLowerCase().contains(lowerCaseFilter)) {
                         return true; // Filter matches last name.
                      }*/
                    return false; // Does not match.
                });
            } else {
                //searchi = searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ? searchTable( table, text, 0, false, 8, 9, 10, 16 ) : searchTable( table, text, 0, false, 0 );
            }
        }
    });
    /*ftextfield.getDocument().addDocumentListener(new DocumentListener() {
       public void changedUpdate(DocumentEvent e) {
    updateFilter(0, ftextfield.getText(), ftable, rowfilter, filterset, null, 6);
       }
            
       public void insertUpdate(DocumentEvent e) {
    updateFilter(1, ftextfield.getText(), ftable, rowfilter, filterset, null, 6);
       }
            
       public void removeUpdate(DocumentEvent e) {
    updateFilter(2, ftextfield.getText(), ftable, rowfilter, filterset, null, 6);
       }
    });*/
    MenuItem kegggl = new MenuItem("KEGG gene lookup");
    kegggl.setOnAction(e -> {
        Gene g = gtable.getSelectionModel().getSelectedItem();
        try {
            Desktop.getDesktop().browse(new URI("http://www.genome.jp/dbget-bin/www_bget?" + g.keggid));
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
    });
    popup.getItems().add(kegggl);
    MenuItem showgenes = new MenuItem("Show genes with same sharing");
    showgenes.setOnAction(e -> {
        genefilterset.clear();
        GeneGroup gg = table.getSelectionModel().getSelectedItem();
        for (GeneGroup g : geneset.allgenegroups) {
            if (gg.species != null && g.species != null) {
                Set<String> ggset = gg.species.keySet();
                Set<String> gset = g.species.keySet();

                if (gset.size() == ggset.size() && gset.containsAll(ggset)) {
                    genefilterset.add(g.index);
                }
            }
        }
        updateFilter(table, label);
    });
    popup.getItems().add(showgenes);
    MenuItem showshared = new MenuItem("Show shared function");
    showshared.setOnAction(e -> {
        filterset.clear();
        Set<Function> startfunc = new HashSet<Function>();
        if (isGeneview()) {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                if (gg.funcentries != null) {
                    if (startfunc.isEmpty()) {
                        startfunc.addAll(gg.funcentries);
                    } else {
                        startfunc.retainAll(gg.funcentries);
                    }
                }
                /*if (startfunc == null)
                startfunc = new HashSet<Function>(gg.funcentries);
                else {
                startfunc.retainAll(gg.funcentries);
                }*/
            }
        } else {
            for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                Set<Function> fset = gg.getFunctions();
                if (startfunc.isEmpty()) {
                    startfunc.addAll(fset);
                } else {
                    startfunc.retainAll(fset);
                }
            }
        }
        for (Function f : geneset.funclist) {
            filterset.add(f.index);
        }
        updateFilter(ftable, null);
    });
    popup.getItems().add(showshared);
    MenuItem showall = new MenuItem("Show all functions");
    showall.setOnAction(e -> {
        filterset.clear();
        Set<Function> startfunc = null;
        if (isGeneview()) {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                if (gg.funcentries != null) {
                    for (Function f : gg.funcentries) {
                        filterset.add(f.index);
                    }
                }
            }
        } else {
            for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                Set<Function> fset = gg.getFunctions();
                for (Function f : fset) {
                    filterset.add(f.index);
                }
            }
        }
        updateFilter(ftable, null);
    });
    popup.getItems().add(showall);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem showgenegroups = new MenuItem("Show gene groups in proximity");
    showgenegroups.setOnAction(e -> {
        proxi(filteredData, false);
        updateFilter(table, label);
    });
    popup.getItems().add(showgenegroups);
    MenuItem selgenegroups = new MenuItem("Select gene groups in proximity");
    selgenegroups.setOnAction(e -> {
        genefilterset.clear();
        proxi(filteredData, false);
        for (int i : genefilterset) {
            table.getSelectionModel().select(i);
        }
        //table.tableChanged( new TableModelEvent( table.getModel() ) );
        if (label != null)
            label.setText(table.getItems().size() + "/" + table.getSelectionModel().getSelectedItems().size());
        //updateFilter(table, genefilter, label);
    });
    popup.getItems().add(selgenegroups);
    MenuItem selgenes = new MenuItem("Select genes in proximity");
    selgenes.setOnAction(e -> {
        genefilterset.clear();
        proxi(filteredData, true);
        for (int i : genefilterset) {
            table.getSelectionModel().select(i);
        }
        //table.tableChanged( new TableModelEvent( table.getModel() ) );
        if (label != null)
            label.setText(table.getItems().size() + "/" + table.getSelectionModel().getSelectedItems().size());
        //updateFilter(table, genefilter, label);
    });
    popup.getItems().add(selgenes);
    MenuItem addgene = new MenuItem("Add gene groups in proximity");
    addgene.setOnAction(e -> {
        proxi(filteredData, false);
        updateFilter(table, label);
    });
    popup.getItems().add(addgene);
    MenuItem remgene = new MenuItem("Remove gene groups in proximity");
    remgene.setOnAction(e -> {
        ObservableList<Integer> rr = table.getSelectionModel().getSelectedIndices();
        if (genefilterset.isEmpty()) {
            Set<Integer> ii = new HashSet<>();
            for (int r : rr)
                ii.add(r);
            for (int i = 0; i < geneset.genelist.size(); i++) {
                if (!ii.contains(i))
                    genefilterset.add(i);
            }
        }
        proxi(filteredData, false);
        updateFilter(table, label);
    });
    popup.getItems().add(remgene);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem showrel = new MenuItem("Show related genes");
    showrel.setOnAction(e -> {
        genefilterset.clear();
        relati(gtable, geneset.genelist, genefilterset, geneset.uclusterlist, false);
        updateFilter(gtable, label);
    });
    popup.getItems().add(showrel);
    MenuItem addrel = new MenuItem("Add related genes");
    addrel.setOnAction(e -> {
        relati(gtable, geneset.genelist, genefilterset, geneset.uclusterlist, false);
        updateFilter(gtable, label);
    });
    popup.getItems().add(addrel);
    MenuItem remrel = new MenuItem("Remove related genes");
    remrel.setOnAction(e -> {
        ObservableList<Integer> rr = gtable.getSelectionModel().getSelectedIndices();
        if (genefilterset.isEmpty()) {
            Set<Integer> ii = new HashSet<>();
            for (int r : rr)
                ii.add(r);
            for (int i = 0; i < geneset.genelist.size(); i++) {
                if (!ii.contains(i))
                    genefilterset.add(i);
            }
        }
        relati(gtable, geneset.genelist, genefilterset, geneset.uclusterlist, true);
        updateFilter(table, label);
    });
    popup.getItems().add(remrel);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem showcloserel = new MenuItem("Show closely related genes");
    showcloserel.setOnAction(e -> {
        genefilterset.clear();
        Set<String> ct = new HashSet<>();
        for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
            // genefilterset.add( gg.index );
            Tegeval tv = gg.tegeval;
            for (Set<String> uset : geneset.iclusterlist) {
                if (uset.contains(tv.name)) {
                    ct.addAll(uset);
                    break;
                }
            }
        }

        for (Gene g : geneset.genelist) {
            Tegeval tv = g.tegeval;
            if (ct.contains(tv.name)) {
                genefilterset.add(g.index);
                break;
            }
        }

        updateFilter(table, label);
    });
    popup.getItems().add(showcloserel);
    MenuItem showdist = new MenuItem("Show distance matrix");
    showdist.setOnAction(e -> {
        JTextArea textarea = new JTextArea();

        try {
            if (clipboardService == null)
                clipboardService = (ClipboardService) ServiceManager.lookup("javax.jnlp.ClipboardService");
            Action action = new CopyAction("Copy", null, "Copy data",
                    new Integer(KeyEvent.VK_CONTROL + KeyEvent.VK_C));
            textarea.getActionMap().put("copy", action);
            grabFocus = true;
        } catch (Exception ee) {
            ee.printStackTrace();
            System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        }
        textarea.setDragEnabled(true);

        JScrollPane scrollpane = new JScrollPane(textarea);
        Gene gg = gtable.getSelectionModel().getSelectedItem();
        if (gg.getSpecies() != null) {
            for (String s : geneset.corrInd) {
                if (s.equals(geneset.corrInd.get(0)))
                    textarea.append(s);
                else
                    textarea.append("\t" + s);
            }

            int i = 0;
            int j = 0;

            int len = 16;
            double[] min = new double[len];
            double[] max = new double[len];

            for (i = 0; i < len; i++) {
                min[i] = Double.MAX_VALUE;
                max[i] = 0.0;
            }

            double[] corrarr = gg.corrarr;
            boolean symmetrize = true;
            if (symmetrize) {
                for (i = 0; i < len; i++) {
                    for (int k = i + 1; k < len; k++) {
                        corrarr[i * len + k] = (corrarr[k * len + i] + corrarr[i * len + k]) / 2.0;
                        corrarr[k * len + i] = corrarr[i * len + k];
                    }
                }
            }

            for (i = 0; i < len; i++) {
                for (int k = 0; k < len; k++) {
                    if (corrarr[i * len + k] < min[i])
                        min[i] = corrarr[i * len + k];
                    if (corrarr[i * len + k] > max[i])
                        max[i] = corrarr[i * len + k];
                }

                /*for (int k = 0; k < len; k++) {
                   corrarr[i * 16 + k] = corrarr[i * 16 + k] - min;
                }*/
            }

            i = 0;
            for (double d : corrarr) {
                double dval = d;
                if (i % len == 0)
                    textarea.append("\n" + dval);
                else
                    textarea.append("\t" + dval);

                i++;
            }
            textarea.append("\n");

            i = 0;
            for (double d : corrarr) {
                double dval = Math.exp((d - min[i / len]) / 20.0 + 1.0) / 100.0; // 0.0 ?
                // 0.0 :
                // 100.0/d;
                if (i % len == 0)
                    textarea.append("\n" + dval);
                else
                    textarea.append("\t" + dval);

                i++;
            }
            double[] newcorr = Arrays.copyOf(corrarr, corrarr.length);
            textarea.append("\nD matrix\n");
            i = 0;
            for (double d : corrarr) {
                double dval = max[i / len] - d;
                newcorr[i] = dval;
                if (i % len == 0)
                    textarea.append("\n" + dval);
                else
                    textarea.append("\t" + dval);

                i++;
            }

            TreeUtil treeutil = new TreeUtil();
            treeutil.neighborJoin(newcorr, geneset.corrInd, null, true, true);
        }

        /*
         * int[] rr = table.getSelectedRows(); for( int r : rr ) { int
         * cr = table.convertRowIndexToModel(r); Gene gg =
         * genelist.get(cr); if( gg.species != null ) { textarea.append(
         * gg.name + ":\n" ); for( String sp : gg.species.keySet() ) {
         * Teginfo stv = gg.species.get( sp ); for( Tegeval tv :
         * stv.tset ) { textarea.append( ">" + tv.cont + " " + tv.teg +
         * " " + tv.eval + "\n" ); for( int i = 0; i < tv.seq.length();
         * i+=70 ) { int end = Math.min(i+70,tv.seq.length());
         * textarea.append( tv.seq.substring(i, end)+"\n" ); //new
         * String( tv.seq, i, Math.min(i+70,tv.seq.length()) )+"\n"); }
         * //textarea.append( ">" + tv.cont + " " + tv.teg + " " +
         * tv.eval + "\n" + tv.seq + "\n" ); } } } }
         */
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);
    });

    /*
     * final List<String> reglist = new ArrayList<String>(); final
     * Map<String,Gene> regidx = new TreeMap<String,Gene>();
     * 
     * for( Gene g : geneset.genelist ) { if( g.species != null ) { for( String key
     * : g.species.keySet() ) { Set<Tegeval> stv = g.species.get(key); for(
     * Tegeval tv : stv ) { regidx.put(tv.cont, g); } } } }
     * 
     * for( String key : regidx.keySet() ) { reglist.add(key); }
     * 
     * final JTable contigtable = new JTable();
     * contigtable.setAutoCreateRowSorter( true ); contigtable.setModel( new
     * TableModel() {
     * 
     * @Override public int getRowCount() { return reglist.size(); }
     * 
     * @Override public int getColumnCount() { return 1; }
     * 
     * @Override public String getColumnName(int columnIndex) { return
     * "Region"; }
     * 
     * @Override public Class<?> getColumnClass(int columnIndex) { return
     * String.class; }
     * 
     * @Override public boolean isCellEditable(int rowIndex, int
     * columnIndex) { return false; }
     * 
     * @Override public Object getValueAt(int rowIndex, int columnIndex) {
     * return reglist.get(rowIndex); }
     * 
     * @Override public void setValueAt(Object aValue, int rowIndex, int
     * columnIndex) { // TODO Auto-generated method stub
     * 
     * }
     * 
     * @Override public void addTableModelListener(TableModelListener l) {
     * // TODO Auto-generated method stub
     * 
     * }
     * 
     * @Override public void removeTableModelListener(TableModelListener l)
     * { // TODO Auto-generated method stub
     * 
     * } });
     * 
     * contigtable.getSelectionModel().addListSelectionListener( new
     * ListSelectionListener() {
     * 
     * @Override public void valueChanged(ListSelectionEvent e) {
     * genefilterset.clear(); int[] rr = contigtable.getSelectedRows(); for(
     * int r : rr ) { String s = (String)contigtable.getValueAt(r, 0); Gene
     * g = regidx.get( s );
     * 
     * genefilterset.add( g.index ); updateFilter(table, genefilter, label);
     * //int k = table.convertRowIndexToView(g.index); //if( k != -1
     * )table.addRowSelectionInterval(k, k); } } }); JScrollPane
     * contigscroll = new JScrollPane( contigtable );
     * 
     * JSplitPane mainsplit = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT );
     * mainsplit.setLeftComponent( contigscroll );
     * mainsplit.setRightComponent( splitpane );
     */
}

From source file:org.terentich.pram.GUIPRAM.java

private void showFileContent(File... files) {
    for (File file : files) {

        JPanel filePanel = new JPanel(new BorderLayout());
        JTextArea textbox = new JTextArea();
        filePanel.add(new JScrollPane(textbox));
        tabPane.add(file.getName(), filePanel);
        tabPane.setSelectedComponent(filePanel);

        try {/*from  w  w  w .  j av  a  2  s  .c o  m*/
            @SuppressWarnings("unchecked")
            List<String> fileContent = FileUtils.readLines(file, CharEncoding.UTF_8);

            for (String line : fileContent) {
                textbox.append(line + "\n");
            }

            textbox.setCaretPosition(0);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

From source file:org.ut.biolab.medsavant.client.variant.ImportVariantsWizard.java

private AbstractWizardPage getAddTagsPage() {
    //setup page//from w  w w  . ja v a  2s. c  o  m
    final DefaultWizardPage page = new DefaultWizardPage("Add Tags") {
        @Override
        public void setupWizardButtons() {
            fireButtonEvent(ButtonEvent.HIDE_BUTTON, ButtonNames.FINISH);
            fireButtonEvent(ButtonEvent.SHOW_BUTTON, ButtonNames.BACK);
            fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT);
        }
    };

    page.addText("Variants can be filtered by tag value in the Filter section.");
    page.addText("Add tags for this set of variants:");

    final String[] patternExamples = { "<Tag Name>", "Sequencer", "Sequencer Version", "Variant Caller",
            "Variant Caller Version", "Technician" };

    locationField = new JComboBox(patternExamples);
    locationField.setEditable(true);

    final JPanel tagContainer = new JPanel();
    ViewUtil.applyVerticalBoxLayout(tagContainer);

    final JTextField valueField = new JTextField();

    final String startingValue = "<Value>";
    valueField.setText(startingValue);

    final JTextArea ta = new JTextArea();
    ta.setRows(10);
    ta.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    ta.setEditable(false);

    JLabel button = ViewUtil.createIconButton(IconFactory.getInstance().getIcon(IconFactory.StandardIcon.ADD));
    button.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {

            if (locationField.getSelectedItem().toString().isEmpty()) {
                DialogUtils.displayError("Tag cannot be empty");
                locationField.requestFocus();
                return;
            } else if (locationField.getSelectedItem().toString().equals(patternExamples[0])) {
                DialogUtils.displayError("Enter a valid tag name");
                locationField.requestFocus();
                return;
            }

            if (valueField.getText().toString().isEmpty()) {
                DialogUtils.displayError("Value cannot be empty");
                valueField.requestFocus();
                return;
            } else if (valueField.getText().equals(startingValue)) {
                DialogUtils.displayError("Enter a valid value");
                valueField.requestFocus();
                return;
            }

            VariantTag tag = new VariantTag((String) locationField.getSelectedItem(), valueField.getText());

            variantTags.add(tag);
            ta.append(tag.toString() + "\n");
            valueField.setText("");
        }
    });

    JPanel container2 = new JPanel();
    ViewUtil.clear(container2);
    ViewUtil.applyHorizontalBoxLayout(container2);
    container2.add(locationField);
    container2.add(ViewUtil.clear(new JLabel(" = ")));
    container2.add(valueField);
    container2.add(button);

    page.addComponent(container2);
    locationField.setToolTipText("Current display range");

    locationField.setPreferredSize(LOCATION_SIZE);
    locationField.setMinimumSize(LOCATION_SIZE);

    valueField.setPreferredSize(LOCATION_SIZE);
    valueField.setMinimumSize(LOCATION_SIZE);

    page.addComponent(tagContainer);

    page.addComponent(new JScrollPane(ta));

    JButton clear = new JButton("Clear");
    clear.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            variantTags.clear();
            ta.setText("");
            addDefaultTags(variantTags, ta);
        }
    });

    addDefaultTags(variantTags, ta);

    page.addComponent(ViewUtil.alignRight(clear));

    return page;

}