List of usage examples for java.lang System getProperty
public static String getProperty(String key)
From source file:br.com.thiagomoreira.bancodobrasil.Main.java
/** * @param args//from w w w. j a v a2 s . c om */ public static void main(String[] args) throws Exception { if (args != null) { NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("pt", "BR")); formatter.setMaximumFractionDigits(2); formatter.setMinimumFractionDigits(2); double total = 0; for (String arg : args) { File input = new File(arg); if (input.exists()) { List<String> lines = IOUtils.readLines(new FileInputStream(input), "ISO-8859-1"); Parser parser = new DefaultParser(); List<Transaction> transactions = parser.parse(lines); TransactionList transactionList = new TransactionList(); transactionList.setStart(parser.getStartDate()); transactionList.setEnd(parser.getEndDate()); transactionList.setTransactions(transactions); CreditCardAccountDetails creditCardAccountDetails = new CreditCardAccountDetails(); creditCardAccountDetails.setAccountNumber("7616-3"); creditCardAccountDetails.setAccountKey(parser.getAccountKey()); CreditCardStatementResponse creditCardStatementResponse = new CreditCardStatementResponse(); creditCardStatementResponse.setAccount(creditCardAccountDetails); creditCardStatementResponse.setCurrencyCode("BRL"); creditCardStatementResponse.setTransactionList(transactionList); Status status = new Status(); status.setCode(Status.KnownCode.SUCCESS); status.setSeverity(Status.Severity.INFO); CreditCardStatementResponseTransaction statementResponse = new CreditCardStatementResponseTransaction(); statementResponse.setClientCookie(UUID.randomUUID().toString()); statementResponse.setStatus(status); statementResponse.setUID(UUID.randomUUID().toString()); statementResponse.setMessage(creditCardStatementResponse); CreditCardResponseMessageSet creditCardResponseMessageSet = new CreditCardResponseMessageSet(); creditCardResponseMessageSet.setStatementResponse(statementResponse); SortedSet<ResponseMessageSet> messageSets = new TreeSet<ResponseMessageSet>(); messageSets.add(creditCardResponseMessageSet); ResponseEnvelope envelope = new ResponseEnvelope(); envelope.setUID(UUID.randomUUID().toString()); envelope.setSecurity(ApplicationSecurity.NONE); envelope.setMessageSets(messageSets); double brazilianRealsamount = parser.getBrazilianRealsAmount(); double dolarsAmount = parser.getDolarsAmount(); double cardTotal = dolarsAmount * parser.getExchangeRate() + brazilianRealsamount; total += cardTotal; System.out.println(creditCardAccountDetails.getAccountKey()); System.out.println("TOTAL EM RS " + formatter.format(brazilianRealsamount)); System.out.println("TOTAL EM US " + formatter.format(dolarsAmount)); System.out.println("TOTAL FATURA EM RS " + formatter.format(cardTotal)); System.out.println(); if (!transactions.isEmpty()) { String parent = System.getProperty("user.home") + "/Downloads"; String fileName = arg.replace(".txt", ".ofx"); File output = new File(parent, fileName); FileOutputStream fos = new FileOutputStream(output); OFXV1Writer writer = new OFXV1Writer(fos); writer.setWriteAttributesOnNewLine(true); AggregateMarshaller marshaller = new AggregateMarshaller(); marshaller.setConversion(new MyFinanceStringConversion()); marshaller.marshal(envelope, writer); writer.flush(); writer.close(); } } } System.out.println("TOTAL FATURAS EM RS " + formatter.format(total)); } }
From source file:FileCompressor.java
public static void main(String[] args) throws IOException { String file = "D:\\XJad.rar.txt"; BufferedReader reader = new BufferedReader(new FileReader(file)); BufferedWriter writer = new BufferedWriter(new FileWriter(file + "_out.txt")); StringBuilder content = new StringBuilder(); String tmp;// ww w . j a va 2 s .c o m while ((tmp = reader.readLine()) != null) { content.append(tmp); content.append(System.getProperty("line.separator")); } FileCompressor f = new FileCompressor(); writer.write(f.compress(content.toString())); writer.close(); reader.close(); reader = new BufferedReader(new FileReader(file + "_out.txt")); StringBuilder content2 = new StringBuilder(); while ((tmp = reader.readLine()) != null) { content2.append(tmp); content2.append(System.getProperty("line.separator")); } String decompressed = f.decompress(content2.toString()); String c = content.toString(); System.out.println(decompressed.equals(c)); }
From source file:me.timothy.ddd.DrunkDuckDispatch.java
License:asdf
public static void main(String[] args) throws LWJGLException { try {//from ww w. j a va2s. 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:com.hortonworks.registries.storage.tool.sql.DatabaseUserInitializer.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH) .desc("Config file path").build()); options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH) .desc("Mysql client jar url to download").build()); options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_JDBC_URL) .desc("JDBC url to connect DBMS via admin.").build()); options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_DB_USER) .desc("Admin user name: should be able to create and grant privileges.").build()); options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_PASSWORD) .desc("Admin user's password: should be able to create and grant privileges.").build()); options.addOption(//from w w w . j a v a 2 s. c o m Option.builder().hasArg().longOpt(OPTION_TARGET_USER).desc("Name of target user.").build()); options.addOption( Option.builder().hasArg().longOpt(OPTION_TARGET_PASSWORD).desc("Password of target user.").build()); options.addOption( Option.builder().hasArg().longOpt(OPTION_TARGET_DATABASE).desc("Target database.").build()); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); String[] neededOptions = { OPTION_CONFIG_FILE_PATH, OPTION_MYSQL_JAR_URL_PATH, OPTION_ADMIN_JDBC_URL, OPTION_ADMIN_DB_USER, OPTION_ADMIN_PASSWORD, OPTION_TARGET_USER, OPTION_TARGET_PASSWORD, OPTION_TARGET_DATABASE }; boolean optNotFound = Arrays.stream(neededOptions).anyMatch(opt -> !commandLine.hasOption(opt)); if (optNotFound) { usage(options); System.exit(1); } String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH); String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH); Optional<AdminOptions> adminOptionsOptional = AdminOptions.from(commandLine); if (!adminOptionsOptional.isPresent()) { usage(options); System.exit(1); } AdminOptions adminOptions = adminOptionsOptional.get(); Optional<TargetOptions> targetOptionsOptional = TargetOptions.from(commandLine); if (!targetOptionsOptional.isPresent()) { usage(options); System.exit(1); } TargetOptions targetOptions = targetOptionsOptional.get(); DatabaseType databaseType = findDatabaseType(adminOptions.getJdbcUrl()); Map<String, Object> conf; try { conf = Utils.readConfig(confFilePath); } catch (IOException e) { System.err.println("Error occurred while reading config file: " + confFilePath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } String bootstrapDirPath = null; try { bootstrapDirPath = System.getProperty("bootstrap.dir"); Proxy proxy = Proxy.NO_PROXY; String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL); String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME); String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD); if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) { URL url = new URL(httpProxyUrl); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort())); if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) { Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername, httpProxyPassword)); } } StorageProviderConfiguration storageProperties = StorageProviderConfiguration.get( adminOptions.getJdbcUrl(), adminOptions.getUsername(), adminOptions.getPassword(), adminOptions.getDatabaseType()); MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy); } catch (Exception e) { System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } try (Connection conn = getConnectionViaAdmin(adminOptions)) { DatabaseCreator databaseCreator = DatabaseCreatorFactory.newInstance(adminOptions.getDatabaseType(), conn); UserCreator userCreator = UserCreatorFactory.newInstance(adminOptions.getDatabaseType(), conn); String database = targetOptions.getDatabase(); String username = targetOptions.getUsername(); createDatabase(databaseCreator, database); createUser(targetOptions, userCreator, username); grantPrivileges(databaseCreator, database, username); } }
From source file:com.p2p.peercds.cli.TorrentMain.java
/** * Torrent reader and creator./*from w w w. jav a 2 s. c o m*/ * * <p> * You can use the {@code main()} function of this class to read or create * torrent files. See usage for details. * </p> * */ public static void main(String[] args) { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n"))); CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option help = parser.addBooleanOption('h', "help"); CmdLineParser.Option filename = parser.addStringOption('t', "torrent"); CmdLineParser.Option create = parser.addBooleanOption('c', "create"); CmdLineParser.Option announce = parser.addStringOption('a', "announce"); try { parser.parse(args); } catch (CmdLineParser.OptionException oe) { System.err.println(oe.getMessage()); usage(System.err); System.exit(1); } // Display help and exit if requested if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) { usage(System.out); System.exit(0); } String filenameValue = (String) parser.getOptionValue(filename); if (filenameValue == null) { usage(System.err, "Torrent file must be provided!"); System.exit(1); } Boolean createFlag = (Boolean) parser.getOptionValue(create); //For repeated announce urls @SuppressWarnings("unchecked") Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce); String[] otherArgs = parser.getRemainingArgs(); if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) { usage(System.err, "Announce URL and a file or directory must be " + "provided to create a torrent file!"); System.exit(1); } OutputStream fos = null; try { if (Boolean.TRUE.equals(createFlag)) { if (filenameValue != null) { fos = new FileOutputStream(filenameValue); } else { fos = System.out; } //Process the announce URLs into URIs List<URI> announceURIs = new ArrayList<URI>(); for (String url : announceURLs) { announceURIs.add(new URI(url)); } //Create the announce-list as a list of lists of URIs //Assume all the URI's are first tier trackers List<List<URI>> announceList = new ArrayList<List<URI>>(); announceList.add(announceURIs); File source = new File(otherArgs[0]); if (!source.exists() || !source.canRead()) { throw new IllegalArgumentException( "Cannot access source file or directory " + source.getName()); } String creator = String.format("%s (ttorrent)", System.getProperty("user.name")); Torrent torrent = null; if (source.isDirectory()) { File[] files = source.listFiles(Constants.hiddenFilesFilter); Arrays.sort(files); torrent = Torrent.create(source, Arrays.asList(files), announceList, creator); } else { torrent = Torrent.create(source, announceList, creator); } torrent.save(fos); } else { Torrent.load(new File(filenameValue), true); } } catch (Exception e) { logger.error("{}", e.getMessage(), e); System.exit(2); } finally { if (fos != System.out) { IOUtils.closeQuietly(fos); } } }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.CollectionSplitter.java
public static void main(String[] args) { Options options = new Options(); options.addOption("i", null, true, "Input file"); options.addOption("o", null, true, "Output file prefix"); options.addOption("p", null, true, "Comma separated probabilities e.g., 0.1,0.2,0.7."); options.addOption("n", null, true, "Comma separated part names, e.g., dev,test,train"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {//from w w w.j a v a 2 s . c o m CommandLine cmd = parser.parse(options, args); InputStream input = null; if (cmd.hasOption("i")) { input = CompressUtils.createInputStream(cmd.getOptionValue("i")); } else { Usage("Specify Input file"); } ArrayList<Double> probs = new ArrayList<Double>(); String[] partNames = null; if (cmd.hasOption("p")) { String parts[] = cmd.getOptionValue("p").split(","); try { double sum = 0; for (String s : parts) { double p = Double.parseDouble(s); if (p <= 0 || p > 1) Usage("All probabilities must be in the range (0,1)"); sum += p; probs.add(p); } if (Math.abs(sum - 1.0) > Float.MIN_NORMAL) { Usage("The sum of probabilities should be equal to 1, but it's: " + sum); } } catch (NumberFormatException e) { Usage("Can't convert some of the probabilities to a floating-point number."); } } else { Usage("Specify part probabilities."); } if (cmd.hasOption("n")) { partNames = cmd.getOptionValue("n").split(","); if (partNames.length != probs.size()) Usage("The number of probabilities is not equal to the number of parts!"); } else { Usage("Specify part names"); } BufferedWriter[] outFiles = new BufferedWriter[partNames.length]; if (cmd.hasOption("o")) { String outPrefix = cmd.getOptionValue("o"); for (int partId = 0; partId < partNames.length; ++partId) { outFiles[partId] = new BufferedWriter(new OutputStreamWriter( CompressUtils.createOutputStream(outPrefix + "_" + partNames[partId] + ".gz"))); } } else { Usage("Specify Output file prefix"); } System.out.println("Using probabilities:"); for (int partId = 0; partId < partNames.length; ++partId) System.out.println(partNames[partId] + " : " + probs.get(partId)); System.out.println("================================================="); XmlIterator inpIter = new XmlIterator(input, YahooAnswersReader.DOCUMENT_TAG); String oneRec = inpIter.readNext(); int docNum = 1; for (; !oneRec.isEmpty(); ++docNum, oneRec = inpIter.readNext()) { double p = Math.random(); if (docNum % 1000 == 0) { System.out.println(String.format("Processed %d documents", docNum)); } BufferedWriter out = null; for (int partId = 0; partId < partNames.length; ++partId) { double pp = probs.get(partId); if (p <= pp || partId + 1 == partNames.length) { out = outFiles[partId]; break; } p -= pp; } oneRec = oneRec.trim() + System.getProperty("line.separator"); out.write(oneRec); } System.out.println(String.format("Processed %d documents", docNum - 1)); // It's important to close all the streams here! for (BufferedWriter f : outFiles) f.close(); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:es.tid.fiware.fiwareconnectors.cygnus.nodes.CygnusApplication.java
/** * Main application to be run when this CygnusApplication is invoked. The only differences with the original one * are the CygnusApplication is used instead of the Application one, and the Management Interface port option in * the command line./*w w w . j a v a 2 s .com*/ * @param args */ public static void main(String[] args) { try { Options options = new Options(); Option option = new Option("n", "name", true, "the name of this agent"); option.setRequired(true); options.addOption(option); option = new Option("f", "conf-file", true, "specify a conf file"); option.setRequired(true); options.addOption(option); option = new Option(null, "no-reload-conf", false, "do not reload " + "conf file if changed"); options.addOption(option); option = new Option("h", "help", false, "display help text"); options.addOption(option); option = new Option("p", "mgmt-if-port", true, "the management interface port"); option.setRequired(false); options.addOption(option); CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); File configurationFile = new File(commandLine.getOptionValue('f')); String agentName = commandLine.getOptionValue('n'); boolean reload = !commandLine.hasOption("no-reload-conf"); if (commandLine.hasOption('h')) { new HelpFormatter().printHelp("flume-ng agent", options, true); return; } // if int mgmtIfPort = 8081; // default value if (commandLine.hasOption('p')) { mgmtIfPort = new Integer(commandLine.getOptionValue('p')).intValue(); } // if // the following is to ensure that by default the agent will fail on startup if the file does not exist if (!configurationFile.exists()) { // if command line invocation, then need to fail fast if (System.getProperty(Constants.SYSPROP_CALLED_FROM_SERVICE) == null) { String path = configurationFile.getPath(); try { path = configurationFile.getCanonicalPath(); } catch (IOException ex) { logger.error("Failed to read canonical path for file: " + path, ex); } // try catch throw new ParseException("The specified configuration file does not exist: " + path); } // if } // if List<LifecycleAware> components = Lists.newArrayList(); CygnusApplication application; if (reload) { EventBus eventBus = new EventBus(agentName + "-event-bus"); PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider( agentName, configurationFile, eventBus, 30); components.add(configurationProvider); application = new CygnusApplication(components, mgmtIfPort); eventBus.register(application); } else { PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider( agentName, configurationFile); application = new CygnusApplication(mgmtIfPort); application.handleConfigurationEvent(configurationProvider.getConfiguration()); } // if else application.start(); final CygnusApplication appReference = application; Runtime.getRuntime().addShutdownHook(new Thread("agent-shutdown-hook") { @Override public void run() { appReference.stop(); } // run }); } catch (Exception e) { logger.error("A fatal error occurred while running. Exception follows.", e); } // try catch }
From source file:net.siegmar.japtproxy.JaptProxyServer.java
/** * Starts the JaptProxyServer with the given parameters. * * @param args command line args./* w w w .j ava2 s . c o m*/ */ public static void main(final String[] args) { if (checkRequiredOptions()) { System.exit(1); } String configFile = System.getProperty(OPT_CONFIG); String contextPath = System.getProperty(OPT_CONTEXT_PATH); String logConfig = System.getProperty(OPT_LOG_CONFIG); final String host = System.getProperty(OPT_HOST); String port = System.getProperty(OPT_PORT); // Check settings if (configFile == null) { configFile = OPT_CONFIG_DEFAULT; } if (contextPath == null) { contextPath = OPT_CONTEXT_PATH_DEFAULT; } if (logConfig == null) { logConfig = OPT_LOG_CONFIG_DEFAULT; } if (port == null) { port = OPT_PORT_DEFAULT; } if (!new File(configFile).exists()) { System.err.println("Config file '" + configFile + "' doesn't exist"); System.exit(1); } try { initializeLogging(logConfig); } catch (final RuntimeException e) { System.err.println("Couldn't initialize logging"); e.printStackTrace(System.err); System.exit(1); } final Logger log = LoggerFactory.getLogger(JaptProxyServer.class); // Remove PID_FILE if specified final String pidFile = System.getenv("PID_FILE"); if (pidFile != null) { log.debug("Will try to delete PID_FILE {} on exit", pidFile); new File(pidFile).deleteOnExit(); } try { final int portNumber = Integer.parseInt(port); startServer(host, portNumber, StringUtils.stripEnd(contextPath, "/")); } catch (final NumberFormatException e) { log.error("The specified port number {} is not a number", port); System.exit(1); } catch (final RuntimeException e) { log.error("Error while starting server", e); System.exit(1); } }
From source file:com.google.cloud.runtimes.builder.Application.java
/** * Main method for invocation from the command line. Handles parsing of command line options. *///from w ww. java 2s . c o m public static void main(String[] args) throws BuildStepException, IOException { addCliOptions(CLI_OPTIONS); CommandLine cmd = parse(args); String[] jdkMappings = cmd.getOptionValues("j"); String[] serverMappings = cmd.getOptionValues("s"); String compatImage = cmd.getOptionValue("c"); String mavenImage = cmd.getOptionValue("m"); String gradleImage = cmd.getOptionValue("g"); boolean disableSourceBuild = cmd.hasOption("n"); Injector injector = Guice .createInjector(new RootModule(mergeSettingsWithDefaults(jdkMappings, serverMappings), compatImage == null ? DEFAULT_COMPAT_RUNTIME_IMAGE : compatImage, mavenImage == null ? DEFAULT_MAVEN_DOCKER_IMAGE : mavenImage, gradleImage == null ? DEFAULT_GRADLE_DOCKER_IMAGE : gradleImage, disableSourceBuild, getAppYamlOverrideSettings(cmd))); // Perform dependency injection and run the application Path workspaceDir = Paths.get(System.getProperty("user.dir")); injector.getInstance(BuildPipelineConfigurator.class).generateDockerResources(workspaceDir); }
From source file:acmi.l2.clientmod.l2_version_switcher.Main.java
public static void main(String[] args) { if (args.length != 3 && args.length != 4) { System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>"); System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME + " 1 \"system\\*\""); System.out.println(//from ww w . j a v a 2 s. c o m " l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48"); System.exit(0); } List<String> argsList = new ArrayList<>(Arrays.asList(args)); String host = argsList.get(0); String game = argsList.get(1); int version = Integer.parseInt(argsList.get(2)); Helper helper = new Helper(host, game, version); boolean available = false; try { available = helper.isAvailable(); } catch (IOException e) { System.err.print(e.getClass().getSimpleName()); if (e.getMessage() != null) { System.err.print(": " + e.getMessage()); } System.err.println(); } System.out.println(String.format("Version %d available: %b", version, available)); if (!available) { System.exit(0); } List<FileInfo> fileInfoList = null; try { fileInfoList = helper.getFileInfoList(); } catch (IOException e) { System.err.println("Couldn\'t get file info map"); System.exit(1); } boolean splash = argsList.remove("--splash"); if (splash) { Optional<FileInfo> splashObj = fileInfoList.stream() .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny(); if (splashObj.isPresent()) { try (InputStream is = new FilterInputStream( Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) { @Override public int read() throws IOException { int b = super.read(); if (b >= 0) b ^= 0x36; return b; } @Override public int read(byte[] b, int off, int len) throws IOException { int r = super.read(b, off, len); if (r >= 0) { for (int i = 0; i < r; i++) b[off + i] ^= 0x36; } return r; } }) { new DataInputStream(is).readFully(new byte[28]); BufferedImage bi = ImageIO.read(is); JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath()); frame.setContentPane(new JComponent() { { setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight())); } @Override protected void paintComponent(Graphics g) { g.drawImage(bi, 0, 0, null); } }); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Splash not found"); } return; } String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null; File l2Folder = new File(System.getProperty("user.dir")); List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> { String filePath = separatorsToSystem(fi.getPath()); if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE)) return false; File file = new File(l2Folder, filePath); try { if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) { System.out.println(filePath + ": OK"); return false; } } catch (IOException e) { System.out.println(filePath + ": couldn't check hash: " + e); return true; } System.out.println(filePath + ": need update"); return true; }).collect(Collectors.toList()); List<String> errors = Collections.synchronizedList(new ArrayList<>()); ExecutorService executor = Executors.newFixedThreadPool(16); CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> { String filePath = separatorsToSystem(fi.getPath()); File file = new File(l2Folder, filePath); File folder = file.getParentFile(); if (!folder.exists()) { if (!folder.mkdirs()) { errors.add(filePath + ": couldn't create parent dir"); return; } } try (InputStream input = Util .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath()))); OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) { byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)]; int pos = 0; int r; while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) { pos += r; if (pos == buffer.length) { output.write(buffer, 0, pos); pos = 0; } } if (pos != 0) { output.write(buffer, 0, pos); } System.out.println(filePath + ": OK"); } catch (IOException e) { String msg = filePath + ": FAIL: " + e.getClass().getSimpleName(); if (e.getMessage() != null) { msg += ": " + e.getMessage(); } errors.add(msg); } }, executor)).toArray(CompletableFuture[]::new); CompletableFuture.allOf(tasks).thenRun(() -> { for (String err : errors) System.err.println(err); executor.shutdown(); }); }