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.kotcrab.vis.editor.util.FileUtils.java

public static void open(FileHandle file) {
    try {/*  w  ww.j  a  v a2  s  .co m*/
        if (OsUtils.isMac()) {
            Runtime.getRuntime().exec("open " + file.path()); //see #123
        } else {
            Desktop.getDesktop().edit(file.file());
        }
    } catch (IOException e) {
        Log.exception(e);
    }
}

From source file:Main.java

private void goWebsite(JLabel website) {
    website.addMouseListener(new MouseAdapter() {
        @Override/* ww  w . j  a  va  2s .c  o  m*/
        public void mouseClicked(MouseEvent e) {
            try {
                try {
                    Desktop.getDesktop().browse(new URI("http://www.java2s.com"));
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (URISyntaxException ex) {

            }
        }
    });
}

From source file:com.github.rwhogg.git_vcr.App.java

/**
 * main is the entry point for Git-VCR//from w  ww.ja  va 2s  .  com
 * @param args Command-line arguments
 */
public static void main(String[] args) {
    Options options = parseCommandLine(args);

    HierarchicalINIConfiguration configuration = null;
    try {
        configuration = getConfiguration();
    } catch (ConfigurationException e) {
        Util.error("could not parse configuration file!");
    }

    // verify we are in a git folder and then construct the repo
    final File currentFolder = new File(".");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository localRepo = null;
    try {
        localRepo = builder.findGitDir().build();
    } catch (IOException e) {
        Util.error("not in a Git folder!");
    }

    // deal with submodules
    assert localRepo != null;
    if (localRepo.isBare()) {
        FileRepositoryBuilder parentBuilder = new FileRepositoryBuilder();
        Repository parentRepo;
        try {
            parentRepo = parentBuilder.setGitDir(new File("..")).findGitDir().build();
            localRepo = SubmoduleWalk.getSubmoduleRepository(parentRepo, currentFolder.getName());
        } catch (IOException e) {
            Util.error("could not find parent of submodule!");
        }
    }

    // if we need to retrieve the patch file, get it now
    URL patchUrl = options.getPatchUrl();
    String patchPath = patchUrl.getFile();
    File patchFile = null;
    HttpUrl httpUrl = HttpUrl.get(patchUrl);
    if (httpUrl != null) {
        try {
            patchFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".diff");
            Request request = new Request.Builder().url(httpUrl).build();
            OkHttpClient client = new OkHttpClient();
            Call call = client.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (!response.isSuccessful()) {
                Util.error("could not retrieve diff file from URL " + patchUrl);
            }
            String content = body.string();
            org.apache.commons.io.FileUtils.write(patchFile, content, (Charset) null);
        } catch (IOException ie) {
            Util.error("could not retrieve diff file from URL " + patchUrl);
        }
    } else {
        patchFile = new File(patchPath);
    }

    // find the patch
    //noinspection ConstantConditions
    if (!patchFile.canRead()) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is not readable!");
    }

    final Git git = new Git(localRepo);

    // handle the branch
    String branchName = options.getBranchName();
    String theOldCommit = null;
    try {
        theOldCommit = localRepo.getBranch();
    } catch (IOException e2) {
        Util.error("could not get reference to current branch!");
    }
    final String oldCommit = theOldCommit; // needed to reference from shutdown hook

    if (branchName != null) {
        // switch to the branch
        try {
            git.checkout().setName(branchName).call();
        } catch (RefAlreadyExistsException e) {
            // FIXME Auto-generated catch block
            e.printStackTrace();
        } catch (RefNotFoundException e) {
            Util.error("the branch " + branchName + " was not found!");
        } catch (InvalidRefNameException e) {
            Util.error("the branch name " + branchName + " is invalid!");
        } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) {
            Util.error("there was a checkout conflict!");
        } catch (GitAPIException e) {
            Util.error("there was an unspecified Git API failure!");
        }
    }

    // ensure there are no changes before we apply the patch
    try {
        if (!git.status().call().isClean()) {
            Util.error("cannot run git-vcr while there are uncommitted changes!");
        }
    } catch (NoWorkTreeException e1) {
        // won't happen
        assert false;
    } catch (GitAPIException e1) {
        Util.error("call to git status failed!");
    }

    // list all the files changed
    String patchName = patchFile.getName();
    Patch patch = new Patch();
    try {
        patch.parse(new FileInputStream(patchFile));
    } catch (FileNotFoundException e) {
        assert false;
    } catch (IOException e) {
        Util.error("could not parse the patch file!");
    }

    ReviewResults oldResults = new ReviewResults(patchName, patch, configuration, false);
    try {
        oldResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // we're about to change the repo, so register a shutdown hook to clean it up
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            cleanupGit(git, oldCommit);
        }
    });

    // apply the patch
    try {
        git.apply().setPatch(new FileInputStream(patchFile)).call();
    } catch (PatchFormatException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is malformatted!");
    } catch (PatchApplyException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " did not apply correctly!");
    } catch (FileNotFoundException e) {
        assert false;
    } catch (GitAPIException e) {
        Util.error(e.getLocalizedMessage());
    }

    ReviewResults newResults = new ReviewResults(patchName, patch, configuration, true);
    try {
        newResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // generate and show the report
    VelocityReport report = new VelocityReport(patch, oldResults, newResults);
    File reportFile = null;
    try {
        reportFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".html");
        org.apache.commons.io.FileUtils.write(reportFile, report.toString(), (String) null);
    } catch (IOException e) {
        Util.error("could not generate the results page!");
    }

    try {
        assert reportFile != null;
        Desktop.getDesktop().open(reportFile);
    } catch (IOException e) {
        Util.error("could not open the results page!");
    }
}

From source file:npm.modules.java

public boolean openafile(String path) throws Exception {
    File file = new File(path);
    Desktop desktop = Desktop.getDesktop();
    desktop.edit(file);/*from   w w w  .  java2 s  .co m*/
    return true;
}

From source file:VASSAL.tools.BrowserSupport.java

public static void openURL(String url) {
    ///* ww  w  .  j av  a2s . co m*/
    // This method is irritatingly complex, because:
    // * There is no java.awt.Desktop in Java 1.5.
    // * java.awt.Desktop seems not to work sometimes on Windows.
    // * BrowserLauncher failes sometimes on Linux, and isn't supported
    //   anymore.
    //
    if (!SystemUtils.IS_JAVA_1_5) {
        if (Desktop.isDesktopSupported()) {
            final Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.BROWSE)) {
                try {
                    desktop.browse(new URI(url));
                    return;
                } catch (IOException e) {
                    // We ignore this on Windows, because Desktop seems flaky
                    if (!SystemUtils.IS_OS_WINDOWS) {
                        ReadErrorDialog.error(e, url);
                        return;
                    }
                } catch (IllegalArgumentException e) {
                    ErrorDialog.bug(e);
                    return;
                } catch (URISyntaxException e) {
                    ErrorDialog.bug(e);
                    return;
                }
            }
        }
    }

    if (browserLauncher != null) {
        browserLauncher.openURLinBrowser(url);
    } else {
        ErrorDialog.show("BrowserSupport.unable_to_launch", url);
    }
}

From source file:com.clank.launcher.swing.SwingHelper.java

public static void browseDir(File file, Component component) {
    try {//from  w  w  w .  j av a2 s . c om
        Desktop.getDesktop().open(file);
    } catch (IOException e) {
        JOptionPane.showMessageDialog(component, _("errors.openDirError", file.getAbsolutePath()),
                _("errorTitle"), JOptionPane.ERROR_MESSAGE);
    }
}

From source file:Main.java

protected void saveToFile() {
    JFileChooser fileChooser = new JFileChooser();
    int retval = fileChooser.showSaveDialog(save);
    if (retval == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        if (file == null) {
            return;
        }//  w  ww.j  a v a2 s.c o m
        if (!file.getName().toLowerCase().endsWith(".txt")) {
            file = new File(file.getParentFile(), file.getName() + ".txt");
        }
        try {
            textArea.write(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            Desktop.getDesktop().open(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:audiomanagershell.commands.PlayCommand.java

@Override
public void execute() throws CommandException, IOException {
    String OS = System.getProperty("os.name").toLowerCase();
    Path file;/*from ww w.  j a  v a 2  s  .  com*/
    if (OS.equals("windows"))
        file = Paths.get(this.pathRef.toString() + "\\" + this.arg);
    else
        file = Paths.get(this.pathRef.toString() + "/" + this.arg);
    String fileName = file.getFileName().toString();
    List<String> acceptedExtensions = Arrays.asList("wav", "mp3", "flac", "mp4");
    //Get the extension of the file
    String extension = FilenameUtils.getExtension(fileName);
    if (Files.isRegularFile(file) && Files.isReadable(file)) {
        if (acceptedExtensions.contains(extension)) {
            Desktop desktop = Desktop.getDesktop();
            desktop.open(file.toFile());
            System.out.printf("The file %s will open shortly...\n", fileName);
        } else {
            throw new NotAudioFileException(fileName);
        }
    } else {
        throw new CommandException(file.toString() + " not a file or can't read");
    }
}

From source file:vazkii.psi.client.core.helper.SharingHelper.java

public static void uploadAndShare(String title, String export) {
    String url = uploadImage(title, export);

    try {//from w  w w  . j ava2s  .  c  om
        String contents = "## " + title + "  \n" + "### [Image + Code](" + url + ")\n"
                + "(to get the code click the link, RES won't show it)\n" + "\n" + "---" + "\n"
                + "*REPLACE THIS WITH A DESCRIPTION OF YOUR SPELL  \n"
                + "Make sure you read the rules before posting. Look on the sidebar: https://www.reddit.com/r/psispellcompendium/  \n"
                + "Delete this part before you submit.*";

        String encodedContents = URLEncoder.encode(contents, "UTF-8");
        String encodedTitle = URLEncoder.encode(title, "UTF-8");

        String redditUrl = "https://www.reddit.com/r/psispellcompendium/submit?title=" + encodedTitle + "&text="
                + encodedContents;

        if (Desktop.isDesktopSupported())
            Desktop.getDesktop().browse(new URI(redditUrl));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.geopoke.GPSSender.java

public void send(List<CacheDetailsNode> caches) {
    try {//www.  java2  s  .  c  o m
        File temp = File.createTempFile("geopoke_gpstemplate", ".html");
        temp.deleteOnExit();
        String fileContents = TEMPLATE_CONTENTS.replace("<!--PLACEHOLDER-->", generateStrs(caches));
        FileUtils.writeStringToFile(temp, fileContents);
        Desktop.getDesktop().browse(temp.toURI());
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}