Example usage for java.util.zip ZipFile getInputStream

List of usage examples for java.util.zip ZipFile getInputStream

Introduction

In this page you can find the example usage for java.util.zip ZipFile getInputStream.

Prototype

public InputStream getInputStream(ZipEntry entry) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:org.dspace.app.itemimport.ItemImportServiceImpl.java

@Override
public String unzip(File zipfile, String destDir) throws IOException {
    // 2//from www .  jav a  2 s  . c o m
    // does the zip file exist and can we write to the temp directory
    if (!zipfile.canRead()) {
        log.error("Zip file '" + zipfile.getAbsolutePath() + "' does not exist, or is not readable.");
    }

    String destinationDir = destDir;
    if (destinationDir == null) {
        destinationDir = tempWorkDir;
    }

    File tempdir = new File(destinationDir);
    if (!tempdir.isDirectory()) {
        log.error("'" + ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir")
                + "' as defined by the key 'org.dspace.app.itemexport.work.dir' in dspace.cfg "
                + "is not a valid directory");
    }

    if (!tempdir.exists() && !tempdir.mkdirs()) {
        log.error("Unable to create temporary directory: " + tempdir.getAbsolutePath());
    }
    String sourcedir = destinationDir + System.getProperty("file.separator") + zipfile.getName();
    String zipDir = destinationDir + System.getProperty("file.separator") + zipfile.getName()
            + System.getProperty("file.separator");

    // 3
    String sourceDirForZip = sourcedir;
    ZipFile zf = new ZipFile(zipfile);
    ZipEntry entry;
    Enumeration<? extends ZipEntry> entries = zf.entries();
    while (entries.hasMoreElements()) {
        entry = entries.nextElement();
        if (entry.isDirectory()) {
            if (!new File(zipDir + entry.getName()).mkdirs()) {
                log.error("Unable to create contents directory: " + zipDir + entry.getName());
            }
        } else {
            System.out.println("Extracting file: " + entry.getName());
            log.info("Extracting file: " + entry.getName());

            int index = entry.getName().lastIndexOf('/');
            if (index == -1) {
                // Was it created on Windows instead?
                index = entry.getName().lastIndexOf('\\');
            }
            if (index > 0) {
                File dir = new File(zipDir + entry.getName().substring(0, index));
                if (!dir.exists() && !dir.mkdirs()) {
                    log.error("Unable to create directory: " + dir.getAbsolutePath());
                }

                //Entries could have too many directories, and we need to adjust the sourcedir
                // file1.zip (SimpleArchiveFormat / item1 / contents|dublin_core|...
                //            SimpleArchiveFormat / item2 / contents|dublin_core|...
                // or
                // file2.zip (item1 / contents|dublin_core|...
                //            item2 / contents|dublin_core|...

                //regex supports either windows or *nix file paths
                String[] entryChunks = entry.getName().split("/|\\\\");
                if (entryChunks.length > 2) {
                    if (StringUtils.equals(sourceDirForZip, sourcedir)) {
                        sourceDirForZip = sourcedir + "/" + entryChunks[0];
                    }
                }

            }
            byte[] buffer = new byte[1024];
            int len;
            InputStream in = zf.getInputStream(entry);
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(zipDir + entry.getName()));
            while ((len = in.read(buffer)) >= 0) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.close();
        }
    }

    //Close zip file
    zf.close();

    if (!StringUtils.equals(sourceDirForZip, sourcedir)) {
        sourcedir = sourceDirForZip;
        System.out.println("Set sourceDir using path inside of Zip: " + sourcedir);
        log.info("Set sourceDir using path inside of Zip: " + sourcedir);
    }

    return sourcedir;
}

From source file:com.amalto.workbench.utils.Util.java

/**
 * DOC hbhong Comment method "unZipFile". same with unZipFile(String zipfile, String unzipdir) method except having
 * a progressMonitor/*from   w  ww  . j a va 2 s  . c  om*/
 * 
 * @param zipfile
 * @param unzipdir
 * @param totalProgress
 * @param monitor
 * @throws IOException
 * @throws Exception
 */
public static void unZipFile(String zipfile, String unzipdir, int totalProgress, IProgressMonitor monitor)
        throws IOException {
    monitor.setTaskName(Messages.Util_50);
    File unzipF = new File(unzipdir);
    if (!unzipF.exists()) {
        unzipF.mkdirs();
    }
    ZipFile zfile = null;

    try {
        zfile = new ZipFile(zipfile);
        int total = zfile.size();
        // System.out.println("zip's entry size:"+total);
        int interval, step;
        if (totalProgress / total > 0) {
            interval = 1;
            step = Math.round(totalProgress / total);
        } else {
            step = 1;
            interval = Math.round(total / totalProgress + 0.5f);
        }
        Enumeration zList = zfile.entries();
        ZipEntry ze = null;
        byte[] buf = new byte[1024];
        int tmp = 1;
        while (zList.hasMoreElements()) {
            ze = (ZipEntry) zList.nextElement();
            monitor.subTask(ze.getName());
            if (ze.isDirectory()) {
                File f = new File(unzipdir + ze.getName());
                f.mkdirs();
                continue;
            }
            unzipdir = unzipdir.replace('\\', '/');
            if (!unzipdir.endsWith("/")) { //$NON-NLS-1$
                unzipdir = unzipdir + "/"; //$NON-NLS-1$
            }
            String filename = unzipdir + ze.getName();
            File zeF = new File(filename);
            if (!zeF.getParentFile().exists()) {
                zeF.getParentFile().mkdirs();
            }

            OutputStream os = null;
            InputStream is = null;
            try {
                os = new BufferedOutputStream(new FileOutputStream(zeF));
                is = new BufferedInputStream(zfile.getInputStream(ze));
                int readLen = 0;
                while ((readLen = is.read(buf, 0, 1024)) != -1) {
                    os.write(buf, 0, readLen);
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (Exception e) {
                }
                try {
                    if (os != null) {
                        os.close();
                    }
                } catch (Exception e) {
                }

            }
            // update monitor
            if (interval == 1) {
                monitor.worked(step);
            } else {
                if (tmp >= interval) {
                    monitor.worked(step);
                    tmp = 1;
                } else {
                    tmp++;
                }
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw e;
    } finally {
        if (zfile != null) {
            try {
                zfile.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.apache.jetspeed.portlets.site.PortalSiteManager.java

private boolean unzipfile(String file, String destination, String sepreator) {
    Enumeration entries;// w  w  w .ja  v  a  2 s  .  c om
    String filePath = "";
    ZipFile zipFile = null;

    try {
        zipFile = new ZipFile(destination + sepreator + file);
        entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            filePath = destination + sepreator + entry.getName();
            createPath(filePath);

            InputStream input = null;
            OutputStream output = null;

            try {
                input = zipFile.getInputStream(entry);
                output = new FileOutputStream(filePath);
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(output);
                IOUtils.closeQuietly(input);
            }
        }
        return true;
    } catch (IOException ioe) {
        log.error("Unexpected IO exception.", ioe);
        return false;
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:dpcs.Interface.java

public Interface() {
    setIconImage(Toolkit.getDefaultToolkit().getImage(Interface.class.getResource("/graphics/Icon.png")));
    setTitle("Droid PC Suite");
    setResizable(false);//from   w  w w . j a  v a2  s. co  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:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java

/** Called when the activity is first created. */
@Override/*from  w  ww  .  j a  va  2 s . c om*/
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        ExceptionHandler.initialize(context);
        if (ExceptionHandler.needReport()) {
            final String fileName = ExceptionHandler.getBugReportFileAbsolutePath();
            final File file = new File(fileName);
            final File fileZip;
            {
                String strFileZip = file.getAbsolutePath();
                {
                    int index = strFileZip.lastIndexOf('.');
                    if (0 < index) {
                        strFileZip = strFileZip.substring(0, index);
                        strFileZip += ".zip";
                    }
                }
                Log.d(TAG, strFileZip);
                fileZip = new File(strFileZip);
                if (fileZip.exists()) {
                    fileZip.delete();
                }
            }
            if (file.exists()) {
                Log.d(TAG, file.getAbsolutePath());
                InputStream inStream = null;
                ZipOutputStream outStream = null;
                try {
                    inStream = new FileInputStream(file);
                    String strFileName = file.getAbsolutePath();
                    {
                        int index = strFileName.lastIndexOf(File.separatorChar);
                        if (0 < index) {
                            strFileName = strFileName.substring(index + 1);
                        }
                    }
                    Log.d(TAG, strFileName);

                    outStream = new ZipOutputStream(new FileOutputStream(fileZip));
                    byte[] buff = new byte[8124];
                    {
                        ZipEntry entry = new ZipEntry(strFileName);
                        outStream.putNextEntry(entry);

                        int len = 0;
                        while (0 < (len = inStream.read(buff))) {
                            outStream.write(buff, 0, len);
                        }
                        outStream.closeEntry();
                    }
                    outStream.finish();
                    outStream.flush();

                } catch (IOException e) {
                    Log.e(TAG, "got exception", e);
                } finally {
                    if (null != outStream) {
                        try {
                            outStream.close();
                        } catch (Exception e) {
                        }
                    }
                    outStream = null;

                    if (null != inStream) {
                        try {
                            inStream.close();
                        } catch (Exception e) {
                        }
                    }
                    inStream = null;
                }
                Log.i(TAG, "zip created");
            }

            if (file.exists()) {
                // upload or send e-mail
                InputStream inStream = null;
                StringBuilder sb = new StringBuilder();
                try {
                    inStream = new FileInputStream(file);
                    byte[] buff = new byte[8124];
                    int readed = 0;
                    do {
                        readed = inStream.read(buff);
                        for (int i = 0; i < readed; i++) {
                            sb.append((char) buff[i]);
                        }
                    } while (readed >= 0);

                    final String str = sb.toString();
                    Log.i(TAG, str);
                } catch (IOException e) {
                    Log.e(TAG, "got exception", e);
                } finally {
                    if (null != inStream) {
                        try {
                            inStream.close();
                        } catch (Exception e) {
                        }
                    }
                    inStream = null;
                }

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                final Locale defaultLocale = Locale.getDefault();

                String title = "";
                String message = "";
                String positive = "";
                String negative = "";

                boolean needDefaultLang = true;
                if (null != defaultLocale) {
                    if (defaultLocale.equals(Locale.JAPANESE) || defaultLocale.equals(Locale.JAPAN)) {
                        title = "";
                        message = "?????????";
                        positive = "?";
                        negative = "";
                        needDefaultLang = false;
                    }
                }
                if (needDefaultLang) {
                    title = "ERROR";
                    message = "Got unexpected error. Do you want to send information of error.";
                    positive = "Send";
                    negative = "Cancel";
                }
                alertDialog.setTitle(title);
                alertDialog.setMessage(message);
                alertDialog.setPositiveButton(positive + " mail", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface di, int i) {
                        DefaultUploaderMailClient.upload(context, file,
                                new String[] { "diverKon+sakura@gmail.com" });
                    }
                });
                alertDialog.setNeutralButton(positive + " http", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface di, int i) {
                        DefaultUploaderWeb.upload(ExceptionHandlerReportApp.this, fileZip,
                                "http://kkkon.sakura.ne.jp/android/bug");
                    }
                });
                alertDialog.setNegativeButton(negative, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface di, int i) {
                        ExceptionHandler.clearReport();
                    }
                });
                alertDialog.show();
            }
            // TODO separate activity for crash report
            //DefaultCheckerAPK.checkAPK( this, null );
        }
        ExceptionHandler.registHandler();
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("ExceptionHandler");
    layout.addView(tv);

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    Button btn2 = new Button(this);
    btn2.setText("reinstall apk");
    btn2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            boolean foundApk = false;
            {
                final String apkPath = context.getPackageCodePath(); // API8
                Log.d(TAG, "PackageCodePath: " + apkPath);
                final File fileApk = new File(apkPath);
                if (fileApk.exists()) {
                    foundApk = true;

                    Intent promptInstall = new Intent(Intent.ACTION_VIEW);
                    promptInstall.setDataAndType(Uri.fromFile(fileApk),
                            "application/vnd.android.package-archive");
                    promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(promptInstall);
                }
            }

            if (false == foundApk) {
                for (int i = 0; i < 10; ++i) {
                    File fileApk = new File("/data/app/" + context.getPackageName() + "-" + i + ".apk");
                    Log.d(TAG, "check apk:" + fileApk.getAbsolutePath());
                    if (fileApk.exists()) {
                        Log.i(TAG, "apk found. path=" + fileApk.getAbsolutePath());
                        /*
                         * // require parmission
                        {
                        final String strCmd = "pm install -r " + fileApk.getAbsolutePath();
                        try
                        {
                            Runtime.getRuntime().exec( strCmd );
                        }
                        catch ( IOException e )
                        {
                            Log.e( TAG, "got exception", e );
                        }
                        }
                        */
                        Intent promptInstall = new Intent(Intent.ACTION_VIEW);
                        promptInstall.setDataAndType(Uri.fromFile(fileApk),
                                "application/vnd.android.package-archive");
                        promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(promptInstall);
                        break;
                    }
                }
            }
        }
    });
    layout.addView(btn2);

    Button btn3 = new Button(this);
    btn3.setText("check apk");
    btn3.setOnClickListener(new View.OnClickListener() {
        private boolean checkApk(final File fileApk, final ZipEntryFilter filter) {
            final boolean[] result = new boolean[1];
            result[0] = true;

            final Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    if (fileApk.exists()) {
                        ZipFile zipFile = null;
                        try {
                            zipFile = new ZipFile(fileApk);
                            List<ZipEntry> list = new ArrayList<ZipEntry>(zipFile.size());
                            for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) {
                                ZipEntry ent = e.nextElement();
                                Log.d(TAG, ent.getName());
                                Log.d(TAG, "" + ent.getSize());
                                final boolean accept = filter.accept(ent);
                                if (accept) {
                                    list.add(ent);
                                }
                            }

                            Log.d(TAG, Build.CPU_ABI); // API 4
                            Log.d(TAG, Build.CPU_ABI2); // API 8

                            final String[] abiArray = { Build.CPU_ABI // API 4
                                    , Build.CPU_ABI2 // API 8
                            };

                            String abiMatched = null;
                            {
                                boolean foundMatched = false;
                                for (final String abi : abiArray) {
                                    if (null == abi) {
                                        continue;
                                    }
                                    if (0 == abi.length()) {
                                        continue;
                                    }

                                    for (final ZipEntry entry : list) {
                                        Log.d(TAG, entry.getName());

                                        final String prefixABI = "lib/" + abi + "/";
                                        if (entry.getName().startsWith(prefixABI)) {
                                            abiMatched = abi;
                                            foundMatched = true;
                                            break;
                                        }
                                    }

                                    if (foundMatched) {
                                        break;
                                    }
                                }
                            }
                            Log.d(TAG, "matchedAbi=" + abiMatched);

                            if (null != abiMatched) {
                                boolean needReInstall = false;

                                for (final ZipEntry entry : list) {
                                    Log.d(TAG, entry.getName());

                                    final String prefixABI = "lib/" + abiMatched + "/";
                                    if (entry.getName().startsWith(prefixABI)) {
                                        final String jniName = entry.getName().substring(prefixABI.length());
                                        Log.d(TAG, "jni=" + jniName);

                                        final String strFileDst = context.getApplicationInfo().nativeLibraryDir
                                                + "/" + jniName;
                                        Log.d(TAG, strFileDst);
                                        final File fileDst = new File(strFileDst);
                                        if (!fileDst.exists()) {
                                            Log.w(TAG, "needReInstall: content missing " + strFileDst);
                                            needReInstall = true;
                                        } else {
                                            assert (entry.getSize() <= Integer.MAX_VALUE);
                                            if (fileDst.length() != entry.getSize()) {
                                                Log.w(TAG, "needReInstall: size broken " + strFileDst);
                                                needReInstall = true;
                                            } else {
                                                //org.apache.commons.io.IOUtils.contentEquals( zipFile.getInputStream( entry ), new FileInputStream(fileDst) );

                                                final int size = (int) entry.getSize();
                                                byte[] buffSrc = new byte[size];

                                                {
                                                    InputStream inStream = null;
                                                    try {
                                                        inStream = zipFile.getInputStream(entry);
                                                        int pos = 0;
                                                        {
                                                            while (pos < size) {
                                                                final int ret = inStream.read(buffSrc, pos,
                                                                        size - pos);
                                                                if (ret <= 0) {
                                                                    break;
                                                                }
                                                                pos += ret;
                                                            }
                                                        }
                                                    } catch (IOException e) {
                                                        Log.d(TAG, "got exception", e);
                                                    } finally {
                                                        if (null != inStream) {
                                                            try {
                                                                inStream.close();
                                                            } catch (Exception e) {
                                                            }
                                                        }
                                                    }
                                                }
                                                byte[] buffDst = new byte[(int) fileDst.length()];
                                                {
                                                    InputStream inStream = null;
                                                    try {
                                                        inStream = new FileInputStream(fileDst);
                                                        int pos = 0;
                                                        {
                                                            while (pos < size) {
                                                                final int ret = inStream.read(buffDst, pos,
                                                                        size - pos);
                                                                if (ret <= 0) {
                                                                    break;
                                                                }
                                                                pos += ret;
                                                            }
                                                        }
                                                    } catch (IOException e) {
                                                        Log.d(TAG, "got exception", e);
                                                    } finally {
                                                        if (null != inStream) {
                                                            try {
                                                                inStream.close();
                                                            } catch (Exception e) {
                                                            }
                                                        }
                                                    }
                                                }

                                                if (Arrays.equals(buffSrc, buffDst)) {
                                                    Log.d(TAG, " content equal " + strFileDst);
                                                    // OK
                                                } else {
                                                    Log.w(TAG, "needReInstall: content broken " + strFileDst);
                                                    needReInstall = true;
                                                }
                                            }

                                        }

                                    }
                                } // for ZipEntry

                                if (needReInstall) {
                                    // need call INSTALL APK
                                    Log.w(TAG, "needReInstall apk");
                                    result[0] = false;
                                } else {
                                    Log.d(TAG, "no need ReInstall apk");
                                }
                            }

                        } catch (IOException e) {
                            Log.d(TAG, "got exception", e);
                        } finally {
                            if (null != zipFile) {
                                try {
                                    zipFile.close();
                                } catch (Exception e) {
                                }
                            }
                        }
                    }
                }

            });
            thread.setName("check jni so");

            thread.start();
            /*
            while ( thread.isAlive() )
            {
            Log.d( TAG, "check thread.id=" + android.os.Process.myTid() + ",state=" + thread.getState() );
            if ( ! thread.isAlive() )
            {
                break;
            }
            AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this );
            final Locale defaultLocale = Locale.getDefault();
                    
            String title = "";
            String message = "";
            String positive = "";
            String negative = "";
                    
            boolean needDefaultLang = true;
            if ( null != defaultLocale )
            {
                if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) )
                {
                    title = "";
                    message = "???????";
                    positive = "?";
                    negative = "";
                    needDefaultLang = false;
                }
            }
            if ( needDefaultLang )
            {
                title = "INFO";
                message = "Now checking installation. Cancel check?";
                positive = "Wait";
                negative = "Cancel";
            }
            alertDialog.setTitle( title );
            alertDialog.setMessage( message );
            alertDialog.setPositiveButton( positive, null);
            alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() {
                    
                @Override
                public void onClick(DialogInterface di, int i) {
                    if ( thread.isAlive() )
                    {
                        Log.d( TAG, "request interrupt" );
                        thread.interrupt();
                    }
                    else
                    {
                        // nothing
                    }
                }
            } );
                    
            if ( ! thread.isAlive() )
            {
                break;
            }
                    
            alertDialog.show();
                    
            if ( ! Thread.State.RUNNABLE.equals(thread.getState()) )
            {
                break;
            }
                    
            }
            */

            try {
                thread.join();
            } catch (InterruptedException e) {
                Log.d(TAG, "got exception", e);
            }

            return result[0];
        }

        @Override
        public void onClick(View view) {
            boolean foundApk = false;
            {
                final String apkPath = context.getPackageCodePath(); // API8
                Log.d(TAG, "PackageCodePath: " + apkPath);
                final File fileApk = new File(apkPath);
                this.checkApk(fileApk, new ZipEntryFilter() {
                    @Override
                    public boolean accept(ZipEntry entry) {
                        if (entry.isDirectory()) {
                            return false;
                        }

                        final String filename = entry.getName();
                        if (filename.startsWith("lib/")) {
                            return true;
                        }

                        return false;
                    }
                });
            }

        }
    });
    layout.addView(btn3);

    Button btn4 = new Button(this);
    btn4.setText("print dir and path");
    btn4.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            {
                final File file = context.getCacheDir();
                Log.d(TAG, "Ctx.CacheDir=" + file.getAbsoluteFile());
            }
            {
                final File file = context.getExternalCacheDir(); // API 8
                if (null == file) {
                    // no permission
                    Log.d(TAG, "Ctx.ExternalCacheDir=");
                } else {
                    Log.d(TAG, "Ctx.ExternalCacheDir=" + file.getAbsolutePath());
                }
            }
            {
                final File file = context.getFilesDir();
                Log.d(TAG, "Ctx.FilesDir=" + file.getAbsolutePath());
            }
            {
                final String value = context.getPackageResourcePath();
                Log.d(TAG, "Ctx.PackageResourcePath=" + value);
            }
            {
                final String[] files = context.fileList();
                if (null == files) {
                    Log.d(TAG, "Ctx.fileList=" + files);
                } else {
                    for (final String filename : files) {
                        Log.d(TAG, "Ctx.fileList=" + filename);
                    }
                }
            }

            {
                final File file = Environment.getDataDirectory();
                Log.d(TAG, "Env.DataDirectory=" + file.getAbsolutePath());
            }
            {
                final File file = Environment.getDownloadCacheDirectory();
                Log.d(TAG, "Env.DownloadCacheDirectory=" + file.getAbsolutePath());
            }
            {
                final File file = Environment.getExternalStorageDirectory();
                Log.d(TAG, "Env.ExternalStorageDirectory=" + file.getAbsolutePath());
            }
            {
                final File file = Environment.getRootDirectory();
                Log.d(TAG, "Env.RootDirectory=" + file.getAbsolutePath());
            }
            {
                final ApplicationInfo appInfo = context.getApplicationInfo();
                Log.d(TAG, "AppInfo.dataDir=" + appInfo.dataDir);
                Log.d(TAG, "AppInfo.nativeLibraryDir=" + appInfo.nativeLibraryDir); // API 9
                Log.d(TAG, "AppInfo.publicSourceDir=" + appInfo.publicSourceDir);
                {
                    final String[] sharedLibraryFiles = appInfo.sharedLibraryFiles;
                    if (null == sharedLibraryFiles) {
                        Log.d(TAG, "AppInfo.sharedLibraryFiles=" + sharedLibraryFiles);
                    } else {
                        for (final String fileName : sharedLibraryFiles) {
                            Log.d(TAG, "AppInfo.sharedLibraryFiles=" + fileName);
                        }
                    }
                }
                Log.d(TAG, "AppInfo.sourceDir=" + appInfo.sourceDir);
            }
            {
                Log.d(TAG, "System.Properties start");
                final Properties properties = System.getProperties();
                if (null != properties) {
                    for (final Object key : properties.keySet()) {
                        String value = properties.getProperty((String) key);
                        Log.d(TAG, " key=" + key + ",value=" + value);
                    }
                }
                Log.d(TAG, "System.Properties end");
            }
            {
                Log.d(TAG, "System.getenv start");
                final Map<String, String> mapEnv = System.getenv();
                if (null != mapEnv) {
                    for (final Map.Entry<String, String> entry : mapEnv.entrySet()) {
                        final String key = entry.getKey();
                        final String value = entry.getValue();
                        Log.d(TAG, " key=" + key + ",value=" + value);
                    }
                }
                Log.d(TAG, "System.getenv end");
            }
        }
    });
    layout.addView(btn4);

    Button btn5 = new Button(this);
    btn5.setText("check INSTALL_NON_MARKET_APPS");
    btn5.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            SettingsCompat.initialize(context);
            if (SettingsCompat.isAllowedNonMarketApps()) {
                Log.d(TAG, "isAllowdNonMarketApps=true");
            } else {
                Log.d(TAG, "isAllowdNonMarketApps=false");
            }
        }
    });
    layout.addView(btn5);

    Button btn6 = new Button(this);
    btn6.setText("send email");
    btn6.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent mailto = new Intent();
            mailto.setAction(Intent.ACTION_SENDTO);
            mailto.setType("message/rfc822");
            mailto.setData(Uri.parse("mailto:"));
            mailto.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
            mailto.putExtra(Intent.EXTRA_SUBJECT, "[BugReport] " + context.getPackageName());
            mailto.putExtra(Intent.EXTRA_TEXT, "body text");
            //mailto.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
            //context.startActivity( mailto );
            Intent intent = Intent.createChooser(mailto, "Send Email");
            if (null != intent) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
                    context.startActivity(intent);
                } catch (android.content.ActivityNotFoundException e) {
                    Log.d(TAG, "got Exception", e);
                }
            }
        }
    });
    layout.addView(btn6);

    Button btn7 = new Button(this);
    btn7.setText("upload http thread");
    btn7.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Log.d(TAG, "brd=" + Build.BRAND);
            Log.d(TAG, "prd=" + Build.PRODUCT);

            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
            Log.d(TAG, "fng=" + Build.FINGERPRINT);
            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

            final Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    Log.d(TAG, "upload thread tid=" + android.os.Process.myTid());
                    try {
                        HttpPost httpPost = new HttpPost("http://kkkon.sakura.ne.jp/android/bug");
                        //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                        httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                new Integer(5 * 1000));
                        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                new Integer(5 * 1000));
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        // <uses-permission android:name="android.permission.INTERNET"/>
                        // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                        HttpResponse response = httpClient.execute(httpPost);
                        Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                    } catch (Exception e) {
                        Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                    }
                    Log.d(TAG, "upload finish");
                }
            });
            thread.setName("upload crash");

            thread.start();
            /*
            while ( thread.isAlive() )
            {
            Log.d( TAG, "thread tid=" + android.os.Process.myTid() + ",state=" + thread.getState() );
            if ( ! thread.isAlive() )
            {
                break;
            }
            AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this );
            final Locale defaultLocale = Locale.getDefault();
                    
            String title = "";
            String message = "";
            String positive = "";
            String negative = "";
                    
            boolean needDefaultLang = true;
            if ( null != defaultLocale )
            {
                if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) )
                {
                    title = "";
                    message = "???????";
                    positive = "?";
                    negative = "";
                    needDefaultLang = false;
                }
            }
            if ( needDefaultLang )
            {
                title = "INFO";
                message = "Now uploading error information. Cancel upload?";
                positive = "Wait";
                negative = "Cancel";
            }
            alertDialog.setTitle( title );
            alertDialog.setMessage( message );
            alertDialog.setPositiveButton( positive, null);
            alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() {
                    
                @Override
                public void onClick(DialogInterface di, int i) {
                    if ( thread.isAlive() )
                    {
                        Log.d( TAG, "request interrupt" );
                        thread.interrupt();
                    }
                    else
                    {
                        // nothing
                    }
                }
            } );
                    
            if ( ! thread.isAlive() )
            {
                break;
            }
                    
            alertDialog.show();
                    
            if ( ! Thread.State.RUNNABLE.equals(thread.getState()) )
            {
                break;
            }
                    
            }
            */

            /*
            try
            {
            thread.join(); // must call. leak handle...
            }
            catch ( InterruptedException e )
            {
            Log.d( TAG, "got Exception", e );
            }
            */
        }
    });
    layout.addView(btn7);

    Button btn8 = new Button(this);
    btn8.setText("upload http AsyncTask");
    btn8.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                @Override
                protected Boolean doInBackground(String... paramss) {
                    Boolean result = true;
                    Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                    try {
                        //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                        Log.d(TAG, "fng=" + Build.FINGERPRINT);
                        final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                        list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                        HttpPost httpPost = new HttpPost(paramss[0]);
                        //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                        httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                new Integer(5 * 1000));
                        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                new Integer(5 * 1000));
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        // <uses-permission android:name="android.permission.INTERNET"/>
                        // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                        HttpResponse response = httpClient.execute(httpPost);
                        Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                    } catch (Exception e) {
                        Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                        result = false;
                    }
                    Log.d(TAG, "upload finish");
                    return result;
                }

            };

            asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
            asyncTask.isCancelled();
        }
    });
    layout.addView(btn8);

    Button btn9 = new Button(this);
    btn9.setText("call checkAPK");
    btn9.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final boolean result = DefaultCheckerAPK.checkAPK(ExceptionHandlerReportApp.this, null);
            Log.i(TAG, "checkAPK result=" + result);
        }
    });
    layout.addView(btn9);

    setContentView(layout);
}

From source file:jhplot.P1D.java

/**
 * Read P1D from a Zipped file. The old content will be lost. The file
 * should contain 2, or 4, or 6, or 10 columns: 1) x,y: data without any
 * errors 2) x,y, y(upper), y(lower) - data with 1st level errors on Y 3)
 * x,y, x(left), x(right), y(upper), y(lower) - data with 1st level errors
 * on X and Y 4) x,y, x(left), x(right), y(upper), y(lower), x(leftSys),
 * x(rightSys), y(upperSys), y(lowerSys) - data with X and Y and 1st and 2nd
 * level errors. Comment lines starting with "#" and "*" are ignored.
 * // w  ww . j  a v  a  2 s  . c  o m
 * @param sfile
 *            File name with input (extension zip)
 * @return zero if success
 */
public int readZip(String sfile) {

    // clear all data
    clear();

    try {
        ZipFile zf = new ZipFile(sfile);
        Enumeration entries = zf.entries();
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

        while (entries.hasMoreElements()) {
            ZipEntry ze = (ZipEntry) entries.nextElement();
            // System.out.println("Read " + ze.getName() + "?");
            String inputLine = input.readLine();
            if (inputLine.equalsIgnoreCase("yes")) {
                long size = ze.getSize();
                if (size > 0) {
                    // System.out.println("Length is " + size);

                    BufferedReader br = new BufferedReader(new InputStreamReader(zf.getInputStream(ze)));

                    read(br); // read data
                    br.close();
                }
            }
        }

    } catch (FileNotFoundException e) {
        ErrorMessage("File not found:" + sfile);
        e.printStackTrace();
        return 1;
    } catch (IOException e) {
        e.printStackTrace();
        return 2;
    }

    return 0;

}

From source file:com.pari.pcb.zip.ZIPProcessor.java

private ZIPFileType processZipEntryInternal(InputStream inStream, String fileName, boolean ignoreBanner,
        final ZipEntry entry, final ZipFile inZip) throws IOException {
    // logger.debug("" + fileName + "...");
    FileInfo fileInfo = new FileInfo();
    ZIPFileResult fileResult = new ZIPFileResult(fileName);
    long start = System.currentTimeMillis();
    boolean insideBanner = false;
    int linesInsideBanner = 0;

    fileInfo.fileType = ZIPFileType.UNKNOWN;
    String line = null;//w  w w.  j av a 2s.c o m
    DSPHandler dspHandler = new ZipImportDSPHandler();
    DSPZipImportData data = new DSPZipImportData();

    List<ScriptInfo> sysScripts = DeviceScriptManagerImpl.getInstance()
            .getSystemDefinedZipPackages(PackageType.ZipInventory, "System");
    dspHandler.handlePackages(data, sysScripts);

    List<ScriptInfo> userScripts = DeviceScriptManagerImpl.getInstance()
            .getUserDefinedZipPackages(PackageType.ZipInventory, customerId, "User");
    dspHandler.handlePackages(data, userScripts);

    BufferedReader br = new BufferedReader(new InputStreamReader(inStream, charset));
    int lineno = 0;
    while ((line = br.readLine()) != null) {
        lineno++;
        if (line.length() >= 35000) // CSCup58209 - Changed from 30000 to 35000 as some lines were very lengthy.
        {
            fileResult.fileType = ZIPFileType.UNKNOWN;
            fileResult.msg = "Not an ASCII file.";
            this.errMsg = "Length of one or more lines is greater than 35K";
            fileResultMap.put(fileName, fileResult);
            // Most probably, not an ascii file
            logger.debug("\tNot an ASCII file. Length of one or more lines is greater than 35K. Done in "
                    + (System.currentTimeMillis() - start) + " msecs");

            return ZIPFileType.UNKNOWN;
        }

        if (!ignoreBanner) {
            // note: If the configuration is
            // pulled using tftp copy, then the banner contains some unprintable characters (ETX=003)
            // instead of ^C.
            if (insideBanner) {
                if (bannerEndPattern.matcher(line).matches()) {
                    insideBanner = false;
                } else {
                    int idx = line.indexOf(3);
                    if (idx >= 0) {
                        insideBanner = false;
                    }
                }
                linesInsideBanner++;
                continue;
            } else {
                if (bannerStartPattern.matcher(line).matches()) {
                    insideBanner = true;
                    if (bannerSameLinePattern.matcher(line).matches()) {
                        insideBanner = false;
                    }
                } else if (bannerStartPattern1.matcher(line).matches()) {
                    int idx1 = line.indexOf(3);
                    if (idx1 >= 0) {
                        insideBanner = true;
                        int idx2 = line.lastIndexOf(3);
                        if (idx2 > idx1) {
                            insideBanner = false;
                        }
                    }
                    continue;
                }
            }
        }

        if (data != null) {
            Map<String, Object> map = data.getAttributes();
            Iterator entries = map.entrySet().iterator();
            while (entries.hasNext()) {
                Matcher m;

                Entry thisEntry = (Entry) entries.next();
                String pattern = thisEntry.getKey().toString();
                m = Pattern.compile(pattern).matcher(line);
                if (m.matches()) {
                    DevProperties prop = (DevProperties) thisEntry.getValue();
                    Map<String, String> prop1 = prop.getProperty();
                    Iterator it = prop1.entrySet().iterator();
                    while (it.hasNext()) {
                        Entry thisEntry1 = (Entry) it.next();

                        if (thisEntry1.getKey().toString().equals("fileType")) {
                            if (prop.getProperty("fileType").equals("ShowTech")) {
                                fileInfo.fileType = ZIPFileType.SHOW_TECH;

                            }

                        }

                    }

                }
            }
        }

        if (fileInfo.fileType == ZIPFileType.SHOW_TECH) {
            break;
        }

        Matcher m = showTechCommandPattern.matcher(line);
        boolean matched = m.matches();
        if (matched) {
            String cmd = m.group(1);
            String cmdLC = cmd.toLowerCase();
            if (cmdLC.contains("show version") || cmdLC.contains("show running-")
                    || cmdLC.contains("show config")) {
                fileInfo.fileType = ZIPFileType.SHOW_TECH;
                // logger.debug("Found out to be show tech file.");
                // If we figure out it is a Show tech output, that overrides everything.
                break;
            }
        }
        m = nxosshowTechCommandPattern.matcher(line);
        matched = m.matches();
        if (matched) {
            String cmd = m.group(1);
            String cmdLC = cmd.toLowerCase();
            if (cmdLC.contains("show version") || cmdLC.contains("show running-")
                    || cmdLC.contains("show config")) {
                fileInfo.fileType = ZIPFileType.SHOW_TECH;
                // If we figure out it is a Show tech output, that overrides everything.
                break;
            }
        }
        m = ipsshowTechCommandPattern.matcher(line);
        matched = m.matches();
        if (matched) {
            String cmd = m.group(1);
            String cmdLC = cmd.toLowerCase();
            if (cmdLC.contains("show version") || cmdLC.contains("show configuration")) {
                fileInfo.fileType = ZIPFileType.SHOW_TECH;
                // If we figure out it is a Show tech output, that overrides everything.
                break;
            }
        }

        handleConfigurationLine(fileInfo, line, data);

        handleVersionLine(fileInfo, line, data);

    }
    if (!ignoreBanner) {
        if (insideBanner) {
            // Something is wrong! We never found the end of a banner. Something wrong with
            // the end-of-banner detection code. Let us try it one more time, this time
            // let us ignore the banner.. just in case.
            logger.warn("File: " + fileName + " Unable to find end of banner commands. "
                    + "Running once more and ignoring banner commands now.");
            try {
                inStream.close();
            } catch (Exception ex) {
            }
            inStream = inZip.getInputStream(entry);
            return processZipEntryInternal(inStream, fileName, true, entry, inZip);
        } else {
            if (lineno > 0) {
                int percentLinesInsideBanner = (linesInsideBanner * 100) / lineno;
                if (percentLinesInsideBanner > 85) {
                    // Something wrong. Somehow, looks like 85% of the file is under banner commands!
                    // Let us try it one more time, this time
                    // let us ignore the banner.. just in case.
                    logger.warn("File: " + fileName + " major portion of the file: (" + percentLinesInsideBanner
                            + "%) "
                            + "is found to be inside banner commands. Trying again by ignoring the banners.");
                    try {
                        inStream.close();
                    } catch (Exception ex) {
                    }
                    inStream = inZip.getInputStream(entry);
                    return processZipEntryInternal(inStream, fileName, true, entry, inZip);
                }
            }
        }
    }
    try {
        inStream.close();
    } catch (Exception ex) {

    }
    switch (fileInfo.fileType) {
    case CONFIG: {
        if (fileInfo.ostype != null) {
            if (fileInfo.ostype.equals("CATOS")) {
                // BUG: 0005383
                if (fileInfo.hostName == null || fileInfo.hostName.trim().length() == 0) {
                    fileInfo.hostName = "Switch";
                }
                // END BUG: 0005383
                configFileInfoMap.put(fileName, fileInfo);
            }
            if (fileInfo.ostype.equals("FWSM")) {
                if (fileInfo.hostName == null || fileInfo.hostName.trim().length() == 0) {
                    fileInfo.hostName = "FWSM";
                }
            }
            if (fileInfo.ostype.equals("PIX")) {
                if (fileInfo.hostName == null || fileInfo.hostName.trim().length() == 0) {
                    fileInfo.hostName = "PIX";
                }
            }
            if (fileInfo.ostype.equals("ASA")) {
                if (fileInfo.hostName == null || fileInfo.hostName.trim().length() == 0) {
                    fileInfo.hostName = "ASA";
                }
            }
            if (fileInfo.ostype.equals("WLC")) {
                if (fileInfo.hostName == null || fileInfo.hostName.trim().length() == 0) {
                    fileInfo.hostName = "Cisco Controller";
                }
            }
        }
        processConiguration(fileName, fileInfo, entry, inZip);
        logger.debug("\t" + fileInfo.ostype + " Configuration. Done in " + (System.currentTimeMillis() - start)
                + " msecs");
        return fileInfo.fileType;
    }
    case VERSION: {
        fileInfo.entryName = entry.getName();
        if ((fileInfo.ostype != null) && (fileInfo.ostype.equals("CATOS"))) {
            versionFileInfoMap.put(fileName, fileInfo);
        }
        processVersionFile(fileName, fileInfo, entry, inZip);
        logger.debug("\t" + fileInfo.ostype + " Version. Done in " + (System.currentTimeMillis() - start)
                + " msecs");
        return fileInfo.fileType;
    }
    case SHOW_TECH: {
        try {
            InputStreamGetter isGetter = new InputStreamGetter() {

                @Override
                public InputStream getInputStream() throws IOException {
                    return inZip.getInputStream(entry);
                }
            };
            processShowTechFile(fileName, ignoreBanner, isGetter, data);
        } catch (Exception ex) {
            logger.error("Exception while processing show tech file: " + fileName, ex);
            fileResult.fileType = ZIPFileType.UNKNOWN;
            fileResult.msg = "Exception while processing file:" + ex.getMessage();
            fileResultMap.put(fileName, fileResult);
            return fileInfo.fileType;
        }
        // logger.debug("\t show tech. Done in " + (System.currentTimeMillis() - start) + " msecs");
        return fileInfo.fileType;
    }
    case UNKNOWN:
    }
    fileResult.fileType = ZIPFileType.UNKNOWN;
    fileResult.msg = "Not a valid file.";
    fileResultMap.put(fileName, fileResult);

    logger.debug("\t Invalid file. Done in " + (System.currentTimeMillis() - start) + " msecs");
    return fileInfo.fileType;
}

From source file:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Import data from a zip archive to a database table
 *
 * @param stmt               statement to use
 * @param zip                zip archive containing the zip entry
 * @param ze                 zip entry within the archive
 * @param xpath              xpath containing the entries to import
 * @param table              name of the table
 * @param executeInsertPhase execute the insert phase?
 * @param executeUpdatePhase execute the update phase?
 * @param updateColumns      columns that should be set to <code>null</code> in a first pass (insert)
 *                           and updated to the provided values in a second pass (update),
 *                           columns that should be used in the where clause have to be prefixed
 *                           with "KEY:", to assign a default value use the expression "columnname:default value",
 *                           if the default value is "@", it will be a negative counter starting at 0, decreasing.
 *                           If the default value starts with "%", it will be set to the column following the "%"
 *                           character in the first pass
 * @throws Exception on errors/*from  w w  w .  j  a  v a 2s  .co  m*/
 */
protected void importTable(Statement stmt, final ZipFile zip, final ZipEntry ze, final String xpath,
        final String table, final boolean executeInsertPhase, final boolean executeUpdatePhase,
        final String... updateColumns) throws Exception {
    //analyze the table
    final ResultSet rs = stmt.executeQuery("SELECT * FROM " + table + " WHERE 1=2");
    StringBuilder sbInsert = new StringBuilder(500);
    StringBuilder sbUpdate = updateColumns.length > 0 ? new StringBuilder(500) : null;
    if (rs == null)
        throw new IllegalArgumentException("Can not analyze table [" + table + "]!");
    sbInsert.append("INSERT INTO ").append(table).append(" (");
    final ResultSetMetaData md = rs.getMetaData();
    final Map<String, ColumnInfo> updateClauseColumns = updateColumns.length > 0
            ? new HashMap<String, ColumnInfo>(md.getColumnCount())
            : null;
    final Map<String, ColumnInfo> updateSetColumns = updateColumns.length > 0
            ? new LinkedHashMap<String, ColumnInfo>(md.getColumnCount())
            : null;
    final Map<String, String> presetColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null;
    //preset to a referenced column (%column syntax)
    final Map<String, String> presetRefColumns = updateColumns.length > 0 ? new HashMap<String, String>(10)
            : null;
    final Map<String, Integer> counters = updateColumns.length > 0 ? new HashMap<String, Integer>(10) : null;
    final Map<String, ColumnInfo> insertColumns = new HashMap<String, ColumnInfo>(
            md.getColumnCount() + (counters != null ? counters.size() : 0));
    int insertIndex = 1;
    int updateSetIndex = 1;
    int updateClauseIndex = 1;
    boolean first = true;
    for (int i = 0; i < md.getColumnCount(); i++) {
        final String currCol = md.getColumnName(i + 1).toLowerCase();
        if (updateColumns.length > 0) {
            boolean abort = false;
            for (String col : updateColumns) {
                if (col.indexOf(':') > 0 && !col.startsWith("KEY:")) {
                    String value = col.substring(col.indexOf(':') + 1);
                    col = col.substring(0, col.indexOf(':'));
                    if ("@".equals(value)) {
                        if (currCol.equalsIgnoreCase(col)) {
                            counters.put(col, 0);
                            insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
                            sbInsert.append(',').append(currCol);
                        }
                    } else if (value.startsWith("%")) {
                        if (currCol.equalsIgnoreCase(col)) {
                            presetRefColumns.put(col, value.substring(1));
                            insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
                            sbInsert.append(',').append(currCol);
                            //                                System.out.println("==> adding presetRefColumn "+col+" with value of "+value.substring(1));
                        }
                    } else if (!presetColumns.containsKey(col))
                        presetColumns.put(col, value);
                }
                if (currCol.equalsIgnoreCase(col)) {
                    abort = true;
                    updateSetColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), updateSetIndex++));
                    break;
                }
            }
            if (abort)
                continue;
        }
        if (first) {
            first = false;
        } else
            sbInsert.append(',');
        sbInsert.append(currCol);
        insertColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
    }
    if (updateColumns.length > 0 && executeUpdatePhase) {
        sbUpdate.append("UPDATE ").append(table).append(" SET ");
        int counter = 0;
        for (String updateColumn : updateSetColumns.keySet()) {
            if (counter++ > 0)
                sbUpdate.append(',');
            sbUpdate.append(updateColumn).append("=?");
        }
        sbUpdate.append(" WHERE ");
        boolean hasKeyColumn = false;
        for (String col : updateColumns) {
            if (!col.startsWith("KEY:"))
                continue;
            hasKeyColumn = true;
            String keyCol = col.substring(4);
            for (int i = 0; i < md.getColumnCount(); i++) {
                if (!md.getColumnName(i + 1).equalsIgnoreCase(keyCol))
                    continue;
                updateClauseColumns.put(keyCol, new ColumnInfo(md.getColumnType(i + 1), updateClauseIndex++));
                sbUpdate.append(keyCol).append("=? AND ");
                break;
            }

        }
        if (!hasKeyColumn)
            throw new IllegalArgumentException("Update columns require a KEY!");
        sbUpdate.delete(sbUpdate.length() - 5, sbUpdate.length()); //remove trailing " AND "
        //"shift" clause indices
        for (String col : updateClauseColumns.keySet()) {
            GenericDivisionImporter.ColumnInfo ci = updateClauseColumns.get(col);
            ci.index += (updateSetIndex - 1);
        }
    }
    if (presetColumns != null) {
        for (String key : presetColumns.keySet())
            sbInsert.append(',').append(key);
    }
    sbInsert.append(")VALUES(");
    for (int i = 0; i < insertColumns.size(); i++) {
        if (i > 0)
            sbInsert.append(',');
        sbInsert.append('?');
    }
    if (presetColumns != null) {
        for (String key : presetColumns.keySet())
            sbInsert.append(',').append(presetColumns.get(key));
    }
    sbInsert.append(')');
    if (DBG) {
        LOG.info("Insert statement:\n" + sbInsert.toString());
        if (updateColumns.length > 0)
            LOG.info("Update statement:\n" + sbUpdate.toString());
    }
    //build a map containing all nodes that require attributes
    //this allows for matching simple xpath queries like "flatstorages/storage[@name='FX_FLAT_STORAGE']/data"
    final Map<String, List<String>> queryAttributes = new HashMap<String, List<String>>(5);
    for (String pElem : xpath.split("/")) {
        if (!(pElem.indexOf('@') > 0 && pElem.indexOf('[') > 0))
            continue;
        List<String> att = new ArrayList<String>(5);
        for (String pAtt : pElem.split("@")) {
            if (!(pAtt.indexOf('=') > 0))
                continue;
            att.add(pAtt.substring(0, pAtt.indexOf('=')));
        }
        queryAttributes.put(pElem.substring(0, pElem.indexOf('[')), att);
    }
    final PreparedStatement psInsert = stmt.getConnection().prepareStatement(sbInsert.toString());
    final PreparedStatement psUpdate = updateColumns.length > 0 && executeUpdatePhase
            ? stmt.getConnection().prepareStatement(sbUpdate.toString())
            : null;
    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final DefaultHandler handler = new DefaultHandler() {
            private String currentElement = null;
            private Map<String, String> data = new HashMap<String, String>(10);
            private StringBuilder sbData = new StringBuilder(10000);
            boolean inTag = false;
            boolean inElement = false;
            int counter;
            List<String> path = new ArrayList<String>(10);
            StringBuilder currPath = new StringBuilder(100);
            boolean insertMode = true;

            /**
             * {@inheritDoc}
             */
            @Override
            public void startDocument() throws SAXException {
                counter = 0;
                inTag = false;
                inElement = false;
                path.clear();
                currPath.setLength(0);
                sbData.setLength(0);
                data.clear();
                currentElement = null;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void processingInstruction(String target, String data) throws SAXException {
                if (target != null && target.startsWith("fx_")) {
                    if (target.equals("fx_mode"))
                        insertMode = "insert".equals(data);
                } else
                    super.processingInstruction(target, data);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endDocument() throws SAXException {
                if (insertMode)
                    LOG.info("Imported [" + counter + "] entries into [" + table + "] for xpath [" + xpath
                            + "]");
                else
                    LOG.info("Updated [" + counter + "] entries in [" + table + "] for xpath [" + xpath + "]");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                pushPath(qName, attributes);
                if (currPath.toString().equals(xpath)) {
                    inTag = true;
                    data.clear();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        String name = attributes.getLocalName(i);
                        if (StringUtils.isEmpty(name))
                            name = attributes.getQName(i);
                        data.put(name, attributes.getValue(i));
                    }
                } else {
                    currentElement = qName;
                }
                inElement = true;
                sbData.setLength(0);
            }

            /**
             * Push a path element from the stack
             *
             * @param qName element name to push
             * @param att attributes
             */
            private void pushPath(String qName, Attributes att) {
                if (att.getLength() > 0 && queryAttributes.containsKey(qName)) {
                    String curr = qName + "[";
                    boolean first = true;
                    final List<String> attList = queryAttributes.get(qName);
                    for (int i = 0; i < att.getLength(); i++) {
                        if (!attList.contains(att.getQName(i)))
                            continue;
                        if (first)
                            first = false;
                        else
                            curr += ',';
                        curr += "@" + att.getQName(i) + "='" + att.getValue(i) + "'";
                    }
                    curr += ']';
                    path.add(curr);
                } else
                    path.add(qName);
                buildPath();
            }

            /**
             * Pop the top path element from the stack
             */
            private void popPath() {
                path.remove(path.size() - 1);
                buildPath();
            }

            /**
             * Rebuild the current path
             */
            private synchronized void buildPath() {
                currPath.setLength(0);
                for (String s : path)
                    currPath.append(s).append('/');
                if (currPath.length() > 1)
                    currPath.delete(currPath.length() - 1, currPath.length());
                //                    System.out.println("currPath: " + currPath);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (currPath.toString().equals(xpath)) {
                    if (DBG)
                        LOG.info("Insert [" + xpath + "]: [" + data + "]");
                    inTag = false;
                    try {
                        if (insertMode) {
                            if (executeInsertPhase) {
                                processColumnSet(insertColumns, psInsert);
                                counter += psInsert.executeUpdate();
                            }
                        } else {
                            if (executeUpdatePhase) {
                                if (processColumnSet(updateSetColumns, psUpdate)) {
                                    processColumnSet(updateClauseColumns, psUpdate);
                                    counter += psUpdate.executeUpdate();
                                }
                            }
                        }
                    } catch (SQLException e) {
                        throw new SAXException(e);
                    } catch (ParseException e) {
                        throw new SAXException(e);
                    }
                } else {
                    if (inTag) {
                        data.put(currentElement, sbData.toString());
                    }
                    currentElement = null;
                }
                popPath();
                inElement = false;
                sbData.setLength(0);
            }

            /**
             * Process a column set
             *
             * @param columns the columns to process
             * @param ps prepared statement to use
             * @return if data other than <code>null</code> has been set
             * @throws SQLException on errors
             * @throws ParseException on date/time conversion errors
             */
            private boolean processColumnSet(Map<String, ColumnInfo> columns, PreparedStatement ps)
                    throws SQLException, ParseException {
                boolean dataSet = false;
                for (String col : columns.keySet()) {
                    ColumnInfo ci = columns.get(col);
                    String value = data.get(col);
                    if (insertMode && counters != null && counters.get(col) != null) {
                        final int newVal = counters.get(col) - 1;
                        value = String.valueOf(newVal);
                        counters.put(col, newVal);
                        //                            System.out.println("new value for " + col + ": " + newVal);
                    }
                    if (insertMode && presetRefColumns != null && presetRefColumns.get(col) != null) {
                        value = data.get(presetRefColumns.get(col));
                        //                            System.out.println("Set presetRefColumn for "+col+" to ["+value+"] from column ["+presetRefColumns.get(col)+"]");
                    }

                    if (value == null)
                        ps.setNull(ci.index, ci.columnType);
                    else {
                        dataSet = true;
                        switch (ci.columnType) {
                        case Types.BIGINT:
                        case Types.NUMERIC:
                            if (DBG)
                                LOG.info("BigInt " + ci.index + "->" + new BigDecimal(value));
                            ps.setBigDecimal(ci.index, new BigDecimal(value));
                            break;
                        case java.sql.Types.DOUBLE:
                            if (DBG)
                                LOG.info("Double " + ci.index + "->" + Double.parseDouble(value));
                            ps.setDouble(ci.index, Double.parseDouble(value));
                            break;
                        case java.sql.Types.FLOAT:
                        case java.sql.Types.REAL:
                            if (DBG)
                                LOG.info("Float " + ci.index + "->" + Float.parseFloat(value));
                            ps.setFloat(ci.index, Float.parseFloat(value));
                            break;
                        case java.sql.Types.TIMESTAMP:
                        case java.sql.Types.DATE:
                            if (DBG)
                                LOG.info("Timestamp/Date " + ci.index + "->"
                                        + FxFormatUtils.getDateTimeFormat().parse(value));
                            ps.setTimestamp(ci.index,
                                    new Timestamp(FxFormatUtils.getDateTimeFormat().parse(value).getTime()));
                            break;
                        case Types.TINYINT:
                        case Types.SMALLINT:
                            if (DBG)
                                LOG.info("Integer " + ci.index + "->" + Integer.valueOf(value));
                            ps.setInt(ci.index, Integer.valueOf(value));
                            break;
                        case Types.INTEGER:
                        case Types.DECIMAL:
                            try {
                                if (DBG)
                                    LOG.info("Long " + ci.index + "->" + Long.valueOf(value));
                                ps.setLong(ci.index, Long.valueOf(value));
                            } catch (NumberFormatException e) {
                                //Fallback (temporary) for H2 if the reported long is a big decimal (tree...)
                                ps.setBigDecimal(ci.index, new BigDecimal(value));
                            }
                            break;
                        case Types.BIT:
                        case Types.CHAR:
                        case Types.BOOLEAN:
                            if (DBG)
                                LOG.info("Boolean " + ci.index + "->" + value);
                            if ("1".equals(value) || "true".equals(value))
                                ps.setBoolean(ci.index, true);
                            else
                                ps.setBoolean(ci.index, false);
                            break;
                        case Types.LONGVARBINARY:
                        case Types.VARBINARY:
                        case Types.BLOB:
                        case Types.BINARY:
                            ZipEntry bin = zip.getEntry(value);
                            if (bin == null) {
                                LOG.error("Failed to lookup binary [" + value + "]!");
                                ps.setNull(ci.index, ci.columnType);
                                break;
                            }
                            try {
                                ps.setBinaryStream(ci.index, zip.getInputStream(bin), (int) bin.getSize());
                            } catch (IOException e) {
                                LOG.error("IOException importing binary [" + value + "]: " + e.getMessage(), e);
                            }
                            break;
                        case Types.CLOB:
                        case Types.LONGVARCHAR:
                        case Types.VARCHAR:
                        case SQL_LONGNVARCHAR:
                        case SQL_NCHAR:
                        case SQL_NCLOB:
                        case SQL_NVARCHAR:
                            if (DBG)
                                LOG.info("String " + ci.index + "->" + value);
                            ps.setString(ci.index, value);
                            break;
                        default:
                            LOG.warn("Unhandled type [" + ci.columnType + "] for column [" + col + "]");
                        }
                    }
                }
                return dataSet;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (inElement)
                    sbData.append(ch, start, length);
            }

        };
        handler.processingInstruction("fx_mode", "insert");
        parser.parse(zip.getInputStream(ze), handler);
        if (updateColumns.length > 0 && executeUpdatePhase) {
            handler.processingInstruction("fx_mode", "update");
            parser.parse(zip.getInputStream(ze), handler);
        }
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, psInsert, psUpdate);
    }
}