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:edu.scripps.fl.pubchem.xmltool.gui.PubChemXMLCreatorGUI.java

public void actionPerformed(ActionEvent e) {
    try {/*from   w w  w .ja v a2  s  .  c om*/
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        if (e.getSource() == jbnFileTemplate) {
            gc.fileChooser(jtfFileTemplate, ".xml", "open");
            jtfFileTemplate.setEnabled(true);
        } else if (e.getSource() == jbnFileExcel) {
            gc.fileChooser(jtfFileExcel, ".xlsx", "open");
        } else if (e.getSource() == jbnRunCreator) {
            String stringTemplate = jtfFileTemplate.getText();
            InputStream fileTemplate;
            if (stringTemplate.equals(template) | stringTemplate.equals("")) {
                URL url = getClass().getClassLoader().getResource("blank.xml");
                fileTemplate = url.openStream();
            } else
                fileTemplate = new FileInputStream(jtfFileTemplate.getText());
            File fileExcel = new File(jtfFileExcel.getText());
            File fileOutput = File.createTempFile("pubchem", ".xml");
            fileOutput.deleteOnExit();
            PubChemAssay assay = new PubChemXMLCreatorController().createPubChemXML(fileTemplate, fileExcel,
                    fileOutput);
            String message = assay.getMessage();
            if (!message.equals("")) {
                int nn = JOptionPane.showOptionDialog(this,
                        notError + message + "\nWould you like to edit your Excel Workbook?", SwingGUI.APP_NAME,
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
                if (nn == JOptionPane.YES_OPTION) {
                    log.info("Opening Excel Workbook with Desktop: " + fileExcel);
                    Desktop.getDesktop().open(fileExcel);
                } else {
                    log.info("Opening XML file: " + fileOutput);
                    Desktop.getDesktop().open(fileOutput);
                }
            } else {
                log.info("Opening XML file: " + fileOutput);
                Desktop.getDesktop().open(fileOutput);
            }
        } else if (e.getSource() == jbnReportCreator) {
            File fileExcel = new File(jtfFileExcel.getText());
            File filePDFOutput = File.createTempFile("PubChem_PDF_Report", ".pdf");
            File fileWordOutput = File.createTempFile("PubChem_Word_Report", ".docx");
            filePDFOutput.deleteOnExit();
            fileWordOutput.deleteOnExit();
            ArrayList<PubChemAssay> assay = new ReportController().createReport(pcDep, fileExcel, filePDFOutput,
                    fileWordOutput, isInternal);
            String message = null;
            for (PubChemAssay xx : assay) {
                message = xx.getMessage();
                if (!message.equals("")) {
                    int nn = JOptionPane.showOptionDialog(this,
                            notError + message + "\nWould you like to edit your Excel Workbook?",
                            SwingGUI.APP_NAME, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                            null, null);
                    if (nn == JOptionPane.YES_OPTION) {
                        log.info("Opening Excel Workbook with Desktop: " + fileExcel);
                        Desktop.getDesktop().open(fileExcel);
                    } else {
                        gc.openPDF(isInternal, filePDFOutput, this);
                        Desktop.getDesktop().open(fileWordOutput);
                    }
                } else {
                    gc.openPDF(isInternal, filePDFOutput, this);
                    Desktop.getDesktop().open(fileWordOutput);
                }
            }
        }
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    } catch (Throwable throwable) {
        SwingGUI.handleError(this, throwable);
    }
}

From source file:org.tinymediamanager.ui.TmmUIHelper.java

public static void openFile(Path file) throws Exception {
    String fileType = "." + FilenameUtils.getExtension(file.getFileName().toString());
    String abs = file.toAbsolutePath().toString();

    if (StringUtils.isNotBlank(Globals.settings.getMediaPlayer())
            && Globals.settings.getAllSupportedFileTypes().contains(fileType)) {
        if (SystemUtils.IS_OS_MAC_OSX) {
            Runtime.getRuntime()/*from   w  w  w  .ja va2 s .c om*/
                    .exec(new String[] { "open", Globals.settings.getMediaPlayer(), "--args", abs });
        } else {
            Runtime.getRuntime().exec(new String[] { Globals.settings.getMediaPlayer(), abs });
        }
    } else if (SystemUtils.IS_OS_WINDOWS) {
        // use explorer directly - ship around access exceptions and the unresolved network bug
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6780505
        Runtime.getRuntime().exec(new String[] { "explorer", abs });
    } else if (SystemUtils.IS_OS_LINUX) {
        // try all different starters
        boolean started = false;
        try {
            Runtime.getRuntime().exec(new String[] { "gnome-open", abs });
            started = true;
        } catch (IOException e) {
        }

        if (!started) {
            try {
                Runtime.getRuntime().exec(new String[] { "kde-open", abs });
                started = true;
            } catch (IOException e) {
            }
        }

        if (!started) {
            try {
                Runtime.getRuntime().exec(new String[] { "xdg-open", abs });
                started = true;
            } catch (IOException e) {
            }
        }

        if (!started && Desktop.isDesktopSupported()) {
            Desktop.getDesktop().open(file.toFile());
        }
    } else if (Desktop.isDesktopSupported()) {
        Desktop.getDesktop().open(file.toFile());

    } else {
        throw new UnsupportedOperationException();
    }
}

From source file:com.google.oacurl.Login.java

private static void launchBrowser(LoginOptions options, String authorizationUrl) {
    logger.log(Level.INFO, "Redirecting to URL: " + authorizationUrl);

    boolean browsed = false;
    if (options.getBrowser() == null) {
        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Action.BROWSE)) {
                try {
                    desktop.browse(URI.create(authorizationUrl));
                    browsed = true;//from www  .  ja v  a  2 s.  c o  m
                } catch (IOException e) {
                    // In some situations "BROWSE" appears supported but throws an
                    // exception.
                    logger.log(Level.WARNING, "Error opening browser for Desktop#browse(String)",
                            options.isVerbose() ? e : null);
                }
            } else {
                logger.log(Level.WARNING, "java.awt.Desktop BROWSE action not supported.");
            }
        } else {
            logger.log(Level.WARNING, "java.awt.Desktop not supported. You should use Java 1.6.");
        }
    }

    if (!browsed) {
        String browser = options.getBrowser();
        if (browser == null) {
            browser = "google-chrome";
        }

        try {
            Runtime.getRuntime().exec(new String[] { browser, authorizationUrl });
        } catch (IOException e) {
            logger.log(Level.SEVERE,
                    "Error running browser: " + browser + ". "
                            + "Specify a browser with --browser or use --nobrowser to print URL.",
                    options.isVerbose() ? e : null);
            System.exit(-1);
        }
    }
}

From source file:org.astrojournal.gui.AJMainGUI.java

/**
 * Visualise the astro journals.//from w w  w .j a  v a  2 s  .c om
 */
public void openJournals() {
    ArrayList<File> files = new ArrayList<File>();
    File journalByTarget = new File(config.getProperty(AJPropertyConstants.FILES_LOCATION.getKey())
            + File.separator + config.getProperty(AJPropertyConstants.LATEX_REPORT_BY_TARGET_FILENAME.getKey())
                    .replace(".tex", ".pdf"));
    files.add(journalByTarget);
    File journalByConstellation = new File(
            config.getProperty(AJPropertyConstants.FILES_LOCATION.getKey()) + File.separator
                    + config.getProperty(AJPropertyConstants.LATEX_REPORT_BY_CONSTELLATION_FILENAME.getKey())
                            .replace(".tex", ".pdf"));
    files.add(journalByConstellation);
    File journalByDate = new File(config.getProperty(AJPropertyConstants.FILES_LOCATION.getKey())
            + File.separator + config.getProperty(AJPropertyConstants.LATEX_REPORT_BY_DATE_FILENAME.getKey())
                    .replace(".tex", ".pdf"));
    files.add(journalByDate);
    File journalByDateTXT = new File(config.getProperty(AJPropertyConstants.FILES_LOCATION.getKey())
            + File.separator + config.getProperty(AJPropertyConstants.TXT_REPORT_BY_DATE_FILENAME.getKey()));
    files.add(journalByDateTXT);

    for (File file : files) {
        if (file.exists()) {
            try {
                if (Desktop.isDesktopSupported()) {
                    Desktop.getDesktop().open(file);
                    log.debug("Open file : " + file.getAbsolutePath());
                } else {
                    log.error("Awt Desktop is not supported!");
                }
            } catch (Exception ex) {
                log.warn(ex);
                log.debug(ex, ex);
            }
        } else {
            log.error("File is not exists!");
        }
    }
}

From source file:de.atomfrede.tools.evalutation.tools.plot.ui.wizard.time.TimePlotWizard.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/* ww  w.  j av a 2 s  . c o  m*/
        protected Object doInBackground() throws Exception {
            StringBuilder fileNameBuilder = new StringBuilder();
            // first collect all datasets
            List<TimeDatasetWrapper> wrappers = ((DatasetSelectionWizardPage) pages.get(1))
                    .getTimeDatasetWrappers();
            TimeDatasetWrapper[] wrappersArray = new TimeDatasetWrapper[wrappers.size()];

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

            int i = 0;
            for (TimeDatasetWrapper 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();
            CustomTimePlot timePlot = new CustomTimePlot(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();
}

From source file:org.tinymediamanager.ui.TmmUIHelper.java

public static void browseUrl(String url) throws Exception {
    if (Desktop.isDesktopSupported()) {
        Desktop.getDesktop().browse(new URI(url));
    } else if (SystemUtils.IS_OS_LINUX) {
        // try all different starters
        boolean started = false;
        try {/*from  ww w .j  av a  2  s . c om*/
            Runtime.getRuntime().exec(new String[] { "gnome-open", url });
            started = true;
        } catch (IOException e) {
        }

        if (!started) {
            try {
                Runtime.getRuntime().exec(new String[] { "kde-open", url });
                started = true;
            } catch (IOException e) {
            }
        }

        if (!started) {
            try {
                Runtime.getRuntime().exec(new String[] { "xdg-open", url });
                started = true;
            } catch (IOException e) {
            }
        }
    } else {
        throw new UnsupportedOperationException();
    }
}

From source file:org.apache.marmotta.splash.startup.StartupListener.java

/**
 * React on the AFTER_START_EVENT of Tomcat and startup the browser to point to the Marmotta installation. Depending
 * on the state of the Marmotta installation, the following actions are carried out:
 * <ul>// www .j  a  va  2s. c  om
 *     <li>in case the Marmotta is started for the first time, show a dialog box with options to select which IP-address to use for
 *     configuring the Marmotta; the IP address will be stored in a separate properties file in MARMOTTA_HOME</li>
 *     <li>in case the Marmotta has already been configured but the IP address that was used is no longer existing on the server,
 *     show a warning dialog (this can happen e.g. for laptops with dynamically changing network configurations)</li>
 *     <li>otherwise, open a browser using the network address that was used previously</li>
 * </ul>
 *
 * @param event LifecycleEvent that has occurred
 */
@Override
public void lifecycleEvent(LifecycleEvent event) {
    if (event.getType().equals(Lifecycle.AFTER_START_EVENT)) {
        if (!GraphicsEnvironment.isHeadless()) {

            String serverName = null;
            int serverPort = 0;

            // open browser window
            if (Desktop.isDesktopSupported()) {

                Properties startupProperties = getStartupProperties();
                if (startupProperties.getProperty("startup.host") != null
                        && startupProperties.getProperty("startup.port") != null) {

                    serverName = startupProperties.getProperty("startup.host");
                    serverPort = Integer.parseInt(startupProperties.getProperty("startup.port"));

                    if (!checkServerName(serverName) || serverPort != getServerPort()) {
                        MessageDialog.show("Warning", "Configured server name not found", "The host name ("
                                + serverName + ") that has been used to configure this \n"
                                + "installation is no longer available on this server. The system \n"
                                + "might behave unexpectedly. Please consider using a localhost configuration \n"
                                + "for systems with dynamic IP addresses!");
                    }

                } else {
                    // show a dialog listing all available addresses of this server and allowing the user to
                    // chose
                    List<Option> choices = new ArrayList<>();

                    Map<String, List<InetAddress>> addressList = listHostAddresses();

                    List<String> hostNames = new ArrayList<String>(addressList.keySet());
                    Collections.sort(hostNames);

                    int loopback = -1;
                    for (int i = 0; i < hostNames.size(); i++) {
                        String hostName = hostNames.get(i);
                        List<InetAddress> addresses = addressList.get(hostName);
                        String label = hostName + " \n(";
                        for (Iterator<InetAddress> it = addresses.iterator(); it.hasNext();) {
                            label += it.next().getHostAddress();
                            if (it.hasNext()) {
                                label += ", ";
                            }
                        }
                        label += ")";

                        String text;

                        if (addresses.get(0).isLoopbackAddress()) {
                            text = "Local IP-Address. Recommended for Laptop use or Demonstration purposes";
                            loopback = loopback < 0 ? i : loopback;
                        } else {
                            text = "Public IP-Address. Recommended for Workstation or Server use";
                        }

                        choices.add(new Option(label, text));
                    }

                    int choice = SelectionDialog.select("Select Server Address",
                            "Select host address to use for configuring the\nApache Marmotta Platform.",
                            WordUtils.wrap(
                                    "For demonstration purposes or laptop installations it is recommended to select \""
                                            + (loopback < 0 ? "localhost" : hostNames.get(loopback))
                                            + "\" below. For server and workstation installations, please select a public IP address.",
                                    60),
                            choices, loopback);

                    if (choice < 0) {
                        log.error("No Server Address selected, server will shut down.");
                        throw new IllegalArgumentException("No Server Addess was selected");
                    }

                    serverName = hostNames.get(choice);
                    serverPort = getServerPort();

                    startupProperties.setProperty("startup.host", serverName);
                    startupProperties.setProperty("startup.port", serverPort + "");

                    storeStartupProperties(startupProperties);
                }

                final Desktop desktop = Desktop.getDesktop();
                if (desktop.isSupported(Desktop.Action.BROWSE) && serverName != null && serverPort > 0) {
                    try {

                        URI uri = new URI("http", null, serverName, serverPort, "/", null, null);
                        desktop.browse(uri);

                    } catch (Exception e1) {
                        System.err.println("could not open browser window, message was: " + e1.getMessage());
                    }

                }
            }
        }

    }
}

From source file:org.keycloak.adapters.installed.KeycloakInstalled.java

public void loginDesktop() throws IOException, VerificationException, OAuthErrorException, URISyntaxException,
        ServerRequest.HttpFailure, InterruptedException {
    CallbackListener callback = new CallbackListener(getLoginResponseWriter());
    callback.start();//from  w  ww.  j  ava 2 s  . com

    String redirectUri = "http://localhost:" + callback.server.getLocalPort();
    String state = UUID.randomUUID().toString();

    KeycloakUriBuilder builder = deployment.getAuthUrl().clone()
            .queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE)
            .queryParam(OAuth2Constants.CLIENT_ID, deployment.getResourceName())
            .queryParam(OAuth2Constants.REDIRECT_URI, redirectUri).queryParam(OAuth2Constants.STATE, state)
            .queryParam(OAuth2Constants.SCOPE, OAuth2Constants.SCOPE_OPENID);
    if (locale != null) {
        builder.queryParam(OAuth2Constants.UI_LOCALES_PARAM, locale.getLanguage());
    }
    String authUrl = builder.build().toString();

    Desktop.getDesktop().browse(new URI(authUrl));

    callback.join();

    if (!state.equals(callback.state)) {
        throw new VerificationException("Invalid state");
    }

    if (callback.error != null) {
        throw new OAuthErrorException(callback.error, callback.errorDescription);
    }

    if (callback.errorException != null) {
        throw callback.errorException;
    }

    processCode(callback.code, redirectUri);

    status = Status.LOGGED_DESKTOP;
}

From source file:Commander.Main.java

private static void run(String name, List<String> options) {
    File fileToRun = null;/* w  ww.  ja  va2 s  . c  o m*/
    File dir;

    //Get the file
    for (String s : defaultLocations) {
        dir = new File(s);
        fileToRun = searchFile(dir, name);
        if (fileToRun != null) {
            //File found
            break;
        }
    }
    if (fileToRun == null) {
        //File not found
        error("Couldn't find file '" + name + "' to run.");
    } else {
        try {
            String extension = name.substring(name.lastIndexOf("."));
            if (extension.equals("jar")) {
                Process p = Runtime.getRuntime()
                        .exec(new String[] { "cmd.exe", "/c", "java -jar " + fileToRun.getAbsolutePath() });
            } else {
                Desktop.getDesktop().open(fileToRun);
            }
            txtCommand.setText(null);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.languagetool.gui.Tools.java

/**
 * Launches the default browser to display a URL.
 * //from w w w  . j a  v a  2  s .  co m
 * @param url the URL to be displayed
 * @since 4.1
 */
static void openURL(URL url) {
    if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
        try {
            Desktop.getDesktop().browse(url.toURI());
        } catch (Exception ex) {
            Tools.showError(ex);
        }
    } else if (SystemUtils.IS_OS_LINUX) {
        //handle the case where Desktop.browse() is not supported, e.g. kubuntu
        //without libgnome
        try {
            Runtime.getRuntime().exec(new String[] { "xdg-open", url.toString() });
        } catch (Exception ex) {
            Tools.showError(ex);
        }
    }
}