List of usage examples for org.apache.commons.cli BasicParser BasicParser
BasicParser
From source file:com.sindicetech.siren.demo.loader.Loader.java
/** checks parameters, instantiate loader and starts load */ public static void main(String[] args) { CommandLineParser cmdLineParser = new BasicParser(); CommandLine cmd = null;//from w w w . jav a 2 s. c o m Options options = buildOptions(); try { cmd = cmdLineParser.parse(options, args); } catch (ParseException e) { showHelpExit(options); } if (cmd.hasOption(HELP_OPT)) { showExtendHelpExit(options); } List<File> filesToProcess = Loader.checkInputFilesAndFolders(cmd.getOptionValues(INPUT_FILE_OPT)); if (filesToProcess.size() == 0) { logger.error("no file to process"); System.exit(-1); } Loader loader = new Loader(new HttpSolrServer(cmd.getOptionValue(URL_OPT, DEFAULT_SOLR_URL)), Loader.retrieveAndChekBatchSize(cmd.getOptionValue(BATCH_OPT)), cmd.getOptionValue(EXT_OPT, DEFAULT_JSON_EXTENSION), !cmd.hasOption(NO_EXT_CHECK_OPT), cmd.hasOption(COMMIT_EACH_OPT), cmd.hasOption(FILENAME_AS_ID_OPT)); loader.loadFiles(filesToProcess); }
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 av a 2 s. co 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.esri.geoevent.test.performance.ConsumerMain.java
/** * Main method - this is used to when running from command line * * @param args Command Line Parameters//from w w w.ja v a 2 s . c om */ @SuppressWarnings("static-access") public static void main(String[] args) { // performer options Options performerOptions = new Options(); performerOptions .addOption(OptionBuilder .withLongOpt("type").withDescription("One of the following values: [" + Protocol.getAllowableValues() + "]. (Default value is tcp).") .hasArg().create("t")); performerOptions.addOption(OptionBuilder.withLongOpt("commandListenerPort").withDescription( "The TCP Port where consumer will listen for commands from the orchestrator. (Default value is 5010).") .hasArg().create("p")); performerOptions.addOption(OptionBuilder.withLongOpt("serverPort") .withDescription("The TCP Port where the server will listen for events. (Default value is 5675)") .hasArg().create("sp")); performerOptions.addOption("h", "help", false, "print the help message"); // parse the command line CommandLineParser parser = new BasicParser(); CommandLine cmd; // parse try { cmd = parser.parse(performerOptions, args, false); } catch (ParseException error) { printHelp(performerOptions); return; } // User requested Help if (cmd.hasOption("h")) { printHelp(performerOptions); return; } if (cmd.getOptions().length == 0) { ConsumerUI ui = new ConsumerUI(); ui.run(); } else { // parse out the performer options String protocolValue = cmd.getOptionValue("t"); String commandListenerPortValue = cmd.getOptionValue("p"); if (protocolValue == null) { protocolValue = "tcp"; } if (commandListenerPortValue == null) { commandListenerPortValue = "5020"; } // validate if (!validateTestHarnessOptions(protocolValue, commandListenerPortValue)) { printHelp(performerOptions); return; } // parse the values Protocol protocol = Protocol.fromValue(protocolValue); boolean isLocal = "local".equalsIgnoreCase(commandListenerPortValue); int commandListenerPort = -1; if (!isLocal) { commandListenerPort = Integer.parseInt(commandListenerPortValue); } int serverPort = NumberUtils.toInt(cmd.getOptionValue("sp"), 5775); PerformanceCollector consumer; switch (protocol) { case TCP: consumer = new TcpEventConsumer(); break; case TCP_SERVER: consumer = new TcpServerEventConsumer(serverPort); break; case WEBSOCKETS: consumer = new WebsocketEventConsumer(); break; case WEBSOCKET_SERVER: consumer = new WebsocketServerEventConsumer(serverPort); break; case ACTIVE_MQ: consumer = new ActiveMQEventConsumer(); break; case RABBIT_MQ: consumer = new RabbitMQEventConsumer(); break; case STREAM_SERVICE: consumer = new StreamServiceEventConsumer(); break; case KAFKA: consumer = new KafkaEventConsumer(); break; case BDS: consumer = new BdsEventConsumer(); break; case AZURE: consumer = new AzureIoTHubConsumer(); break; default: return; } consumer.listenOnCommandPort((isLocal ? 5020 : commandListenerPort), true); } }
From source file:com.google.api.ads.adwords.jaxws.extensions.kratu.KratuMain.java
/** * Main method./*from w ww . j a v a 2s.c om*/ * * @param args the command line arguments. */ public static void main(String args[]) { // Proxy JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault()); ProxySelector.setDefault(ps); Options options = createCommandLineOptions(); boolean errors = false; String propertiesPath = CLASSPATH_AW_REPORT_MODEL_PROPERTIES_LOCATION; try { CommandLineParser parser = new BasicParser(); CommandLine cmdLine = parser.parse(options, args); if (cmdLine.hasOption("file")) { propertiesPath = cmdLine.getOptionValue("file"); } System.out.println("Using properties from: " + propertiesPath); if (cmdLine.hasOption("startServer")) { // Start the Rest Server System.out.println("Starting Rest Server..."); initApplicationContextAndProperties(propertiesPath); updateAccounts(); RestServer.createRestServer(appCtx, propertiesPath); } else { if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) { if (cmdLine.hasOption("processKratus")) { // Process Kratus, this process runs for the whole MCC // within the given dates and creates a daily Kratu per account. System.out.println("Starting Process Kratus..."); initApplicationContextAndProperties(propertiesPath); updateAccounts(); KratuProcessor kratuProcessor = appCtx.getBean(KratuProcessor.class); kratuProcessor.processKratus(cmdLine.getOptionValue("startDate"), cmdLine.getOptionValue("endDate")); System.exit(0); } else { // Download Reports, // this porcess downloads 7 report types for each account under the MCC System.out.println("Starting Download Reports porcess..."); AwReporting.main(args); System.exit(0); } } else { errors = true; System.out.println("Configuration incomplete. Missing options for command line."); } } } catch (IOException e) { errors = true; System.out.println("Properties file (" + propertiesPath + ") not found: " + e.getMessage()); } catch (ParseException e) { errors = true; System.out.println("Error parsing the values for the command line options: " + e.getMessage()); } catch (Exception e) { errors = true; System.out.println("Unexpected error: " + e.getMessage()); } if (errors) { printHelpMessage(options); System.exit(1); } }
From source file:com.kappaware.logtrawler.Main.java
@SuppressWarnings("static-access") static public void main(String[] argv) throws Throwable { Config config;/*from w w w.ja v a2 s. c o m*/ Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("config-file") .withDescription("JSON configuration file").create("c")); options.addOption(OptionBuilder.hasArg().withArgName("folder").withLongOpt("folder") .withDescription("Folder to monitor").create("f")); options.addOption(OptionBuilder.hasArg().withArgName("exclusion").withLongOpt("exclusion") .withDescription("Exclusion regex").create("x")); options.addOption(OptionBuilder.hasArg().withArgName("adminEndpoint").withLongOpt("admin-endpoint") .withDescription("Endpoint for admin REST").create("e")); options.addOption(OptionBuilder.hasArg().withArgName("outputFlow").withLongOpt("output-flow") .withDescription("Target to post result on").create("o")); options.addOption(OptionBuilder.hasArg().withArgName("hostname").withLongOpt("hostname") .withDescription("This hostname").create("h")); options.addOption(OptionBuilder.withLongOpt("displayDot").withDescription("Display Dot").create("d")); options.addOption(OptionBuilder.hasArg().withArgName("mimeType").withLongOpt("mime-type") .withDescription("Valid MIME type").create("m")); options.addOption(OptionBuilder.hasArg().withArgName("allowedAdmin").withLongOpt("allowedAdmin") .withDescription("Allowed admin network").create("a")); options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("gen-config-file") .withDescription("Generate JSON configuration file").create("g")); options.addOption(OptionBuilder.hasArg().withArgName("maxBatchSize").withLongOpt("max-batch-size") .withDescription("Max JSON batch (array) size").create("b")); CommandLineParser clParser = new BasicParser(); CommandLine line; String configFile = null; try { // parse the command line argument line = clParser.parse(options, argv); if (line.hasOption("c")) { configFile = line.getOptionValue("c"); config = Json.fromJson(Config.class, new BufferedReader(new InputStreamReader(new FileInputStream(configFile)))); } else { config = new Config(); } if (line.hasOption("f")) { String[] fs = line.getOptionValues("f"); // Get the first agent (Create it if needed) if (config.getAgents() == null || config.getAgents().size() == 0) { Config.Agent agent = new Config.Agent("default"); config.addAgent(agent); } Config.Agent agent = config.getAgents().iterator().next(); for (String f : fs) { agent.addFolder(new Config.Agent.Folder(f, false)); } } if (line.hasOption("e")) { String e = line.getOptionValue("e"); config.setAdminEndpoint(e); } if (line.hasOption("o")) { String[] es = line.getOptionValues("o"); if (config.getAgents() != null) { for (Agent agent : config.getAgents()) { for (String s : es) { agent.addOuputFlow(s); } } } } if (line.hasOption("h")) { String e = line.getOptionValue("h"); config.setHostname(e); } if (line.hasOption("x")) { if (config.getAgents() != null) { for (Agent agent : config.getAgents()) { if (agent.getFolders() != null) { for (Folder folder : agent.getFolders()) { String[] exs = line.getOptionValues("x"); for (String ex : exs) { folder.addExcludedPath(ex); } } } } } } if (line.hasOption("m")) { if (config.getAgents() != null) { for (Agent agent : config.getAgents()) { String[] exs = line.getOptionValues("m"); for (String ex : exs) { agent.addLogMimeType(ex); } } } } if (line.hasOption("a")) { String[] exs = line.getOptionValues("a"); for (String ex : exs) { config.addAdminAllowedNetwork(ex); } } if (line.hasOption("d")) { config.setDisplayDot(true); } if (line.hasOption("b")) { Integer i = getIntegerParameter(line, "b"); if (config.getAgents() != null) { for (Agent agent : config.getAgents()) { agent.setOutputMaxBatchSize(i); } } } config.setDefault(); if (line.hasOption("g")) { String fileName = line.getOptionValue("g"); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false))); out.println(Json.toJson(config, true)); out.flush(); out.close(); System.exit(0); } } catch (ParseException exp) { // oops, something went wrong usage(options, exp.getMessage()); return; } try { // Check config if (config.getAgents() == null || config.getAgents().size() < 1) { throw new ConfigurationException("At least one folder to monitor must be provided!"); } Map<String, AgentHandler> agentHandlerByName = new HashMap<String, AgentHandler>(); for (Config.Agent agent : config.getAgents()) { agentHandlerByName.put(agent.getName(), new AgentHandler(agent)); } if (!Utils.isNullOrEmpty(config.getAdminEndpoint())) { new AdminServer(config, agentHandlerByName); } } catch (ConfigurationException e) { log.error(e.toString()); System.exit(1); } catch (Throwable t) { log.error("Error in main", t); System.exit(2); } }
From source file:fi.helsinki.cs.iot.kahvihub.KahviHub.java
public static void main(String[] args) throws InterruptedException { // create Options object Options options = new Options(); // add conf file option options.addOption("c", true, "config file"); CommandLineParser parser = new BasicParser(); CommandLine cmd;/*from w ww . jav a 2 s . c om*/ try { cmd = parser.parse(options, args); String configFile = cmd.getOptionValue("c"); if (configFile == null) { Log.e(TAG, "The config file option was not provided"); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("d", options); System.exit(-1); } else { try { HubConfig hubConfig = ConfigurationFileParser.parseConfigurationFile(configFile); Path libdir = Paths.get(hubConfig.getLibdir()); if (hubConfig.isDebugMode()) { File dir = libdir.toFile(); if (dir.exists() && dir.isDirectory()) for (File file : dir.listFiles()) file.delete(); } final IotHubHTTPD server = new IotHubHTTPD(hubConfig.getPort(), libdir, hubConfig.getHost()); init(hubConfig); try { server.start(); } catch (IOException ioe) { Log.e(TAG, "Couldn't start server:\n" + ioe); System.exit(-1); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.stop(); Log.i(TAG, "Server stopped"); } }); while (true) { Thread.sleep(1000); } } catch (ConfigurationParsingException | IOException e) { System.out.println("1:" + e.getMessage()); Log.e(TAG, e.getMessage()); System.exit(-1); } } } catch (ParseException e) { System.out.println(e.getMessage()); Log.e(TAG, e.getMessage()); System.exit(-1); } }
From source file:com.browseengine.bobo.index.MakeBobo.java
/** * @param args//from w w w . j av a2 s . co m */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Option help = new Option("help", false, "print this message"); OptionBuilder.withArgName("path"); OptionBuilder.hasArg(); OptionBuilder.withDescription("data source - required"); Option src = OptionBuilder.create("source"); src.setRequired(true); OptionBuilder.withArgName("path"); OptionBuilder.hasArg(); OptionBuilder.withDescription("index to create - required"); Option index = OptionBuilder.create("index"); index.setRequired(true); OptionBuilder.withArgName("file"); OptionBuilder.hasArg(); OptionBuilder.withDescription("field configuration - optional"); Option conf = OptionBuilder.create("conf"); OptionBuilder.withArgName("class"); OptionBuilder.hasArg(); OptionBuilder.withDescription("class name of the data digester - default: xml digester"); Option digesterOpt = OptionBuilder.create("digester"); OptionBuilder.withArgName("name"); OptionBuilder.hasArg(); OptionBuilder.withDescription("character set name - default: UTF-8"); Option charset = OptionBuilder.create("charset"); OptionBuilder.withArgName("maxdocs"); OptionBuilder.hasArg(); OptionBuilder.withDescription("maximum number of documents - default: 100"); Option maxdocs = OptionBuilder.create("maxdocs"); Options options = new Options(); options.addOption(help); options.addOption(conf); options.addOption(index); options.addOption(src); options.addOption(charset); options.addOption(digesterOpt); options.addOption(maxdocs); // create the parser CommandLineParser parser = new BasicParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); String output = line.getOptionValue("index"); File data = new File(line.getOptionValue("source")); Class digesterClass; if (line.hasOption("digester")) digesterClass = Class.forName(line.getOptionValue("digester")); else throw new RuntimeException("digester not specified"); Charset chset; if (line.hasOption("charset")) { chset = Charset.forName(line.getOptionValue("charset")); } else { chset = Charset.forName("UTF-8"); } int maxDocs; try { maxDocs = Integer.parseInt(line.getOptionValue("maxdocs")); } catch (Exception e) { maxDocs = 100; } FileDigester digester; try { Constructor constructor = digesterClass.getConstructor(new Class[] { File.class }); digester = (FileDigester) constructor.newInstance(new Object[] { data }); digester.setCharset(chset); digester.setMaxDocs(maxDocs); } catch (Exception e) { throw new RuntimeException("Invalid digester class.", e); } BoboIndexer indexer = new BoboIndexer(digester, FSDirectory.open(new File(output))); indexer.index(); } catch (ParseException exp) { exp.printStackTrace(); usage(options); } catch (ClassNotFoundException e) { System.out.println("Invalid digester class."); usage(options); } }
From source file:com.adobe.aem.demomachine.gui.AemDemo.java
public static void main(String[] args) { String demoMachineRootFolder = null; // Command line options for this tool Options options = new Options(); options.addOption("f", true, "Path to Demo Machine root folder"); CommandLineParser parser = new BasicParser(); try {/* ww w . j av a 2 s .c om*/ CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("f")) { demoMachineRootFolder = cmd.getOptionValue("f"); } } catch (ParseException ex) { logger.error(ex.getMessage()); } // Let's grab the version number for the core Maven file String mavenFilePath = (demoMachineRootFolder != null ? demoMachineRootFolder : System.getProperty("user.dir")) + File.separator + "java" + File.separator + "core" + File.separator + "pom.xml"; File mavenFile = new File(mavenFilePath); if (mavenFile.exists() && !mavenFile.isDirectory()) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document; document = builder.parse(mavenFile); NodeList list = document.getElementsByTagName("version"); if (list != null && list.getLength() > 0) { aemDemoMachineVersion = list.item(0).getFirstChild().getNodeValue(); } } catch (Exception e) { logger.error("Can't parse Maven pom.xml file"); } } // Let's check if we have a valid build.xml file to work with... String buildFilePath = (demoMachineRootFolder != null ? demoMachineRootFolder : System.getProperty("user.dir")) + File.separator + "build.xml"; logger.debug("Trying to load build file from " + buildFilePath); buildFile = new File(buildFilePath); if (buildFile.exists() && !buildFile.isDirectory()) { // Launching the main window EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.getLookAndFeelDefaults().put("defaultFont", new Font("Arial", Font.BOLD, 14)); AemDemo window = new AemDemo(); window.frameMain.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } else { logger.error("No valid build.xml file to work with"); System.exit(-1); } }
From source file:com.esri.geoevent.test.performance.ProducerMain.java
/** * Main method - this is used to when running from command line * * @param args Command Line Options/*from ww w .java 2 s . c o m*/ */ @SuppressWarnings("static-access") public static void main(String[] args) { // performer options Options performerOptions = new Options(); performerOptions .addOption(OptionBuilder .withLongOpt("type").withDescription("One of the following values: [" + Protocol.getAllowableValues() + "]. (Default value is tcp).") .hasArg().create("t")); performerOptions.addOption(OptionBuilder.withLongOpt("commandListenerPort").withDescription( "The TCP Port where producer will listen for commands from the orchestrator. (Default value is 5020).") .hasArg().create("p")); performerOptions.addOption(OptionBuilder.withLongOpt("serverPort") .withDescription("The TCP Port where the server will produce events. (Default value is 5665)") .hasArg().create("sp")); performerOptions.addOption("h", "help", false, "print the help message"); // parse the command line CommandLineParser parser = new BasicParser(); CommandLine cmd = null; // parse try { cmd = parser.parse(performerOptions, args, false); } catch (ParseException error) { printHelp(performerOptions); return; } if (cmd.getOptions().length == 0) { // No Args Start GUI ProducerUI ui = new ProducerUI(); ui.run(); } else { // User Request Help Page if (cmd.hasOption("h")) { printHelp(performerOptions); return; } // parse out the performer options String protocolValue = cmd.getOptionValue("t"); String commandListenerPortValue = cmd.getOptionValue("p"); if (protocolValue == null) { protocolValue = "tcp"; } if (commandListenerPortValue == null) { commandListenerPortValue = "5010"; } // validate if (!validateTestHarnessOptions(protocolValue, commandListenerPortValue)) { printHelp(performerOptions); return; } // parse the values Protocol protocol = Protocol.fromValue(protocolValue); boolean isLocal = "local".equalsIgnoreCase(commandListenerPortValue); int commandListenerPort = -1; if (!isLocal) { commandListenerPort = Integer.parseInt(commandListenerPortValue); } int serverPort = NumberUtils.toInt(cmd.getOptionValue("sp"), 5665); PerformanceCollector producer = null; switch (protocol) { case TCP: producer = new TcpEventProducer(); break; case TCP_SERVER: producer = new TcpServerEventProducer(serverPort); break; case WEBSOCKETS: producer = new WebsocketEventProducer(); break; case ACTIVE_MQ: producer = new ActiveMQEventProducer(); break; case RABBIT_MQ: producer = new RabbitMQEventProducer(); break; case STREAM_SERVICE: producer = new StreamServiceEventProducer(); break; case KAFKA: producer = new KafkaEventProducer(); break; case WEBSOCKET_SERVER: producer = new WebsocketServerEventProducer(serverPort); break; case AZURE: producer = new AzureIoTHubProducer(); break; case REST_JSON: producer = new JsonEventProducer(); break; default: return; } producer.listenOnCommandPort((isLocal ? 5010 : commandListenerPort), true); } }
From source file:com.frostvoid.trekwar.server.TrekwarServer.java
public static void main(String[] args) { // load language try {/* w w w . j a va 2 s.c o m*/ lang = new Language(Language.ENGLISH); } catch (IOException ioe) { System.err.println("FATAL ERROR: Unable to load language file!"); System.exit(1); } System.out.println(lang.get("trekwar_server") + " " + VERSION); System.out.println("==============================================".substring(0, lang.get("trekwar_server").length() + 1 + VERSION.length())); // Handle parameters Options options = new Options(); options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg() .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load"); options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg() .withDescription("the port number to bind to (default 8472)").create("p")); options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg() .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s")); options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg() .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF") .create("l")); options.addOption("h", "help", false, "prints this help message"); CommandLineParser cliParser = new BasicParser(); try { CommandLine cmd = cliParser.parse(options, args); String portStr = cmd.getOptionValue("p"); String galaxyFileStr = cmd.getOptionValue("g"); String saveIntervalStr = cmd.getOptionValue("s"); String logLevelStr = cmd.getOptionValue("l"); if (cmd.hasOption("h")) { HelpFormatter help = new HelpFormatter(); help.printHelp("TrekwarServer", options); System.exit(0); } if (cmd.hasOption("g") && galaxyFileStr != null) { galaxyFileName = galaxyFileStr; } else { throw new ParseException("galaxy file not specified"); } if (cmd.hasOption("p") && portStr != null) { port = Integer.parseInt(portStr); if (port < 1 || port > 65535) { throw new NumberFormatException(lang.get("port_number_out_of_range")); } } else { port = 8472; } if (cmd.hasOption("s") && saveIntervalStr != null) { saveInterval = Integer.parseInt(saveIntervalStr); if (saveInterval < 1 || saveInterval > 100) { throw new NumberFormatException("Save Interval out of range (1-100)"); } } else { saveInterval = 5; } if (cmd.hasOption("l") && logLevelStr != null) { if (logLevelStr.equalsIgnoreCase("finest")) { LOG.setLevel(Level.FINEST); } else if (logLevelStr.equalsIgnoreCase("finer")) { LOG.setLevel(Level.FINER); } else if (logLevelStr.equalsIgnoreCase("fine")) { LOG.setLevel(Level.FINE); } else if (logLevelStr.equalsIgnoreCase("config")) { LOG.setLevel(Level.CONFIG); } else if (logLevelStr.equalsIgnoreCase("info")) { LOG.setLevel(Level.INFO); } else if (logLevelStr.equalsIgnoreCase("warning")) { LOG.setLevel(Level.WARNING); } else if (logLevelStr.equalsIgnoreCase("severe")) { LOG.setLevel(Level.SEVERE); } else if (logLevelStr.equalsIgnoreCase("off")) { LOG.setLevel(Level.OFF); } else if (logLevelStr.equalsIgnoreCase("all")) { LOG.setLevel(Level.ALL); } else { System.err.println("ERROR: invalid log level: " + logLevelStr); System.err.println("Run again with -h flag to see valid log level values"); System.exit(1); } } else { LOG.setLevel(Level.INFO); } // INIT LOGGING try { LOG.setUseParentHandlers(false); initLogging(); } catch (IOException ex) { System.err.println("Unable to initialize logging to file"); System.err.println(ex); System.exit(1); } } catch (Exception ex) { System.err.println("ERROR: " + ex.getMessage()); System.err.println("use -h for help"); System.exit(1); } LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up"); // LOAD GALAXY File galaxyFile = new File(galaxyFileName); if (galaxyFile.exists()) { try { long timer = System.currentTimeMillis(); LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile)); galaxy = (Galaxy) ois.readObject(); timer = System.currentTimeMillis() - timer; LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer); ois.close(); } catch (IOException ioe) { LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe); } catch (ClassNotFoundException cnfe) { LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe); } } else { System.err.println("Error: file " + galaxyFileName + " not found"); System.exit(1); } // if turn == 0 (start of game), execute first turn to update fog of war. if (galaxy.getCurrentTurn() == 0) { TurnExecutor.executeTurn(galaxy); } LOG.log(Level.INFO, "Current turn : {0}", galaxy.getCurrentTurn()); LOG.log(Level.INFO, "Turn speed : {0} seconds", galaxy.getTurnSpeed() / 1000); LOG.log(Level.INFO, "Save Interval : {0}", saveInterval); LOG.log(Level.INFO, "Users / max : {0} / {1}", new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() }); // START SERVER try { server = new ServerSocket(port); LOG.log(Level.INFO, "Server listening on port {0}", port); } catch (BindException be) { LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port); System.err.println(be); System.exit(1); } catch (IOException ioe) { LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port); System.err.println(ioe); System.exit(1); } galaxy.startup(); Thread timerThread = new Thread(new Runnable() { @Override @SuppressWarnings("SleepWhileInLoop") public void run() { while (true) { try { Thread.sleep(1000); // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING) if (System.currentTimeMillis() > galaxy.nextTurnDate) { StringBuffer loggedInUsers = new StringBuffer(); for (User u : galaxy.getLoggedInUsers()) { loggedInUsers.append(u.getUsername()).append(", "); } long time = TurnExecutor.executeTurn(galaxy); LOG.log(Level.INFO, "Turn {0} executed in {1} ms", new Object[] { galaxy.getCurrentTurn(), time }); LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString()); LOG.log(Level.INFO, "===================================================================================="); if (galaxy.getCurrentTurn() % saveInterval == 0) { saveGalaxy(); } galaxy.lastTurnDate = System.currentTimeMillis(); galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed; } } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e); } } } }); timerThread.start(); // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS while (true) { Socket clientConnection; try { clientConnection = server.accept(); ClientSession c = new ClientSession(clientConnection, galaxy); Thread t = new Thread(c); t.start(); } catch (IOException ex) { LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex); } } }