Example usage for javax.swing JOptionPane showInputDialog

List of usage examples for javax.swing JOptionPane showInputDialog

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static Object showInputDialog(Component parentComponent, Object message, String title, int messageType,
        Icon icon, Object[] selectionValues, Object initialSelectionValue) throws HeadlessException 

Source Link

Document

Prompts the user for input in a blocking dialog where the initial selection, possible selections, and all other options can be specified.

Usage

From source file:org.eurocarbdb.application.glycoworkbench.plugin.s3.Cockpit.java

private void generateTorrentUrl() {
    final S3Object[] objects = getSelectedObjects();

    if (objects.length != 1) {
        log.warn("Ignoring Generate Public URL object command, can only operate on a single object");
        return;// w  w  w. j  a v  a2  s .c  om
    }
    S3Object currentObject = objects[0];

    // Generate URL
    String torrentUrl = S3Service.createTorrentUrl(currentSelectedBucket.getName(), currentObject.getKey());

    // Display signed URL
    JOptionPane.showInputDialog(ownerFrame, "Torrent URL for '" + currentObject.getKey() + "'.", "Torrent URL",
            JOptionPane.INFORMATION_MESSAGE, null, null, torrentUrl);
}

From source file:org.interreg.docexplore.authoring.AuthoringMenu.java

public AuthoringMenu(final AuthoringToolFrame authoringTool) {
    this.tool = authoringTool;

    this.recent = new LinkedList<String>();
    readRecent();//from ww  w.java  2 s  . c  o  m
    this.file = new JMenu(XMLResourceBundle.getBundledString("generalMenuFile"));
    add(file);

    newItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuNew")) {
        public void actionPerformed(ActionEvent arg0) {
            newFile();
        }
    });
    loadItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuLoad")) {
        public void actionPerformed(ActionEvent arg0) {
            load();
        }
    });
    saveItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuSave")) {
        public void actionPerformed(ActionEvent arg0) {
            save();
        }
    });
    saveAsItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuSaveAs")) {
        public void actionPerformed(ActionEvent arg0) {
            saveAs();
        }
    });
    exportItem = new JMenuItem(
            new AbstractAction(XMLResourceBundle.getBundledString("generalMenuExport") + "...") {
                public void actionPerformed(ActionEvent arg0) {
                    GuiUtils.blockUntilComplete(new ProgressRunnable() {
                        public void run() {
                            try {
                                authoringTool.readerExporter.doExport(authoringTool.editor.link);
                            } catch (Exception ex) {
                                ErrorHandler.defaultHandler.submit(ex);
                            }
                        }

                        public float getProgress() {
                            return (float) authoringTool.readerExporter.progress[0];
                        }
                    }, authoringTool.editor);
                }
            });
    webExportItem = new JMenuItem(
            new AbstractAction(XMLResourceBundle.getBundledString("generalMenuWebExport") + "...") {
                public void actionPerformed(ActionEvent arg0) {
                    GuiUtils.blockUntilComplete(new ProgressRunnable() {
                        public void run() {
                            try {
                                authoringTool.webExporter.doExport(authoringTool.editor.link);
                            } catch (Exception ex) {
                                ErrorHandler.defaultHandler.submit(ex);
                            }
                        }

                        public float getProgress() {
                            return (authoringTool.webExporter.copyComplete ? .5f : 0f)
                                    + (float) (.5 * authoringTool.webExporter.progress[0]);
                        }
                    }, authoringTool.editor);
                }
            });
    //      webExportItem = new JMenuItem(new AbstractAction("Web export") {public void actionPerformed(ActionEvent arg0)
    //      {
    //         GuiUtils.blockUntilComplete(new Runnable() {public void run()
    //         {
    //            try 
    //            {
    //               new WebStaticExporter().doExport(authoringTool.editor.link.getBook(authoringTool.editor.link.getLink().getAllBookIds().get(0)));
    //            }
    //            catch (Exception ex) {ErrorHandler.defaultHandler.submit(ex);}
    //         }}, authoringTool.editor);
    //      }});
    //      webExportItem.setEnabled(false);
    quitItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuQuit")) {
        public void actionPerformed(ActionEvent arg0) {
            authoringTool.quit();
        }
    });
    buildFileMenu();

    JMenu edit = new JMenu(XMLResourceBundle.getBundledString("generalMenuEdit"));
    this.undoItem = new JMenuItem();
    undoItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                authoringTool.historyManager.undo();
            } catch (Exception ex) {
                ErrorHandler.defaultHandler.submit(ex);
            }
        }
    });
    edit.add(undoItem);
    this.redoItem = new JMenuItem();
    redoItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                authoringTool.historyManager.redo();
            } catch (Exception ex) {
                ErrorHandler.defaultHandler.submit(ex);
            }
        }
    });
    edit.add(redoItem);
    JMenuItem viewHistory = new JMenuItem(XMLResourceBundle.getBundledString("generalMenuEditViewHistory"));
    viewHistory.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            authoringTool.historyDialog.setVisible(true);
        }
    });
    edit.add(viewHistory);

    edit.addSeparator();

    edit.add(new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("fixChars")) {
        public void actionPerformed(ActionEvent arg0) {
            Object res = JOptionPane.showInputDialog(tool, XMLResourceBundle.getBundledString("fixCharsMsg"),
                    XMLResourceBundle.getBundledString("fixChars"), JOptionPane.QUESTION_MESSAGE, null,
                    new Object[] { XMLResourceBundle.getBundledString("fixCharsWin"),
                            XMLResourceBundle.getBundledString("fixCharsMac") },
                    XMLResourceBundle.getBundledString("fixCharsWin"));
            if (res == null)
                return;
            try {
                convertPresentation(tool.defaultFile,
                        res.equals(XMLResourceBundle.getBundledString("fixCharsWin")) ? "ISO-8859-1"
                                : "x-MacRoman");
            } catch (Exception e) {
                ErrorHandler.defaultHandler.submit(e);
            }
            try {
                tool.editor.reset();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }));

    //TODO: remove!
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            int lastPage = book.getLastPageNumber();
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               Set<Region> regions = page.getRegions();
    //               if (regions.size() > 2)
    //               {
    //                  Region highest = null;
    //                  int max = -1;
    //                  for (Region region : regions)
    //                     for (Point point : region.getOutline())
    //                        if (max < 0 || point.y < max)
    //                           {max = point.y; highest = region;}
    //                  Region middle = null;
    //                  max = -1;
    //                  for (Region region : regions)
    //                     if (region != highest)
    //                        for (Point point : region.getOutline())
    //                           if (max < 0 || point.y < max)
    //                              {max = point.y; middle = region;}
    //                  if (regions.size() > 3)
    //                  {
    //                     max = -1;
    //                     Region newMiddle = null;
    //                     for (Region region : regions)
    //                        if (region != highest && region != middle)
    //                           for (Point point : region.getOutline())
    //                              if (max < 0 || point.y < max)
    //                                 {max = point.y; newMiddle = region;}
    //                     middle = newMiddle;
    //                  }
    //                  MetaDataKey display = book.getLink().getKey("display", "");
    //                  for (Map.Entry<MetaDataKey, List<MetaData>> entry : highest.getMetaData().entrySet())
    //                     for (MetaData md : entry.getValue())
    //                        if (md.getType().equals(MetaData.textType))
    //                        {
    //                           String val = "<b>"+md.getString()+"</b>\n";
    //                           for (Map.Entry<MetaDataKey, List<MetaData>> entry2 : middle.getMetaData().entrySet())
    //                              for (MetaData md2 : entry2.getValue())
    //                                 if (md2.getType().equals(MetaData.textType) && TextElement.getStyle(md, tool.styleManager) == TextElement.getStyle(md2, tool.styleManager))
    //                                    val = val+"\n"+md2.getString();
    //                           md.setString(val);
    //                        }
    //                  boolean hasImage = false;
    //                  for (Map.Entry<MetaDataKey, List<MetaData>> entry2 : middle.getMetaData().entrySet())
    //                     for (MetaData md2 : entry2.getValue())
    //                        if (md2.getType().equals(MetaData.imageType))
    //                        {
    //                           MetaData imageMd = new MetaData(book.getLink(), display, md2.getType(), md2.getValue());
    //                           if (!hasImage)
    //                              BookImporter.insert(imageMd, highest, 0);
    //                           else BookImporter.insert(imageMd, highest, BookImporter.getHighestRank(highest)+1);
    //                           hasImage = true;
    //                        }
    //                  page.removeRegion(middle);
    //               }
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            int lastPage = book.getLastPageNumber();
    //            MetaDataKey display = book.getLink().getKey("display", "");
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               Set<Region> regions = page.getRegions();
    //               for (Region region : regions)
    //               {
    //                  List<MetaData> mds = region.getMetaDataListForKey(display);
    //                     for (MetaData md : mds)
    //                        if (md.getType().equals(MetaData.textType))
    //                        {
    //                           String val = md.getString().trim();
    //                           if (!val.startsWith("<i>") || !val.endsWith("</i>"))
    //                              continue;
    //                           TextElement.getStyleMD(md).setString("4");
    //                           md.setString(val.substring(3, val.length()-4));
    //                           System.out.println(md.getString());
    //                        }
    //               }
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            int lastPage = book.getLastPageNumber();
    //            MetaDataKey display = book.getLink().getKey("display", "");
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               Set<Region> regions = page.getRegions();
    //               for (Region region : regions)
    //               {
    //                  int max = BookImporter.getHighestRank(region);
    //                  for (int i=0;i<max;i++)
    //                  {
    //                     MetaData md1 = BookImporter.getAtRank(region, i);
    //                     if (md1 == null || !md1.getType().equals(MetaData.textType))
    //                        continue;
    //                     MetaData style1 = TextElement.getStyleMD(md1);
    //                     if (!style1.getString().equals("0"))
    //                        continue;
    //                     MetaData md2 = BookImporter.getAtRank(region, i+1);
    //                     if (md2 == null || !md2.getType().equals(MetaData.textType))
    //                        continue;
    //                     MetaData style2 = TextElement.getStyleMD(md2);
    //                     if (!style2.getString().equals("1"))
    //                        continue;
    //                     BookImporter.setRank(md1, i+1);
    //                     BookImporter.setRank(md2, i);
    //                     i++;
    //                  }
    //               }
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            MetaDataKey mini = book.getLink().getOrCreateKey("mini", "");
    //            MetaDataKey dim = book.getLink().getOrCreateKey("dimension", "");
    //            int lastPage = book.getLastPageNumber();
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               List<MetaData> mds = page.getMetaDataListForKey(mini);
    //               if (mds != null)
    //                  for (MetaData md : mds)
    //                     page.removeMetaData(md);
    //               mds = page.getMetaDataListForKey(dim);
    //               if (mds != null)
    //                  for (MetaData md : mds)
    //                     page.removeMetaData(md);
    //               DocExploreDataLink.getImageDimension(page, true);
    //               DocExploreDataLink.getImageMini(page, false);
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));

    add(edit);

    JMenu view = new JMenu(XMLResourceBundle.getBundledString("generalMenuView"));
    add(view);

    JMenuItem styles = new JMenuItem(XMLResourceBundle.getBundledString("styleEdit") + "...",
            ImageUtils.getIcon("pencil-24x24.png"));
    styles.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            authoringTool.styleManager.styleDialog.setVisible(true);
        }
    });
    view.add(styles);

    helpToggle = new JCheckBoxMenuItem(
            new AbstractAction(XMLResourceBundle.getBundledString("viewHelpToggle")) {
                public void actionPerformed(ActionEvent arg0) {
                    authoringTool.displayHelp = helpToggle.isSelected();
                    authoringTool.repaint();
                }
            });
    helpToggle.setSelected(tool.startup.showHelp);
    view.add(helpToggle);

    JMenu helpMenu = new JMenu(XMLResourceBundle.getString("management-lrb", "generalMenuHelp"));
    if (Desktop.isDesktopSupported()) {
        final Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            helpMenu.add(new AbstractAction(
                    XMLResourceBundle.getString("management-lrb", "generalMenuHelpContents")) {
                public void actionPerformed(ActionEvent e) {
                    try {
                        File doc = new File(DocExploreTool.getExecutableDir(), "MMT documentation.htm");
                        desktop.open(doc);
                    } catch (Exception ex) {
                        ErrorHandler.defaultHandler.submit(ex, true);
                    }
                }
            });
            helpMenu.add(new AbstractAction(
                    XMLResourceBundle.getString("management-lrb", "generalMenuHelpWebsite")) {
                public void actionPerformed(ActionEvent e) {
                    try {
                        File link = new File(DocExploreTool.getExecutableDir(), "website.url");
                        desktop.open(link);
                    } catch (Exception ex) {
                        ErrorHandler.defaultHandler.submit(ex, true);
                    }
                }
            });
        }
    }
    helpMenu.add(new AbstractAction(XMLResourceBundle.getString("management-lrb", "generalMenuHelpAbout")) {
        public void actionPerformed(ActionEvent e) {
            final JDialog splash = new JDialog(tool, true);
            splash.setLayout(new BorderLayout());
            SplashScreen screen = new SplashScreen("logoAT.png");
            splash.add(screen, BorderLayout.NORTH);
            screen.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent e) {
                    splash.setVisible(false);
                }
            });
            splash.setUndecorated(true);
            screen.setText(
                    "<html>DocExplore 2009-2014" + "<br/>Released under the CeCILL v2.1 license" + "</html>");
            splash.pack();
            splash.setAlwaysOnTop(true);
            GuiUtils.centerOnScreen(splash);
            splash.setVisible(true);
        }
    });
    add(helpMenu);

    historyChanged(authoringTool.historyManager);
    authoringTool.historyManager.addHistoryListener(this);
}

From source file:org.interreg.docexplore.GeneralConfigPanel.java

String browseClasses(File file) {
    try {/*from w  w w  .  j  a va 2 s .com*/
        List<Class<?>> metaDataPlugins = new LinkedList<Class<?>>();
        List<Class<?>> analysisPlugins = new LinkedList<Class<?>>();
        List<Class<?>> clientPlugins = new LinkedList<Class<?>>();
        List<Class<?>> serverPlugins = new LinkedList<Class<?>>();
        List<Class<?>> inputPlugins = new LinkedList<Class<?>>();

        List<URL> urls = Startup.extractDependencies(file.getName().substring(0, file.getName().length() - 4),
                file.getName());
        urls.add(file.toURI().toURL());
        URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[] {}),
                this.getClass().getClassLoader());

        JarFile jarFile = new JarFile(file);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (!entry.getName().endsWith(".class") || entry.getName().indexOf('$') > 0)
                continue;
            String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.');
            Class<?> clazz = null;
            try {
                clazz = loader.loadClass(className);
                System.out.println("Reading " + className);
            } catch (NoClassDefFoundError e) {
                System.out.println("Couldn't read " + className);
            }
            if (clazz == null)
                continue;

            if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()))
                continue;
            if (MetaDataPlugin.class.isAssignableFrom(clazz))
                metaDataPlugins.add(clazz);
            if (AnalysisPlugin.class.isAssignableFrom(clazz))
                analysisPlugins.add(clazz);
            if (ClientPlugin.class.isAssignableFrom(clazz))
                clientPlugins.add(clazz);
            if (ServerPlugin.class.isAssignableFrom(clazz))
                serverPlugins.add(clazz);
            if (InputPlugin.class.isAssignableFrom(clazz))
                inputPlugins.add(clazz);
        }
        jarFile.close();

        @SuppressWarnings("unchecked")
        Pair<String, String>[] classes = new Pair[metaDataPlugins.size() + analysisPlugins.size()
                + clientPlugins.size() + serverPlugins.size() + inputPlugins.size()];
        if (classes.length == 0)
            throw new Exception("Invalid plugin (no entry points were found).");

        int cnt = 0;
        for (Class<?> clazz : metaDataPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "MetaData plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : analysisPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Analysis plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : clientPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader client plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : serverPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader server plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : inputPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader input plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        @SuppressWarnings("unchecked")
        Pair<String, String> res = (Pair<String, String>) JOptionPane.showInputDialog(this,
                "Please select an entry point for the plugin:", "Plugin entry point",
                JOptionPane.QUESTION_MESSAGE, null, classes, classes[0]);
        if (res != null)
            return res.first;
    } catch (Throwable e) {
        ErrorHandler.defaultHandler.submit(e);
    }
    return null;
}

From source file:org.jets3t.apps.cockpitlite.CockpitLite.java

/**
 * Performs the real work of downloading files by comparing the download candidates against
 * existing files, prompting the user whether to overwrite any pre-existing file versions,
 * and starting {@link S3ServiceMulti#downloadObjects} where the real work is done.
 *
 *//* w w  w . j  a  va 2s  . c om*/
private void performObjectsDownload(FileComparerResults comparisonResults, Map s3DownloadObjectsMap) {
    try {

        // Determine which files to download, prompting user whether to over-write existing files
        List objectKeysForDownload = new ArrayList();
        objectKeysForDownload.addAll(comparisonResults.onlyOnServerKeys);

        int newFiles = comparisonResults.onlyOnServerKeys.size();
        int unchangedFiles = comparisonResults.alreadySynchronisedKeys.size();
        int changedFiles = comparisonResults.updatedOnClientKeys.size()
                + comparisonResults.updatedOnServerKeys.size();

        if (unchangedFiles > 0 || changedFiles > 0) {
            // Ask user whether to replace existing unchanged and/or existing changed files.
            log.debug(
                    "Files for download clash with existing local files, prompting user to choose which files to replace");
            List options = new ArrayList();
            String message = "Of the " + (newFiles + unchangedFiles + changedFiles)
                    + " object(s) being downloaded:\n\n";

            if (newFiles > 0) {
                message += newFiles + " file(s) are new.\n\n";
                options.add(DOWNLOAD_NEW_FILES_ONLY);
            }
            if (changedFiles > 0) {
                message += changedFiles + " file(s) have changed.\n\n";
                options.add(DOWNLOAD_NEW_AND_CHANGED_FILES);
            }
            if (unchangedFiles > 0) {
                message += unchangedFiles + " file(s) already exist and are unchanged.\n\n";
                options.add(DOWNLOAD_ALL_FILES);
            }
            message += "Please choose which file(s) you wish to download:";

            Object response = JOptionPane.showInputDialog(ownerFrame, message, "Replace file(s)?",
                    JOptionPane.QUESTION_MESSAGE, null, options.toArray(), DOWNLOAD_NEW_AND_CHANGED_FILES);

            if (response == null) {
                return;
            }

            if (DOWNLOAD_NEW_FILES_ONLY.equals(response)) {
                // No change required to default objectKeysForDownload list.
            } else if (DOWNLOAD_ALL_FILES.equals(response)) {
                objectKeysForDownload.addAll(comparisonResults.updatedOnClientKeys);
                objectKeysForDownload.addAll(comparisonResults.updatedOnServerKeys);
                objectKeysForDownload.addAll(comparisonResults.alreadySynchronisedKeys);
            } else if (DOWNLOAD_NEW_AND_CHANGED_FILES.equals(response)) {
                objectKeysForDownload.addAll(comparisonResults.updatedOnClientKeys);
                objectKeysForDownload.addAll(comparisonResults.updatedOnServerKeys);
            } else {
                // Download cancelled.
                return;
            }
        }

        log.debug("Downloading " + objectKeysForDownload.size() + " objects");
        if (objectKeysForDownload.size() == 0) {
            return;
        }

        // Create array of objects for download.
        final S3Object[] objects = new S3Object[objectKeysForDownload.size()];
        int objectIndex = 0;
        for (Iterator iter = objectKeysForDownload.iterator(); iter.hasNext();) {
            objects[objectIndex++] = (S3Object) s3DownloadObjectsMap.get(iter.next());
        }

        (new Thread() {
            @Override
            public void run() {
                try {
                    SignatureRequest[] signedRequests = requestSignedRequests(
                            SignatureRequest.SIGNATURE_TYPE_GET, objects);

                    if (signedRequests != null) {
                        // Setup files to write to, creating parent directories when necessary.
                        downloadObjectsToFileMap = new HashMap();
                        ArrayList downloadPackageList = new ArrayList();
                        for (int i = 0; i < signedRequests.length; i++) {
                            S3Object object = signedRequests[i].buildObject();

                            File file = new File(downloadDirectory, object.getKey());

                            // Create local directories corresponding to objects flagged as dirs.
                            if (object.isDirectoryPlaceholder()) {
                                file = new File(downloadDirectory,
                                        ObjectUtils.convertDirPlaceholderKeyNameToDirName(objects[i].getKey()));
                                file.mkdirs();
                            }

                            DownloadPackage downloadPackage = ObjectUtils.createPackageForDownload(object, file,
                                    true, false, null);
                            if (downloadPackage == null) {
                                continue;
                            }
                            downloadPackage.setSignedUrl(signedRequests[i].getSignedUrl());

                            downloadObjectsToFileMap.put(object.getKey(), file);
                            downloadPackageList.add(downloadPackage);
                        }
                        DownloadPackage[] downloadPackagesArray = (DownloadPackage[]) downloadPackageList
                                .toArray(new DownloadPackage[downloadPackageList.size()]);

                        // Perform downloads.
                        s3ServiceMulti.downloadObjects(downloadPackagesArray);
                    }
                } catch (Exception e) {
                    log.error("Download failed", e);
                    ErrorDialog.showDialog(ownerFrame, null, cockpitLiteProperties.getProperties(),
                            "Download failed, please try again", e);
                }
            }
        }).start();
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        String message = "Unable to download objects";
        log.error(message, e);
        ErrorDialog.showDialog(ownerFrame, this, cockpitLiteProperties.getProperties(), message, e);
    }
}

From source file:org.jets3t.apps.cockpitlite.CockpitLite.java

private void performFilesUpload(FileComparerResults comparisonResults,
        Map<String, String> objectKeyToFilepathMap) {
    try {/*from  ww w  . jav  a  2  s.c  o  m*/
        // Determine which files to upload, prompting user whether to over-write existing files
        List fileKeysForUpload = new ArrayList();
        fileKeysForUpload.addAll(comparisonResults.onlyOnClientKeys);

        int newFiles = comparisonResults.onlyOnClientKeys.size();
        int unchangedFiles = comparisonResults.alreadySynchronisedKeys.size();
        int changedFiles = comparisonResults.updatedOnClientKeys.size()
                + comparisonResults.updatedOnServerKeys.size();

        if (unchangedFiles > 0 || changedFiles > 0) {
            // Ask user whether to replace existing unchanged and/or existing changed files.
            log.debug(
                    "Files for upload clash with existing S3 objects, prompting user to choose which files to replace");
            List options = new ArrayList();
            String message = "Of the " + objectKeyToFilepathMap.size() + " file(s) being uploaded:\n\n";

            if (newFiles > 0) {
                message += newFiles + " file(s) are new.\n\n";
                options.add(UPLOAD_NEW_FILES_ONLY);
            }
            if (changedFiles > 0) {
                message += changedFiles + " file(s) have changed.\n\n";
                options.add(UPLOAD_NEW_AND_CHANGED_FILES);
            }
            if (unchangedFiles > 0) {
                message += unchangedFiles + " file(s) already exist and are unchanged.\n\n";
                options.add(UPLOAD_ALL_FILES);
            }
            message += "Please choose which file(s) you wish to upload:";

            Object response = JOptionPane.showInputDialog(ownerFrame, message, "Replace file(s)?",
                    JOptionPane.QUESTION_MESSAGE, null, options.toArray(), UPLOAD_NEW_AND_CHANGED_FILES);

            if (response == null) {
                return;
            }

            if (UPLOAD_NEW_FILES_ONLY.equals(response)) {
                // No change required to default fileKeysForUpload list.
            } else if (UPLOAD_ALL_FILES.equals(response)) {
                fileKeysForUpload.addAll(comparisonResults.updatedOnClientKeys);
                fileKeysForUpload.addAll(comparisonResults.updatedOnServerKeys);
                fileKeysForUpload.addAll(comparisonResults.alreadySynchronisedKeys);
            } else if (UPLOAD_NEW_AND_CHANGED_FILES.equals(response)) {
                fileKeysForUpload.addAll(comparisonResults.updatedOnClientKeys);
                fileKeysForUpload.addAll(comparisonResults.updatedOnServerKeys);
            } else {
                // Upload cancelled.
                stopProgressDialog();
                return;
            }
        }

        if (fileKeysForUpload.size() == 0) {
            return;
        }

        final String[] statusText = new String[1];
        statusText[0] = "Prepared 0 of " + fileKeysForUpload.size() + " file(s) for upload";
        startProgressDialog(statusText[0], "", 0, 100, null, null);

        long bytesToProcess = 0;
        for (Iterator iter = fileKeysForUpload.iterator(); iter.hasNext();) {
            File file = new File(objectKeyToFilepathMap.get(iter.next().toString()));
            bytesToProcess += file.length();
        }

        BytesProgressWatcher progressWatcher = new BytesProgressWatcher(bytesToProcess) {
            @Override
            public void updateBytesTransferred(long byteCount) {
                super.updateBytesTransferred(byteCount);

                String detailsText = formatBytesProgressWatcherDetails(this, false);
                int progressValue = (int) ((double) getBytesTransferred() * 100 / getBytesToTransfer());
                updateProgressDialog(statusText[0], detailsText, progressValue);
            }
        };

        // Populate S3Objects representing upload files with metadata etc.
        final S3Object[] objects = new S3Object[fileKeysForUpload.size()];
        int objectIndex = 0;
        for (Iterator iter = fileKeysForUpload.iterator(); iter.hasNext();) {
            String fileKey = iter.next().toString();
            File file = new File(objectKeyToFilepathMap.get(fileKey));

            S3Object newObject = ObjectUtils.createObjectForUpload(fileKey, file, null, false, progressWatcher);

            statusText[0] = "Prepared " + (objectIndex + 1) + " of " + fileKeysForUpload.size()
                    + " file(s) for upload";

            objects[objectIndex++] = newObject;
        }

        stopProgressDialog();

        // Confirm we have permission to do this.
        SignatureRequest[] signedRequests = requestSignedRequests(SignatureRequest.SIGNATURE_TYPE_PUT, objects);

        if (signedRequests != null) {
            // Upload the files.
            SignedUrlAndObject[] urlAndObjs = new SignedUrlAndObject[signedRequests.length];
            for (int i = 0; i < signedRequests.length; i++) {
                urlAndObjs[i] = new SignedUrlAndObject(signedRequests[i].getSignedUrl(), objects[i]);
            }

            s3ServiceMulti.putObjects(urlAndObjs);
        }

    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        stopProgressDialog();
        String message = "Unable to upload object(s)";
        log.error(message, e);
        ErrorDialog.showDialog(ownerFrame, this, cockpitLiteProperties.getProperties(), message, e);
    }
}

From source file:org.jets3t.apps.cockpitlite.CockpitLite.java

private void generatePublicGetUrl() {
    final S3Object[] objects = getSelectedObjects();

    if (objects.length != 1) {
        log.warn("Ignoring Generate Public URL object command, can only operate on a single object");
        return;/*from w w  w.  j  av  a2s .  c o  m*/
    }
    S3Object currentObject = objects[0];

    try {
        String hostAndBucket = null;
        if (userVanityHost != null) {
            hostAndBucket = userVanityHost;
        } else {
            boolean disableDnsBuckets = false;

            String s3Endpoint = Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME)
                    .getStringProperty("s3service.s3-endpoint", Constants.S3_DEFAULT_HOSTNAME);
            hostAndBucket = ServiceUtils.generateS3HostnameForBucket(userBucketName, disableDnsBuckets,
                    s3Endpoint);

            if (!ServiceUtils.isBucketNameValidDNSName(userBucketName)) {
                // If bucket name isn't DNS compatible, we must include the bucket
                // name as a URL path item.
                hostAndBucket += "/" + userBucketName;
            }
        }

        String url = "http://" + hostAndBucket + "/" + userPath + currentObject.getKey();

        // Display signed URL
        String dialogText = "Public URL for '" + currentObject.getKey() + "'.";
        // Ensure dialog text is at least 150 characters (to force dialog to be wider)
        if (dialogText.length() < 150) {
            int charsShort = 150 - dialogText.length();
            StringBuffer padding = new StringBuffer();
            for (int i = 0; i < charsShort / 2; i++) {
                padding.append(" ");
            }
            dialogText = padding.toString() + dialogText + padding.toString();
        }

        JOptionPane.showInputDialog(ownerFrame, dialogText, "URL", JOptionPane.INFORMATION_MESSAGE, null, null,
                url);

    } catch (NumberFormatException e) {
        String message = "Hours must be a valid decimal value; eg 3, 0.1";
        log.error(message, e);
        ErrorDialog.showDialog(ownerFrame, this, cockpitLiteProperties.getProperties(), message, e);
    } catch (Exception e) {
        String message = "Unable to generate public GET URL";
        log.error(message, e);
        ErrorDialog.showDialog(ownerFrame, this, cockpitLiteProperties.getProperties(), message, e);
    }
}

From source file:org.kepler.gui.RenameComponentEntityAction.java

public void actionPerformed(ActionEvent e) {
    super.actionPerformed(e);

    if (isDebugging)
        log.debug("RenameComponentEntityAction.actionPerformed()");

    NamedObj object = null;//from  ww w  . j a  v  a  2 s .co m
    if (_obj == null) {
        object = getTarget();
    } else {
        object = _obj;
    }

    if (isDebugging)
        log.debug(object.getClass().getName());

    if (object instanceof ComponentEntity) {

        // TODO very similar to code in RenameComponentEntityAction,
        // find a way to merge?

        Component parentComponent = (Component) _parent;
        String message = "Enter a new name: ";
        String warnMessage = "ERROR name cannot contain the < sign";
        String title = "Rename";
        int messageType = JOptionPane.QUESTION_MESSAGE;
        String initialValue = object.getName();

        String newName = (String) JOptionPane.showInputDialog(parentComponent, message, title, messageType,
                null, null, initialValue);
        if (newName == null) {
            // user hit the cancel button
            return;
        }

        int lessThan = newName.indexOf("<");
        if (lessThan >= 0) {
            JOptionPane.showMessageDialog(parentComponent, warnMessage, "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {

            RenameUtil.renameComponentEntity((ComponentEntity) object, newName);
            _parent.setTitle(object.getName());

        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(_parent, "A problem occured.");
        }
    }

}

From source file:org.monome.pages.AbletonClipSkipperPage.java

public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Add MIDI Output")) {
        String[] midiOutOptions = this.monome.getMidiOutOptions();
        String deviceName = (String) JOptionPane.showInputDialog(this.monome, "Choose a MIDI Output to add",
                "Add MIDI Output", JOptionPane.PLAIN_MESSAGE, null, midiOutOptions, "");

        if (deviceName == null) {
            return;
        }/* www  .  j a  v  a  2 s .c om*/
        this.addMidiOutDevice(deviceName);
    }

    if (e.getActionCommand().equals("Refresh from Ableton")) {
        this.refreshAbleton();
    }
}

From source file:org.monome.pages.MachineDrumInterfacePage.java

public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Set MIDI Output")) {
        String[] midiOutOptions = this.monome.getMidiOutOptions();
        String deviceName = (String) JOptionPane.showInputDialog(this.monome, "Choose a MIDI Output to add",
                "Set MIDI Output", JOptionPane.PLAIN_MESSAGE, null, midiOutOptions, "");

        if (deviceName == null) {
            return;
        }//from w  w  w  .j  a  v a 2 s .c om

        this.addMidiOutDevice(deviceName);
    }

    if (e.getActionCommand().equals("Update Preferences")) {
        this.speed = Integer.parseInt(this.getSpeedTF().getText());
    }
}

From source file:org.monome.pages.MIDIFadersPage.java

public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Add MIDI Output")) {
        String[] midiOutOptions = this.monome.getMidiOutOptions();
        String deviceName = (String) JOptionPane.showInputDialog(this.monome, "Choose a MIDI Output to add",
                "Add MIDI Output", JOptionPane.PLAIN_MESSAGE, null, midiOutOptions, "");

        if (deviceName == null) {
            return;
        }/*from   w w w  .j av  a 2  s.  c  om*/

        this.addMidiOutDevice(deviceName);
    }

    if (e.getActionCommand().equals("Update Preferences")) {
        this.delayAmount = Integer.parseInt(this.getDelayTF().getText());
        this.midiChannel = Integer.parseInt(this.getChannelTF().getText()) - 1;
        if (this.midiChannel < 0)
            this.midiChannel = 0;
        this.ccOffset = Integer.parseInt(this.getCcOffsetTF().getText());
    }
}