Example usage for java.awt Desktop isDesktopSupported

List of usage examples for java.awt Desktop isDesktopSupported

Introduction

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

Prototype

public static boolean isDesktopSupported() 

Source Link

Document

Tests whether this class is supported on the current platform.

Usage

From source file:com.rest.samples.getReportFromJasperServer.java

public static void main(String[] args) {
    // TODO code application logic here
    String url = "http://username:password@10.49.28.3:8081/jasperserver/rest_v2/reports/Reportes/vencimientos.pdf?feini=2016-09-30&fefin=2016-09-30";
    try {/*from   w w  w .java2  s  .  c  o  m*/
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/pdf");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        OutputStream os = new FileOutputStream(new File("vencimientos.pdf"));
        int read = 0;
        byte[] bytes = new byte[2048];

        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        is.close();
        os.close();

        if (Desktop.isDesktopSupported()) {
            File pdfFile = new File("vencimientos.pdf");
            Desktop.getDesktop().open(pdfFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.msopentech.ThaliClient.ProxyDesktop.java

public static void main(String[] rgs) throws InterruptedException, URISyntaxException, IOException {

    final ProxyDesktop instance = new ProxyDesktop();
    try {//from  w  ww.j a  v a  2s.c  om
        instance.initialize();
    } catch (RuntimeException e) {
        System.out.println(e);
    }

    // Attempt to launch the default browser to our page
    if (Desktop.isDesktopSupported()) {
        Desktop.getDesktop().browse(new URI("http://localhost:" + localWebserverPort));
    }

    // Register to shutdown the server properly from a sigterm
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            instance.shutdown();
        }
    });

    // Let user press enter to kill the console session
    Console console = System.console();
    if (console != null) {
        console.format("\nPress ENTER to exit.\n");
        console.readLine();
        instance.shutdown();
    } else {
        // Don't exit on your own when running without a console (debugging in an IDE).
        while (true) {
            Thread.sleep(500);
        }
    }
}

From source file:it.anyplace.sync.webclient.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("C", "set-config", true, "set config file for s-client");
    options.addOption("h", "help", false, "print help");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("s-client", options);
        return;//from  w  ww.jav a 2s. c o m
    }

    File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C"))
            : new File(System.getProperty("user.home"), ".s-client.properties");
    logger.info("using config file = {}", configFile);
    try (ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile)) {
        FileUtils.cleanDirectory(configuration.getTemp());
        KeystoreHandler.newLoader().loadAndStore(configuration);
        logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace());
        try (HttpService httpService = new HttpService(configuration)) {
            httpService.start();
            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(
                        URI.create("http://localhost:" + httpService.getPort() + "/web/webclient.html"));
            }
            httpService.join();
        }
    }
}

From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuth.java

public static void main(String[] args) {
    // TODO code application logic here

    String host = "10.49.28.3";
    String port = "8081";
    String reportName = "vencimientos";
    String params = "feini=2016-09-30&fefin=2016-09-30";
    String url = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{params}";
    url = url.replace("{host}", host);
    url = url.replace("{port}", port);
    url = url.replace("{reportName}", reportName);
    url = url.replace("{params}", params);

    try {/* w w w .j  a  v a  2 s  .co  m*/
        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password"));
        CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build();

        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/pdf");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        OutputStream os = new FileOutputStream(new File("vencimientos.pdf"));
        int read = 0;
        byte[] bytes = new byte[2048];

        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        is.close();
        os.close();

        if (Desktop.isDesktopSupported()) {
            File pdfFile = new File("vencimientos.pdf");
            Desktop.getDesktop().open(pdfFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuthFormatURL.java

public static void main(String[] args) {
    // TODO code application logic here
    Map<String, String> params = new HashMap<String, String>();
    params.put("host", "10.49.28.3");
    params.put("port", "8081");
    params.put("reportName", "vencimientos");
    params.put("parametros", "feini=2016-09-30&fefin=2016-09-30");
    StrSubstitutor sub = new StrSubstitutor(params, "{", "}");
    String urlTemplate = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{parametros}";
    String url = sub.replace(urlTemplate);

    try {//  ww w .ja  va 2  s  .co  m
        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("jasperadmin", "jasperadmin"));
        CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build();

        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/pdf");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        OutputStream os = new FileOutputStream(new File("vencimientos.pdf"));
        int read = 0;
        byte[] bytes = new byte[2048];

        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        is.close();
        os.close();

        if (Desktop.isDesktopSupported()) {
            File pdfFile = new File("vencimientos.pdf");
            Desktop.getDesktop().open(pdfFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.serotonin.m2m2.Main.java

/**
 *
 * @param args/*from   ww w  .j a v a  2  s . c  o m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    Providers.add(ICoreLicense.class, new CoreLicenseDefinition());

    Common.MA_HOME = System.getProperty("ma.home");
    Common.M2M2_HOME = Common.MA_HOME;

    new File(Common.MA_HOME, "RESTART").delete();

    Common.envProps = new ReloadingProperties("env");

    openZipFiles();
    ClassLoader moduleClassLoader = loadModules();

    Lifecycle lifecycle = new Lifecycle();
    Providers.add(ILifecycle.class, lifecycle);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            ((ILifecycle) Providers.get(ILifecycle.class)).terminate();
        }
    });
    try {
        lifecycle.initialize(moduleClassLoader);
        if ((!GraphicsEnvironment.isHeadless()) && (Desktop.isDesktopSupported())
                && (Common.envProps.getBoolean("web.openBrowserOnStartup"))) {
            Desktop.getDesktop().browse(new URI(new StringBuilder().append("http://localhost:")
                    .append(Common.envProps.getInt("web.port", 8088)).toString()));
        }
    } catch (Exception e) {
        LOG.error("Error during initialization", e);
        lifecycle.terminate();
    }
}

From source file:org.jdal.util.processor.JasperReportFileProcessor.java

public static void main(String[] args) {
    try {/*from  w w w .j a  va2s.c o m*/
        JasperReport report = JasperCompileManager
                .compileReport("/home/jose/Projects/telmma/Documents/Code/testParameters.jrxml");

        System.out.println("Query en el jasper: " + report.getQuery().getText());
        for (JRParameter param : report.getParameters()) {
            if (!param.isSystemDefined())
                System.out.println(param.getName());
        }
        Map<String, Object> parameters = new HashMap<String, Object>();
        // TEST
        parameters.put("NombreCiudad", "Huelva");

        JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, new JREmptyDataSource());
        byte[] reportBin = JasperExportManager.exportReportToPdf(jasperPrint);

        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            File outputFile;
            try {
                outputFile = File.createTempFile("simple_report", ".pdf");
                //outputFile.deleteOnExit();
                // Create the file with the raw data provided by the file processor 
                FileUtils.writeByteArrayToFile(outputFile, reportBin);

                System.out.println("OutputFile -> " + outputFile.getName() + " " + outputFile.getTotalSpace());

                desktop.open(outputFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.image32.demo.simpleapi.SimpleApiDemo.java

final public static void main(String[] args) {
    me = new SimpleApiDemo();
    me.contentHandlers = new ContentHandler();

    //load configurations
    try {/*from   w w  w  .j  a v  a2 s  .c o m*/
        Properties prop = new Properties();
        InputStream input = SimpleApiDemo.class.getResourceAsStream("/demoConfig.properties");

        // load a properties file
        prop.load(input);
        image32ApiClientId = prop.getProperty("image32ApiClientId");
        image32ApiSecrect = prop.getProperty("image32ApiSecrect");
        image32ApiAuthUrl = prop.getProperty("image32ApiAuthUrl");
        image32ApiGetStudiesUrl = prop.getProperty("image32ApiGetStudiesUrl");
        demoDataFile = prop.getProperty("demoDataFile");
        input.close();
    } catch (Exception ex) {
        logger.info("No configuration found.");
        System.exit(1);
    }

    // test port availability
    while (!checkPortAvailablity(port)) {
        if (port > 8090) {
            logger.info("Port is not available. Exiting...");
            System.exit(1);
        }
        port++;
    }
    ;

    // run server
    server = new Server(port);
    HashSessionIdManager hashSessionIdManager = new HashSessionIdManager();
    server.setSessionIdManager(hashSessionIdManager);

    WebAppContext homecontext = new WebAppContext();
    homecontext.setContextPath("/home");
    ResourceCollection resources = new ResourceCollection(new String[] { "site" });
    homecontext.setBaseResource(resources);

    HashSessionManager manager = new HashSessionManager();
    manager.setSecureCookies(true);
    SessionHandler sessionHandler = new SessionHandler(manager);

    sessionHandler.setHandler(me.contentHandlers);

    ContextHandler context = new ContextHandler();
    context.setContextPath("/app");
    context.setResourceBase(".");
    context.setClassLoader(Thread.currentThread().getContextClassLoader());
    context.setHandler(sessionHandler);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { homecontext, context });

    server.setHandler(handlers);

    try {
        server.start();
        logger.info("Server started on port " + port);
        logger.info("Please access this demo from browser with this url: http://localhost:" + port);

        if (Desktop.isDesktopSupported())
            Desktop.getDesktop().browse(new URI("http://localhost:" + port + "/home"));

        server.join();
    } catch (Exception exception) {
        logger.error(exception.getMessage());
    }
    System.exit(1);
}

From source file:me.timothy.ddd.DrunkDuckDispatch.java

License:asdf

public static void main(String[] args) throws LWJGLException {
    try {//  ww w  .  j  a v a2  s .  co  m
        float defaultDisplayWidth = SizeScaleSystem.EXPECTED_WIDTH / 2;
        float defaultDisplayHeight = SizeScaleSystem.EXPECTED_HEIGHT / 2;
        boolean fullscreen = false, defaultDisplay = !fullscreen;
        File resolutionInfo = new File("graphics.json");

        if (resolutionInfo.exists()) {
            try (FileReader fr = new FileReader(resolutionInfo)) {
                JSONObject obj = (JSONObject) new JSONParser().parse(fr);
                Set<?> keys = obj.keySet();
                for (Object o : keys) {
                    if (o instanceof String) {
                        String key = (String) o;
                        switch (key.toLowerCase()) {
                        case "width":
                            defaultDisplayWidth = JSONCompatible.getFloat(obj, key);
                            break;
                        case "height":
                            defaultDisplayHeight = JSONCompatible.getFloat(obj, key);
                            break;
                        case "fullscreen":
                            fullscreen = JSONCompatible.getBoolean(obj, key);
                            defaultDisplay = !fullscreen;
                            break;
                        }
                    }
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
            float expHeight = defaultDisplayWidth
                    * (SizeScaleSystem.EXPECTED_HEIGHT / SizeScaleSystem.EXPECTED_WIDTH);
            float expWidth = defaultDisplayHeight
                    * (SizeScaleSystem.EXPECTED_WIDTH / SizeScaleSystem.EXPECTED_HEIGHT);
            if (Math.round(defaultDisplayWidth) != Math.round(expWidth)) {
                if (defaultDisplayHeight < expHeight) {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, defaultDisplayWidth, expHeight);
                    defaultDisplayHeight = expHeight;
                } else {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, expWidth, defaultDisplayHeight);
                    defaultDisplayWidth = expWidth;
                }
            }
        }
        File dir = null;
        String os = getOS();
        if (os.equals("windows")) {
            dir = new File(System.getenv("APPDATA"), "timgames/");
        } else {
            dir = new File(System.getProperty("user.home"), ".timgames/");
        }
        File lwjglDir = new File(dir, "lwjgl-2.9.1/");
        Resources.init();
        Resources.downloadIfNotExists(lwjglDir, "lwjgl-2.9.1.zip", "http://umad-barnyard.com/lwjgl-2.9.1.zip",
                "Necessary LWJGL natives couldn't be found, I can attempt "
                        + "to download it, but I make no promises",
                "Unfortunately I was unable to download it, so I'll open up the "
                        + "link to the official download. Make sure you get LWJGL version 2.9.1, "
                        + "and you put it at " + dir.getAbsolutePath() + "/lwjgl-2.9.1.zip",
                new Runnable() {

                    @Override
                    public void run() {
                        if (!Desktop.isDesktopSupported()) {
                            JOptionPane.showMessageDialog(null,
                                    "I couldn't " + "even do that! Download it manually and try again");
                            return;
                        }

                        try {
                            Desktop.getDesktop().browse(new URI("http://www.lwjgl.org/download.php"));
                        } catch (IOException | URISyntaxException e) {
                            JOptionPane.showMessageDialog(null,
                                    "Oh cmon.. Address is http://www.lwjgl.org/download.php, good luck");
                            System.exit(1);
                        }
                    }

                }, 5843626);

        Resources.extractIfNotFound(lwjglDir, "lwjgl-2.9.1.zip", "lwjgl-2.9.1");
        System.setProperty("org.lwjgl.librarypath",
                new File(dir, "lwjgl-2.9.1/lwjgl-2.9.1/native/" + os).getAbsolutePath()); // deal w/ it
        System.setProperty("net.java.games.input.librarypath", System.getProperty("org.lwjgl.librarypath"));

        Resources.downloadIfNotExists("entities.json", "http://umad-barnyard.com/ddd/entities.json", 16142);
        Resources.downloadIfNotExists("map.binary", "http://umad-barnyard.com/ddd/map.binary", 16142);
        Resources.downloadIfNotExists("victory.txt", "http://umad-barnyard.com/ddd/victory.txt", 168);
        Resources.downloadIfNotExists("failure.txt", "http://umad-barnyard.com/ddd/failure.txt", 321);
        File resFolder = new File("resources/");
        if (!resFolder.exists() && !new File("player-still.png").exists()) {
            Resources.downloadIfNotExists("resources.zip", "http://umad-barnyard.com/ddd/resources.zip", 54484);
            Resources.extractIfNotFound(new File("."), "resources.zip", "player-still.png");
            new File("resources.zip").delete();
        }
        File soundFolder = new File("sounds/");
        if (!soundFolder.exists()) {
            soundFolder.mkdirs();
            Resources.downloadIfNotExists("sounds/sounds.zip", "http://umad-barnyard.com/ddd/sounds.zip",
                    1984977);
            Resources.extractIfNotFound(soundFolder, "sounds.zip", "asdfasdffadasdf");
            new File(soundFolder, "sounds.zip").delete();
        }
        AppGameContainer appgc;
        ddd = new DrunkDuckDispatch();
        appgc = new AppGameContainer(ddd);
        appgc.setTargetFrameRate(60);
        appgc.setShowFPS(false);
        appgc.setAlwaysRender(true);
        if (fullscreen) {
            DisplayMode[] modes = Display.getAvailableDisplayModes();
            DisplayMode current, best = null;
            float ratio = 0f;
            for (int i = 0; i < modes.length; i++) {
                current = modes[i];
                float rX = (float) current.getWidth() / SizeScaleSystem.EXPECTED_WIDTH;
                float rY = (float) current.getHeight() / SizeScaleSystem.EXPECTED_HEIGHT;
                System.out.println(current.getWidth() + "x" + current.getHeight() + " -> " + rX + "x" + rY);
                if (rX == rY && rX > ratio) {
                    best = current;
                    ratio = rX;
                }
            }
            if (best == null) {
                System.out.println("Failed to find an appropriately scaled resolution, using default display");
                defaultDisplay = true;
            } else {
                appgc.setDisplayMode(best.getWidth(), best.getHeight(), true);
                SizeScaleSystem.setRealHeight(best.getHeight());
                SizeScaleSystem.setRealWidth(best.getWidth());
                System.out.println("I choose " + best.getWidth() + "x" + best.getHeight());
            }
        }

        if (defaultDisplay) {
            SizeScaleSystem.setRealWidth(Math.round(defaultDisplayWidth));
            SizeScaleSystem.setRealHeight(Math.round(defaultDisplayHeight));
            appgc.setDisplayMode(Math.round(defaultDisplayWidth), Math.round(defaultDisplayHeight), false);
        }
        ddd.logger.info(
                "SizeScaleSystem: " + SizeScaleSystem.getRealWidth() + "x" + SizeScaleSystem.getRealHeight());
        appgc.start();
    } catch (SlickException ex) {
        LogManager.getLogger(DrunkDuckDispatch.class.getSimpleName()).catching(Level.ERROR, ex);
    }
}

From source file:org.apache.http.examples.me.ClientMultiThreadedExecution.java

public static void runBroswer(String webSite) {
    try {/*from   w w  w .j  a va 2 s. c  o m*/
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isDesktopSupported() && desktop.isSupported(Desktop.Action.BROWSE)) {
            URI uri = new URI(webSite);
            desktop.browse(uri);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (URISyntaxException ex) {
        ex.printStackTrace();
    }
}