List of usage examples for java.lang Integer parseInt
public static int parseInt(String s) throws NumberFormatException
From source file:com.github.xbn.examples.regexutil.non_xbn.UserInputNumInRangeWRegex.java
public static final void main(String[] ignored) { int num = -1; boolean isNum = false; int iRangeMax = 2055; //"": Dummy string, to reuse matcher Matcher mtchrNumNegThrPos = Pattern.compile("-?\\b(20(5[0-5]|[0-4][0-9])|1?[0-9]{1,3})\\b").matcher(""); do {/*from ww w. ja va2 s .com*/ System.out.print("Enter a number between -" + iRangeMax + " and " + iRangeMax + ": "); String strInput = (new Scanner(System.in)).next(); if (!NumberUtils.isNumber(strInput)) { System.out.println("Not a number. Try again."); } else if (!mtchrNumNegThrPos.reset(strInput).matches()) { System.out.println("Not in range. Try again."); } else { //Safe to convert num = Integer.parseInt(strInput); isNum = true; } } while (!isNum); System.out.println("Number: " + num); }
From source file:com.zenoss.zenpacks.zenjmx.ZenJmxMain.java
/** * @param args/*ww w.j ava2 s . c o m*/ */ public static void main(String[] args) throws Exception { HashMap<String, Level> loggingLevel = new HashMap<String, Level>(); loggingLevel.put(ERROR, Level.ERROR); loggingLevel.put(WARNING, Level.WARN); loggingLevel.put(INFO, Level.INFO); loggingLevel.put(DEBUG, Level.DEBUG); Configuration config = Configuration.instance(); parseArguments(config, args); if (config.propertyExists(OptionsFactory.LOG_SEVERITY)) { String levelOpt = config.getProperty(OptionsFactory.LOG_SEVERITY); Level level = loggingLevel.get(levelOpt); if (level != null) { _logger.info("setting root logger to " + level); Logger.getRootLogger().setLevel(level); } else { _logger.warn("Ignoring unknown log severity " + levelOpt); } } String port = config.getProperty(OptionsFactory.LISTEN_PORT, OptionsFactory.DEFAULT_LISTENPORT); Server server = new Server(); Connector connector = new SocketConnector(); connector.setPort(Integer.parseInt(port)); server.setConnectors(new Connector[] { connector }); ServletHandler handler = new ServletHandler(); ServletHolder holder = new ServletHolder(new XmlRpcServlet()); handler.addServletWithMapping(holder, "/"); // handler.start(); handler.initialize(); server.setHandler(handler); try { server.start(); } catch (Exception e) { System.exit(10); } server.join(); }
From source file:br.com.fabiopereira.quebrazip.JavaZipSplitter.java
public static void main(String[] args) { help();/*w w w . j a v a 2s . c om*/ boolean split = true; boolean zip_path = false, origin_path = false; boolean sizeinbytes = false; for (String arg : args) { if (arg.trim().equalsIgnoreCase("-join")) split = false; if (zip_path) { BIN_PATH = arg; zip_path = false; } if (origin_path) { ORIGEM_PATH = arg; origin_path = false; } if (sizeinbytes) { bytesSize = Integer.parseInt(arg); sizeinbytes = false; } if (arg.trim().equalsIgnoreCase("-bin")) zip_path = true; if (arg.trim().equalsIgnoreCase("-origin")) origin_path = true; if (arg.trim().equalsIgnoreCase("-sizeinbytes")) sizeinbytes = true; } if (zip_path || origin_path || sizeinbytes) { System.err.println("Error: invalid use of arguments"); return; } if (split) { System.out.println("Spliting zip '" + BIN_PATH + "'"); split(); } else { System.out.println("Joining files at '" + ORIGEM_PATH + "'"); join(); } }
From source file:com.xoom.rabbit.test.Main.java
public static void main(String[] args) throws InterruptedException { if (args.length != 9) { System.out.println(/*from www. j ava 2s . c o m*/ "usage: java -jar target/rabbit-tester-0.1-SNAPSHOT-standalone.jar [consumer_threads] [number_of_messages] [amqp_host] [amqp_port] [produce] [consume] [message size in bytes] [username] [password]"); return; } final long startTime = System.currentTimeMillis(); int consumerThreads = Integer.parseInt(args[0]); final int messages = Integer.parseInt(args[1]); String host = args[2]; int port = Integer.parseInt(args[3]); boolean produce = Boolean.parseBoolean(args[4]); boolean consume = Boolean.parseBoolean(args[5]); final int messageSize = Integer.parseInt(args[6]); String username = args[7]; String password = args[8]; if (produce) { System.out.println("Sending " + messages + " messages to " + host + ":" + port); } if (consume) { System.out.println("Consuming " + messages + " messages from " + host + ":" + port); } if (!produce && !consume) { System.out.println("Not producing or consuming any messages."); } CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port); connectionFactory.setUsername(username); connectionFactory.setPassword(password); connectionFactory.setChannelCacheSize(consumerThreads + 1); RabbitAdmin amqpAdmin = new RabbitAdmin(connectionFactory); DirectExchange exchange = new DirectExchange(EXCHANGE_NAME, true, false); Queue queue = new Queue(QUEUE_NAME); amqpAdmin.declareExchange(exchange); amqpAdmin.declareQueue(queue); amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY)); final AmqpTemplate amqpTemplate = new RabbitTemplate(connectionFactory); final CountDownLatch producerLatch = new CountDownLatch(messages); final CountDownLatch consumerLatch = new CountDownLatch(messages); SimpleMessageListenerContainer listenerContainer = null; if (consume) { listenerContainer = new SimpleMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setQueueNames(QUEUE_NAME); listenerContainer.setConcurrentConsumers(consumerThreads); listenerContainer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { if (consumerLatch.getCount() == 1) { System.out.println("Finished consuming " + messages + " messages in " + (System.currentTimeMillis() - startTime) + "ms"); } consumerLatch.countDown(); } }); listenerContainer.start(); } if (produce) { while (producerLatch.getCount() > 0) { try { byte[] message = new byte[messageSize]; RND.nextBytes(message); amqpTemplate.send(EXCHANGE_NAME, ROUTING_KEY, new Message(message, new MessageProperties())); producerLatch.countDown(); } catch (Exception e) { System.out.println("Failed to send message " + (messages - producerLatch.getCount()) + " will retry forever."); } } } if (consume) { consumerLatch.await(); listenerContainer.shutdown(); } connectionFactory.destroy(); }
From source file:at.tuwien.ifs.somtoolbox.apps.SOMToolboxMain.java
/** * Central Main for SOMToolbox.// w ww.ja v a 2s .c o m * * @param args the command line args */ public static void main(String[] args) { int screenWidth = 80; try { screenWidth = Integer.parseInt(System.getenv("COLUMNS")); } catch (Exception e) { screenWidth = 80; } JSAP jsap = new JSAP(); try { jsap.registerParameter(new UnflaggedOption("main", JSAP.STRING_PARSER, null, false, false)); jsap.registerParameter(new Switch("gui", 'G', "gui")); jsap.registerParameter(new Switch("version", JSAP.NO_SHORTFLAG, "version")); jsap.registerParameter(new Switch("listmains", JSAP.NO_SHORTFLAG, "list-mains")); jsap.registerParameter( new FlaggedOption("help", JSAP.STRING_PARSER, null, false, JSAP.NO_SHORTFLAG, "help")); } catch (JSAPException e) { assert false; } JSAPResult result = jsap.parse(args); ArrayList<Class<? extends SOMToolboxApp>> runnables = SubClassFinder.findSubclassesOf(SOMToolboxApp.class, true); Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR); // args > 0 boolean useGUI = result.getBoolean("gui", false); if (useGUI) { UiUtils.setSOMToolboxLookAndFeel(); } if (result.getBoolean("listmains")) { if (useGUI) { showAvailableRunnables(runnables, args); } else { printAvailableRunnables(screenWidth, runnables); } } else if (result.getBoolean("version")) { if (result.userSpecified("main")) { printVersion(result.getString("main")); } else { printVersion("somtoolbox"); } } else if (result.userSpecified("main")) { String mainClass = result.getString("main"); String[] cleanArgs = Arrays.copyOfRange(args, 1, args.length); if (!invokeMainClass(runnables, mainClass, cleanArgs, useGUI)) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe("Runnable \"" + mainClass + "\" not found."); printAvailableRunnables(screenWidth, runnables); } } else if (result.contains("help")) { if (result.getString("help") != null) { invokeMainClass(runnables, result.getString("help"), new String[] { "--help" }, useGUI); } else { printHelp(); } } else { if (useGUI) { showAvailableRunnables(runnables, args); } else { printAvailableRunnables(screenWidth, runnables); } } }
From source file:FileList.java
public static void main(String[] args) { final int assumedLineLength = 50; File file = new File(args[0]); List<String> fileList = new ArrayList<String>((int) (file.length() / assumedLineLength) * 2); BufferedReader reader = null; int lineCount = 0; try {//from w w w . j ava2 s .c o m reader = new BufferedReader(new FileReader(file)); for (String line = reader.readLine(); line != null; line = reader.readLine()) { fileList.add(line); lineCount++; } } catch (IOException e) { System.err.format("Could not read %s: %s%n", file, e); System.exit(1); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } int repeats = Integer.parseInt(args[1]); Random random = new Random(); for (int i = 0; i < repeats; i++) { System.out.format("%d: %s%n", i, fileList.get(random.nextInt(lineCount - 1))); } }
From source file:PodbaseMetadataMigration2.java
public static void main(String[] args) throws Exception { System.out.println("Running data migration"); String projectString = FileUtils.readFileToString(new File("projects.txt")); Map<String, Integer> projectIdMapping = new HashMap<String, Integer>(); for (String line : projectString.split("\n")) { String[] split = line.split(":"); int id = Integer.parseInt(split[0].trim()); String name = split[1].trim(); projectIdMapping.put(name, id);/*from ww w. j a v a 2 s. co m*/ } System.out.println("Reading projects.."); List<ProjectEntry> projects = dataFromFile("./migrate/projects.data", ProjectEntry.class); projectIdMap = parseProjectMap(projects, projectIdMapping); System.out.println("Found " + projects.size() + " projects."); System.out.println("Reading tags.."); List<TagEntry> tags = dataFromFile("./migrate/tags.data", TagEntry.class); System.out.println("Found " + tags.size() + " tags."); System.out.println("Reading templates.."); List<TemplateEntry> templates = dataFromFile("./migrate/templates.data", TemplateEntry.class); System.out.println("Found " + templates.size() + " templates."); System.out.println("Reading template fields.."); List<TemplateFieldEntry> templateFields = dataFromFile("./migrate/template_fields.data", TemplateFieldEntry.class); System.out.println("Found " + templateFields.size() + " templateFields."); int entryCount = tags.size() + templates.size() + templateFields.size(); //System.out.println("Generating Project SQL"); //String projectSql = generateSql((List<AbstractEntry>)(List<?>)projects); System.out.println("Generating Attribute SQL"); String imageAttributes = generateSql((List<AbstractEntry>) (List<?>) tags); System.out.println("Generating Image SQL"); String databaseImages = generateDatabaseImageSql(); //System.out.println("Generating Directory SQL"); //String directorySql = generateDirectorySql(projects); //System.out.println("Generating Template SQL"); //String templateSql = generateSql((List<AbstractEntry>)(List<?>)templates); //System.out.println("Generating Field SQL"); //String fieldsSql = generateSql((List<AbstractEntry>)(List<?>)templateFields); System.out.println("Writing database.sql"); BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./database.sql"))); //bw.append(projectSql); //bw.append("\n\n"); bw.append(databaseImages); bw.append("\n\n"); //bw.append(directorySql); //bw.append("\n\n"); bw.append(imageAttributes); bw.append("\n\n"); // bw.append(templateSql); // bw.append("\n\n"); // bw.append(fieldsSql); // bw.append("\n\n"); bw.close(); System.out.println("Writing missingImages.txt"); bw = new BufferedWriter(new FileWriter(new File("./missingImages.txt"))); for (String img : missingImages) { bw.append(img + "\n"); } bw.close(); System.out.println("Migration completed successfully!"); }
From source file:edu.cmu.lti.oaqa.annographix.apps.SolrSimpleIndexApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption("i", null, true, "Input File"); options.addOption("u", null, true, "Solr URI"); options.addOption("n", null, true, "Batch size"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {//w ww .j a va 2s . c o m CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("i")) { inputFile = cmd.getOptionValue("i"); } else { Usage("Specify Input File"); } if (cmd.hasOption("u")) { solrURI = cmd.getOptionValue("u"); } else { Usage("Specify Solr URI"); } if (cmd.hasOption("n")) { batchQty = Integer.parseInt(cmd.getOptionValue("n")); } SolrServerWrapper solrServer = new SolrServerWrapper(solrURI); BufferedReader inpText = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(inputFile))); XmlHelper xmlHlp = new XmlHelper(); String docText = XmlHelper.readNextXMLIndexEntry(inpText); for (int docNum = 1; docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) { // 1. Read document text Map<String, String> docFields = null; HashMap<String, Object> objDocFields = new HashMap<String, Object>(); try { docFields = xmlHlp.parseXMLIndexEntry(docText); } catch (SAXException e) { System.err.println("Parsing error, offending DOC:" + NL + docText); throw new Exception("Parsing error."); } for (Map.Entry<String, String> e : docFields.entrySet()) { //System.out.println(e.getKey() + " " + e.getValue()); objDocFields.put(e.getKey(), e.getValue()); } solrServer.indexDocument(objDocFields); if ((docNum - 1) % batchQty == 0) solrServer.indexCommit(); } solrServer.indexCommit(); } 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:metaTile.Main.java
/** * @param args// w ww .j ava 2s . com * @throws IOException */ public static void main(String[] args) throws IOException { try { /* parse the command line arguments */ // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption("i", "input", true, "File to read original tile list from."); options.addOption("o", "output", true, "File to write shorter meta-tile list to."); options.addOption("m", "metatiles", true, "Number of tiles in x and y direction to group into one meta-tile."); // parse the command line arguments CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption("input") || !commandLine.hasOption("output") || !commandLine.hasOption("metatiles")) printUsage(options); String inputFileName = commandLine.getOptionValue("input"); String outputFileName = commandLine.getOptionValue("output"); int metaTileSize = Integer.parseInt(commandLine.getOptionValue("metatiles")); ArrayList<RenderingTile> tiles = new ArrayList<RenderingTile>(); BufferedReader tileListReader = new BufferedReader(new FileReader(new File(inputFileName))); BufferedWriter renderMetatileListWriter = new BufferedWriter(new FileWriter(new File(outputFileName))); String line = tileListReader.readLine(); while (line != null) { String[] columns = line.split("/"); if (columns.length == 3) tiles.add(new RenderingTile(Integer.parseInt(columns[0]), Integer.parseInt(columns[1]), Integer.parseInt(columns[2]))); line = tileListReader.readLine(); } tileListReader.close(); int hits = 0; // tiles which we are already rendering as the top left corner of 4x4 metatiles HashSet<RenderingTile> whitelist = new HashSet<RenderingTile>(); // for each tile in the list see if it has a meta-tile in the whitelist already for (int i = 0; i < tiles.size(); i++) { boolean hit = false; // by default we aren't already rendering this tile as part of another metatile for (int dx = 0; dx < metaTileSize; dx++) { for (int dy = 0; dy < metaTileSize; dy++) { RenderingTile candidate = new RenderingTile(tiles.get(i).z, tiles.get(i).x - dx, tiles.get(i).y - dy); if (whitelist.contains(candidate)) { hit = true; // now exit the two for loops iterating over tiles inside a meta-tile dx = metaTileSize; dy = metaTileSize; } } } // if this tile doesn't already have a meta-tile in the whitelist, add it if (hit == false) { hits++; renderMetatileListWriter.write(tiles.get(i).toString() + "/" + metaTileSize + "\n"); whitelist.add(tiles.get(i)); } } renderMetatileListWriter.close(); System.out.println( "Reduced " + tiles.size() + " tiles into " + hits + " metatiles of size " + metaTileSize); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.annuletconsulting.homecommand.server.HomeCommand.java
/** * This class will accept commands from a node in each room. For it to react to events on the server * computer, it must be also running as a node. However the server can cause all nodes to react * to an event happening on any node, such as an email or text arriving. A call on a node device * could pause all music devices, for example. * /*w w w. j a va 2 s .c o m*/ * @param args */ public static void main(String[] args) { try { socket = Integer.parseInt(HomeComandProperties.getInstance().getServerPort()); nonJavaUserModulesPath = HomeComandProperties.getInstance().getNonJavaUserDir(); } catch (Exception exception) { System.out.println("Error loading from properties file."); exception.printStackTrace(); } try { sharedKey = HomeComandProperties.getInstance().getSharedKey(); if (sharedKey == null) System.out.println("shared_key is null, commands without valid signatures will be processed."); } catch (Exception exception) { System.out.println("shared_key not found in properties file."); exception.printStackTrace(); } try { if (args.length > 0) { String arg0 = args[0]; if (arg0.equals("help") || arg0.equals("?") || arg0.equals("usage") || arg0.equals("-help") || arg0.equals("-?")) { System.out.println( "The defaults can be changed by editing the HomeCommand.properties file, or you can override them temporarily using command line options."); System.out.println("\nHome Command Server command line overrride usage:"); System.out.println( "hcserver [server_port] [java_user_module_directory] [non_java_user_module_directory]"); //TODO make hcserver.sh System.out.println("\nDefaults:"); System.out.println("server_port: " + socket); System.out.println("java_user_module_directory: " + userModulesPath); System.out.println("non_java_user_module_directory: " + nonJavaUserModulesPath); System.out.println("\n2013 | Annulet, LLC"); } socket = Integer.parseInt(arg0); } if (args.length > 1) userModulesPath = args[1]; if (args.length > 2) nonJavaUserModulesPath = args[2]; System.out.println("Config loaded, initializing modules."); modules.add(new HueLightModule()); System.out.println("HueLightModule initialized."); modules.add(new QuestionModule()); System.out.println("QuestionModule initialized."); modules.add(new MathModule()); System.out.println("MathModule initialized."); modules.add(new MusicModule()); System.out.println("MusicModule initialized."); modules.add(new NonCopyrightInfringingGenericSpaceExplorationTVShowModule()); System.out.println("NonCopyrightInfringingGenericSpaceExplorationTVShowModule initialized."); modules.add(new HelpModule()); System.out.println("HelpModule initialized."); modules.add(new SetUpModule()); System.out.println("SetUpModule initialized."); modules.addAll(NonJavaUserModuleLoader.loadModulesAt(nonJavaUserModulesPath)); System.out.println("NonJavaUserModuleLoader initialized."); ServerSocket serverSocket = new ServerSocket(socket); System.out.println("Listening..."); while (!end) { Socket socket = serverSocket.accept(); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); PrintWriter output = new PrintWriter(socket.getOutputStream(), true); int character; StringBuffer inputStrBuffer = new StringBuffer(); while ((character = isr.read()) != 13) { inputStrBuffer.append((char) character); } System.out.println(inputStrBuffer.toString()); String[] cmd; // = inputStrBuffer.toString().split(" "); String result = "YOUR REQUEST WAS NOT VALID JSON"; if (inputStrBuffer.substring(0, 1).equals("{")) { nodeType = extractElement(inputStrBuffer.toString(), "node_type"); if (sharedKey != null) { if (validateSignature(extractElement(inputStrBuffer.toString(), "time_stamp"), extractElement(inputStrBuffer.toString(), "signature"))) { if ("Y".equalsIgnoreCase(extractElement(inputStrBuffer.toString(), "cmd_encoded"))) cmd = decryptCommand(extractElement(inputStrBuffer.toString(), "command")); else cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } else result = "YOUR SIGNATURE DID NOT MATCH, CHECK SHARED KEY"; } else { cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } } System.out.println(result); output.print(result); output.print((char) 13); output.close(); isr.close(); socket.close(); } serverSocket.close(); System.out.println("Shutting down."); } catch (Exception exception) { exception.printStackTrace(); } }