List of usage examples for java.util StringTokenizer nextToken
public String nextToken()
From source file:com.cloud.sample.UserCloudAPIExecutor.java
public static void main(String[] args) { // Host/*w ww. j av a 2 s . c o m*/ String host = null; // Fully qualified URL with http(s)://host:port String apiUrl = null; // ApiKey and secretKey as given by your CloudStack vendor String apiKey = null; String secretKey = null; try { Properties prop = new Properties(); prop.load(new FileInputStream("usercloud.properties")); // host host = prop.getProperty("host"); if (host == null) { System.out.println( "Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file."); } // apiUrl apiUrl = prop.getProperty("apiUrl"); if (apiUrl == null) { System.out.println( "Please specify a valid API URL in the format of command=¶m1=¶m2=... in your usercloud.properties file."); } // apiKey apiKey = prop.getProperty("apiKey"); if (apiKey == null) { System.out.println( "Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file."); } // secretKey secretKey = prop.getProperty("secretKey"); if (secretKey == null) { System.out.println( "Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file."); } if (apiUrl == null || apiKey == null || secretKey == null) { return; } System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'"); // Step 1: Make sure your APIKey is URL encoded String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8"); // Step 2: URL encode each parameter value, then sort the parameters and apiKey in // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey. // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using // '&' to delimit // the string List<String> sortedParams = new ArrayList<String>(); sortedParams.add("apikey=" + encodedApiKey.toLowerCase()); StringTokenizer st = new StringTokenizer(apiUrl, "&"); String url = null; boolean first = true; while (st.hasMoreTokens()) { String paramValue = st.nextToken(); String param = paramValue.substring(0, paramValue.indexOf("=")); String value = URLEncoder .encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8"); if (first) { url = param + "=" + value; first = false; } else { url = url + "&" + param + "=" + value; } sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase()); } Collections.sort(sortedParams); System.out.println("Sorted Parameters: " + sortedParams); // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key String sortedUrl = null; first = true; for (String param : sortedParams) { if (first) { sortedUrl = param; first = false; } else { sortedUrl = sortedUrl + "&" + param; } } System.out.println("sorted URL : " + sortedUrl); String encodedSignature = signRequest(sortedUrl, secretKey); // Step 4: Construct the final URL we want to send to the CloudStack Management Server // Final result should look like: // http(s)://://client/api?&apiKey=&signature= String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature; System.out.println("final URL : " + finalUrl); // Step 5: Perform a HTTP GET on this URL to execute the command HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(finalUrl); int responseCode = client.executeMethod(method); if (responseCode == 200) { // SUCCESS! System.out.println("Successfully executed command"); } else { // FAILED! System.out.println("Unable to execute command with response code: " + responseCode); } } catch (Throwable t) { System.out.println(t); } }
From source file:com.groupC1.control.network.TelnetClientExample.java
/*** * Main for the TelnetClient.//from ww w. j a va2 s . c om ***/ public static void main(String[] args) throws Exception { args = new String[] { "169.254.0.10", "10001" }; FileOutputStream fout = null; if (args.length < 1) { System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]"); System.exit(1); } String remoteip = args[0]; int remoteport; if (args.length > 1) { remoteport = (new Integer(args[1])).intValue(); } else { remoteport = 23; } try { fout = new FileOutputStream("spy.log", true); } catch (IOException e) { System.err.println("Exception while opening the spy file: " + e.getMessage()); } tc = new org.apache.commons.net.telnet.TelnetClient(); TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false); EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false); SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true); try { tc.addOptionHandler(ttopt); tc.addOptionHandler(echoopt); tc.addOptionHandler(gaopt); } catch (InvalidTelnetOptionException e) { System.err.println("Error registering option handlers: " + e.getMessage()); } while (true) { boolean end_loop = false; try { tc.connect(remoteip, remoteport); Thread reader = new Thread(new TelnetClientExample()); tc.registerNotifHandler(new TelnetClientExample()); System.out.println("TelnetClient"); System.out.println("Type AYT to send an AYT telnet command"); System.out.println("Type OPT to print a report of status of options (0-24)"); System.out.println("Type REGISTER to register a new SimpleOptionHandler"); System.out.println("Type UNREGISTER to unregister an OptionHandler"); System.out.println("Type SPY to register the spy (connect to port 3333 to spy)"); System.out.println("Type UNSPY to stop spying the connection"); reader.start(); OutputStream outstr = tc.getOutputStream(); byte[] buff = new byte[1024]; int ret_read = 0; do { try { ret_read = System.in.read(buff); if (ret_read > 0) { if ((new String(buff, 0, ret_read)).startsWith("AYT")) { try { System.out.println("Sending AYT"); System.out.println("AYT response:" + tc.sendAYT(5000)); } catch (IOException e) { System.err.println("Exception waiting AYT response: " + e.getMessage()); } } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) { System.out.println("Status of options:"); for (int ii = 0; ii < 25; ii++) { System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii)); } } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = Integer.parseInt(st.nextToken()); boolean initlocal = Boolean.parseBoolean(st.nextToken()); boolean initremote = Boolean.parseBoolean(st.nextToken()); boolean acceptlocal = Boolean.parseBoolean(st.nextToken()); boolean acceptremote = Boolean.parseBoolean(st.nextToken()); SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote, acceptlocal, acceptremote); tc.addOptionHandler(opthand); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error registering option: " + e.getMessage()); } else { System.err.println("Invalid REGISTER command."); System.err.println( "Use REGISTER optcode initlocal initremote acceptlocal acceptremote"); System.err.println("(optcode is an integer.)"); System.err.println( "(initlocal, initremote, acceptlocal, acceptremote are boolean)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = (new Integer(st.nextToken())).intValue(); tc.deleteOptionHandler(opcode); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error unregistering option: " + e.getMessage()); } else { System.err.println("Invalid UNREGISTER command."); System.err.println("Use UNREGISTER optcode"); System.err.println("(optcode is an integer)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) { tc.registerSpyStream(fout); } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) { tc.stopSpyStream(); } else { try { outstr.write(buff, 0, ret_read); outstr.flush(); } catch (IOException e) { end_loop = true; } } } } catch (IOException e) { System.err.println("Exception while reading keyboard:" + e.getMessage()); end_loop = true; } } while ((ret_read > 0) && (end_loop == false)); try { tc.disconnect(); } catch (IOException e) { System.err.println("Exception while connecting:" + e.getMessage()); } } catch (IOException e) { System.err.println("Exception while connecting:" + e.getMessage()); System.exit(1); } } }
From source file:PopClean.java
public static void main(String args[]) { try {// ww w.j a v a 2 s. 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:examples.TelnetClientExample.java
/*** * Main for the TelnetClientExample./*from w w w . j a v a 2s . c o m*/ ***/ public static void main(String[] args) throws IOException { FileOutputStream fout = null; if (args.length < 1) { System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]"); System.exit(1); } String remoteip = args[0]; int remoteport; if (args.length > 1) { remoteport = (new Integer(args[1])).intValue(); } else { remoteport = 23; } try { fout = new FileOutputStream("spy.log", true); } catch (Exception e) { System.err.println("Exception while opening the spy file: " + e.getMessage()); } tc = new TelnetClient(); TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false); EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false); SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true); try { tc.addOptionHandler(ttopt); tc.addOptionHandler(echoopt); tc.addOptionHandler(gaopt); } catch (InvalidTelnetOptionException e) { System.err.println("Error registering option handlers: " + e.getMessage()); } while (true) { boolean end_loop = false; try { tc.connect(remoteip, remoteport); Thread reader = new Thread(new TelnetClientExample()); tc.registerNotifHandler(new TelnetClientExample()); System.out.println("TelnetClientExample"); System.out.println("Type AYT to send an AYT telnet command"); System.out.println("Type OPT to print a report of status of options (0-24)"); System.out.println("Type REGISTER to register a new SimpleOptionHandler"); System.out.println("Type UNREGISTER to unregister an OptionHandler"); System.out.println("Type SPY to register the spy (connect to port 3333 to spy)"); System.out.println("Type UNSPY to stop spying the connection"); reader.start(); OutputStream outstr = tc.getOutputStream(); byte[] buff = new byte[1024]; int ret_read = 0; do { try { ret_read = System.in.read(buff); if (ret_read > 0) { if ((new String(buff, 0, ret_read)).startsWith("AYT")) { try { System.out.println("Sending AYT"); System.out.println("AYT response:" + tc.sendAYT(5000)); } catch (Exception e) { System.err.println("Exception waiting AYT response: " + e.getMessage()); } } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) { System.out.println("Status of options:"); for (int ii = 0; ii < 25; ii++) System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii)); } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = (new Integer(st.nextToken())).intValue(); boolean initlocal = (new Boolean(st.nextToken())).booleanValue(); boolean initremote = (new Boolean(st.nextToken())).booleanValue(); boolean acceptlocal = (new Boolean(st.nextToken())).booleanValue(); boolean acceptremote = (new Boolean(st.nextToken())).booleanValue(); SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote, acceptlocal, acceptremote); tc.addOptionHandler(opthand); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error registering option: " + e.getMessage()); } else { System.err.println("Invalid REGISTER command."); System.err.println( "Use REGISTER optcode initlocal initremote acceptlocal acceptremote"); System.err.println("(optcode is an integer.)"); System.err.println( "(initlocal, initremote, acceptlocal, acceptremote are boolean)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = (new Integer(st.nextToken())).intValue(); tc.deleteOptionHandler(opcode); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error unregistering option: " + e.getMessage()); } else { System.err.println("Invalid UNREGISTER command."); System.err.println("Use UNREGISTER optcode"); System.err.println("(optcode is an integer)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) { try { tc.registerSpyStream(fout); } catch (Exception e) { System.err.println("Error registering the spy"); } } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) { tc.stopSpyStream(); } else { try { outstr.write(buff, 0, ret_read); outstr.flush(); } catch (Exception e) { end_loop = true; } } } } catch (Exception e) { System.err.println("Exception while reading keyboard:" + e.getMessage()); end_loop = true; } } while ((ret_read > 0) && (end_loop == false)); try { tc.disconnect(); } catch (Exception e) { System.err.println("Exception while connecting:" + e.getMessage()); } } catch (Exception e) { System.err.println("Exception while connecting:" + e.getMessage()); System.exit(1); } } }
From source file:ch.unizh.ini.jaer.projects.gesture.vlccontrol.TelnetClientExample.java
/*** * Main for the TelnetClientExample.//from w w w .j a va 2 s .c o m ***/ public static void main(String[] args) throws IOException { FileOutputStream fout = null; if (args.length < 1) { System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]"); System.exit(1); } String remoteip = args[0]; int remoteport; if (args.length > 1) { remoteport = (new Integer(args[1])).intValue(); } else { remoteport = 23; } try { fout = new FileOutputStream("spy.log", true); } catch (Exception e) { System.err.println("Exception while opening the spy file: " + e.getMessage()); } tc = new TelnetClient(); TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false); EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false); SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true); try { tc.addOptionHandler(ttopt); tc.addOptionHandler(echoopt); tc.addOptionHandler(gaopt); } catch (InvalidTelnetOptionException e) { System.err.println("Error registering option handlers: " + e.getMessage()); } while (true) { boolean end_loop = false; try { tc.connect(remoteip, remoteport); Thread reader = new Thread(new TelnetClientExample()); tc.registerNotifHandler(new TelnetClientExample()); System.out.println("TelnetClientExample"); System.out.println("Type AYT to send an AYT telnet command"); System.out.println("Type OPT to print a report of status of options (0-24)"); System.out.println("Type REGISTER to register a new SimpleOptionHandler"); System.out.println("Type UNREGISTER to unregister an OptionHandler"); System.out.println("Type SPY to register the spy (connect to port 3333 to spy)"); System.out.println("Type UNSPY to stop spying the connection"); reader.start(); OutputStream outstr = tc.getOutputStream(); byte[] buff = new byte[1024]; int ret_read = 0; do { try { ret_read = System.in.read(buff); if (ret_read > 0) { if ((new String(buff, 0, ret_read)).startsWith("AYT")) { try { System.out.println("Sending AYT"); System.out.println("AYT response:" + tc.sendAYT(5000)); } catch (Exception e) { System.err.println("Exception waiting AYT response: " + e.getMessage()); } } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) { System.out.println("Status of options:"); for (int ii = 0; ii < 25; ii++) { System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii)); } } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = (new Integer(st.nextToken())).intValue(); boolean initlocal = (new Boolean(st.nextToken())).booleanValue(); boolean initremote = (new Boolean(st.nextToken())).booleanValue(); boolean acceptlocal = (new Boolean(st.nextToken())).booleanValue(); boolean acceptremote = (new Boolean(st.nextToken())).booleanValue(); SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote, acceptlocal, acceptremote); tc.addOptionHandler(opthand); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error registering option: " + e.getMessage()); } else { System.err.println("Invalid REGISTER command."); System.err.println( "Use REGISTER optcode initlocal initremote acceptlocal acceptremote"); System.err.println("(optcode is an integer.)"); System.err.println( "(initlocal, initremote, acceptlocal, acceptremote are boolean)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = (new Integer(st.nextToken())).intValue(); tc.deleteOptionHandler(opcode); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error unregistering option: " + e.getMessage()); } else { System.err.println("Invalid UNREGISTER command."); System.err.println("Use UNREGISTER optcode"); System.err.println("(optcode is an integer)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) { try { tc.registerSpyStream(fout); } catch (Exception e) { System.err.println("Error registering the spy"); } } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) { tc.stopSpyStream(); } else { try { outstr.write(buff, 0, ret_read); outstr.flush(); } catch (Exception e) { end_loop = true; } } } } catch (Exception e) { System.err.println("Exception while reading keyboard:" + e.getMessage()); end_loop = true; } } while ((ret_read > 0) && (end_loop == false)); try { tc.disconnect(); } catch (Exception e) { System.err.println("Exception while connecting:" + e.getMessage()); } } catch (Exception e) { System.err.println("Exception while connecting:" + e.getMessage()); System.exit(1); } } }
From source file:com.hzih.sslvpn.servlet.TelnetClientExample.java
/** * Main for the TelnetClientExample.//from www. java2s .co m * * */ public static void main(String[] args) throws Exception { FileOutputStream fout = null; if (args.length < 1) { System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]"); System.exit(1); } String remoteip = args[0]; int remoteport; if (args.length > 1) { remoteport = (new Integer(args[1])).intValue(); } else { remoteport = 23; } try { fout = new FileOutputStream("spy.log", true); } catch (IOException e) { System.err.println("Exception while opening the spy file: " + e.getMessage()); } tc = new TelnetClient(); TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false); EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false); SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true); try { tc.addOptionHandler(ttopt); tc.addOptionHandler(echoopt); tc.addOptionHandler(gaopt); } catch (InvalidTelnetOptionException e) { System.err.println("Error registering option handlers: " + e.getMessage()); } while (true) { boolean end_loop = false; try { tc.connect(remoteip, remoteport); Thread reader = new Thread(new TelnetClientExample()); tc.registerNotifHandler(new TelnetClientExample()); System.out.println("TelnetClientExample"); System.out.println("Type AYT to send an AYT telnet command"); System.out.println("Type OPT to print a report of status of options (0-24)"); System.out.println("Type REGISTER to register a new SimpleOptionHandler"); System.out.println("Type UNREGISTER to unregister an OptionHandler"); System.out.println("Type SPY to register the spy (connect to port 3333 to spy)"); System.out.println("Type UNSPY to stop spying the connection"); reader.start(); OutputStream outstr = tc.getOutputStream(); byte[] buff = new byte[1024]; int ret_read = 0; do { try { ret_read = System.in.read(buff); if (ret_read > 0) { if ((new String(buff, 0, ret_read)).startsWith("AYT")) { try { System.out.println("Sending AYT"); System.out.println("AYT response:" + tc.sendAYT(5000)); } catch (IOException e) { System.err.println("Exception waiting AYT response: " + e.getMessage()); } } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) { System.out.println("Status of options:"); for (int ii = 0; ii < 25; ii++) { System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii)); } } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = Integer.parseInt(st.nextToken()); boolean initlocal = Boolean.parseBoolean(st.nextToken()); boolean initremote = Boolean.parseBoolean(st.nextToken()); boolean acceptlocal = Boolean.parseBoolean(st.nextToken()); boolean acceptremote = Boolean.parseBoolean(st.nextToken()); SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote, acceptlocal, acceptremote); tc.addOptionHandler(opthand); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error registering option: " + e.getMessage()); } else { System.err.println("Invalid REGISTER command."); System.err.println( "Use REGISTER optcode initlocal initremote acceptlocal acceptremote"); System.err.println("(optcode is an integer.)"); System.err.println( "(initlocal, initremote, acceptlocal, acceptremote are boolean)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = (new Integer(st.nextToken())).intValue(); tc.deleteOptionHandler(opcode); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error unregistering option: " + e.getMessage()); } else { System.err.println("Invalid UNREGISTER command."); System.err.println("Use UNREGISTER optcode"); System.err.println("(optcode is an integer)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) { tc.registerSpyStream(fout); } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) { tc.stopSpyStream(); } else { try { outstr.write(buff, 0, ret_read); outstr.flush(); } catch (IOException e) { end_loop = true; } } } } catch (IOException e) { System.err.println("Exception while reading keyboard:" + e.getMessage()); end_loop = true; } } while ((ret_read > 0) && (end_loop == false)); try { tc.disconnect(); } catch (IOException e) { System.err.println("Exception while connecting:" + e.getMessage()); } } catch (IOException e) { System.err.println("Exception while connecting:" + e.getMessage()); System.exit(1); } } }
From source file:LogStrTok.java
public static void main(String argv[]) { StringTokenizer matcher = new StringTokenizer(logEntryLine); System.out.println("tokens = " + matcher.countTokens()); // StringTokenizer CAN NOT count if you are changing the delimiter! // if (matcher.countTokens() != NUM_FIELDS) { // System.err.println("Bad log entry (or bug in StringTokenizer?):"); // System.err.println(logEntryLine); // }//from w ww.java 2 s. c om System.out.println("Hostname: " + matcher.nextToken()); // StringTokenizer makes you ask for tokens in order to skip them: matcher.nextToken(); // eat the "-" matcher.nextToken(); // again System.out.println("Date/Time: " + matcher.nextToken("]")); //matcher.nextToken(" "); // again System.out.println("Request: " + matcher.nextToken("\"")); matcher.nextToken(" "); // again System.out.println("Response: " + matcher.nextToken()); System.out.println("ByteCount: " + matcher.nextToken()); System.out.println("Referer: " + matcher.nextToken("\"")); matcher.nextToken(" "); // again System.out.println("User-Agent: " + matcher.nextToken("\"")); }
From source file:com.ibm.crail.storage.StorageServer.java
public static void main(String[] args) throws Exception { Logger LOG = CrailUtils.getLogger(); CrailConfiguration conf = new CrailConfiguration(); CrailConstants.updateConstants(conf); CrailConstants.printConf();// w w w . j av a 2 s . c o m CrailConstants.verify(); int splitIndex = 0; for (String param : args) { if (param.equalsIgnoreCase("--")) { break; } splitIndex++; } //default values StringTokenizer tokenizer = new StringTokenizer(CrailConstants.STORAGE_TYPES, ","); if (!tokenizer.hasMoreTokens()) { throw new Exception("No storage types defined!"); } String storageName = tokenizer.nextToken(); int storageType = 0; HashMap<String, Integer> storageTypes = new HashMap<String, Integer>(); storageTypes.put(storageName, storageType); for (int type = 1; tokenizer.hasMoreElements(); type++) { String name = tokenizer.nextToken(); storageTypes.put(name, type); } int storageClass = -1; //custom values if (args != null) { Option typeOption = Option.builder("t").desc("storage type to start").hasArg().build(); Option classOption = Option.builder("c").desc("storage class the server will attach to").hasArg() .build(); Options options = new Options(); options.addOption(typeOption); options.addOption(classOption); CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, splitIndex)); if (line.hasOption(typeOption.getOpt())) { storageName = line.getOptionValue(typeOption.getOpt()); storageType = storageTypes.get(storageName).intValue(); } if (line.hasOption(classOption.getOpt())) { storageClass = Integer.parseInt(line.getOptionValue(classOption.getOpt())); } } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Storage tier", options); System.exit(-1); } } if (storageClass < 0) { storageClass = storageType; } StorageTier storageTier = StorageTier.createInstance(storageName); if (storageTier == null) { throw new Exception("Cannot instantiate datanode of type " + storageName); } String extraParams[] = null; splitIndex++; if (args.length > splitIndex) { extraParams = new String[args.length - splitIndex]; for (int i = splitIndex; i < args.length; i++) { extraParams[i - splitIndex] = args[i]; } } storageTier.init(conf, extraParams); storageTier.printConf(LOG); RpcClient rpcClient = RpcClient.createInstance(CrailConstants.NAMENODE_RPC_TYPE); rpcClient.init(conf, args); rpcClient.printConf(LOG); ConcurrentLinkedQueue<InetSocketAddress> namenodeList = CrailUtils.getNameNodeList(); ConcurrentLinkedQueue<RpcConnection> connectionList = new ConcurrentLinkedQueue<RpcConnection>(); while (!namenodeList.isEmpty()) { InetSocketAddress address = namenodeList.poll(); RpcConnection connection = rpcClient.connect(address); connectionList.add(connection); } RpcConnection rpcConnection = connectionList.peek(); if (connectionList.size() > 1) { rpcConnection = new RpcDispatcher(connectionList); } LOG.info("connected to namenode(s) " + rpcConnection.toString()); StorageServer server = storageTier.launchServer(); StorageRpcClient storageRpc = new StorageRpcClient(storageType, CrailStorageClass.get(storageClass), server.getAddress(), rpcConnection); HashMap<Long, Long> blockCount = new HashMap<Long, Long>(); long sumCount = 0; while (server.isAlive()) { StorageResource resource = server.allocateResource(); if (resource == null) { break; } else { storageRpc.setBlock(resource.getAddress(), resource.getLength(), resource.getKey()); DataNodeStatistics stats = storageRpc.getDataNode(); long newCount = stats.getFreeBlockCount(); long serviceId = stats.getServiceId(); long oldCount = 0; if (blockCount.containsKey(serviceId)) { oldCount = blockCount.get(serviceId); } long diffCount = newCount - oldCount; blockCount.put(serviceId, newCount); sumCount += diffCount; LOG.info("datanode statistics, freeBlocks " + sumCount); } } while (server.isAlive()) { DataNodeStatistics stats = storageRpc.getDataNode(); long newCount = stats.getFreeBlockCount(); long serviceId = stats.getServiceId(); long oldCount = 0; if (blockCount.containsKey(serviceId)) { oldCount = blockCount.get(serviceId); } long diffCount = newCount - oldCount; blockCount.put(serviceId, newCount); sumCount += diffCount; LOG.info("datanode statistics, freeBlocks " + sumCount); Thread.sleep(2000); } }
From source file:edu.asu.bscs.csiebler.waypointapplication.WaypointServerStub.java
/** * * @param args/*from www .j av a 2 s. co m*/ */ public static void main(String args[]) { try { String url = "http://127.0.0.1:8080/"; if (args.length > 0) { url = args[0]; } WaypointServerStub cjc = new WaypointServerStub(url); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.print( "Enter end or {remove|get|getNames|getCategoryNames|getNamesInCategory|dist|bear} arg1 arg2 eg remove Toreros >"); String inStr = stdin.readLine(); StringTokenizer st = new StringTokenizer(inStr); String opn = st.nextToken(); while (!opn.equalsIgnoreCase("end")) { switch (opn) { case "remove": { boolean result = cjc.remove(st.nextToken()); System.out.println("response: " + result); break; } case "get": { Waypoint result = cjc.get(st.nextToken()); System.out.println("response: " + result.toJsonString()); break; } case "getNames": { String[] result = cjc.getNames(); for (int i = 0; i < result.length; i++) { System.out.println("response[" + i + "] is " + result[i]); } break; } case "getCategoryNames": { String[] result = cjc.getCategoryNames(); for (int i = 0; i < result.length; i++) { System.out.println("response[" + i + "] is " + result[i]); } break; } case "getNamesInCategory": { String[] result = cjc.getNamesInCategory(st.nextToken()); for (int i = 0; i < result.length; i++) { System.out.println("response[" + i + "] is " + result[i]); } break; } case "dist": { double result = cjc.distanceGCTo(st.nextToken(), st.nextToken()); System.out.println("response: " + result); break; } case "bear": { double result = cjc.bearingGCInitTo(st.nextToken(), st.nextToken()); System.out.println("response: " + result); break; } default: { break; } } System.out.print( "Enter end or {remove|get|getNames|getCategoryNames|getNamesInCategory|dist|bear} arg1 arg2 eg remove Toreros >"); inStr = stdin.readLine(); st = new StringTokenizer(inStr); opn = st.nextToken(); } } catch (Exception e) { System.out.println("Oops, you didn't enter the right stuff"); } }
From source file:ReadTemp.java
/** * Method main//from www . j a v a2 s . c o m * * * @param args * * @throws OneWireException * @throws OneWireIOException * */ public static void main(String[] args) throws OneWireIOException, OneWireException { boolean usedefault = false; DSPortAdapter access = null; String adapter_name = null; String port_name = null; variableNames = new HashMap(); if ((args == null) || (args.length < 1)) { try { access = OneWireAccessProvider.getDefaultAdapter(); if (access == null) throw new Exception(); } catch (Exception e) { System.out.println("Couldn't get default adapter!"); printUsageString(); return; } usedefault = true; } if (!usedefault) { StringTokenizer st = new StringTokenizer(args[0], "_"); if (st.countTokens() != 2) { printUsageString(); return; } adapter_name = st.nextToken(); port_name = st.nextToken(); System.out.println("Adapter Name: " + adapter_name); System.out.println("Port Name: " + port_name); } if (access == null) { try { access = OneWireAccessProvider.getAdapter(adapter_name, port_name); } catch (Exception e) { System.out.println("That is not a valid adapter/port combination."); Enumeration en = OneWireAccessProvider.enumerateAllAdapters(); while (en.hasMoreElements()) { DSPortAdapter temp = (DSPortAdapter) en.nextElement(); System.out.println("Adapter: " + temp.getAdapterName()); Enumeration f = temp.getPortNames(); while (f.hasMoreElements()) { System.out.println(" Port name : " + ((String) f.nextElement())); } } return; } } boolean scan = false; if (args.length > 1) { if (args[1].compareTo("--scan") == 0) scan = true; } else { populateVariableNames(); } while (true) { access.adapterDetected(); access.targetAllFamilies(); access.beginExclusive(true); access.reset(); access.setSearchAllDevices(); boolean next = access.findFirstDevice(); if (!next) { System.out.println("Could not find any iButtons!"); return; } while (next) { OneWireContainer owc = access.getDeviceContainer(); boolean isTempContainer = false; TemperatureContainer tc = null; try { tc = (TemperatureContainer) owc; isTempContainer = true; } catch (Exception e) { tc = null; isTempContainer = false; //just to reiterate } if (isTempContainer) { String id = owc.getAddressAsString(); if (scan) { System.out.println("= Temperature Sensor Found: " + id); } else { double high = 0.0; double low = 0.0; byte[] state = tc.readDevice(); boolean selectable = tc.hasSelectableTemperatureResolution(); if (selectable) try { tc.setTemperatureResolution(0.0625, state); } catch (Exception e) { System.out.println("= Could not set resolution for " + id + ": " + e.toString()); } try { tc.writeDevice(state); } catch (Exception e) { System.out.println("= Could not write device state, all changes lost."); System.out.println("= Exception occurred for " + id + ": " + e.toString()); } boolean conversion = false; try { tc.doTemperatureConvert(state); conversion = true; } catch (Exception e) { System.out.println("= Could not complete temperature conversion..."); System.out.println("= Exception occurred for " + id + ": " + e.toString()); } if (conversion) { state = tc.readDevice(); double temp = tc.getTemperature(state); if (temp < 84) { double temp_f = (9.0 / 5.0) * temp + 32; setVariable(id, Double.toString(temp_f)); } System.out.println("= Reported temperature from " + (String) variableNames.get(id) + "(" + id + "):" + temp); } } } next = access.findNextDevice(); } if (!scan) { try { Thread.sleep(60 * 5 * 1000); } catch (Exception e) { } } else { System.exit(0); } } }