List of usage examples for java.io BufferedReader readLine
public String readLine() throws IOException
From source file:SendMail.java
public static void main(String[] args) { try {//from w w w .j av a2 s . c om // If the user specified a mailhost, tell the system about it. if (args.length >= 1) System.getProperties().put("mail.host", args[0]); // A Reader stream to read from the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Ask the user for the from, to, and subject lines System.out.print("From: "); String from = in.readLine(); System.out.print("To: "); String to = in.readLine(); System.out.print("Subject: "); String subject = in.readLine(); // Establish a network connection for sending mail URL u = new URL("mailto:" + to); // Create a mailto: URL URLConnection c = u.openConnection(); // Create its URLConnection c.setDoInput(false); // Specify no input from it c.setDoOutput(true); // Specify we'll do output System.out.println("Connecting..."); // Tell the user System.out.flush(); // Tell them right now c.connect(); // Connect to mail host PrintWriter out = // Get output stream to host new PrintWriter(new OutputStreamWriter(c.getOutputStream())); // We're talking to the SMTP server now. // Write out mail headers. Don't let users fake the From address out.print("From: \"" + from + "\" <" + System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName() + ">\r\n"); out.print("To: " + to + "\r\n"); out.print("Subject: " + subject + "\r\n"); out.print("\r\n"); // blank line to end the list of headers // Now ask the user to enter the body of the message System.out.println("Enter the message. " + "End with a '.' on a line by itself."); // Read message line by line and send it out. String line; for (;;) { line = in.readLine(); if ((line == null) || line.equals(".")) break; out.print(line + "\r\n"); } // Close (and flush) the stream to terminate the message out.close(); // Tell the user it was successfully sent. System.out.println("Message sent."); } catch (Exception e) { // Handle any exceptions, print error message. System.err.println(e); System.err.println("Usage: java SendMail [<mailhost>]"); } }
From source file:test.TestJavaService.java
/** * Main. The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag. If it is specified, * we test code on the AWS instance. If it is not, we test code running locally. * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file * org.qcert.javasrc.Main. Remaining non-flag arguments are file names. There must be at least one. The number of such * arguments and what they should contain depends on the verb. * @throws Exception/*from ww w . j ava 2 s. c om*/ */ public static void main(String[] args) throws Exception { /* Parse command line */ List<String> files = new ArrayList<>(); String loc = "localhost", verb = null; for (String arg : args) { if (arg.equals("-remote")) loc = REMOTE_LOC; else if (arg.startsWith("-")) illegal(); else if (verb == null) verb = arg; else files.add(arg); } /* Simple consistency checks and verb-specific parsing */ if (files.size() == 0) illegal(); String file = files.remove(0); String schema = null; switch (verb) { case "parseSQL": case "serialRule2CAMP": case "sqlSchema2JSON": if (files.size() != 0) illegal(); break; case "techRule2CAMP": if (files.size() != 1) illegal(); schema = files.get(0); break; case "csv2JSON": if (files.size() < 1) illegal(); break; default: illegal(); } /* Assemble information from arguments */ String url = String.format("http://%s:9879?verb=%s", loc, verb); byte[] contents = Files.readAllBytes(Paths.get(file)); String toSend; if ("serialRule2CAMP".equals(verb)) toSend = Base64.getEncoder().encodeToString(contents); else toSend = new String(contents); if ("techRule2CAMP".equals(verb)) toSend = makeSpecialJson(toSend, schema); else if ("csv2JSON".equals(verb)) toSend = makeSpecialJson(toSend, files); HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(toSend); entity.setContentType("text/plain"); post.setEntity(entity); HttpResponse resp = client.execute(post); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity answer = resp.getEntity(); InputStream s = answer.getContent(); BufferedReader rdr = new BufferedReader(new InputStreamReader(s)); String line = rdr.readLine(); while (line != null) { System.out.println(line); line = rdr.readLine(); } rdr.close(); s.close(); } else System.out.println(resp.getStatusLine()); }
From source file:animalclient.AnimalClient.java
/** * @param args the command line arguments *///from ww w . jav a 2s .c o m public static void main(String[] arg) throws IOException, MalformedURLException, ParseException { // TODO code application logic here InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String username; String password; System.out.println("Username:"); username = br.readLine(); System.out.println("Password:"); password = br.readLine(); AnimalJerseyClient client = new AnimalJerseyClient(username, password); System.out.println(""); System.out.println( "Willkommen bei ihrer Tierhandlung fr exotische Tiere. Geben sie help ein fr weitere Informationen"); String auswahl = br.readLine(); if (auswahl.equals("help")) { System.out.println("Sie haben folgende Auswahlmglichkeiten:"); System.out.println("1. Listen sie alle verfgbaren Tiere auf."); System.out.println("2. Kaufen sie ein Tier."); System.out.println("3. Suchen sie nach einem Tier."); System.out.println("4. Whrung ndern."); auswahl = br.readLine(); makeDecision(client, auswahl); } else { makeDecision(client, auswahl); } System.out.print("End"); }
From source file:POP3Demo.java
public static void main(String[] args) throws Exception { int POP3Port = 110; Socket client = new Socket("127.0.0.1", POP3Port); InputStream is = client.getInputStream(); BufferedReader sockin = new BufferedReader(new InputStreamReader(is)); OutputStream os = client.getOutputStream(); PrintWriter sockout = new PrintWriter(os, true); String cmd = "user Smith"; sockout.println(cmd);//w ww . j a va2 s .c o m String reply = sockin.readLine(); cmd = "pass "; sockout.println(cmd + "popPassword"); reply = sockin.readLine(); cmd = "stat"; sockout.println(cmd); reply = sockin.readLine(); if (reply == null) return; cmd = "retr 1"; sockout.println(cmd); if (cmd.toLowerCase().startsWith("retr") && reply.charAt(0) == '+') do { reply = sockin.readLine(); System.out.println("S:" + reply); if (reply != null && reply.length() > 0) if (reply.charAt(0) == '.') break; } while (true); cmd = "quit"; sockout.println(cmd); client.close(); }
From source file:JSON.JasonJSON.java
public static void main(String[] args) throws Exception { URL Url = new URL("http://api.wunderground.com/api/22b4347c464f868e/conditions/q/Colorado/COS.json"); //This next URL is still being played with. Some of the formatting is hard to figure out, but Wunderground //writes a perfectly formatted JSON file that is easy to read with Java. // URL Url = new URL("https://api.darksky.net/forecast/08959bb1e2c7eae0f3d1fafb5d538032/38.886,-104.7201"); try {//from w w w .j ava 2 s. co m HttpURLConnection urlCon = (HttpURLConnection) Url.openConnection(); // This part will read the data returned thru HTTP and load it into memory // I have this code left over from my CIT260 project. InputStream stream = urlCon.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } // The next lines read certain parts of the JSON data and print it out on the screen //Creates the JSONObject object and loads the JSON file from the URLConnection //Into a StringWriter object. I am printing this out in raw format just so I can see it doing something JSONObject json = new JSONObject(result.toString()); JSONObject coloradoInfo = (JSONObject) json.get("current_observation"); StringWriter out = new StringWriter(); json.write(out); String jsonTxt = json.toString(); System.out.print(jsonTxt); List<String> list = new ArrayList<>(); JSONArray array = json.getJSONArray(jsonTxt); System.out.print(jsonTxt); // for (int i =0;i<array.length();i++){ //list.add(array.getJSONObject(i).getString("current_observation")); //} String wunderGround = "Data downloaded from: " + coloradoInfo.getJSONObject("image").getString("title") + "\nLink\t\t: " + coloradoInfo.getJSONObject("image").getString("link") + "\nCity\t\t: " + coloradoInfo.getJSONObject("display_location").getString("city") + "\nState\t\t: " + coloradoInfo.getJSONObject("display_location").getString("state_name") + "\nTime\t\t: " + coloradoInfo.get("observation_time_rfc822") + "\nTemperature\t\t: " + coloradoInfo.get("temperature_string") + "\nWindchill\t\t: " + coloradoInfo.get("windchill_string") + "\nRelative Humidity\t: " + coloradoInfo.get("relative_humidity") + "\nWind\t\t\t: " + coloradoInfo.get("wind_string") + "\nWind Direction\t\t: " + coloradoInfo.get("wind_dir") + "\nBarometer Pressure\t\t: " + coloradoInfo.get("pressure_in"); System.out.println("\nColorado Springs Weather:"); System.out.println("____________________________________"); System.out.println(wunderGround); } catch (IOException e) { System.out.println("***ERROR*******************ERROR********************. " + "\nURL: " + Url.toString() + "\nERROR: " + e.toString()); } }
From source file:de.zib.vold.userInterface.ABI.java
public static void main(String[] args) { ABI abi = new ABI(); while (true) { try {//from w w w .ja v a2 s . c o m InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.print("#: "); String s = br.readLine(); if (null == s) break; String[] a = s.split("\\s+"); if (a.length < 1) { System.out.println("ERROR: The following commands are valid:"); System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*"); System.out.println("ERROR: lookup <scope> <type> <keyname>"); System.out.println("ERROR: exit"); continue; } else if (a[0].equals("lookup") || a[0].equals("l")) { if (a.length < 4) { System.out.println("ERROR: Syntax for lookup is:"); System.out.println("ERROR: lookup <scope> <type> <keyname>"); continue; } Map<Key, Set<String>> result; try { result = abi.frontend.lookup(new Key(a[1], a[2], a[3])); } catch (VoldException e) { System.out.println( "An internal error occured: " + e.getClass().getName() + ": " + e.getMessage()); continue; } for (Map.Entry<Key, Set<String>> entry : result.entrySet()) { Key k = entry.getKey(); System.out.println("+Found ('" + k.get_scope() + "', '" + k.get_type() + "', '" + k.get_keyname() + "')"); for (String v : entry.getValue()) { System.out.println("-" + v); } } } else if (a[0].equals("insert") || a[0].equals("i")) { if (a.length < 5) { System.out.println("ERROR: Syntax for insert is:"); System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*"); continue; } Key k = new Key(a[2], a[3], a[4]); Set<String> values = new HashSet<String>(); for (int i = 5; i < a.length; ++i) { values.add(a[i]); } try { abi.frontend.insert(a[1], k, values, DateTime.now().getMillis()); } catch (VoldException e) { System.out.println( "An internal error occured: " + e.getClass().getName() + ": " + e.getMessage()); continue; } } else if (a[0].equals("exit") || a[0].equals("x")) { break; } else { System.out.println("ERROR: Unknown command!"); System.out.println("ERROR: The following commands are valid:"); System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*"); System.out.println("ERROR: lookup <scope> <type> <keyname>"); System.out.println("ERROR: exit"); } } catch (IOException e) { e.printStackTrace(); } } System.exit(0); }
From source file:org.dlut.mycloudserver.service.performancemonitor.PerformanceListener.java
public static void main(String[] args) { long t1 = System.currentTimeMillis(); String url = "http://127.0.0.1:8001"; URLConnection conn;/* w ww. ja va 2s . co m*/ try { conn = new URL(url).openConnection(); conn.setConnectTimeout(1000); conn.setReadTimeout(1000); InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String res = br.readLine(); br.close(); is.close(); JSONObject jsonRes = JSON.parseObject(res); double loadAverage = jsonRes.getDoubleValue("loadAverage"); System.out.println(loadAverage); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } long t2 = System.currentTimeMillis(); System.out.println((t2 - t1) + "ms"); }
From source file:es.us.isa.ideas.utilities.HashPassword.java
public static void main(String[] args) throws IOException { Md5PasswordEncoder encoder;/* ww w .jav a 2 s .c o m*/ InputStreamReader stream; BufferedReader reader; String line, hash; encoder = new Md5PasswordEncoder(); stream = new InputStreamReader(System.in); reader = new BufferedReader(stream); System.out.println("Enter passwords to be hashed or <ENTER> to quit"); line = reader.readLine(); while (!line.isEmpty()) { hash = encoder.encodePassword(line, null); System.out.println(hash); line = reader.readLine(); } }
From source file:httpclient.client.ClientInteractiveAuthentication.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // Create local execution context HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet("http://localhost/test"); boolean trying = true; while (trying) { System.out.println("executing request " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget, localContext); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Consume response content HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent();// ww w .j av a 2s. co m } int sc = response.getStatusLine().getStatusCode(); AuthState authState = null; if (sc == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (authState != null) { System.out.println("----------------------------------------"); AuthScope authScope = authState.getAuthScope(); System.out.println("Please provide credentials"); System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort()); System.out.println(" Realm: " + authScope.getRealm()); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter username: "); String user = console.readLine(); System.out.print("Enter password: "); String password = console.readLine(); if (user != null && user.length() > 0) { Credentials creds = new UsernamePasswordCredentials(user, password); httpclient.getCredentialsProvider().setCredentials(authScope, creds); trying = true; } else { trying = false; } } else { trying = false; } } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
From source file:com.gemini.httpclienttest.HttpClientTestMain.java
public static void main(String[] args) { //authenticate with the server URL url;//w w w . jav a 2 s.c o m try { url = new URL("http://198.11.209.34:5000/v2.0/tokens"); } catch (MalformedURLException ex) { System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0"); return; } CloseableHttpClient httpclient = HttpClientBuilder.create().build(); try { HttpPost httpPost = new HttpPost(url.toString()); httpPost.setHeader("Content-Type", "application/json"); StringEntity strEntity = new StringEntity( "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}"); httpPost.setEntity(strEntity); //System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPost); try { //get the response status code String respStatus = response.getStatusLine().getReasonPhrase(); //get the response body int bytes = response.getEntity().getContent().available(); InputStream body = response.getEntity().getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(body)); String line; StringBuffer sbJSON = new StringBuffer(); while ((line = in.readLine()) != null) { sbJSON.append(line); } String json = sbJSON.toString(); EntityUtils.consume(response.getEntity()); GsonBuilder gsonBuilder = new GsonBuilder(); Object parsedJson = gsonBuilder.create().fromJson(json, Object.class); System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString()); if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) { com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson; if (treeJson.containsKey("id")) { String s = (String) treeJson.getOrDefault("id", "no key provided"); System.out.printf("\n\ntree contained id %s\n", s); } else { System.out.printf("\n\ntree does not contain key id\n"); } } } catch (IOException ex) { System.out.print(ex); } finally { response.close(); } } catch (IOException ex) { System.out.print(ex); } finally { //lots of exceptions, just the connection and exit try { httpclient.close(); } catch (IOException | NoSuchMethodError ex) { System.out.print(ex); return; } } }