Example usage for java.awt Desktop isSupported

List of usage examples for java.awt Desktop isSupported

Introduction

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

Prototype

public boolean isSupported(Action action) 

Source Link

Document

Tests whether an action is supported on the current platform.

Usage

From source file:de.hybris.platform.marketplaceintegrationbackoffice.utils.MarketplaceintegrationbackofficeHttpClientImpl.java

@Override
public boolean redirectRequest(final String requestUrl) throws IOException {

    final boolean result = true;
    final RestTemplate restTemplate = new RestTemplate();

    final java.net.URI uri = java.net.URI.create(requestUrl);
    final java.awt.Desktop dp = java.awt.Desktop.getDesktop();
    if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
        dp.browse(uri);/*from   w  w w  . j av  a  2  s  .c o  m*/
    }
    restTemplate.execute(requestUrl, HttpMethod.GET, new RequestCallback() {
        @Override
        public void doWithRequest(final ClientHttpRequest request) throws IOException {
            // empty block should be documented
        }
    }, new ResponseExtractor<Object>() {
        @Override
        public Object extractData(final ClientHttpResponse response) throws IOException {
            final HttpStatus statusCode = response.getStatusCode();
            LOG.debug("Response status: " + statusCode.toString());
            return response.getStatusCode();
        }
    });
    return result;
}

From source file:com.tag.Hyperlink.java

private void init() {
    setHorizontalAlignment(SwingConstants.LEFT);
    setBackground(Color.WHITE);//from  w  ww  .  ja  va2 s  .c om
    setBorder(null);
    setBorderPainted(false);
    setOpaque(false);

    String toolTip = getUri().toString();
    setToolTipText(toolTip);

    addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Desktop desktop = Desktop.getDesktop();
            boolean mail = desktop.isSupported(Action.BROWSE);
            if (mail) {
                try {
                    desktop.browse(uri);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    });
}

From source file:spartanfinal.ProcessFiles.java

public void openFile(File file) {
    Desktop desktop = Desktop.getDesktop();
    if (desktop.isSupported(Desktop.Action.OPEN)) {
        for (Desktop.Action action : Desktop.Action.values()) {

        }//from   w  ww.  ja v a 2  s  .  c o  m
        try {

            desktop.open(file);
        } catch (Exception t) {
            String[] commands = { "cmd.exe", "/c", "start", "\"test\"", "\"" + file.getAbsolutePath() + "\"" };
            try {
                Process p = Runtime.getRuntime().exec(commands);
                p.waitFor();

            } catch (Exception l) {
            }
        }
    } else {

    }

}

From source file:org.brickred.tools.GenerateToken.java

private void getAccessToken() throws Exception {
    SocialAuthConfig config = SocialAuthConfig.getDefault();
    config.load();//  w  w  w .  j  a  v a2 s .c  o m
    SocialAuthManager manager = new SocialAuthManager();
    manager.setSocialAuthConfig(config);

    URL aURL = new URL(successURL);
    host = aURL.getHost();
    port = aURL.getPort();
    port = port == -1 ? 80 : port;
    callbackPath = aURL.getPath();

    if (tokenFilePath == null) {
        tokenFilePath = System.getProperty("user.home");
    }
    startServer();
    String url = manager.getAuthenticationUrl(providerId, successURL);
    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Action.BROWSE)) {
            try {
                desktop.browse(URI.create(url));
                // return;
            } catch (IOException e) {
                // handled below
            }
        }
    }

    lock.lock();
    try {
        while (code == null && error == null) {
            gotAuthorizationResponse.awaitUninterruptibly();
        }
        if (error != null) {
            throw new IOException("User authorization failed (" + error + ")");
        }
    } finally {
        lock.unlock();
    }
    stop();

    manager.getAuthenticationUrl(providerId, successURL);
    AccessGrant accessGrant = manager.createAccessGrant(providerId, code, successURL);

    Exporter.exportAccessGrant(accessGrant, tokenFilePath);

    LOG.info("Access Grant Object saved in a file  :: " + tokenFilePath + File.separatorChar
            + accessGrant.getProviderId() + "_accessGrant_file.txt");
}

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>/*from  ww  w .  j  ava2s  .  c o m*/
 *     <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.echocat.velma.dialogs.AboutDialog.java

protected void createIntroduction(@Nonnull Resources resources) {
    final URL iconUrl = resources.getIconUrl(48);

    final StringBuilder body = new StringBuilder();
    body.append("<html>");
    body.append("<head><style>" + "td { margin-right: 10px; }" + "</style></head>");
    body.append("<body style='font-family: sans; font-size: 1em'><table><tr>");
    body.append("<td valign='top'><img src='").append(iconUrl).append("' /></td>");
    body.append("<td valign='top'>");
    body.append("<h2>").append(escapeHtml4(resources.getApplicationName()));
    final String version = resources.getVersion();
    if (!isEmpty(version)) {
        body.append("<br/><span style='font-size: 0.6em'>")
                .append(resources.formatEscaped("versionText", version)).append("</span>");
    }//from w  w w.  j  av a 2 s.com
    body.append("</h2>");

    body.append("<p>Copyright 2011-2012 <a href='https://echocat.org'>echocat</a></p>");
    body.append("<p><a href='http://mozilla.org/MPL/2.0/'>")
            .append(resources.formatEscaped("licensedUnder", "MPL 2.0")).append("</a></p>");

    body.append("<p><table cellpadding='0' cellspacing='0'>");
    body.append("<tr><td>").append(resources.formatEscaped("xHomepage", "echocat"))
            .append(":</td><td><a href='https://echocat.org'>echocat.org</a></td></tr>");
    body.append("<tr><td>").append(resources.formatEscaped("xHomepage", "Velma"))
            .append(":</td><td><a href='https://velma.echocat.org'>velma.echocat.org</a></td></tr>");
    body.append("</table></p>");

    body.append("<h4>").append(resources.formatEscaped("developers"))
            .append("</h4><table cellpadding='0' cellspacing='0'>");
    body.append(
            "<tr><td>Gregor Noczinski</td><td><a href='mailto:gregor@noczinski.eu'>gregor@noczinski.eu</a></td><td><a href='https://github.com/blaubaer'>github.com/blaubaer</a></td></tr>");
    body.append("</table>");

    body.append("</td>");
    body.append("</tr></table></body></html>");

    final JTextPane text = new JTextPane();
    text.setMargin(new Insets(0, 0, 0, 0));
    text.setContentType("text/html");
    text.setText(body.toString());
    text.setFont(new Font(DIALOG, PLAIN, 12));
    text.setBackground(new Color(255, 255, 255, 0));
    text.setEditable(false);
    text.addHyperlinkListener(new HyperlinkListener() {
        @Override
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == ACTIVATED && isDesktopSupported()) {
                final Desktop desktop = getDesktop();
                if (desktop.isSupported(BROWSE)) {
                    try {
                        desktop.browse(e.getURL().toURI());
                    } catch (IOException | URISyntaxException exception) {
                        LOG.error("Could not open " + e.getURL() + " because of an exception.", exception);
                    }
                } else {
                    LOG.error("Could not open " + e.getURL() + " because browse is not supported by desktop.");
                }
            }
            repaint();
        }
    });
    text.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {
            repaint();
        }

        @Override
        public void mousePressed(MouseEvent e) {
            repaint();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            repaint();
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            repaint();
        }

        @Override
        public void mouseExited(MouseEvent e) {
            repaint();
        }
    });
    add(text, new CC().spanX(2).growX().minWidth("10px"));
}

From source file:com.ssn.ws.rest.service.LoginWithInstagram.java

public void login() {
    try {// w  w w.jav a 2  s.c  o m
        server = SSNHttpServer.createSSNHttpServer("Instagram", loginModel, homeForm);
        if (server != null) {

            connectionFactory = new InstagramConnectionFactory(SSNConstants.SSN_INSTAGRAM_CLIENT_ID,
                    SSNConstants.SSN_INSTAGRAM_CLIENT_SECRET);
            oauthOperations = connectionFactory.getOAuthOperations();
            OAuth2Parameters params = new OAuth2Parameters();
            params.setRedirectUri(redirectUri);
            String authorizeUrl = oauthOperations.buildAuthorizeUrl(GrantType.AUTHORIZATION_CODE, params);

            java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
            if (!desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
                System.exit(1);
            }

            java.net.URI uri = new java.net.URI(authorizeUrl);
            desktop.browse(uri);
        }

    } catch (Exception e) {
        logger.error(e.getMessage());
    }

}

From source file:plugin.notes.gui.JIcon.java

/**
 *  Launches a file into the appropriate program for the OS we are running on
 *///from   w ww.ja va2 s.c o m
private void launchFile() {
    if (PCGFile.isPCGenCharacterOrPartyFile(launch)) {
        plugin.loadRecognizedFileType(launch);
    } else {
        boolean opened = false;

        // Use desktop if available
        if (Desktop.isDesktopSupported()) {
            Desktop d = Desktop.getDesktop();
            if (d.isSupported(Desktop.Action.OPEN)) {
                try {
                    d.open(launch);
                    opened = true;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        if (!opened) {
            if (SystemUtils.IS_OS_UNIX) {
                String openCmd = SystemUtils.IS_OS_MAC_OSX ? "/usr/bin/open" : "xdg-open";
                String filePath = launch.getAbsolutePath();
                String[] args = { openCmd, filePath };
                Logging.debugPrintLocalised("Runtime.getRuntime().exec: [{0}] [{1}]", args[0], args[1]);

                try {
                    Runtime.getRuntime().exec(args);
                } catch (IOException e) {
                    Logging.errorPrint(e.getMessage(), e);
                }
            } else if (SystemUtils.IS_OS_WINDOWS) {
                try {
                    String start = ("rundll32 url.dll,FileProtocolHandler file://" + launch.getAbsoluteFile());
                    Runtime.getRuntime().exec(start);
                } catch (Exception e) {
                    Logging.errorPrint(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.help.HelpManager.java

public void openInBrowser(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {//from   w  ww  .  j a v a2 s .  co m
            desktop.browse(uri);
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    } else {
        System.err.println("Desktop not supported, cannout open browser");
    }
}

From source file:DesktopAppTest.java

public DesktopAppFrame() {
    setLayout(new GridBagLayout());
    final JFileChooser chooser = new JFileChooser();
    JButton fileChooserButton = new JButton("...");
    final JTextField fileField = new JTextField(20);
    fileField.setEditable(false);/*from ww  w  .j  av a 2 s  .com*/
    JButton openButton = new JButton("Open");
    JButton editButton = new JButton("Edit");
    JButton printButton = new JButton("Print");
    final JTextField browseField = new JTextField();
    JButton browseButton = new JButton("Browse");
    final JTextField toField = new JTextField();
    final JTextField subjectField = new JTextField();
    JButton mailButton = new JButton("Mail");

    openButton.setEnabled(false);
    editButton.setEnabled(false);
    printButton.setEnabled(false);
    browseButton.setEnabled(false);
    mailButton.setEnabled(false);

    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN))
            openButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.EDIT))
            editButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.PRINT))
            printButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.BROWSE))
            browseButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.MAIL))
            mailButton.setEnabled(true);
    }

    fileChooserButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (chooser.showOpenDialog(DesktopAppFrame.this) == JFileChooser.APPROVE_OPTION)
                fileField.setText(chooser.getSelectedFile().getAbsolutePath());
        }
    });

    openButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().open(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    editButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().edit(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    printButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().print(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    browseButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI(browseField.getText()));
            } catch (URISyntaxException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    mailButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                String subject = percentEncode(subjectField.getText());
                URI uri = new URI("mailto:" + toField.getText() + "?subject=" + subject);

                System.out.println(uri);
                Desktop.getDesktop().mail(uri);
            } catch (URISyntaxException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    JPanel buttonPanel = new JPanel();
    ((FlowLayout) buttonPanel.getLayout()).setHgap(2);
    buttonPanel.add(openButton);
    buttonPanel.add(editButton);
    buttonPanel.add(printButton);

    add(fileChooserButton, new GBC(0, 0).setAnchor(GBC.EAST).setInsets(2));
    add(fileField, new GBC(1, 0).setFill(GBC.HORIZONTAL));
    add(buttonPanel, new GBC(2, 0).setAnchor(GBC.WEST).setInsets(0));
    add(browseField, new GBC(1, 1).setFill(GBC.HORIZONTAL));
    add(browseButton, new GBC(2, 1).setAnchor(GBC.WEST).setInsets(2));
    add(new JLabel("To:"), new GBC(0, 2).setAnchor(GBC.EAST).setInsets(5, 2, 5, 2));
    add(toField, new GBC(1, 2).setFill(GBC.HORIZONTAL));
    add(mailButton, new GBC(2, 2).setAnchor(GBC.WEST).setInsets(2));
    add(new JLabel("Subject:"), new GBC(0, 3).setAnchor(GBC.EAST).setInsets(5, 2, 5, 2));
    add(subjectField, new GBC(1, 3).setFill(GBC.HORIZONTAL));

    pack();
}