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.web.session.WebSessionBase.java

protected void debugPageToTempFile(String page, boolean displayFile) throws IOException {
    File file = File.createTempFile(getClass().getName(), ".html");
    IOUtils.write(page, new FileOutputStream(file));
    if (displayFile)
        Desktop.getDesktop().open(file);
}

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

/**
 *  Launches a file into the appropriate program for the OS we are running on
 *///from  w w  w  . j ava 2  s.c om
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.yccheok.jstock.gui.CompanyNews.java

static void openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {/*  w w w .j  a  v  a2  s.c  om*/
            desktop.browse(uri);
        } catch (Exception e) {
            log.error(null, e);
        }
    }
}

From source file:org.geopublishing.atlasStyler.swing.AtlasStylerSaveAsLayerToSLDAction.java

@Override
public void actionPerformed(ActionEvent e) {

    boolean backup = false;

    File startWithFile = new File(System.getProperty("user.home"), styledLayer.getTitle().toString() + ".sld");

    if (styledLayer.getSldFile() != null)
        startWithFile = styledLayer.getSldFile();

    File exportFile = AsSwingUtil.chooseFileSave(owner, startWithFile,
            ASUtil.R("StyledLayerSLD.ChooseFileLocationDialog.Title"),
            new FileExtensionFilter(ASUtil.FILTER_SLD));

    if (exportFile == null)
        return;/*from   w w  w.  ja va  2s  . c  o m*/

    if (!(exportFile.getName().toLowerCase().endsWith(".sld")
            || exportFile.getName().toLowerCase().endsWith(".xml"))) {
        exportFile = new File(exportFile.getParentFile(), exportFile.getName() + ".sld");
    }

    styledLayer.setSldFile(exportFile);

    if (styledLayer.getSldFile().exists()) {
        try {
            FileUtils.copyFile(styledLayer.getSldFile(),
                    IOUtil.changeFileExt(styledLayer.getSldFile(), "sld.bak"));
            backup = true;
        } catch (IOException e1) {
            LOGGER.warn("could not create a backup of the existing .sld", e1);
            return;
        }
    }

    try {
        StylingUtil.saveStyleToSld(styledLayer.getStyle(), styledLayer.getSldFile());
        StylingUtil.saveStyleToSld(styledLayer.getStyle(),
                ASUtil.changeToOptimizedFilename(styledLayer.getSldFile()), true,
                getOptimizedTitle(styledLayer));

        Object[] options = { "OK", ASUtil.R("AtlasStylerSaveLayerToSLD.OpenFile"),
                ASUtil.R("AtlasStylerSaveLayerToSLD.OpenProductive") };
        int dialogValue = 0;

        if (backup) {
            dialogValue = JOptionPane.showOptionDialog(owner,
                    ASUtil.R("AtlasStylerGUI.saveToSLDFileSuccessAndBackedUp",
                            IOUtil.escapePath(styledLayer.getSldFile())),
                    "", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        } else {
            dialogValue = JOptionPane.showOptionDialog(owner,
                    ASUtil.R("AtlasStylerGUI.saveToSLDFileSuccess",
                            IOUtil.escapePath(styledLayer.getSldFile())),
                    "", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        }
        if (dialogValue == JOptionPane.NO_OPTION) {
            Desktop desktop = Desktop.getDesktop();
            desktop.open(styledLayer.getSldFile());
        }
        if (dialogValue == JOptionPane.CANCEL_OPTION) {
            Desktop desktop = Desktop.getDesktop();
            desktop.open(ASUtil.changeToOptimizedFilename(styledLayer.getSldFile()));
        }

        List<Exception> es = StylingUtil.validateSld(new FileInputStream(styledLayer.getSldFile()));
        if (es.size() > 0) {
            ExceptionDialog.show(owner,
                    new IllegalStateException(ASUtil.R("AtlasStylerExport.WarningSLDNotValid",
                            IOUtil.escapePath(styledLayer.getSldFile())), es.get(0)));
        }

    } catch (Exception e1) {
        LOGGER.error("saveStyleToSLD", e1);
        ExceptionDialog.show(owner, e1);
        return;
    }
}

From source file:context.ui.misc.FileHandler.java

/**
 *
 * @param url/*w  w w.  j  a v a  2  s  . com*/
 */
public static void openWebpage(String url) {
    try {
        URI uri = new URI(url);
        Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
        if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
            desktop.browse(uri);
        }
    } catch (URISyntaxException ex) {
        Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:net.sf.jabref.gui.worker.SendAsEMailAction.java

@Override
public void run() {
    if (!Desktop.isDesktopSupported()) {
        message = Localization.lang("Error creating email");
        return;//  ww  w .  j a va 2  s .  com
    }

    BasePanel panel = frame.getCurrentBasePanel();
    if (panel == null) {
        return;
    }
    if (panel.getSelectedEntries().isEmpty()) {
        message = Localization.lang("This operation requires one or more entries to be selected.");
        return;
    }

    StringWriter sw = new StringWriter();
    List<BibEntry> bes = panel.getSelectedEntries();

    // write the entries using sw, which is used later to form the email content
    BibEntryWriter bibtexEntryWriter = new BibEntryWriter(
            new LatexFieldFormatter(LatexFieldFormatterPreferences.fromPreferences(Globals.prefs)), true);

    for (BibEntry entry : bes) {
        try {
            bibtexEntryWriter.write(entry, sw, panel.getBibDatabaseContext().getMode());
        } catch (IOException e) {
            LOGGER.warn("Problem creating BibTeX file for mailing.", e);
        }
    }

    List<String> attachments = new ArrayList<>();

    // open folders is needed to indirectly support email programs, which cannot handle
    //   the unofficial "mailto:attachment" property
    boolean openFolders = JabRefPreferences.getInstance()
            .getBoolean(JabRefPreferences.OPEN_FOLDERS_OF_ATTACHED_FILES);

    List<File> fileList = FileUtil.getListOfLinkedFiles(bes,
            frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory());
    for (File f : fileList) {
        attachments.add(f.getPath());
        if (openFolders) {
            try {
                JabRefDesktop.openFolderAndSelectFile(f.getAbsolutePath());
            } catch (IOException e) {
                LOGGER.debug("Cannot open file", e);
            }
        }
    }

    String mailTo = "?Body=".concat(sw.getBuffer().toString());
    mailTo = mailTo.concat("&Subject=");
    mailTo = mailTo.concat(JabRefPreferences.getInstance().get(JabRefPreferences.EMAIL_SUBJECT));
    for (String path : attachments) {
        mailTo = mailTo.concat("&Attachment=\"").concat(path);
        mailTo = mailTo.concat("\"");
    }

    URI uriMailTo;
    try {
        uriMailTo = new URI("mailto", mailTo, null);
    } catch (URISyntaxException e1) {
        message = Localization.lang("Error creating email");
        LOGGER.warn(message, e1);
        return;
    }

    Desktop desktop = Desktop.getDesktop();
    try {
        desktop.mail(uriMailTo);
    } catch (IOException e) {
        message = Localization.lang("Error creating email");
        LOGGER.warn(message, e);
        return;
    }

    message = String.format("%s: %d", Localization.lang("Entries added to an email"), bes.size());
}

From source file:org.pdfsam.App.java

private void doOpen(OpenFileRequest event) {
    if (Desktop.isDesktopSupported()) {
        try {/*w  w  w .  j av  a 2 s  .  co m*/
            Desktop.getDesktop().open(event.getFile());
        } catch (IOException e) {
            LOG.error("Unable to open '{}'", event.getFile().getAbsoluteFile());
        }
    }
}

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

private void getAccessToken() throws Exception {
    SocialAuthConfig config = SocialAuthConfig.getDefault();
    config.load();//  w  w  w  . j a  va2s  . c  om
    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:appmain.AppMain.java

private void openFile(File file) {
    try {//from  ww w  .  ja va2 s.c  o m
        if (Desktop.isDesktopSupported()) {
            Desktop.getDesktop().open(file);
        }
    } catch (IOException ioe) {

    }
}

From source file:com.khepry.utilities.GenericUtilities.java

public static void displayOutFile(String outFilePath, Handler handler) {
    if (handler != null) {
        Logger.getLogger("").addHandler(handler);
    }//from w w  w .ja va2s  .com
    File outFile = new File(outFilePath);
    if (outFile.exists()) {
        try {
            Desktop.getDesktop().open(outFile);
        } catch (IOException ex) {
            Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        }
    } else {
        Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, outFilePath,
                new FileNotFoundException());
    }
}