List of usage examples for java.lang Integer parseInt
public static int parseInt(String s) throws NumberFormatException
From source file:friendsandfollowers.DBFriendsIDs.java
public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException, FileNotFoundException, UnsupportedEncodingException { // Check arguments that passed in if ((args == null) || (args.length == 0)) { System.err.println("2 Parameters are required plus one optional " + "parameter to launch a Job."); System.err.println("First: String 'OUTPUT: /output/path/'"); System.err.println("Second: (int) Number of ids to fetch. " + "Provide number which increment by 5000 " + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids."); System.err.println("Third (optional): 'screen_name / user_id_str'"); System.err.println("If 3rd argument not provided then provide" + " Twitter users through database."); System.exit(-1);/*w ww.jav a2 s. c o m*/ } MysqlDB DB = new MysqlDB(); AppOAuth AppOAuths = new AppOAuth(); Misc helpers = new Misc(); String endpoint = "/friends/ids"; String OutputDirPath = null; try { OutputDirPath = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } int IDS_TO_FETCH_INT = -1; try { IDS_TO_FETCH_INT = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.err.println("Argument" + args[1] + " must be an integer."); System.exit(-1); } int IDS_TO_FETCH = 0; if (IDS_TO_FETCH_INT > 5000) { float IDS_TO_FETCH_F = (float) IDS_TO_FETCH_INT / 5000; IDS_TO_FETCH = (int) Math.ceil(IDS_TO_FETCH_F); } else if ((IDS_TO_FETCH_INT <= 5000) && (IDS_TO_FETCH_INT > 0)) { IDS_TO_FETCH = 1; } String targetedUser = ""; if (args.length == 3) { try { targetedUser = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an String."); System.exit(-1); } } try { TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint); Twitter twitter = tf.getInstance(); int RemainingCalls = AppOAuths.RemainingCalls; int RemainingCallsCounter = 0; System.out.println("First Time Remianing Calls: " + RemainingCalls); String Screen_name = AppOAuths.screen_name; System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name); IDs ids; System.out.println("Listing friends ids."); // if targetedUser not provided by argument, then look into database. if (StringUtils.isEmpty(targetedUser)) { String selectQuery = "SELECT * FROM `followings_parent` WHERE " + "`targeteduser` != '' AND " + "`nextcursor` != '0' AND " + "`nextcursor` != '2'"; ResultSet results = DB.selectQ(selectQuery); int numRows = DB.numRows(results); if (numRows < 1) { System.err.println("No User in database to get friendsIDS"); System.exit(-1); } OUTERMOST: while (results.next()) { int following_parent_id = results.getInt("id"); targetedUser = results.getString("targeteduser"); long cursor = results.getLong("nextcursor"); System.out.println("Targeted User: " + targetedUser); int idsLoopCounter = 0; int totalIDs = 0; // put idsJSON in a file PrintWriter writer = new PrintWriter(OutputDirPath + "/" + targetedUser, "UTF-8"); // call different functions for screen_name and id_str Boolean chckedNumaric = helpers.isNumeric(targetedUser); do { ids = null; try { if (chckedNumaric) { long LongValueTargetedUser = Long.valueOf(targetedUser).longValue(); ids = twitter.getFriendsIDs(LongValueTargetedUser, cursor); } else { ids = twitter.getFriendsIDs(targetedUser, cursor); } } catch (TwitterException te) { // do not throw if user has protected tweets, // or if they deleted their account if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED || te.getStatusCode() == HttpResponseCode.NOT_FOUND) { System.out.println(targetedUser + " is protected or account is deleted"); } else { System.out.println("Friends Get Exception: " + te.getMessage()); } // If rate limit reached then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println( "New User Loaded OAuth" + " Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } // update cursor in "followings_parent" String fieldValues = "`nextcursor` = 2"; String where = "id = " + following_parent_id; DB.Update("`followings_parent`", fieldValues, where); // If error then switch to next user continue OUTERMOST; } if (ids.getIDs().length > 0) { idsLoopCounter++; totalIDs += ids.getIDs().length; System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length); JSONObject responseDetailsJson = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (long id : ids.getIDs()) { jsonArray.put(id); } Object idsJSON = responseDetailsJson.put("ids", jsonArray); writer.println(idsJSON); } // If rate limit reached then switch Auth user. RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println("New User Loaded OAuth " + "Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } if (IDS_TO_FETCH_INT != -1) { if (idsLoopCounter == IDS_TO_FETCH) { break; } } } while ((cursor = ids.getNextCursor()) != 0); writer.close(); System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs); System.out.println(); // update cursor in "followings_parent" String fieldValues = "`nextcursor` = " + cursor; String where = "id = " + following_parent_id; DB.Update("`followings_parent`", fieldValues, where); } // loop through every result found in db } else { // Second Argument Sets, so we are here. System.out.println("screen_name / user_id_str " + "passed by argument"); int idsLoopCounter = 0; int totalIDs = 0; // put idsJSON in a file PrintWriter writer = new PrintWriter( OutputDirPath + "/" + targetedUser + "_ids_" + helpers.getUnixTimeStamp(), "UTF-8"); // call different functions for screen_name and id_str Boolean chckedNumaric = helpers.isNumeric(targetedUser); long cursor = -1; do { ids = null; try { if (chckedNumaric) { long LongValueTargetedUser = Long.valueOf(targetedUser).longValue(); ids = twitter.getFriendsIDs(LongValueTargetedUser, cursor); } else { ids = twitter.getFriendsIDs(targetedUser, cursor); } } catch (TwitterException te) { // do not throw if user has protected tweets, // or if they deleted their account if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED || te.getStatusCode() == HttpResponseCode.NOT_FOUND) { System.out.println(targetedUser + " is protected or account is deleted"); } else { System.out.println("Friends Get Exception: " + te.getMessage()); } System.exit(-1); } if (ids.getIDs().length > 0) { idsLoopCounter++; totalIDs += ids.getIDs().length; System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length); JSONObject responseDetailsJson = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (long id : ids.getIDs()) { jsonArray.put(id); } Object idsJSON = responseDetailsJson.put("ids", jsonArray); writer.println(idsJSON); } // If rate limit reach then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println("New User Loaded OAuth Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } if (IDS_TO_FETCH_INT != -1) { if (idsLoopCounter == IDS_TO_FETCH) { break; } } } while ((cursor = ids.getNextCursor()) != 0); writer.close(); System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs); System.out.println(); } } catch (TwitterException te) { // te.printStackTrace(); System.err.println("Failed to get friends' ids: " + te.getMessage()); System.exit(-1); } System.out.println("!!!! DONE !!!!"); }
From source file:cc.wikitools.lucene.ScoreWikipediaArticle.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(// w ww .j a va2 s . c o m OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption( OptionBuilder.withArgName("num").hasArg().withDescription("article id").create(ID_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("article title").create(TITLE_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!(cmdline.hasOption(ID_OPTION) || cmdline.hasOption(TITLE_OPTION)) || !cmdline.hasOption(INDEX_OPTION) || !cmdline.hasOption(QUERY_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ScoreWikipediaArticle.class.getName(), options); System.exit(-1); } File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION)); if (!indexLocation.exists()) { System.err.println("Error: " + indexLocation + " does not exist!"); System.exit(-1); } String queryText = cmdline.getOptionValue(QUERY_OPTION); WikipediaSearcher searcher = new WikipediaSearcher(indexLocation); PrintStream out = new PrintStream(System.out, true, "UTF-8"); if (cmdline.hasOption(ID_OPTION)) { out.println("score: " + searcher.scoreArticle(queryText, Integer.parseInt(cmdline.getOptionValue(ID_OPTION)))); } else { out.println("score: " + searcher.scoreArticle(queryText, cmdline.getOptionValue(TITLE_OPTION))); } searcher.close(); out.close(); }
From source file:org.eclipse.swt.snippets.Snippet363.java
public static void main(String[] args) { Display display = new Display(); errorIcon = display.getSystemImage(SWT.ICON_ERROR); Shell shell = new Shell(display); shell.setText("Snippet 363"); shell.setLayout(new GridLayout(2, false)); shell.setText("LiveRegion Test"); icon = new Label(shell, SWT.NONE); icon.setLayoutData(new GridData(32, 32)); liveLabel = new Text(shell, SWT.READ_ONLY); GC gc = new GC(liveLabel); Point pt = gc.textExtent(errorMessage); GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false); data.minimumWidth = (int) (pt.x + gc.getFontMetrics().getAverageCharacterWidth() * 2); gc.dispose();// ww w. j a v a2 s. c o m liveLabel.setLayoutData(data); liveLabel.setText(""); liveLabel.getAccessible().addAccessibleAttributeListener(new AccessibleAttributeAdapter() { @Override public void getAttributes(AccessibleAttributeEvent e) { e.attributes = new String[] { "container-live", "polite", "live", "polite", "container-live-role", "status", }; } }); final Label textFieldLabel = new Label(shell, SWT.NONE); textFieldLabel.setText("Type a number:"); textFieldLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); final Text textField = new Text(shell, SWT.SINGLE | SWT.BORDER); textField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); final Button okButton = new Button(shell, SWT.PUSH); okButton.setText("OK"); okButton.setLayoutData(new GridData(SWT.END, SWT.CENTER, false, false, 2, 1)); okButton.setEnabled(false); textField.addModifyListener(e -> { boolean isNumber = false; String textValue = textField.getText(); try { Integer.parseInt(textValue); isNumber = true; setMessageText(false, "Thank-you"); } catch (NumberFormatException ex) { if (textValue.isEmpty()) { setMessageText(false, ""); } else { setMessageText(true, "Error: Number expected."); } } okButton.setEnabled(isNumber); }); textField.setFocus(); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:com.slothpetrochemical.bridgeprob.BridgeProblemApp.java
public static void main(final String[] args) throws ParseException { Options commandLineOptions = createOptions(); PosixParser clParser = new PosixParser(); CommandLine cl = clParser.parse(commandLineOptions, args); if (cl.getArgs().length == 0 || cl.hasOption("h")) { new HelpFormatter().printHelp("crossing_times...", commandLineOptions); } else {/*from w ww . ja va 2s . co m*/ String[] clArgs = cl.getArgs(); Integer[] times = new Integer[clArgs.length]; for (int i = 0; i < clArgs.length; ++i) { Integer intTime = Integer.parseInt(clArgs[i]); times[i] = intTime; } Arrays.sort(times); BridgeProblemApp app = new BridgeProblemApp(Arrays.asList(times)); app.run(); } }
From source file:PopClean.java
public static void main(String args[]) { try {//from ww w . j av a 2s . c o m String hostname = null, username = null, password = null; int port = 110; int sizelimit = -1; String subjectPattern = null; Pattern pattern = null; Matcher matcher = null; boolean delete = false; boolean confirm = true; // Handle command-line arguments for (int i = 0; i < args.length; i++) { if (args[i].equals("-user")) username = args[++i]; else if (args[i].equals("-pass")) password = args[++i]; else if (args[i].equals("-host")) hostname = args[++i]; else if (args[i].equals("-port")) port = Integer.parseInt(args[++i]); else if (args[i].equals("-size")) sizelimit = Integer.parseInt(args[++i]); else if (args[i].equals("-subject")) subjectPattern = args[++i]; else if (args[i].equals("-debug")) debug = true; else if (args[i].equals("-delete")) delete = true; else if (args[i].equals("-force")) // don't confirm confirm = false; } // Verify them if (hostname == null || username == null || password == null || sizelimit == -1) usage(); // Make sure the pattern is a valid regexp if (subjectPattern != null) { pattern = Pattern.compile(subjectPattern); matcher = pattern.matcher(""); } // Say what we are going to do System.out .println("Connecting to " + hostname + " on port " + port + " with username " + username + "."); if (delete) { System.out.println("Will delete all messages longer than " + sizelimit + " bytes"); if (subjectPattern != null) System.out.println("that have a subject matching: [" + subjectPattern + "]"); } else { System.out.println("Will list subject lines for messages " + "longer than " + sizelimit + " bytes"); if (subjectPattern != null) System.out.println("that have a subject matching: [" + subjectPattern + "]"); } // If asked to delete, ask for confirmation unless -force is given if (delete && confirm) { System.out.println(); System.out.print("Do you want to proceed (y/n) [n]: "); System.out.flush(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); String response = console.readLine(); if (!response.equals("y")) { System.out.println("No messages deleted."); System.exit(0); } } // Connect to the server, and set up streams s = new Socket(hostname, port); in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); // Read the welcome message from the server, confirming it is OK. System.out.println("Connected: " + checkResponse()); // Now log in send("USER " + username); // Send username, wait for response send("PASS " + password); // Send password, wait for response System.out.println("Logged in"); // Check how many messages are waiting, and report it String stat = send("STAT"); StringTokenizer t = new StringTokenizer(stat); System.out.println(t.nextToken() + " messages in mailbox."); System.out.println("Total size: " + t.nextToken()); // Get a list of message numbers and sizes send("LIST"); // Send LIST command, wait for OK response. // Now read lines from the server until we get . by itself List msgs = new ArrayList(); String line; for (;;) { line = in.readLine(); if (line == null) throw new IOException("Unexpected EOF"); if (line.equals(".")) break; msgs.add(line); } // Now loop through the lines we read one at a time. // Each line should specify the message number and its size. int nummsgs = msgs.size(); for (int i = 0; i < nummsgs; i++) { String m = (String) msgs.get(i); StringTokenizer st = new StringTokenizer(m); int msgnum = Integer.parseInt(st.nextToken()); int msgsize = Integer.parseInt(st.nextToken()); // If the message is too small, ignore it. if (msgsize <= sizelimit) continue; // If we're listing messages, or matching subject lines // find the subject line for this message String subject = null; if (!delete || pattern != null) { subject = getSubject(msgnum); // get the subject line // If we couldn't find a subject, skip the message if (subject == null) continue; // If this subject does not match the pattern, then // skip the message if (pattern != null) { matcher.reset(subject); if (!matcher.matches()) continue; } // If we are listing, list this message if (!delete) { System.out.println("Subject " + msgnum + ": " + subject); continue; // so we never delete it } } // If we were asked to delete, then delete the message if (delete) { send("DELE " + msgnum); if (pattern == null) System.out.println("Deleted message " + msgnum); else System.out.println("Deleted message " + msgnum + ": " + subject); } } // When we're done, log out and shutdown the connection shutdown(); } catch (Exception e) { // If anything goes wrong print exception and show usage System.err.println(e); usage(); // Always try to shutdown nicely so the server doesn't hang on us shutdown(); } }
From source file:org.ala.repository.Validator.java
/** * Main method//from w w w.j a v a 2s.c om * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:spring.xml"); Validator validator = (Validator) context.getBean("validator"); Integer id = 1008; if (args.length > 0) { id = Integer.parseInt(args[0]); } validator.setInfoSourceId(id); validator.findAndValidateFiles(); }
From source file:implementation.java
public static void main(String[] args) throws IOException { // Network Variables KUSOCKET ClientSocket = new KUSOCKET(); ENDPOINT ClientAddress = new ENDPOINT("0.0.0.0", 0); ENDPOINT BroadcastAddress = new ENDPOINT("255.255.255.255", TokenAccess.SERVER_PORT_NUMBER); ENDPOINT AnyAddress = new ENDPOINT("0.0.0.0", 0); ENDPOINT ServerAddress = new ENDPOINT(); MESSAGE OutgoingMessage = new MESSAGE(); MESSAGE IncomingMessage = new MESSAGE(); // Output variables int CommentLength = TokenAccess.COMMENT_LENGTH; String Comment = new String(); // Protocol variables Timer firstnode = new Timer(); Timer tokentimer = new Timer(); Timer tokenlost = new Timer(); Timer exit = new Timer(); int DialogueNumber = 0; int numRetries = 0; Integer addressIP[] = new Integer[2]; int trigger = 0; String lanAddress = "192.168.1.67"; // Create socket and await connection /////////////////////////////////////// // -------------------------------------------------------------------------- // FINITE STATE MACHINE // -------------------------------------------------------------------------- System.err.println("FSM Started ===================" + '\n'); // FSM variables TokenAccess.STATES state = TokenAccess.STATES.STATE_INITIAL; // Initial STATE TokenAccess.STATES lastState = state; // Last STATE boolean bContinueEventWait = false; boolean bContinueStateLoop = true; String last = null;//ww w .j a v a 2s . c om ClientSocket.CreateUDPSocket(ClientAddress); while (bContinueStateLoop) { switch (state) { case STATE_INITIAL: firstnode.Start(TokenAccess.firstnode); state = TokenAccess.STATES.STATE_STARTED; bContinueEventWait = false; // Stop Events loop break; case STATE_STARTED: ClientSocket.MakeConnection(AnyAddress); if (firstnode.isExpired()) { tokentimer.Start(TokenAccess.tokentimer); System.out.println("implementation.main()"); // adding local host ip to array String t = InetAddress.getLocalHost().getHostAddress(); String[] split = t.split("\\."); addressIP[0] = Integer.parseInt(split[3]); System.out.println(split[3]); state = TokenAccess.STATES.STATE_TOKENED; bContinueEventWait = false;// Stop Events loop } boolean isMessageQueued = false; isMessageQueued = ClientSocket.RetrieveQueuedMessage(TokenAccess.READ_INTERVAL, IncomingMessage, ServerAddress); if (isMessageQueued && (IncomingMessage.Type == TokenAccess.PDU_CONNECT)) { System.out.println("ring exists"); //pdu_connect used instead of ring exisits state = TokenAccess.STATES.STATE_tokenLess; bContinueEventWait = false; } case STATE_tokenLess: ClientSocket.MakeConnection(AnyAddress); while (state == TokenAccess.STATES.STATE_tokenLess) { // Instructs the socket to accept // building ip address message OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_CONNECT, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); //broadcasting ip address ClientSocket.DeliverMessage(OutgoingMessage, BroadcastAddress); // System.out.println("broadcasting address"); isMessageQueued = ClientSocket.RetrieveQueuedMessage(TokenAccess.READ_INTERVAL, IncomingMessage, ServerAddress); //will trigger if used on a 192 network i didnt know how to use regex for any number and a dot if (isMessageQueued == true && (IncomingMessage.Type == TokenAccess.PDU_CLOSE)) { System.out.println("pdu close"); String ipaddress = IncomingMessage.Buffer; for (int n : addressIP) { if (addressIP[n] == Integer.parseInt(ipaddress)) { String a; a = Integer.toString(addressIP[n]); OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_ACK, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); ENDPOINT exitAddress = new ENDPOINT(a, TokenAccess.SERVER_PORT_NUMBER); ClientSocket.DeliverMessage(OutgoingMessage, exitAddress); addressIP = ArrayUtils.removeElement(addressIP, n); } } } if (last != null && tokenlost.bRunning == false) { tokenlost.Start(TokenAccess.tokenlost); last = null; System.out.println("token lost timer started"); } if (isMessageQueued == true && (IncomingMessage.Type == TokenAccess.CMD_CONNECT)) { System.out.println("token lost timer stopped"); tokenlost.Stop(); } if (tokenlost.isExpired()) { System.out.println("token lost"); for (int n = 0; n < addressIP.length; n++) { String ipaddress = InetAddress.getLocalHost().toString(); int lastdot = ipaddress.lastIndexOf(".") + 1; ipaddress = ipaddress.substring(lastdot, ipaddress.length()); System.out.println(n); if (addressIP[n] == null) { } else { if (addressIP[n] == Integer.parseInt(ipaddress)) { String a; a = Integer.toString(addressIP[n]); System.out.println("variable a " + a); OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_ACK, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); ENDPOINT exitAddress = new ENDPOINT(lanAddress, TokenAccess.SERVER_PORT_NUMBER); ClientSocket.DeliverMessage(OutgoingMessage, exitAddress); OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_TOKEN, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); String b = Integer.toString(addressIP[n]); b = lanAddress; System.out.println(b); ENDPOINT exitAddresss = new ENDPOINT(b, TokenAccess.SERVER_PORT_NUMBER); ClientSocket.DeliverMessage(OutgoingMessage, exitAddresss); } } } } if (exit.isExpired()) { OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_CLOSE, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); exit.Start(30); } if (isMessageQueued && (IncomingMessage.Type == TokenAccess.PDU_TOKEN)) { tokenlost.Stop(); System.out.println(IncomingMessage.Type); state = TokenAccess.STATES.STATE_TOKENED; tokentimer.Start(TokenAccess.tokentimer); break; } } case STATE_TOKENED: while (state == TokenAccess.STATES.STATE_TOKENED) { //send data OutgoingMessage.BuildMessage(0, 0, "ALIVE", CommentLength); ClientSocket.DeliverMessage(OutgoingMessage, BroadcastAddress); tokenlost.Stop(); while (trigger == 0) { System.out.println("TOKENED"); trigger++; } if (tokentimer.isExpired()) { trigger = 0; System.out.println("token expired"); String ipaddress = InetAddress.getLocalHost().toString(); // System.out.println( "System name : "+ipaddress); for (int n = 0; n < addressIP.length; n++) { // System.out.println(n); int lastdot = ipaddress.lastIndexOf(".") + 1; ipaddress = ipaddress.substring(lastdot, ipaddress.length()); // System.out.println("IP address: "+ipaddress); int address1 = Integer.parseInt(ipaddress); System.out.println("made it to line 214"); System.out.println(n); System.out.println(addressIP[0]); if (addressIP[n] == address1) { String a; a = Integer.toString(addressIP[n]); System.out.println("variable a = " + a); String ip = InetAddress.getLocalHost().getHostAddress(); System.out.println("line 226"); System.out.println(ip); OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_TOKEN, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); String b; System.out.println("line 222"); if (n + 1 >= addressIP.length) { b = (ip); // System.out.println(b); } else { b = ip; } System.out.println(b); //b = InetAddress.getLocalHost().toString().substring(0, lastdot); // int slash = b.indexOf("/"); System.out.println(b); ENDPOINT exitAddresss = new ENDPOINT(b, TokenAccess.SERVER_PORT_NUMBER); ClientSocket.DeliverMessage(OutgoingMessage, exitAddresss); System.out.println("exiting tokened state"); state = TokenAccess.STATES.STATE_tokenLess; last = "1"; } break; } } } case STATE_EXIT: while (state == TokenAccess.STATES.STATE_EXIT) { System.exit(0); } } } }
From source file:malware_classification.Malware_Classification.java
/** * @param args the command line arguments. Order is malicious_filename, * benign filename, (optional) bin_size//from w w w.j a va2s .c o m */ public static void main(String[] args) { String malicious_file_path = args[0]; String benign_file_path = args[1]; int curr_bin_size; if (args.length > 2) { curr_bin_size = Integer.parseInt(args[2]); } else { curr_bin_size = -1; } String pid_str = ManagementFactory.getRuntimeMXBean().getName(); logger.setLevel(Level.CONFIG); logger.log(Level.INFO, pid_str); boolean found_file = false; String output_base = "std_output"; File output_file = null; for (int i = 0; !found_file; i++) { output_file = new File(output_base + i + ".txt"); found_file = !output_file.exists(); } FileHandler fh = null; try { fh = new FileHandler(output_file.getAbsolutePath()); } catch (IOException ex) { Logger.getLogger(Malware_Classification.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(Malware_Classification.class.getName()).log(Level.SEVERE, null, ex); } logger.addHandler(fh); logger.info("Writing output in " + output_file.getAbsolutePath()); Malware_Classification classifier = new Malware_Classification(malicious_file_path, benign_file_path, curr_bin_size); // classifier.run_tests(); }
From source file:eu.fbk.dkm.sectionextractor.PageClassMerger.java
public static void main(String args[]) throws IOException { CommandLineWithLogger commandLineWithLogger = new CommandLineWithLogger(); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("WikiData ID file").isRequired().withLongOpt("wikidata-id").create("i")); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("Airpedia Person file").isRequired().withLongOpt("airpedia").create("a")); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Output file") .isRequired().withLongOpt("output").create("o")); CommandLine commandLine = null;//from w w w . j a v a2 s.co m try { commandLine = commandLineWithLogger.getCommandLine(args); PropertyConfigurator.configure(commandLineWithLogger.getLoggerProps()); } catch (Exception e) { System.exit(1); } String wikiIDFileName = commandLine.getOptionValue("wikidata-id"); String airpediaFileName = commandLine.getOptionValue("airpedia"); String outputFileName = commandLine.getOptionValue("output"); HashMap<Integer, String> wikiIDs = new HashMap<>(); HashSet<Integer> airpediaClasses = new HashSet<>(); List<String> strings; logger.info("Loading file " + wikiIDFileName); strings = Files.readLines(new File(wikiIDFileName), Charsets.UTF_8); for (String line : strings) { line = line.trim(); if (line.length() == 0) { continue; } if (line.startsWith("#")) { continue; } String[] parts = line.split("\t"); if (parts.length < 2) { continue; } int id; try { id = Integer.parseInt(parts[0]); } catch (Exception e) { continue; } wikiIDs.put(id, parts[1]); } logger.info("Loading file " + airpediaFileName); strings = Files.readLines(new File(airpediaFileName), Charsets.UTF_8); for (String line : strings) { line = line.trim(); if (line.length() == 0) { continue; } if (line.startsWith("#")) { continue; } String[] parts = line.split("\t"); if (parts.length < 2) { continue; } int id; try { id = Integer.parseInt(parts[0]); } catch (Exception e) { continue; } airpediaClasses.add(id); } logger.info("Saving information"); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName)); for (int i : wikiIDs.keySet()) { if (!airpediaClasses.contains(i)) { continue; } writer.append(wikiIDs.get(i)).append("\n"); } writer.close(); }
From source file:edu.clemson.cs.nestbed.server.tools.BuildTestbed.java
public static void main(String[] args) { try {/*from ww w .j a v a2s . c o m*/ BasicConfigurator.configure(); //loadProperties(); if (args.length < 2) { System.out.println("Usage: BuildTestbed <testbedID> <inputfile>"); System.exit(0); } int testbedID = Integer.parseInt(args[0]); String filename = args[1]; Connection conn = null; Statement statement = null; MoteSqlAdapter adapter = new MoteSqlAdapter(); Map<Integer, Mote> motes = adapter.readMotes(); log.info(motes); String connStr = System.getProperty("nestbed.options.databaseConnectionString"); log.info("connStr: " + connStr); conn = DriverManager.getConnection(connStr); statement = conn.createStatement(); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = in.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); int address = Integer.parseInt(tokenizer.nextToken()); String serial = tokenizer.nextToken(); int xLoc = Integer.parseInt(tokenizer.nextToken()); int yLoc = Integer.parseInt(tokenizer.nextToken()); log.info("Input Mote:\n" + "-----------\n" + "address: " + address + "\n" + "serial: " + serial + "\n" + "xLoc: " + xLoc + "\n" + "yLoc: " + yLoc); for (Mote i : motes.values()) { if (i.getMoteSerialID().equals(serial)) { String query = "INSERT INTO MoteTestbedAssignments" + "(testbedID, moteID, moteAddress," + " moteLocationX, moteLocationY) VALUES (" + testbedID + ", " + i.getID() + ", " + address + ", " + xLoc + ", " + yLoc + ")"; log.info(query); statement.executeUpdate(query); } } } conn.commit(); } catch (Exception ex) { log.error("Exception in main", ex); } }