All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.lespaul361.commons.commonroutines.utilities.DesktopApi Maven / Gradle / Ivy

There is a newer version: 1.6.0
Show newest version
/*
 * Copyright (C) 2019 Charles Hamilton
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 * code found at https://stackoverflow.com/questions/18004150/desktop-api-is-not-supported-on-the-current-platform
 */
package com.github.lespaul361.commons.commonroutines.utilities;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * Some basic methods
 */
public class DesktopApi {

    /**
     * Attempts to open a browser
     *
     * @param uri the url
     * @return a boolean
     */
    public static boolean browse(URI uri) {

        if (openSystemSpecific(uri.toString())) {
            return true;
        }

        if (browseDESKTOP(uri)) {
            return true;
        }

        return false;
    }

    /**
     * /**
     * Attempts to open a browser
     *
     * @param URL the url
     * @return a boolean
     * @throws URISyntaxException a URISyntaxException
     */
    public static boolean browse(String URL) throws URISyntaxException {

        if (openSystemSpecific(URL)) {
            return true;
        }
        try {

        } catch (Exception e) {
        }

        if (browseDESKTOP(URI.create(URL))) {
            return true;
        }

        return false;
    }

    /**
     * Opens a file
     *
     * @param file the file
     * @return a boolean
     */
    public static boolean open(File file) {

        if (openSystemSpecific(file.getPath())) {
            return true;
        }

        if (openDESKTOP(file)) {
            return true;
        }

        return false;
    }

    /**
     * Edits a file
     *
     * @param file the file
     * @return a boolean
     */
    public static boolean edit(File file) {

        // you can try something like
        // runCommand("gimp", "%s", file.getPath())
        // based on user preferences.
        if (openSystemSpecific(file.getPath())) {
            return true;
        }

        if (editDESKTOP(file)) {
            return true;
        }

        return false;
    }

    /**
     * Opens a browser window
     *
     * @param url the url
     * @return the exit value
     * @throws Exception an exception
     */
    public static int openBrowserWindow(String url) throws Exception {
        EnumOS os = getOs();
        Runtime rt = Runtime.getRuntime();
        Process process = null;
        if (os.isLinux()) {
            String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
                "netscape", "opera", "links", "lynx"};

            StringBuffer cmd = new StringBuffer();
            for (int i = 0; i < browsers.length; i++) {
                cmd.append((i == 0 ? "" : " || ") + browsers[i] + " \"" + url + "\" ");
            }

            process = rt.exec(new String[]{"sh", "-c", cmd.toString()});
        } else if (os.isMac()) {
            process = rt.exec("open" + url);
        } else if (os.isWindows()) {
            process = rt.exec("rundll32 url.dll,FileProtocolHandler " + url);
        } else {
            throw new Exception("Unknown OS");
        }

        int exitval = process.waitFor();
        return exitval;
    }

    private static boolean openSystemSpecific(String what) {

        EnumOS os = getOs();

        if (os.isLinux()) {
            if (runCommand("kde-open", "%s", what)) {
                return true;
            }
            if (runCommand("gnome-open", "%s", what)) {
                return true;
            }
            if (runCommand("xdg-open", "%s", what)) {
                return true;
            }
        }

        if (os.isMac()) {
            if (runCommand("open", "%s", what)) {
                return true;
            }
        }

        if (os.isWindows()) {
            if (runCommand("explorer", "%s", what)) {
                return true;
            }
        }

        return false;
    }

    private static boolean browseDESKTOP(URI uri) {

        logOut("Trying to use Desktop.getDesktop().browse() with " + uri.toString());
        try {
            if (!Desktop.isDesktopSupported()) {
                logErr("Platform is not supported.");
                return false;
            }

            if (!Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                logErr("BROWSE is not supported.");
                return false;
            }

            Desktop.getDesktop().browse(uri);

            return true;
        } catch (Throwable t) {
            logErr("Error using desktop browse.", t);
            return false;
        }
    }

    private static boolean openDESKTOP(File file) {

        logOut("Trying to use Desktop.getDesktop().open() with " + file.toString());
        try {
            if (!Desktop.isDesktopSupported()) {
                logErr("Platform is not supported.");
                return false;
            }

            if (!Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
                logErr("OPEN is not supported.");
                return false;
            }

            Desktop.getDesktop().open(file);

            return true;
        } catch (Throwable t) {
            logErr("Error using desktop open.", t);
            return false;
        }
    }

    private static boolean editDESKTOP(File file) {

        logOut("Trying to use Desktop.getDesktop().edit() with " + file);
        try {
            if (!Desktop.isDesktopSupported()) {
                logErr("Platform is not supported.");
                return false;
            }

            if (!Desktop.getDesktop().isSupported(Desktop.Action.EDIT)) {
                logErr("EDIT is not supported.");
                return false;
            }

            Desktop.getDesktop().edit(file);

            return true;
        } catch (Throwable t) {
            logErr("Error using desktop edit.", t);
            return false;
        }
    }

    private static boolean runCommand(String command, String args, String file) {

        logOut("Trying to exec:\n   cmd = " + command + "\n   args = " + args + "\n   %s = " + file);

        String[] parts = prepareCommand(command, args, file);

        try {
            Process p = Runtime.getRuntime().exec(parts);
            if (p == null) {
                return false;
            }

            try {
                int retval = p.exitValue();
                if (retval == 0) {
                    logErr("Process ended immediately.");
                    return false;
                } else {
                    logErr("Process crashed.");
                    return false;
                }
            } catch (IllegalThreadStateException itse) {
                logErr("Process is running.");
                return true;
            }
        } catch (IOException e) {
            logErr("Error running command.", e);
            return false;
        }
    }

    private static String[] prepareCommand(String command, String args, String file) {

        List parts = new ArrayList();
        parts.add(command);

        if (args != null) {
            for (String s : args.split(" ")) {
                s = String.format(s, file); // put in the filename thing

                parts.add(s.trim());
            }
        }

        return parts.toArray(new String[parts.size()]);
    }

    private static void logErr(String msg, Throwable t) {
        System.err.println(msg);
        t.printStackTrace();
    }

    private static void logErr(String msg) {
        System.err.println(msg);
    }

    private static void logOut(String msg) {
        System.out.println(msg);
    }

    /**
     * OS versions
     */
    public static enum EnumOS {

        /**
         *
         */
        linux,

        /**
         *
         */
        macos,

        /**
         *
         */
        solaris,

        /**
         *
         */
        unknown,

        /**
         *
         */
        windows;

        /**
         *
         * @return a boolean
         */
        public boolean isLinux() {

            return this == linux || this == solaris;
        }

        /**
         *
         * @return a boolean
         */
        public boolean isMac() {

            return this == macos;
        }

        /**
         *
         * @return a boolean
         */
        public boolean isWindows() {
            return this == windows;
        }

        /**
         *
         * @return a boolean
         */
        public boolean isUknown() {
            return this == unknown;
        }
    }

    /**
     * Gets the OS version
     *
     * @return the OS
     */
    public static EnumOS getOs() {

        String s = System.getProperty("os.name").toLowerCase();

        if (s.contains("win")) {
            return EnumOS.windows;
        }

        if (s.contains("mac")) {
            return EnumOS.macos;
        }

        if (s.contains("solaris")) {
            return EnumOS.solaris;
        }

        if (s.contains("sunos")) {
            return EnumOS.solaris;
        }

        if (s.contains("linux")) {
            return EnumOS.linux;
        }

        if (s.contains("unix")) {
            return EnumOS.linux;
        } else {
            return EnumOS.unknown;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy