List of usage examples for java.awt Desktop getDesktop
public static synchronized Desktop getDesktop()
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 . jav a 2 s.c om*/ 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. j a v a2 s . c o 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 a2s . c om * @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 ww w . ja v a2 s . c om*/ 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 {/* w ww.j a va 2 s. c om*/ 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 {//from w ww . java 2s . c om 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.b3log.solo.Starter.java
/** * Main.//ww w .j av a2s. c o m * * @param args the specified arguments * @throws java.lang.Exception if start failed */ public static void main(final String[] args) throws Exception { final Logger logger = Logger.getLogger(Starter.class); final Options options = new Options(); final Option listenPortOpt = Option.builder("lp").longOpt("listen_port").argName("LISTEN_PORT").hasArg() .desc("listen port, default is 8080").build(); options.addOption(listenPortOpt); final Option serverSchemeOpt = Option.builder("ss").longOpt("server_scheme").argName("SERVER_SCHEME") .hasArg().desc("browser visit protocol, default is http").build(); options.addOption(serverSchemeOpt); final Option serverHostOpt = Option.builder("sh").longOpt("server_host").argName("SERVER_HOST").hasArg() .desc("browser visit domain name, default is localhost").build(); options.addOption(serverHostOpt); final Option serverPortOpt = Option.builder("sp").longOpt("server_port").argName("SERVER_PORT").hasArg() .desc("browser visit port, default is 8080").build(); options.addOption(serverPortOpt); final Option staticServerSchemeOpt = Option.builder("sss").longOpt("static_server_scheme") .argName("STATIC_SERVER_SCHEME").hasArg() .desc("browser visit static resource protocol, default is http").build(); options.addOption(staticServerSchemeOpt); final Option staticServerHostOpt = Option.builder("ssh").longOpt("static_server_host") .argName("STATIC_SERVER_HOST").hasArg() .desc("browser visit static resource domain name, default is localhost").build(); options.addOption(staticServerHostOpt); final Option staticServerPortOpt = Option.builder("ssp").longOpt("static_server_port") .argName("STATIC_SERVER_PORT").hasArg().desc("browser visit static resource port, default is 8080") .build(); options.addOption(staticServerPortOpt); final Option runtimeModeOpt = Option.builder("rm").longOpt("runtime_mode").argName("RUNTIME_MODE").hasArg() .desc("runtime mode (DEVELOPMENT/PRODUCTION), default is DEVELOPMENT").build(); options.addOption(runtimeModeOpt); options.addOption("h", "help", false, "print help for the command"); final HelpFormatter helpFormatter = new HelpFormatter(); final CommandLineParser commandLineParser = new DefaultParser(); CommandLine commandLine; final boolean isWindows = System.getProperty("os.name").toLowerCase().contains("windows"); final String cmdSyntax = isWindows ? "java -cp WEB-INF/lib/*;WEB-INF/classes org.b3log.solo.Starter" : "java -cp WEB-INF/lib/*:WEB-INF/classes org.b3log.solo.Starter"; final String header = "\nSolo is a blogging system written in Java, feel free to create your or your team own blog.\nSolo Java ???\n\n"; final String footer = "\nReport bugs or request features please visit our project website: https://github.com/b3log/solo\n\n"; try { commandLine = commandLineParser.parse(options, args); } catch (final ParseException e) { helpFormatter.printHelp(cmdSyntax, header, options, footer, true); return; } if (commandLine.hasOption("h")) { helpFormatter.printHelp(cmdSyntax, header, options, footer, true); return; } String portArg = commandLine.getOptionValue("listen_port"); if (!Strings.isNumeric(portArg)) { portArg = "8080"; } String serverScheme = commandLine.getOptionValue("server_scheme"); Latkes.setServerScheme(serverScheme); String serverHost = commandLine.getOptionValue("server_host"); Latkes.setServerHost(serverHost); String serverPort = commandLine.getOptionValue("server_port"); Latkes.setServerPort(serverPort); String staticServerScheme = commandLine.getOptionValue("static_server_scheme"); Latkes.setStaticServerScheme(staticServerScheme); String staticServerHost = commandLine.getOptionValue("static_server_host"); Latkes.setStaticServerHost(staticServerHost); String staticServerPort = commandLine.getOptionValue("static_server_port"); Latkes.setStaticServerPort(staticServerPort); String runtimeMode = commandLine.getOptionValue("runtime_mode"); if (null != runtimeMode) { Latkes.setRuntimeMode(RuntimeMode.valueOf(runtimeMode)); } Latkes.setScanPath("org.b3log.solo"); // For Latke IoC logger.info("Standalone mode, see [https://github.com/b3log/solo/wiki/standalone_mode] for more details."); Latkes.initRuntimeEnv(); String webappDirLocation = "src/main/webapp/"; // POM structure in dev env final File file = new File(webappDirLocation); if (!file.exists()) { webappDirLocation = "."; // production environment } final int port = Integer.valueOf(portArg); final Server server = new Server(port); final WebAppContext root = new WebAppContext(); root.setParentLoaderPriority(true); // Use parent class loader root.setContextPath("/"); root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml"); root.setResourceBase(webappDirLocation); server.setHandler(root); try { server.start(); } catch (final Exception e) { logger.log(Level.ERROR, "Server start failed", e); System.exit(-1); } serverScheme = Latkes.getServerScheme(); serverHost = Latkes.getServerHost(); serverPort = Latkes.getServerPort(); final String contextPath = Latkes.getContextPath(); try { Desktop.getDesktop() .browse(new URI(serverScheme + "://" + serverHost + ":" + serverPort + contextPath)); } catch (final Throwable e) { // Ignored } server.join(); }
From source file:Main.java
public static void runExecutableOrBatch(String pathToExecutableOrBatch, String executableOrBatch) throws IOException { Desktop.getDesktop().open(new File(pathToExecutableOrBatch + executableOrBatch)); }
From source file:Main.java
/** * Opens the given website in the default browser, or show a message saying * that no default browser could be accessed. */// w ww . java 2 s .com public static void browse(Component parent, String uri) { boolean error = false; if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Action.BROWSE)) { try { Desktop.getDesktop().browse(new URI(uri)); } catch (URISyntaxException ex) { throw new RuntimeException(ex); } catch (IOException ex) { error = true; } } else { error = true; } if (error) { String msg = "Impossible to open the default browser from the application.\nSorry."; JOptionPane.showMessageDialog(parent, msg); } }
From source file:Main.java
/** * Opens the given website in the default browser, or shows a message saying * that no default browser could be accessed. *//* ww w . ja va 2 s . co m*/ public static void browse(String url, Component msgParent) { boolean error = false; if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Action.BROWSE)) { try { Desktop.getDesktop().browse(new URI(url)); } catch (URISyntaxException ex) { throw new RuntimeException(ex); } catch (IOException ex) { error = true; } } else { error = true; } if (error) { String msg = "Impossible to open the default browser from the application.\nSorry."; JOptionPane.showMessageDialog(msgParent, msg); } }