Example usage for java.awt Desktop getDesktop

List of usage examples for java.awt Desktop getDesktop

Introduction

In this page you can find the example usage for java.awt Desktop getDesktop.

Prototype

public static synchronized Desktop getDesktop() 

Source Link

Document

Returns the Desktop instance of the current desktop context.

Usage

From source file:com.igormaznitsa.ideamindmap.utils.IdeaUtils.java

public static void openInSystemViewer(@Nonnull final DialogProvider dialogProvider,
        @Nullable final VirtualFile theFile) {
    final File file = vfile2iofile(theFile);

    if (file == null) {
        LOGGER.error("Can't find file to open, null provided");
        dialogProvider.msgError("Can't find file to open");
    } else {//from w  w w.j  a v a  2  s .  c om
        final Runnable startEdit = new Runnable() {
            @Override
            public void run() {
                boolean ok = false;
                if (Desktop.isDesktopSupported()) {
                    final Desktop dsk = Desktop.getDesktop();
                    if (dsk.isSupported(Desktop.Action.OPEN)) {
                        try {
                            dsk.open(file);
                            ok = true;
                        } catch (Throwable ex) {
                            LOGGER.error("Can't open file in system viewer : " + file, ex);//NOI18N
                        }
                    }
                }
                if (!ok) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialogProvider.msgError("Can't open file in system viewer! See the log!");//NOI18N
                            Toolkit.getDefaultToolkit().beep();
                        }
                    });
                }
            }
        };
        final Thread thr = new Thread(startEdit, " MMDStartFileEdit");//NOI18N
        thr.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(final Thread t, final Throwable e) {
                LOGGER.error("Detected uncaught exception in openInSystemViewer() for file " + file, e);
            }
        });

        thr.setDaemon(true);
        thr.start();
    }
}

From source file:com.ethercamp.harmony.desktop.HarmonyDesktop.java

private static void openBrowser(String url) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {/*  w w  w  . jav  a 2s  .  c  o  m*/
            desktop.browse(URI.create(url));
        } catch (Exception e) {
            log.error("Problem opening browser", e);
        }
    }
}

From source file:de.perdoctus.ebikeconnect.gui.MainWindowController.java

public void openGithubUrl() {
    if (Desktop.isDesktopSupported()) {
        try {/*from   ww  w  .  j av  a2  s  .co  m*/
            Desktop.getDesktop().browse(URI.create(rb.getString("github-url")));
        } catch (IOException e) {
            logger.error("Failed to open browser.", e);
        }
    }
}

From source file:org.isatools.isacreator.ontologyselectiontool.ViewTermDefinitionUI.java

private JPanel createOntologyInformationPane(final OntologyBranch term) {
    JPanel contentPane = new JPanel(new BorderLayout());
    contentPane.setBackground(Color.WHITE);
    contentPane.setBorder(new EmptyBorder(2, 2, 2, 2));

    JEditorPane ontologyInfoPane = createOntologyInformationDisplay(term);

    JScrollPane ontologyInfoScroller = new JScrollPane(ontologyInfoPane,
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    ontologyInfoScroller.getViewport().setBackground(UIHelper.BG_COLOR);
    ontologyInfoScroller.setBorder(new EmptyBorder(2, 2, 2, 2));

    IAppWidgetFactory.makeIAppScrollPane(ontologyInfoScroller);

    contentPane.add(ontologyInfoScroller, BorderLayout.CENTER);

    JLabel viewOntologyInBrowser = new JLabel("View in resource.");
    viewOntologyInBrowser.addMouseListener(new CommonMouseAdapter() {
        @Override/*from  w  w w . ja v  a 2  s.  co  m*/
        public void mouseExited(MouseEvent mouseEvent) {
            super.mouseExited(mouseEvent);
        }

        @Override
        public void mouseEntered(MouseEvent mouseEvent) {
            super.mouseEntered(mouseEvent);
        }

        @Override
        public void mousePressed(MouseEvent mouseEvent) {
            super.mousePressed(mouseEvent);
            try {
                String termSource = term.getComments().get("Source");
                System.out.println("Source: " + termSource);
                System.out.println("Accession: " + term.getBranchIdentifier());
                String serviceProvider = term.getComments().get("Service Provider");

                System.out.println("Service Provider: " + serviceProvider);
                String url = "";

                if (serviceProvider.equalsIgnoreCase("ols")) {
                    url = "http://www.ebi.ac.uk/ontology-lookup/?termId=" + termSource + ":"
                            + term.getComments().get("accession");
                } else if (serviceProvider.equalsIgnoreCase("bioportal")) {
                    url = "http://bioportal.bioontology.org/ontologies/"
                            + termSource.substring(termSource.lastIndexOf("/") + 1) + "?p=classes&conceptid="
                            + term.getBranchIdentifier();
                }

                System.out.println(url);
                Desktop.getDesktop().browse(new URI(url));
            } catch (Exception e) {
                System.err.println("Unable to open URL: " + e.getMessage());
            }
        }
    });

    UIHelper.renderComponent(viewOntologyInBrowser, UIHelper.VER_10_BOLD, new Color(28, 117, 188), false);
    contentPane.add(viewOntologyInBrowser, BorderLayout.SOUTH);

    return contentPane;
}

From source file:gdt.jgui.entity.procedure.JProcedurePanel.java

/**
 * Get the context menu./*from   w w w .  j a  v a  2 s . c o  m*/
 * @return the context menu.
 */
@Override
public JMenu getContextMenu() {
    menu = new JMenu("Context");
    menu.addMenuListener(new MenuListener() {
        @Override
        public void menuSelected(MenuEvent e) {
            menu.removeAll();
            JMenuItem runItem = new JMenuItem("Run");
            runItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    run();
                }
            });
            menu.add(runItem);
            Entigrator entigrator = console.getEntigrator(entihome$);
            Sack procedure = entigrator.getEntityAtKey(entityKey$);
            if (procedure.getElementItem("parameter", "noreset") == null) {
                JMenuItem resetItem = new JMenuItem("Reset");
                resetItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int response = JOptionPane.showConfirmDialog(console.getContentPanel(),
                                "Reset source to default ?", "Confirm", JOptionPane.YES_NO_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (response == JOptionPane.YES_OPTION)
                            reset();
                    }
                });
                menu.add(resetItem);
            }
            JMenuItem folderItem = new JMenuItem("Open folder");
            folderItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        File file = new File(entihome$ + "/" + entityKey$);
                        Desktop.getDesktop().open(file);
                    } catch (Exception ee) {
                        Logger.getLogger(getClass().getName()).info(ee.toString());
                    }
                }
            });
            menu.add(folderItem);
            try {
                //Entigrator entigrator=console.getEntigrator(entihome$);
                Sack entity = entigrator.getEntityAtKey(entityKey$);
                String template$ = entity.getAttributeAt("template");
                if (template$ != null) {
                    JMenuItem adaptClone = new JMenuItem("Adapt clone");
                    adaptClone.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            try {
                                adaptClone(console, getLocator());
                            } catch (Exception ee) {
                                Logger.getLogger(getClass().getName()).info(ee.toString());
                            }
                        }
                    });
                    menu.add(adaptClone);
                }
            } catch (Exception ee) {
                Logger.getLogger(getClass().getName()).info(ee.toString());
            }
        }

        @Override
        public void menuDeselected(MenuEvent e) {
        }

        @Override
        public void menuCanceled(MenuEvent e) {
        }
    });
    return menu;
}

From source file:savant.view.dialog.PluginRepositoryDialog.java

public final Component getCenterPanel(List<TreeBrowserEntry> roots) {
    table = new TreeTable(new TreeBrowserModel(roots) {
        @Override//from ww  w .  j a  v a2 s. c  om
        public String[] getColumnNames() {
            return new String[] { "Name", "Description", "Web Site" };
        }

        @Override
        public CellStyle getCellStyleAt(int rowIndex, int columnIndex) {
            return null;
        }
    });
    table.setSortable(true);
    table.setRespectRenderPreferredHeight(true);

    // configure the TreeTable
    table.setExpandAllAllowed(true);
    table.setShowTreeLines(false);
    table.setSortingEnabled(false);
    table.setRowHeight(18);
    table.setShowGrid(false);
    table.setIntercellSpacing(new Dimension(0, 0));
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    //table.expandAll();
    table.expandFirstLevel();
    table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int col = table.columnAtPoint(e.getPoint());
            if (col == 2) {
                Object o = table.getModel().getValueAt(table.rowAtPoint(e.getPoint()), col);
                if (o != null && (o instanceof URL)) {
                    System.out.println(o.toString());
                    try {
                        Desktop.getDesktop().browse(((URL) o).toURI());
                    } catch (Exception x) {
                        LOG.error("Unable to open link for " + o, x);
                    }
                    return;
                }
            }
            if (e.getClickCount() == 2) {
                downloadSelectedItem(true);
            }
        }
    });

    // do not select row when expanding a row.
    table.setSelectRowWhenToggling(false);

    table.getColumnModel().getColumn(0).setPreferredWidth(200);
    table.getColumnModel().getColumn(1).setPreferredWidth(520);
    table.getColumnModel().getColumn(2).setPreferredWidth(80);

    table.getColumnModel().getColumn(0).setCellRenderer(new FileRowCellRenderer());
    table.getColumnModel().getColumn(2).setCellRenderer(new WebLinkRenderer());

    // add searchable feature
    TableSearchable searchable = new TableSearchable(table) {

        @Override
        protected String convertElementToString(Object item) {
            if (item instanceof TreeBrowserEntry) {
                return ((TreeBrowserEntry) item).getType();
            }
            return super.convertElementToString(item);
        }
    };
    searchable.setMainIndex(0); // only search for name column

    JScrollPane scrollPane = new JScrollPane(table);

    JPanel panel = new JPanel(new BorderLayout(6, 6));
    panel.add(scrollPane, BorderLayout.CENTER);
    panel.setPreferredSize(new Dimension(800, 500));
    return panel;
}

From source file:Exporters.ExportToWord.java

public void compileNotes(File outfile, Vulnerability vuln) {
    System.out.println("==ExportToWord=compileNotes: " + outfile.getAbsolutePath());
    try {//from   w w w .j  a va 2  s. co  m

        WordprocessingMLPackage template = getTemplate();
        MainDocumentPart bodyPart = template.getMainDocumentPart();

        // get and delete the vuln table from the document.
        //List<Object> Tables = getAllElementFromObject(bodyPart, XWPFTable.class);
        //XWPFTable table = (XWPFTable)Tables.get(0);
        /*
        List<Object> content = bodyPart.getContent();
        Iterator it = content.iterator();
        while (it.hasNext()) {
        Object obj = it.next();
        content.remove(obj);
        }
            */

        bodyPart.addStyledParagraphOfText("Heading2", vuln.getTitle());

        Enumeration enums = vuln.getAffectedHosts().elements();
        while (enums.hasMoreElements()) {
            Host host = (Host) enums.nextElement();
            String header = host.getIp_address() + " - " + host.getHostname() + " - " + host.getPortnumber()
                    + "/" + host.getProtocol();
            bodyPart.addStyledParagraphOfText("Heading3", header);
            Note note = host.getNotes();
            String[] paragraphs = note.getNote_text().split("\\n");
            for (String para : paragraphs) {
                bodyPart.addStyledParagraphOfText("Code", para);
            }
        }

        if (outfile.exists() == false) {
            template.save(outfile);
        }

        try {
            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().open(outfile);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

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

}

From source file:com.k42b3.neodym.oauth.Oauth.java

public boolean authorizeToken() throws Exception {
    String url;/*from  ww w .j ava 2s  .co  m*/

    if (this.provider.getAuthorizationUrl().indexOf('?') == -1) {
        url = this.provider.getAuthorizationUrl() + "?oauth_token=" + this.token;
    } else {
        url = this.provider.getAuthorizationUrl() + "&oauth_token=" + this.token;
    }

    URI authUrl = new URI(url);

    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();

        if (desktop.isSupported(Desktop.Action.BROWSE)) {
            desktop.browse(authUrl);
        } else {
            JOptionPane.showMessageDialog(null, "Visit the following URL: " + authUrl);
        }
    } else {
        JOptionPane.showMessageDialog(null, "Visit the following URL: " + authUrl);
    }

    verificationCode = JOptionPane.showInputDialog("Please enter the verification Code");

    return true;
}

From source file:io.bitsquare.common.util.Utilities.java

public static void openDirectory(File directory) throws IOException {
    if (!isLinux() && Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
        Desktop.getDesktop().open(directory);
    } else {/*from   ww  w .  ja  va2  s.c  om*/
        // Maybe Application.HostServices works in those cases?
        // HostServices hostServices = getHostServices();
        // hostServices.showDocument(uri.toString());

        // On Linux Desktop is poorly implemented.
        // See https://stackoverflow.com/questions/18004150/desktop-api-is-not-supported-on-the-current-platform
        if (!DesktopUtil.open(directory))
            throw new IOException("Failed to open directory: " + directory.toString());
    }
}

From source file:de.atomfrede.tools.evalutation.tools.plot.ui.wizard.simple.SimplePlotWizard.java

@Override
public void onFinished(List<WizardPage> arg0, WizardSettings arg1) {
    this.setVisible(false);

    busyDialog = new BusyDialog("Please wait while plots are generated...");
    busyDialog.setLocationRelativeTo(DialogUtil.getInstance().getFrame());
    DialogUtil.getInstance().showStandardDialog(busyDialog);

    SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {

        @Override/*from   w  w  w  . j  a  va 2  s .  c om*/
        protected Object doInBackground() throws Exception {
            StringBuilder fileNameBuilder = new StringBuilder();
            // first collect all datasets
            List<XYDatasetWrapper> wrappers = ((DatasetSelectionWizardPage) pages.get(1)).getDatasetWrappers();
            XYDatasetWrapper[] wrappersArray = new XYDatasetWrapper[wrappers.size()];

            int width = ((FileSelectionWizardPage) pages.get(0)).getEnteredWidth();
            int height = ((FileSelectionWizardPage) pages.get(0)).getEnteredHeight();

            int i = 0;
            for (XYDatasetWrapper wrapper : wrappers) {
                wrappersArray[i] = wrapper;
                if (i == 0)
                    fileNameBuilder.append(wrapper.getSeriesName());
                else
                    fileNameBuilder.append("-" + wrapper.getSeriesName());
                i++;
            }

            String date = DateFormat.getDateInstance().format(new Date());

            String fileName = date + "-" + fileNameBuilder.toString();
            CustomSimplePlot timePlot = new CustomSimplePlot(dataFile, fileName, width, height, wrappersArray);
            try {
                timePlot.plot();
            } catch (Exception e) {
                log.error("The requested data could not be plotted", e);
            }
            try {
                Desktop.getDesktop().open(new File(Options.getOutputFolder(), fileName + ".pdf"));
            } catch (IOException e) {
                log.error("Generated file could not be opened.", e);
            }

            return null;
        }

        @Override
        protected void done() {
            busyDialog.dispose();
            dispose();
        }

    };

    worker.execute();

}