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:modmanager.MainWindow.java

private void openGameDirectoryMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_openGameDirectoryMenuItemActionPerformed
{//GEN-HEADEREND:event_openGameDirectoryMenuItemActionPerformed
    if (Desktop.isDesktopSupported()) {
        try {/*from  w  w  w  . j  av a2s . c  om*/
            Desktop.getDesktop().open(modifications.getSkyrimDirectory());
        } catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:openaf.AFCmdOS.java

/**
 * /*  w ww.j  a va  2s . c  o m*/
 * @param in
 * @param out
 * @param appoperation2
 * @throws Exception  
 */
protected com.google.gson.JsonObject execute(com.google.gson.JsonObject pmIn, String op, boolean processScript,
        StringBuilder theInput, boolean isolatePMs) throws Exception {

    // 3. Process input
    //
    INPUT_TYPE = inputtype.INPUT_SCRIPT;

    if (((!pipe) && (!filescript) && (!processScript) && (!injectcode) && (!injectclass))) {
        if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
            /*injectscript = true;
            injectscriptfile = "/js/openafgui.js";
            filescript = true;*/
            injectclass = true;
            injectclassfile = "openafgui_js";
            filescript = false;
            silentMode = true;
        }
    }

    if (processScript || filescript || injectcode || injectclass) {
        // Obtain script
        String script = null;

        if (filescript) {
            if (injectscript) {
                script = IOUtils.toString(getClass().getResourceAsStream(injectscriptfile), "UTF-8");
            } else {
                boolean isZip = false;
                boolean isOpack = false;
                com.google.gson.JsonObject pm = null;
                ZipFile tmpZip = null;

                // Determine if it's opack/zip
                DataInputStream dis = new DataInputStream(
                        new BufferedInputStream(new FileInputStream(scriptfile.replaceFirst("::[^:]+$", ""))));
                int test = dis.readInt();
                dis.close();
                if (test == 0x504b0304) {
                    isZip = true;
                    try {
                        tmpZip = new ZipFile(scriptfile.replaceFirst("::[^:]+$", ""));
                        isOpack = tmpZip.getEntry(OPACK) != null;
                        zip = tmpZip;
                    } catch (Exception e) {
                    }

                    if (isOpack) {
                        if (scriptfile.indexOf("::") <= 0) {
                            pm = new Gson().fromJson(
                                    IOUtils.toString(zip.getInputStream(zip.getEntry(OPACK)), (Charset) null),
                                    JsonObject.class);
                            try {
                                pm.get("main");
                            } catch (Exception e) {
                                isZip = false;
                            }
                        }
                    }
                }

                // Read normal script or opack/zip
                if (isZip) {
                    if (scriptfile.indexOf("::") <= 0 && isOpack) {
                        if (pm.get("main").getAsString().length() > 0) {
                            script = IOUtils.toString(
                                    zip.getInputStream(zip.getEntry(pm.get("main").getAsString())), "UTF-8");
                            scriptfile = scriptfile + "/" + pm.get("main").getAsString();
                        } else {
                            throw new Exception("Can't execute main script in " + scriptfile);
                        }
                    } else {
                        try {
                            script = IOUtils.toString(
                                    zip.getInputStream(zip.getEntry(scriptfile.replaceFirst(".+::", ""))),
                                    "UTF-8");
                        } catch (NullPointerException e) {
                            throw new Exception("Can't find " + scriptfile.replaceFirst(".+::", ""));
                        }
                    }
                } else {
                    script = FileUtils.readFileToString(new File(scriptfile), (Charset) null);
                    zip = null;
                }
            }

        } else {
            if (!injectclass)
                script = theInput.toString();
        }

        if (script != null) {
            script = script.replaceAll("^#.*", "//");
            script = script.replaceFirst(PREFIX_SCRIPT, "");

            if (daemon)
                script = "ow.loadServer().simpleCheckIn('" + scriptfile + "'); " + script
                        + "; ow.loadServer().daemon();";
            if (injectcode)
                script += code;
        }

        Context cx = (Context) jse.getNotSafeContext();
        cx.setErrorReporter(new OpenRhinoErrorReporter());

        String includeScript = "";
        NativeObject jsonPMOut = new NativeObject();

        synchronized (this) {
            Object opmIn;
            opmIn = AFBase.jsonParse(pmIn.toString());

            Object noSLF4JErrorOnly = Context.javaToJS(__noSLF4JErrorOnly, (Scriptable) jse.getGlobalscope());
            ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__noSLF4JErrorOnly",
                    noSLF4JErrorOnly);

            ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "pmIn", opmIn);
            ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__pmIn", opmIn);

            // Add pmOut object
            Object opmOut = Context.javaToJS(jsonPMOut, (Scriptable) jse.getGlobalscope());
            ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "pmOut", opmOut);
            ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__pmOut", opmOut);

            // Add expr object
            Object opmExpr = Context.javaToJS(exprInput, (Scriptable) jse.getGlobalscope());
            ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "expr", opmExpr);
            ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__expr", opmExpr);
            ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__args", args);

            // Add scriptfile object
            if (filescript) {
                Object scriptFile = Context.javaToJS(scriptfile, (Scriptable) jse.getGlobalscope());
                ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__scriptfile", scriptFile);
                ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__iszip",
                        (zip == null) ? false : true);
            }

            // Add AF class
            ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), AFBase.class, false, true);

            // Add DB class
            ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), DB.class, false, true);

            // Add CSV class
            ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), CSV.class, false, true);

            // Add IO class
            ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), IOBase.class, false, true);

            // Add this object
            Scriptable afScript = null;
            //if  (!ScriptableObject.hasProperty((Scriptable) jse.getGlobalscope(), "AF")) {
            afScript = (Scriptable) jse.newObject((Scriptable) jse.getGlobalscope(), "AF");
            //}

            if (!ScriptableObject.hasProperty((Scriptable) jse.getGlobalscope(), "af"))
                ((IdScriptableObject) jse.getGlobalscope()).put("af", (Scriptable) jse.getGlobalscope(),
                        afScript);

            // Add the IO object
            if (!ScriptableObject.hasProperty((Scriptable) jse.getGlobalscope(), "io"))
                ((IdScriptableObject) jse.getGlobalscope()).put("io", (Scriptable) jse.getGlobalscope(),
                        jse.newObject(jse.getGlobalscope(), "IO"));

        }

        // Compile & execute script
        /*try {
           InputStream in1 = getClass().getResourceAsStream("/js/openaf.js");
           includeScript = IOUtils.toString(in1, (Charset) null);
           numberOfIncludedLines = numberOfIncludedLines + includeScript.split("\r\n|\r|\n").length;
           AFCmdBase.jse.addNumberOfLines(includeScript);
        } catch (Exception e) {
           SimpleLog.log(logtype.DEBUG, "Error including openaf.js", e);
        }*/
        AFBase.runFromClass(Class.forName("openaf_js").getDeclaredConstructor().newInstance());
        cx.setErrorReporter(new OpenRhinoErrorReporter());

        if (isolatePMs) {
            script = "(function(__pIn) { var __pmOut = {}; var __pmIn = __pIn; " + script
                    + "; return __pmOut; })(" + pmIn.toString() + ")";
        }

        Object res = null;
        if (injectscript || filescript || injectcode || processScript) {
            Context cxl = (Context) jse.enterContext();
            org.mozilla.javascript.Script compiledScript = cxl.compileString(includeScript + script, scriptfile,
                    1, null);
            res = compiledScript.exec(cxl, (Scriptable) jse.getGlobalscope());
            jse.exitContext();
        }

        if (injectclass) {
            res = AFBase.runFromClass(Class.forName(injectclassfile).getDeclaredConstructor().newInstance());
        }

        if (isolatePMs && res != null && !(res instanceof Undefined)) {
            jsonPMOut = (NativeObject) res;
        } else {
            // Obtain pmOut as output
            jsonPMOut = (NativeObject) ((ScriptableObject) jse.getGlobalscope()).get("__pmOut");
        }

        // Convert to ParameterMap
        Object stringify = NativeJSON.stringify(cx, (Scriptable) jse.getGlobalscope(), jsonPMOut, null, null);
        com.google.gson.Gson gson = new com.google.gson.Gson();
        pmOut = gson.fromJson(stringify.toString(), com.google.gson.JsonObject.class);

        // Leave Rhino
        //org.mozilla.javascript.Context.exit();
        //jse.exitContext();
    }

    return pmOut;
}

From source file:org.cirdles.ambapo.userInterface.AmbapoUIController.java

@FXML
private void clickOpenTemplateLatLongToUTM(ActionEvent event) throws IOException {
    final Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    File file = new File(getClass().getResource("latLongToUTMTemplate.csv").getFile());

    if (desktop != null && desktop.isSupported(Desktop.Action.OPEN)) {
        desktop.open(file);//from  w  ww. j av  a 2 s. c o  m
    } else {
        throw new UnsupportedOperationException("Open action not supported");
    }
}

From source file:com.mightypocket.ashot.Mediator.java

@Action(name = ACTION_OPEN_DESTINATION_FOLDER)
public void openDestinationFolder() {
    if (Desktop.isDesktopSupported()) {
        try {/*from  w  w  w  . jav a 2s  .  c o m*/
            Desktop.getDesktop().open(new File(p.get(PREF_DEFAULT_FILE_FOLDER, "")));
        } catch (Exception ignore) {
        }
    }
}

From source file:net.ftb.util.OSUtils.java

/**
 * Opens the given path with the default application
 * @param path The path//from   w ww.jav  a 2 s  .  co m
 */
public static void open(File path) {
    if (!path.exists()) {
        return;
    }
    try {
        if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
            Desktop.getDesktop().open(path);
        } else if (getCurrentOS() == OS.UNIX) {
            // Work-around to support non-GNOME Linux desktop environments with xdg-open installed
            if (new File("/usr/bin/xdg-open").exists() || new File("/usr/local/bin/xdg-open").exists()) {
                new ProcessBuilder("xdg-open", path.toString()).start();
            }
        }
    } catch (Exception e) {
        Logger.logError("Could not open file", e);
    }
}

From source file:org.cirdles.ambapo.userInterface.AmbapoUIController.java

@FXML
private void clickOpenTemplateUTMToLatLong(ActionEvent event) throws IOException {
    final Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    File file = new File(getClass().getResource("utmToLatLongTemplate.csv").getFile());

    if (desktop != null && desktop.isSupported(Desktop.Action.OPEN)) {
        desktop.open(file);//from w  w w .j a v a2  s. c  o  m
    } else {
        throw new UnsupportedOperationException("Open action not supported");
    }
}

From source file:net.pms.newgui.LanguageSelection.java

private JComponent buildComponent() {
    // UIManager manages to get the background color wrong for text
    // components on OS X, so we apply the color manually
    Color backgroundColor = UIManager.getColor("Panel.background");
    rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));

    // It needs to be something in the title text, or the size calculation for the border will be wrong.
    selectionPanelBorder.setTitle(" ");
    selectionPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(selectionPanelBorder,
                    BorderFactory.createEmptyBorder(10, 5, 10, 5))));
    selectionPanel.setLayout(new BoxLayout(selectionPanel, BoxLayout.PAGE_AXIS));
    descriptionText.setEditable(false);//from w  w w  . j a va  2  s . c  om
    descriptionText.setBackground(backgroundColor);
    descriptionText.setFocusable(false);
    descriptionText.setLineWrap(true);
    descriptionText.setWrapStyleWord(true);
    descriptionText.setBorder(BorderFactory.createEmptyBorder(5, 15, 10, 15));
    selectionPanel.add(descriptionText);

    jLanguage = new JComboBox<>(keyedModel);
    jLanguage.setEditable(false);
    jLanguage.setPreferredSize(new Dimension(50, jLanguage.getPreferredSize().height));
    jLanguage.addActionListener(new LanguageComboBoxActionListener());
    languagePanel.setLayout(new BoxLayout(languagePanel, BoxLayout.PAGE_AXIS));
    languagePanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15));
    languagePanel.add(jLanguage);
    selectionPanel.add(languagePanel);

    warningText.setEditable(false);
    warningText.setFocusable(false);
    warningText.setBackground(backgroundColor);
    warningText.setFont(warningText.getFont().deriveFont(Font.BOLD));
    warningText.setLineWrap(true);
    warningText.setWrapStyleWord(true);
    warningText.setBorder(BorderFactory.createEmptyBorder(5, 15, 0, 15));
    selectionPanel.add(warningText);

    // It needs to be something in the title text, or the size calculation for the border will be wrong.
    infoTextBorder.setTitle(" ");
    infoText.setBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5), BorderFactory
                    .createCompoundBorder(infoTextBorder, BorderFactory.createEmptyBorder(15, 20, 20, 20))));
    infoText.setEditable(false);
    infoText.setFocusable(false);
    infoText.setBackground(backgroundColor);
    infoText.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);

    // This exercise is to avoid using the default shared StyleSheet with padding
    CustomHTMLEditorKit editorKit = new CustomHTMLEditorKit();
    StyleSheet styleSheet = new StyleSheet();
    styleSheet.addRule("a { color: #0000EE; text-decoration:underline; }");
    editorKit.setStyleSheet(styleSheet);
    infoText.setEditorKit(editorKit);
    infoText.addHyperlinkListener(new HyperlinkListener() {

        @Override
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                boolean error = false;
                if (Desktop.isDesktopSupported()) {
                    try {
                        Desktop.getDesktop().browse(new URI(e.getDescription()));
                    } catch (IOException | URISyntaxException ex) {
                        LOGGER.error("Language selection failed to open translation page hyperlink: ",
                                ex.getMessage());
                        LOGGER.trace("", ex);
                        error = true;
                    }
                } else {
                    LOGGER.warn("Desktop is not supported, the clicked translation page link can't be opened");
                    error = true;
                }
                if (error) {
                    JOptionPane.showOptionDialog(dialog,
                            String.format(buildString("LanguageSelection.6", true), PMS.CROWDIN_LINK),
                            buildString("Dialog.Error"), JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE,
                            null, null, null);
                }
            }
        }

    });

    rootPanel.add(selectionPanel);
    rootPanel.add(infoText);

    applyButton.addActionListener(new ApplyButtonActionListener());
    applyButton.setActionCommand("apply");

    selectButton.addActionListener(new SelectButtonActionListener());
    selectButton.setActionCommand("select");

    return rootPanel;

}

From source file:gdt.jgui.entity.webset.JWeblinkEditor.java

/**
 * Get the context menu.//from  w  ww .j  av a  2  s. co  m
 * @return the context menu.
 */
@Override
public JMenu getContextMenu() {
    JMenu menu = new JMenu("Context");
    JMenuItem doneItem = new JMenuItem("Done");
    doneItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            save();
            if (requesterResponseLocator$ != null) {
                try {
                    byte[] ba = Base64.decodeBase64(requesterResponseLocator$);
                    String responseLocator$ = new String(ba, "UTF-8");
                    JConsoleHandler.execute(console, responseLocator$);
                } catch (Exception ee) {
                    Logger.getLogger(getClass().getName()).severe(ee.toString());
                }
            } else
                console.back();

        }
    });
    menu.add(doneItem);
    JMenuItem cancelItem = new JMenuItem("Cancel");
    cancelItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                browseUrl(console, locator$);
            } catch (Exception ee) {
                Logger.getLogger(getClass().getName()).info(ee.toString());
            }
        }
    });
    menu.add(cancelItem);
    menu.addSeparator();
    JMenuItem browseItem = new JMenuItem("Browse");
    browseItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI(addressField.getText()));
            } catch (Exception ee) {
                Logger.getLogger(JWeblinkEditor.class.getName()).info(ee.toString());
            }
        }
    });
    menu.add(browseItem);
    return menu;
}

From source file:org.richie.codeGen.ui.GenAndPreviewUI.java

/**
 * windows//from  ww w  .  j a  v a  2 s .  c  o  m
 * 
 * @param filePath
 */
private void openFile(String filePath) {
    try {
        Desktop.getDesktop().open(new File(filePath));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.codelibs.fess.web.IndexAction.java

@Execute(validator = true, input = "index")
public String go() throws IOException {
    Map<String, Object> doc = null;
    try {/* w  ww .  j  a  v a  2 s  . co  m*/
        doc = searchService.getDocument(fieldHelper.docIdField + ":" + indexForm.docId,
                queryHelper.getResponseFields(), new String[] { fieldHelper.clickCountField });
    } catch (final Exception e) {
        logger.warn("Failed to request: " + indexForm.docId, e);
    }
    if (doc == null) {
        errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                "errors.docid_not_found", indexForm.docId);
        return "error.jsp";
    }
    final Object urlObj = doc.get(fieldHelper.urlField);
    if (urlObj == null) {
        errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                "errors.document_not_found", indexForm.docId);
        return "error.jsp";
    }
    final String url = urlObj.toString();

    if (Constants.TRUE.equals(crawlerProperties.getProperty(Constants.SEARCH_LOG_PROPERTY, Constants.TRUE))) {
        final String userSessionId = userInfoHelper.getUserCode();
        if (userSessionId != null) {
            final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper();
            final ClickLog clickLog = new ClickLog();
            clickLog.setUrl(url);
            LocalDateTime now = systemHelper.getCurrentTime();
            clickLog.setRequestedTime(now);
            clickLog.setQueryRequestedTime(LocalDateTime
                    .ofInstant(Instant.ofEpochMilli(Long.parseLong(indexForm.rt)), ZoneId.systemDefault()));
            clickLog.setUserSessionId(userSessionId);
            clickLog.setDocId(indexForm.docId);
            long clickCount = 0;
            final Object count = doc.get(fieldHelper.clickCountField);
            if (count instanceof Long) {
                clickCount = ((Long) count).longValue();
            }
            clickLog.setClickCount(clickCount);
            searchLogHelper.addClickLog(clickLog);
        }
    }

    String hash;
    if (StringUtil.isNotBlank(indexForm.hash)) {
        final String value = URLUtil.decode(indexForm.hash, Constants.UTF_8);
        final StringBuilder buf = new StringBuilder(value.length() + 100);
        for (final char c : value.toCharArray()) {
            if (CharUtil.isUrlChar(c) || c == ' ') {
                buf.append(c);
            } else {
                try {
                    buf.append(URLEncoder.encode(String.valueOf(c), Constants.UTF_8));
                } catch (final UnsupportedEncodingException e) {
                    // NOP
                }
            }
        }
        hash = buf.toString();
    } else {
        hash = StringUtil.EMPTY;
    }

    if (isFileSystemPath(url)) {
        if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.SEARCH_FILE_PROXY_PROPERTY, Constants.TRUE))) {
            final CrawlingConfigHelper crawlingConfigHelper = ComponentUtil.getCrawlingConfigHelper();
            try {
                crawlingConfigHelper.writeContent(doc);
                return null;
            } catch (final Exception e) {
                logger.error("Failed to load: " + doc, e);
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.not_load_from_server", url);
                return "error.jsp";
            }
        } else if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.SEARCH_DESKTOP_PROPERTY, Constants.FALSE))) {
            final String path = url.replaceFirst("file:/+", "//");
            final File file = new File(path);
            if (!file.exists()) {
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.not_found_on_file_system", url);
                return "error.jsp";
            }
            final Desktop desktop = Desktop.getDesktop();
            try {
                desktop.open(file);
            } catch (final Exception e) {
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.could_not_open_on_system", url);
                logger.warn("Could not open " + path, e);
                return "error.jsp";
            }

            ResponseUtil.getResponse().setStatus(HttpServletResponse.SC_NO_CONTENT);
            return null;
        } else {
            ResponseUtil.getResponse().sendRedirect(url + hash);
        }
    } else {
        ResponseUtil.getResponse().sendRedirect(url + hash);
    }
    return null;
}