Example usage for javax.swing JOptionPane YES_OPTION

List of usage examples for javax.swing JOptionPane YES_OPTION

Introduction

In this page you can find the example usage for javax.swing JOptionPane YES_OPTION.

Prototype

int YES_OPTION

To view the source code for javax.swing JOptionPane YES_OPTION.

Click Source Link

Document

Return value from class method if YES is chosen.

Usage

From source file:edu.ucla.stat.SOCR.analyses.gui.PrincipalComponentAnalysis.java

/**This method defines the specific statistical Analysis to be carried our on the user specified data. ANOVA is done in this case. */
public void doAnalysis() {

    if (dataTable.isEditing())
        dataTable.getCellEditor().stopCellEditing();

    if (!hasExample) {
        JOptionPane.showMessageDialog(this, DATA_MISSING_MESSAGE);
        return;//w ww. j  a  v  a 2 s  . c  o  m
    }

    Data data = new Data();

    String firstMessage = "Would you like to use all the data columns in this Principal Components Analysis?";
    String title = "SOCR - Principal Components Analysis";
    String secondMessage = "Please enter the column numbers (seperated by comma) that you would like to use.";
    String columnNumbers = "";

    int reply = JOptionPane.showConfirmDialog(null, firstMessage, title, JOptionPane.YES_NO_OPTION);
    if (reply == JOptionPane.YES_OPTION) {
        String cellValue = null;
        int originalRow = 0;

        for (int k = 0; k < dataTable.getRowCount(); k++) {
            cellValue = ((String) dataTable.getValueAt(k, 0));

            if (cellValue != null && !cellValue.equals("")) {
                originalRow++;

            }
        }

        cellValue = null;
        int originalColumn = 0;

        for (int k = 0; k < dataTable.getColumnCount(); k++) {
            cellValue = ((String) dataTable.getValueAt(0, k));

            if (cellValue != null && !cellValue.equals("")) {
                originalColumn++;

            }
        }

        dataRow = originalRow;
        dataColumn = originalColumn;

        String PCA_Data1[][] = new String[originalRow][originalColumn];
        double PCA_Data[][] = new double[originalRow][originalColumn];

        for (int k = 0; k < originalRow; k++)
            for (int j = 0; j < originalColumn; j++) {

                if (dataTable.getValueAt(k, j) != null && !dataTable.getValueAt(k, j).equals("")) {
                    PCA_Data1[k][j] = (String) dataTable.getValueAt(k, j);
                    PCA_Data[k][j] = Double.parseDouble(PCA_Data1[k][j]);
                }
            }

        double PCA_Adjusted_Data[][] = new double[originalRow][originalColumn];
        double column_Total = 0;
        double column_Mean = 0;

        for (int j = 0; j < originalColumn; j++)
            for (int k = 0; k < originalRow; k++) {
                column_Total += PCA_Data[k][j];

                if (k == (originalRow - 1)) {
                    column_Mean = column_Total / originalRow;

                    for (int p = 0; p < originalRow; p++) {
                        PCA_Adjusted_Data[p][j] = PCA_Data[p][j] - column_Mean;
                    }
                    column_Total = 0;
                    column_Mean = 0;
                }
            }

        Covariance cov = new Covariance(PCA_Adjusted_Data);
        RealMatrix matrix = cov.getCovarianceMatrix();

        EigenDecomposition eigenDecomp = new EigenDecomposition(matrix, 0);

        storedData = eigenDecomp;

        RealMatrix eigenvectorMatrix = eigenDecomp.getV();

        EValueArray = eigenDecomp.getRealEigenvalues();

        eigenvectorMatrix = eigenvectorMatrix.transpose();

        double eigenvectorArray[][] = eigenvectorMatrix.getData();

        /*for (int j = 0; j < 3; j++)
            for (int k = 0; k < 3; k++)
            {
                System.out.println(eigenvectorArray[j][k] + " ");
            } */

        Matrix matrix1 = new Matrix(eigenvectorArray);
        Matrix matrix2 = new Matrix(PCA_Adjusted_Data);
        matrix2 = matrix2.transpose();

        Matrix finalProduct = matrix1.times(matrix2);
        finalProduct = finalProduct.transpose();

        double finalArray[][] = finalProduct.getArrayCopy();

        for (int j = 0; j < originalRow; j++)
            for (int k = 0; k < originalColumn; k++) {
                PCATable.setValueAt(finalArray[j][k], j, k);
            }

        xData = new double[originalRow];
        yData = new double[originalRow];

        for (int i = 0; i < originalRow; i++) {
            xData[i] = finalArray[i][0];
        }
        for (int i = 0; i < originalRow; i++) {
            yData[i] = finalArray[i][1];
        }

        dependentHeader = "C1";
        independentHeader = "C2";
    }

    else { // start here
        try {
            columnNumbers = JOptionPane.showInputDialog(secondMessage);
        } catch (Exception e) {
        }

        String columnNumbersFinal = "," + columnNumbers.replaceAll("\\s", "") + ",";

        Vector<Integer> locationOfComma = new Vector<Integer>(100);

        for (int i = 0; i < columnNumbersFinal.length(); i++) {
            char d = columnNumbersFinal.charAt(i);
            if (d == ',')
                locationOfComma.add(i);
        }

        Vector<Integer> vector = new Vector<Integer>(100); // vector containing column selected numbers

        for (int i = 0; i < locationOfComma.size() - 1; i++) {
            String temp = columnNumbersFinal.substring(locationOfComma.get(i) + 1, locationOfComma.get(i + 1));
            if (temp == "")
                continue;
            vector.add((Integer.parseInt(temp) - 1));

        }

        dependentHeader = "C" + (vector.get(0) + 1);
        independentHeader = "C" + (vector.get(1) + 1);

        // System.out.println("Vector size is: " + vector.size() + "\n");                

        String cellValue = null;
        int originalRow = 0;

        for (int k = 0; k < dataTable.getRowCount(); k++) {
            cellValue = ((String) dataTable.getValueAt(k, 0));

            if (cellValue != null && !cellValue.equals("")) {
                originalRow++;

            }
        }

        int originalColumn = vector.size();

        dataRow = originalRow;
        dataColumn = originalColumn;

        String PCA_Data1[][] = new String[originalRow][originalColumn];
        double PCA_Data[][] = new double[originalRow][originalColumn];

        for (int k = 0; k < originalRow; k++)
            for (int j = 0; j < originalColumn; j++) {

                if (dataTable.getValueAt(k, vector.get(j)) != null
                        && !dataTable.getValueAt(k, vector.get(j)).equals("")) {
                    PCA_Data1[k][j] = (String) dataTable.getValueAt(k, vector.get(j));
                    PCA_Data[k][j] = Double.parseDouble(PCA_Data1[k][j]);
                }
            }

        double PCA_Adjusted_Data[][] = new double[originalRow][originalColumn];
        double column_Total = 0;
        double column_Mean = 0;

        for (int j = 0; j < originalColumn; j++)
            for (int k = 0; k < originalRow; k++) {
                column_Total += PCA_Data[k][j];

                if (k == (originalRow - 1)) {
                    column_Mean = column_Total / originalRow;

                    for (int p = 0; p < originalRow; p++) {
                        PCA_Adjusted_Data[p][j] = PCA_Data[p][j] - column_Mean;
                    }
                    column_Total = 0;
                    column_Mean = 0;
                }
            }

        Covariance cov = new Covariance(PCA_Adjusted_Data);
        RealMatrix matrix = cov.getCovarianceMatrix();

        EigenDecomposition eigenDecomp = new EigenDecomposition(matrix, 0);

        storedData = eigenDecomp;

        RealMatrix eigenvectorMatrix = eigenDecomp.getV();

        EValueArray = eigenDecomp.getRealEigenvalues(); // added              

        eigenvectorMatrix = eigenvectorMatrix.transpose();

        double eigenvectorArray[][] = eigenvectorMatrix.getData();

        /*for (int j = 0; j < 3; j++)
            for (int k = 0; k < 3; k++)
            {
                System.out.println(eigenvectorArray[j][k] + " ");
            } */

        Matrix matrix1 = new Matrix(eigenvectorArray);
        Matrix matrix2 = new Matrix(PCA_Adjusted_Data);
        matrix2 = matrix2.transpose();

        Matrix finalProduct = matrix1.times(matrix2);
        finalProduct = finalProduct.transpose();

        double finalArray[][] = finalProduct.getArrayCopy();

        /* for (int j = 0; j < dataTable.getColumnCount(); j++)
            for (int k = 0; k < dataTable.getRowCount(); k++)
            {
                System.out.println(finalArray[j][k] + " ");
            }*/

        for (int j = 0; j < originalRow; j++)
            for (int k = 0; k < originalColumn; k++) {
                PCATable.setValueAt(finalArray[j][k], j, k);
            }

        xData = new double[originalRow];
        yData = new double[originalRow];

        for (int i = 0; i < originalRow; i++) {
            xData[i] = finalArray[i][0];
        }

        for (int i = 0; i < originalRow; i++) {
            yData[i] = finalArray[i][1];
        }
    }

    map = new HashMap<Double, double[]>();

    for (int i = 0; i < dataColumn; i++) {
        map.put(EValueArray[i], storedData.getEigenvector(i).toArray());
    }

    Arrays.sort(EValueArray);

    xData1 = new double[EValueArray.length]; // for Scree Plot
    yData1 = new double[EValueArray.length];

    for (int i = 0; i < EValueArray.length; i++) {
        xData1[i] = i + 1;
    }

    for (int i = 0; i < EValueArray.length; i++) {
        yData1[i] = EValueArray[i];
    }

    for (int i = 0; i < yData1.length / 2; i++) {
        double temp = yData1[i];
        yData1[i] = yData1[yData1.length - i - 1];
        yData1[yData1.length - i - 1] = temp;
    }

    for (int i = 0; i < xData1.length; i++) {
        System.out.println("xData1 contains: " + xData1[i] + "\n");
    }

    for (int i = 0; i < yData1.length; i++) {
        System.out.println("yData1 contains: " + yData1[i] + "\n");
    }

    for (int i = 0; i < EValueArray.length / 2; i++) {
        double temp = EValueArray[i];
        EValueArray[i] = EValueArray[EValueArray.length - i - 1];
        EValueArray[EValueArray.length - i - 1] = temp;
    }

    resultPanelTextArea.append(
            "Click on \"PCA RESULT\" panel to view the transformed data (Eigenvector Transposed * Adjusted Data Transposed)");

    resultPanelTextArea.append("\n\nThe real eigenvalues (in descending order) are: \n\n");
    resultPanelTextArea.append("" + round(EValueArray[0], 3));

    for (int i = 1; i < EValueArray.length; i++) {
        resultPanelTextArea.append("\n" + round(EValueArray[i], 3));
    }
    resultPanelTextArea.append("\n\nThe corresponding eigenvectors (in columns) are: \n\n");

    double temp[] = new double[100];

    for (int j = 0; j < temp.length; j++)
        for (int i = 0; i < EValueArray.length; i++) {
            temp = map.get(EValueArray[i]);
            resultPanelTextArea.append("" + round(temp[j], 3) + "\t");
            if (i == EValueArray.length - 1) {
                resultPanelTextArea.append("\n");
            }
        }

    doGraph();
}

From source file:edu.mit.fss.examples.member.gui.PowerSubsystemPanel.java

/**
 * Export this panel's generation dataset.
 *///from   ww  w .  j  a  v  a2s.  com
private void exportDataset() {
    if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this)) {
        File f = fileChooser.getSelectedFile();

        if (!f.exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
                "Overwrite existing file " + f.getName() + "?", "File Exists", JOptionPane.YES_NO_OPTION)) {

            logger.info("Exporting dataset to file " + f.getPath() + ".");
            try {
                BufferedWriter bw = Files.newBufferedWriter(Paths.get(f.getPath()), Charset.defaultCharset());

                StringBuilder b = new StringBuilder();
                b.append(" Generation\n").append("Time, Value\n");
                for (int j = 0; j < generationSeries.getItemCount(); j++) {
                    b.append(generationSeries.getTimePeriod(j).getStart().getTime()).append(", ")
                            .append(generationSeries.getValue(j)).append("\n");
                }

                bw.write(b.toString());
                bw.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }
}

From source file:de.ipk_gatersleben.ag_nw.graffiti.plugins.gui.webstart.MainM.java

/**
 * Constructs a new instance of the editor.
 * @param addPluginFile// w w w.  ja v a2 s.  c  o m
 */
public MainM(String applicationName, String[] args, String[] addon, SplashScreenInterface splashScreen,
        String addPluginFile, final boolean showMainFrame) {

    setupLogger();

    ClassLoader cl = this.getClass().getClassLoader();
    String path = this.getClass().getPackage().getName().replace('.', '/');
    ImageIcon icon = new ImageIcon(cl.getResource(path + "/vanted_logo.png"));

    if (splashScreen != null && (splashScreen instanceof DBEsplashScreen)) {
        ((DBEsplashScreen) splashScreen).setIconImage(icon.getImage());
    }

    splashScreen.setVisible(showMainFrame);

    GravistoMainHelper.createApplicationSettingsFolder(splashScreen);

    if (!showMainFrame && !(new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_accepted")).exists()
            && !(new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_rejected")).exists()) { // command line version automatically rejects
        // kegg
        try {
            new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_rejected").createNewFile();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    if (!(new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_accepted")).exists()
            && !(new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_rejected")).exists()) {

        ReleaseInfo.setIsFirstRun(true);

        splashScreen.setVisible(false);
        splashScreen.setText("Request KEGG License Status");
        int result = askForEnablingKEGG();
        if (result == JOptionPane.YES_OPTION) {
            try {
                new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_accepted").createNewFile();
            } catch (IOException e) {
                ErrorMsg.addErrorMessage(e);
            }
        }
        if (result == JOptionPane.NO_OPTION) {
            try {
                new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_rejected").createNewFile();
            } catch (IOException e) {
                ErrorMsg.addErrorMessage(e);
            }
        }
        if (result == JOptionPane.CANCEL_OPTION) {
            JOptionPane.showMessageDialog(null, "Startup of VANTED is aborted.",
                    "VANTED Program Features Initialization", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
        }
        splashScreen.setVisible(true);
    }

    GravistoMainHelper.initApplicationExt(args, splashScreen, cl, addPluginFile, addon);
}

From source file:de.ipk_gatersleben.ag_nw.graffiti.plugins.gui.webstart.MainM.java

public static boolean doEnableKEGGaskUser() {
    return askForEnablingKEGG() == JOptionPane.YES_OPTION;
}

From source file:fi.smaa.jsmaa.gui.JSMAAMainFrame.java

private boolean checkSaveCurrentModel() {
    if (!modelManager.getSaved()) {
        int conf = JOptionPane.showConfirmDialog(this, "Current model not saved. Do you want do save changes?",
                "Save changed", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                ImageFactory.IMAGELOADER.getIcon(FileNames.ICON_STOP));
        if (conf == JOptionPane.CANCEL_OPTION) {
            return false;
        } else if (conf == JOptionPane.YES_OPTION) {
            if (!save()) {
                return false;
            }//from w w  w.  j  a v  a  2s  . c  o m
        }
    }
    return true;
}

From source file:dataviewer.DataViewer.java

/**
 * Creates new form DataViewer//w  ww.  j av  a 2s  . c o  m
 */
public DataViewer() {
    try {
        for (Enum ee : THREAD.values()) {
            t[ee.ordinal()] = new Thread();
        }
        initComponents();
        DropTarget dropTarget = new DropTarget(tr_files, new DropTargetListenerImpl());
        TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {
                javax.swing.JTree tree = (javax.swing.JTree) e.getSource();
                TreePath path = tree.getSelectionPath();
                Object[] pnode = (Object[]) path.getPath();
                String name = pnode[pnode.length - 1].toString();
                String ex = getExtension(name);
                if (ex.equals(".txt") || ex.equals(".dat") || ex.equals(".csv") || ex.equals(".tsv")) {
                    selected_file = name;
                } else {
                    selected_file = "";
                }
            }
        };
        tr_files.addTreeSelectionListener(treeSelectionListener);

        tr_files.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() >= 2) {
                    if (!"".equals(selected_file)) {
                        //count_data();
                        read_data();
                    } else {
                        TreePath path = tr_files.getSelectionPath();
                        if (path.getLastPathComponent().toString().equals(cur_path)) {
                            cur_path = (new File(cur_path)).getParent();
                        } else {
                            cur_path = cur_path + File.separator + path.getLastPathComponent().toString();
                        }
                        fill_tree();
                    }
                }
            }
        });

        tr_files.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                    cur_path = (new File(cur_path)).getParent();
                    fill_tree();
                } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (!"".equals(selected_file)) {
                        //count_data();
                        read_data();
                    } else {
                        TreePath path = tr_files.getSelectionPath();
                        if (path.getLastPathComponent().toString().equals(cur_path)) {
                            cur_path = (new File(cur_path)).getParent();
                        } else {
                            cur_path = cur_path + File.separator + path.getLastPathComponent().toString();
                        }
                        fill_tree();
                    }
                } else if (evt.getKeyCode() == KeyEvent.VK_DELETE) {

                    if (!"".equals(selected_file)) {
                        String name = cur_path + File.separator + selected_file;
                        if ((new File(name)).isFile()) {
                            int dialogResult = JOptionPane.showConfirmDialog(null,
                                    "Selected file [" + selected_file
                                            + "] will be removed and not recoverable.",
                                    "Are you sure?", JOptionPane.YES_NO_OPTION);
                            if (dialogResult == JOptionPane.YES_OPTION) {
                                (new File(name)).delete();
                                fill_tree();
                            }
                        }

                    } else {
                        JOptionPane.showMessageDialog(null,
                                "For safety concern, removing folder is not supported.", "Information",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        tr_files.setCellRenderer(new MyTreeCellRenderer());
        p_count.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

        //tp_menu.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ctrl1, "tab_read");
        //tp_menu.getActionMap().put("tab_read", (Action) new ActionListenerImpl());
        //tp_menu.setMnemonicAt(0, KeyEvent.VK_1);
        //tp_menu.setMnemonicAt(1, KeyEvent.VK_2);
        /*InputMap inputMap = tp_menu.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
         ActionMap actionMap = tp_menu.getActionMap();
                
         KeyStroke ctrl1 = KeyStroke.getKeyStroke("ctrl 1");
         inputMap.put(ctrl1, "tab_read");
         actionMap.put("tab_read", new AbstractAction() {
                
         @Override
         public void actionPerformed(ActionEvent arg0) {
         tp_menu.setSelectedIndex(0);
         }
         });
                
         KeyStroke ctrl2 = KeyStroke.getKeyStroke("ctrl 2");
         inputMap.put(ctrl2, "tab_analyze");
         actionMap.put("tab_analyze", new AbstractAction() {
                
         @Override
         public void actionPerformed(ActionEvent arg0) {
         tp_menu.setSelectedIndex(1);
         }
         });*/
        config();
    } catch (Exception e) {
        txt_count.setText(e.getMessage());
    }
}

From source file:edu.clemson.cs.nestbed.client.gui.TestbedManagerFrame.java

private void doExit() {
    int choice;//w ww . j a va  2  s .com

    choice = JOptionPane.showConfirmDialog(this, "Do you wish to exit NESTbed?", "Exit Confirmation",
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (choice == JOptionPane.YES_OPTION) {
        log.fatal("Application shutdown per user request.");
        System.exit(0);
    }
}

From source file:com.ssn.event.controller.SSNShareController.java

@Override
public void mouseClicked(MouseEvent e) {
    Object mouseEventObj = e.getSource();
    if (mouseEventObj != null && mouseEventObj instanceof JLabel) {
        JLabel label = (JLabel) mouseEventObj;
        getShareForm().setCursor(new Cursor(Cursor.WAIT_CURSOR));
        // Tracking this sharing event in Google Analytics
        GoogleAnalyticsUtil.track(SSNConstants.SSN_APP_EVENT_SHARING);
        Thread thread = null;/*from ww w.  ja  v  a 2 s . c o  m*/
        switch (label.getName()) {
        case "FacebookSharing":
            thread = new Thread() {
                boolean isAlreadyLoggedIn = false;

                @Override
                public void run() {

                    Set<String> sharedFileList = getFiles();
                    AccessGrant facebookAccessGrant = getHomeModel().getHomeForm().getFacebookAccessGrant();
                    if (facebookAccessGrant == null) {
                        try {
                            LoginWithFacebook loginWithFacebook = new LoginWithFacebook(null);
                            loginWithFacebook.setHomeForm(getHomeModel().getHomeForm());
                            loginWithFacebook.login();

                            boolean processFurther = false;
                            while (!processFurther) {
                                facebookAccessGrant = getHomeModel().getHomeForm().getFacebookAccessGrant();
                                if (facebookAccessGrant == null) {
                                    Thread.sleep(10000);
                                } else {
                                    processFurther = true;
                                    isAlreadyLoggedIn = true;
                                }
                            }
                        } catch (InterruptedException ex) {
                            logger.error(ex);
                        }
                    }

                    FacebookConnectionFactory connectionFactory = new FacebookConnectionFactory(
                            SSNConstants.SSN_FACEBOOK_API_KEY, SSNConstants.SSN_FACEBOOK_SECRET_KEY);
                    Connection<Facebook> connection = connectionFactory.createConnection(facebookAccessGrant);
                    Facebook facebook = connection.getApi();
                    MediaOperations mediaOperations = facebook.mediaOperations();

                    if (!isAlreadyLoggedIn) {
                        // SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                        SSNConfirmationDialogBox confirmeDialog = new SSNConfirmationDialogBox();
                        FacebookProfile userProfile = facebook.userOperations().getUserProfile();
                        String userName = "";
                        if (userProfile != null) {
                            userName = userProfile.getName() != null ? userProfile.getName()
                                    : userProfile.getFirstName();
                        }
                        confirmeDialog.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(),
                                "Confirmation", "",
                                "You are already logged in with " + userName + ", Click OK to continue.");
                        int result = confirmeDialog.getResult();
                        if (result == JOptionPane.YES_OPTION) {
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                                    messageDialogBox.initDialogBoxUI(
                                            SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                                            "Successfully uploaded.");
                                    messageDialogBox.setFocusable(true);

                                }
                            });
                        } else if (result == JOptionPane.NO_OPTION) {

                            AccessGrant facebookAccessGrant1 = null;
                            if (facebookAccessGrant1 == null) {
                                try {
                                    LoginWithFacebook loginWithFacebook = new LoginWithFacebook(null);
                                    loginWithFacebook.setHomeForm(getHomeModel().getHomeForm());
                                    loginWithFacebook.login();

                                    boolean processFurther = false;
                                    while (!processFurther) {
                                        facebookAccessGrant1 = getHomeModel().getHomeForm()
                                                .getFacebookAccessGrant();
                                        if (facebookAccessGrant1 == null) {
                                            Thread.sleep(10000);
                                        } else {
                                            processFurther = true;
                                            //isAlreadyLoggedIn = true;
                                        }
                                    }
                                    connectionFactory = new FacebookConnectionFactory(
                                            SSNConstants.SSN_FACEBOOK_API_KEY,
                                            SSNConstants.SSN_FACEBOOK_SECRET_KEY);
                                    connection = connectionFactory.createConnection(facebookAccessGrant);
                                    facebook = connection.getApi();
                                    mediaOperations = facebook.mediaOperations();
                                } catch (InterruptedException ex) {
                                    logger.error(ex);
                                }
                            }
                        }
                    }

                    String[] videoSupported = SSNConstants.SSN_VIDEO_FORMAT_SUPPORTED;
                    final List<String> videoSupportedList = Arrays.asList(videoSupported);

                    for (String file : sharedFileList) {
                        String fileExtension = file.substring(file.lastIndexOf(".") + 1, file.length());
                        Resource resource = new FileSystemResource(file);

                        if (!videoSupportedList.contains(fileExtension.toUpperCase())) {
                            String output = mediaOperations.postPhoto(resource);
                        } else {
                            String output = mediaOperations.postVideo(resource);
                        }

                    }

                    getShareForm().dispose();
                }
            };
            thread.start();
            break;
        case "TwitterSharing":
            LoginWithTwitter.deniedPermission = false;
            thread = new Thread() {
                boolean isAlreadyLoggedIn = false;

                @Override
                public void run() {
                    Set<String> sharedFileList = getFiles();
                    OAuthToken twitterOAuthToken = getHomeModel().getHomeForm().getTwitterOAuthToken();
                    if (twitterOAuthToken == null) {
                        try {
                            LoginWithTwitter loginWithTwitter = new LoginWithTwitter(null);
                            loginWithTwitter.setHomeForm(getHomeModel().getHomeForm());
                            loginWithTwitter.login();

                            boolean processFurther = false;
                            while (!processFurther) {
                                if (LoginWithTwitter.deniedPermission)
                                    break;

                                twitterOAuthToken = getHomeModel().getHomeForm().getTwitterOAuthToken();
                                if (twitterOAuthToken == null) {
                                    Thread.sleep(10000);
                                } else {
                                    processFurther = true;
                                    isAlreadyLoggedIn = true;
                                }
                            }
                        } catch (IOException | InterruptedException ex) {
                            logger.error(ex);
                        }
                    }
                    if (!LoginWithTwitter.deniedPermission) {
                        Twitter twitter = new TwitterTemplate(SSNConstants.SSN_TWITTER_API_KEY,
                                SSNConstants.SSN_TWITTER_SECRET_KEY, twitterOAuthToken.getValue(),
                                twitterOAuthToken.getSecret());
                        TimelineOperations timelineOperations = twitter.timelineOperations();
                        if (!isAlreadyLoggedIn) {
                            SSNConfirmationDialogBox confirmeDialog = new SSNConfirmationDialogBox();
                            TwitterProfile userProfile = twitter.userOperations().getUserProfile();

                            String userName = "";
                            if (userProfile != null) {
                                userName = twitter.userOperations().getScreenName() != null
                                        ? twitter.userOperations().getScreenName()
                                        : userProfile.getName();
                            }
                            confirmeDialog.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(),
                                    "Confirmation", "",
                                    "You are already logged in with " + userName + ", Click OK to continue.");
                            int result = confirmeDialog.getResult();
                            if (result == JOptionPane.YES_OPTION) {
                                SwingUtilities.invokeLater(new Runnable() {
                                    public void run() {
                                        SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                                        messageDialogBox.initDialogBoxUI(
                                                SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                                                "Successfully uploaded.");
                                        messageDialogBox.setFocusable(true);

                                    }
                                });
                            } else if (result == JOptionPane.NO_OPTION) {

                                twitterOAuthToken = null;
                                if (twitterOAuthToken == null) {
                                    try {
                                        LoginWithTwitter loginWithTwitter = new LoginWithTwitter(null);
                                        loginWithTwitter.setHomeForm(getHomeModel().getHomeForm());
                                        loginWithTwitter.login();

                                        boolean processFurther = false;
                                        while (!processFurther) {
                                            twitterOAuthToken = getHomeModel().getHomeForm()
                                                    .getTwitterOAuthToken();
                                            if (twitterOAuthToken == null) {
                                                Thread.sleep(10000);
                                            } else {
                                                processFurther = true;

                                            }
                                        }
                                        twitter = new TwitterTemplate(SSNConstants.SSN_TWITTER_API_KEY,
                                                SSNConstants.SSN_TWITTER_SECRET_KEY,
                                                twitterOAuthToken.getValue(), twitterOAuthToken.getSecret());
                                        timelineOperations = twitter.timelineOperations();
                                    } catch (IOException | InterruptedException ex) {
                                        logger.error(ex);
                                    }
                                }
                            }
                        }

                        for (String file : sharedFileList) {
                            Resource image = new FileSystemResource(file);

                            TweetData tweetData = new TweetData("At " + new Date());
                            tweetData.withMedia(image);
                            timelineOperations.updateStatus(tweetData);
                        }
                    } else {
                        SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                        messageDialogBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Alert",
                                "", "User denied for OurHive App permission on twitter.");
                        messageDialogBox.setFocusable(true);
                    }
                    getShareForm().dispose();
                }

            };
            thread.start();
            break;
        case "InstagramSharing":
            break;
        case "MailSharing":
            try {
                String OS = System.getProperty("os.name").toLowerCase();

                Set<String> sharedFileList = getFiles();
                Set<String> voiceNoteList = new HashSet<String>();
                for (String sharedFile : sharedFileList) {
                    String voiceNote = SSNDao.getVoiceCommandPath(new File(sharedFile).getAbsolutePath());
                    if (voiceNote != null && !voiceNote.isEmpty()) {
                        voiceNoteList.add(voiceNote);
                    }
                }
                sharedFileList.addAll(voiceNoteList);

                String fileFullPath = "";
                String caption = "";
                if (sharedFileList.size() == 1) {
                    fileFullPath = sharedFileList.toArray(new String[0])[0];

                    caption = SSMMediaGalleryPanel.readMetaDataForTitle(new File(fileFullPath));

                } else if (sharedFileList.size() > 1) {
                    fileFullPath = SSNHelper.createZipFileFromMultipleFiles(sharedFileList);
                }

                if (OS.contains("win")) {

                    // String subject = "SSN Subject";
                    String subject = caption.equals("") ? SSNConstants.SSN_SHARE_WITH_MAIL_SUBJECT : caption;
                    String body = "";
                    String m = "&subject=%s&body=%s";

                    String outLookExeDir = "C:\\Program Files\\Microsoft Office\\Office14\\Outlook.exe";
                    String mailCompose = "/c";
                    String note = "ipm.note";
                    String mailBodyContent = "/m";

                    m = String.format(m, subject, body);
                    String slashA = "/a";

                    String mailClientConfigParams[] = null;
                    Process startMailProcess = null;

                    mailClientConfigParams = new String[] { outLookExeDir, mailCompose, note, mailBodyContent,
                            m, slashA, fileFullPath };
                    startMailProcess = Runtime.getRuntime().exec(mailClientConfigParams);
                    OutputStream out = startMailProcess.getOutputStream();
                    File zipFile = new File(fileFullPath);
                    zipFile.deleteOnExit();
                } else if (OS.indexOf("mac") >= 0) {
                    //Process p = Runtime.getRuntime().exec(new String[]{String.format("open -a mail ", fileFullPath)});
                    Desktop desktop = Desktop.getDesktop();
                    String mailTo = caption.equals("") ? "?SUBJECT=" + SSNConstants.SSN_SHARE_WITH_MAIL_SUBJECT
                            : caption;
                    URI uriMailTo = null;
                    uriMailTo = new URI("mailto", mailTo, null);
                    desktop.mail(uriMailTo);
                }

                this.getShareForm().dispose();
            } catch (Exception ex) {
                logger.error(ex);
            }
            break;
        case "moveCopy":
            getShareForm().dispose();
            File album = new File(SSNHelper.getSsnHiveDirPath());
            File[] albumPaths = album.listFiles();
            Vector albumNames = new Vector();
            for (int i = 0; i < albumPaths.length; i++) {
                if (!(albumPaths[i].getName().equals("OurHive")) && SSNHelper.lastAlbum != null
                        && !(albumPaths[i].getName().equals(SSNHelper.lastAlbum)))
                    albumNames.add(albumPaths[i].getName());
            }
            if (SSNHelper.lastAlbum != null && !SSNHelper.lastAlbum.equals("OurHive"))
                albumNames.insertElementAt("OurHive", 0);

            SSNInputDialogBox inputBox = new SSNInputDialogBox(true, albumNames);
            inputBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Copy Media",
                    "Please Select Album Name");
            String destAlbumName = inputBox.getTextValue();
            if (StringUtils.isNotBlank(destAlbumName)) {
                homeModel.moveAlbum(destAlbumName, getFiles());
            }

        }
        getShareForm().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
}

From source file:com.seanmadden.net.fast.FastInterpretype.java

public void clearWindows() {
    boolean windowCleared = false;
    int selected = JOptionPane.showConfirmDialog(null,
            "Would you like to save the current conversation before clearing?", "Save before clearing?",
            JOptionPane.YES_NO_CANCEL_OPTION);
    if (selected == JOptionPane.YES_OPTION) {
        windowCleared = saveLogToFile();
    } else if (selected == JOptionPane.NO_OPTION) {
        windowCleared = true;//w  w w .  j  a v a 2 s.c o m
    }

    if (windowCleared) {
        si.sendRawDataToPort(DataPacket.generateClearConvoPayload());
        mw.clearWindow();
        String username = JOptionPane.showInputDialog("What is your name?");
        si.sendRawDataToPort(DataPacket.generateSignedOnPayload(username));
        mw.acceptText(username + " (you) has signed on.\n");
        mw.setLocalUserName(username);
    }
}

From source file:de.evaluationtool.gui.EvaluationFrameActionListener.java

private void saveXML() {
    JFileChooser chooser = new JFileChooser("Save evaluation result as alignment XML");
    chooser.setCurrentDirectory(frame.defaultDirectory);
    int returnVal = chooser.showSaveDialog(frame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile().exists() && (JOptionPane.showConfirmDialog(frame,
                "File already exists. Overwrite?") != JOptionPane.YES_OPTION)) {
            return;
        }//from   w  w  w .  j a  v  a  2  s.co  m
        try {
            frame.saveXML(chooser.getSelectedFile(), SaveXMLMode.SAVE_EVERYTHING);
        } catch (JDOMException | IOException e) {
            JOptionPane.showConfirmDialog(frame, e, "Error saving XML", JOptionPane.ERROR_MESSAGE);
        }
    }
}