List of usage examples for java.io BufferedReader readLine
public String readLine() throws IOException
From source file:Grep0.java
public static void main(String[] args) throws IOException { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); if (args.length != 1) { System.err.println("Usage: MatchLines pattern"); System.exit(1);//from w w w . j a va2 s .c om } Pattern patt = Pattern.compile(args[0]); Matcher matcher = patt.matcher(""); String line = null; while ((line = is.readLine()) != null) { matcher.reset(line); if (matcher.find()) { System.out.println("MATCH: " + line); } } }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.FormFileUploaderClientApplication.java
/** * Run the program.//from ww w .j av a 2s. c om * * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value. */ public static void main(String[] args) { // takes file path from first program's argument if (args.length < 1) { logger.error("****** Path to input file must be first argument to program! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } String filePath = args[0]; File uploadFile = new File(filePath); if (!uploadFile.exists()) { logger.error("****** File does not exist at expected locations! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } if (args.length > 1) { serverUrl = args[1]; } logger.info("File to upload: " + filePath); CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverUrl); FileBody bin = new FileBody(uploadFile); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, bin).build(); httppost.setEntity(reqEntity); logger.info("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { logger.info("HTTP Response Status Line: " + response.getStatusLine()); // Expecting a 200 Status Code if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String reason = response.getStatusLine().getReasonPhrase(); logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode() + "] -- Reason (if available): " + reason); } else { HttpEntity resEntity = response.getEntity(); InputStream is = resEntity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String output; StringBuilder sb = new StringBuilder("Response data received:"); while ((output = in.readLine()) != null) { sb.append(System.getProperty("line.separator")); sb.append(output); } logger.info(sb.toString()); in.close(); EntityUtils.consume(resEntity); } } finally { response.close(); } } catch (Exception e) { logger.error("Caught exception: " + e.getMessage(), e); } finally { try { httpclient.close(); } catch (IOException e) { logger.warn("Exception closing HTTP client: " + e.getMessage(), e); } logger.info("DONE"); } }
From source file:edu.umd.cloud9.demo.DemoPackJSON.java
/** * Runs the demo.//from w w w. ja v a 2 s. c om */ public static void main(String[] args) throws IOException, JSONException { if (args.length != 2) { System.out.println("usage: [input] [output]"); System.exit(-1); } String infile = args[0]; String outfile = args[1]; sLogger.info("input: " + infile); sLogger.info("output: " + outfile); Configuration conf = new JobConf(); FileSystem fs = FileSystem.get(conf); SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, new Path(outfile), LongWritable.class, JSONObjectWritable.class); // read in raw text records, line separated BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile))); // the key LongWritable l = new LongWritable(); JSONObjectWritable json = new JSONObjectWritable(); long cnt = 0; String line; while ((line = data.readLine()) != null) { // write the record json.clear(); json.put("text", line); l.set(cnt); writer.append(l, json); cnt++; } data.close(); writer.close(); sLogger.info("Wrote " + cnt + " records."); }
From source file:mobisocial.nfcserver.DesktopNfcServer.java
public static void main(String[] args) { try {//w w w . j a v a 2 s.co m Contract server; if (args.length > 0 && args[0].equals("tcp")) { // recoverable failure; if args is null, length == 0. server = new TcpNdefServer(args); } else if (args.length > 0 && args[0].equals("junction")) { server = new JunctionNdefServer(args); } else { server = new BluetoothNdefServer(args); //Builder<BluetoothNdefServer>().build(); } String content = ConnectionHandoverManager.USER_HANDOVER_PREFIX + Base64.encodeBase64URLSafeString(getHandoverNdef(server.getHandoverUrl()).toByteArray()); System.out.println("Welcome to DesktopNfc!"); System.out.println("Service running on " + server.getHandoverUrl()); System.out.println("Your configuration QR is: " + QR.getQrl(content)); // QRL server.start(); NfcInterface nfc = getInstance(); final String PROMPT = "> "; BufferedReader lineReader = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.print(PROMPT); String line = lineReader.readLine().trim(); nfc.share(line); } } catch (Exception e) { e.printStackTrace(); } }
From source file:nl.raja.niruraji.pa.PlayGround.java
public static void main(String[] args) { try {/*w w w. j a v a 2 s . c o m*/ // create HTTP Client HttpClient httpClient = HttpClientBuilder.create().build(); String url = "http://buienradar.nl/Json/GetTwentyFourHourForecast?geolocationid=2751773"; // Create new getRequest with below mentioned URL HttpGet getRequest = new HttpGet(url); // Add additional header to getRequest which accepts application/xml data //getRequest.addHeader("accept", "application/xml"); // Execute your request and catch response HttpResponse response = httpClient.execute(getRequest); // Check for HTTP response code: 200 = success if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } String result = EntityUtils.toString(response.getEntity()); JSONObject myObject = new JSONObject(result); // Get-Capture Complete application/xml body response BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("============Output:============"); // Simply iterate through XML response and show on console. while ((output = br.readLine()) != null) { System.out.println(output); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:niclients.main.pubni.java
public static void main(String[] args) throws UnsupportedEncodingException { HttpClient client = new DefaultHttpClient(); if (commandparser(args)) { niname = addauthorityToNiname(niname, authority); }/*w w w .j av a 2 s . c o m*/ niname = niUtils.makenif(niname, filename); if (niname != null) { if (createpub()) { try { HttpResponse response = client.execute(post); int resp_code = response.getStatusLine().getStatusCode(); System.err.println("RESP_CODE: " + Integer.toString(resp_code)); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Niname creation failed!\n"); } } else { System.out.println("Command line parsing failed!\n"); } }
From source file:edu.asu.bscs.csiebler.calculatorrpc.CalcJavaClient.java
public static void main(String args[]) { try {//from w w w. jav a 2 s.c o m String url = "http://127.0.0.1:8080/"; if (args.length > 0) { url = args[0]; } CalcJavaClient cjc = new CalcJavaClient(url); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter end or {+|-|*|/} double double eg + 3 5 >"); String inStr = stdin.readLine(); StringTokenizer st = new StringTokenizer(inStr); String opn = st.nextToken(); while (!opn.equalsIgnoreCase("end")) { if (opn.equalsIgnoreCase("+")) { double result = cjc.add(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())); System.out.println("response: " + result); } else if (opn.equalsIgnoreCase("-")) { double result = cjc.subtract(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())); System.out.println("response: " + result); } else if (opn.equalsIgnoreCase("*")) { double result = cjc.multiply(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())); System.out.println("response: " + result); } else if (opn.equalsIgnoreCase("/")) { double result = cjc.divide(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())); System.out.println("response: " + result); } System.out.print("Enter end or {+|-|*|/} double double eg + 3 5 >"); 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:icevaluation.BingAPIAccess.java
public static void main(String[] args) { String searchText = "arts site:wikipedia.org"; searchText = searchText.replaceAll(" ", "%20"); // String accountKey="jTRIJt9d8DR2QT/Z3BJCAvY1BfoXj0zRYgSZ8deqHHo"; String accountKey = "JfeJSA3x6CtsyVai0+KEP0A6CYEUBT8VWhZmm9CS738"; byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes()); String accountKeyEnc = new String(accountKeyBytes); URL url;/* w w w . j a v a 2s . c o m*/ try { url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27" + searchText + "%27&$format=JSON"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder sb = new StringBuilder(); String output; System.out.println("Output from Server .... \n"); //write json to string sb int c = 0; if ((output = br.readLine()) != null) { System.out.println("Output is: " + output); sb.append(output); c++; //System.out.println("C:"+c); } conn.disconnect(); //find webtotal among output int find = sb.indexOf("\"WebTotal\":\""); int startindex = find + 12; System.out.println("Find: " + find); int lastindex = sb.indexOf("\",\"WebOffset\""); System.out.println(sb.substring(startindex, lastindex)); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:calendarevent.CalendarEvent.java
/** * @param args the command line arguments *//*from www . j ava 2s.co m*/ public static void main(String[] args) { // TODO code application logic here /* This has to be replaced with the json data coming from the getJsonData() method Expecting the Json will be in the format from the above methid. */ String jsonString = "{\n" + " \"kind\": \"calendar#events\",\n" + " \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/QElT1PHkP9d3G5VSndpdEMlSzKE\\\"\",\n" + " \"summary\": \"PushEvents\",\n" + " \"description\": \"Hackathon\",\n" + " \"updated\": \"2014-03-29T22:35:18.495Z\",\n" + " \"timeZone\": \"Asia/Calcutta\",\n" + " \"accessRole\": \"reader\",\n" + " \"items\": [\n" + " {\n" + " \"kind\": \"calendar#event\",\n" + " \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/MTM5NjEyNTQwNzcxMTAwMA\\\"\",\n" + " \"id\": \"q28lprjb8ad3m17955lf1p9d48\",\n" + " \"status\": \"confirmed\",\n" + " \"htmlLink\": \"https://www.google.com/calendar/event?eid=cTI4bHByamI4YWQzbTE3OTU1bGYxcDlkNDggM3RvcjdvamZxaWhlamNqNjduOWw0dDhnMmNAZw\",\n" + " \"created\": \"2014-03-29T20:36:47.000Z\",\n" + " \"updated\": \"2014-03-29T20:36:47.711Z\",\n" + " \"summary\": \"Test API\",\n" + " \"creator\": {\n" + " \"email\": \"vrohitrao@gmail.com\",\n" + " \"displayName\": \"Rohith Vallu\"\n" + " },\n" + " \"organizer\": {\n" + " \"email\": \"3tor7ojfqihejcj67n9l4t8g2c@group.calendar.google.com\",\n" + " \"displayName\": \"PushEvents\",\n" + " \"self\": true\n" + " },\n" + " \"start\": {\n" + " \"dateTime\": \"2014-03-30T02:30:00+05:30\"\n" + " },\n" + " \"end\": {\n" + " \"dateTime\": \"2014-03-30T03:30:00+05:30\"\n" + " },\n" + " \"iCalUID\": \"q28lprjb8ad3m17955lf1p9d48@google.com\",\n" + " \"sequence\": 0\n" + " },\n" + " {\n" + " \"kind\": \"calendar#event\",\n" + " \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/MTM5NjEzMjUzMjQxNzAwMA\\\"\",\n" + " \"id\": \"jgpue3stuo3js5qlsodob84voo\",\n" + " \"status\": \"confirmed\",\n" + " \"htmlLink\": \"https://www.google.com/calendar/event?eid=amdwdWUzc3R1bzNqczVxbHNvZG9iODR2b28gM3RvcjdvamZxaWhlamNqNjduOWw0dDhnMmNAZw\",\n" + " \"created\": \"2014-03-29T22:35:32.000Z\",\n" + " \"updated\": \"2014-03-29T22:35:32.417Z\",\n" + " \"summary\": \"Test Events\",\n" + " \"description\": \"Hack!!\",\n" + " \"location\": \"Northeastern University, Huntington Avenue, Boston, MA, United States\",\n" + " \"creator\": {\n" + " \"email\": \"vrohitrao@gmail.com\",\n" + " \"displayName\": \"Rohith Vallu\"\n" + " },\n" + " \"organizer\": {\n" + " \"email\": \"3tor7ojfqihejcj67n9l4t8g2c@group.calendar.google.com\",\n" + " \"displayName\": \"PushEvents\",\n" + " \"self\": true\n" + " },\n" + " \"start\": {\n" + " \"dateTime\": \"2014-03-30T04:30:00+05:30\"\n" + " },\n" + " \"end\": {\n" + " \"dateTime\": \"2014-03-30T19:30:00+05:30\"\n" + " },\n" + " \"visibility\": \"public\",\n" + " \"iCalUID\": \"jgpue3stuo3js5qlsodob84voo@google.com\",\n" + " \"sequence\": 0\n" + " }\n" + " ]\n" + "}"; Gson gson = new Gson(); try { JSONObject jsonData = new JSONObject(jsonString); JSONArray jsonArray = jsonData.getJSONArray("items"); JSONObject eventData; Event event = new Event(); for (int i = 0; i < jsonArray.length(); i++) { System.out.println(jsonArray.get(i).toString()); Items item = gson.fromJson(jsonArray.get(i).toString(), Items.class); event.setSummary(item.getSummary()); event.setLocation(item.getLocation()); /* Will be adding the attendees here ArrayList<EventAttendee> attendees = new ArrayList<EventAttendee>(); attendees.add(new EventAttendee().setEmail("attendeeEmail")); // ... event.setAttendees(attendees); */ Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + 3600000); DateTime start = new DateTime(startDate, TimeZone.getDefault().getDefault().getTimeZone("UTC")); event.setStart(new EventDateTime().setDateTime(start)); DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC")); event.setEnd(new EventDateTime().setDateTime(end)); HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); Calendar.Builder builder = new Calendar.Builder(transport, jsonFactory, null); String clientID = "937140966210.apps.googleusercontent.com"; String redirectURL = "urn:ietf:wg:oauth:2.0:oob"; String clientSecret = "qMFSb_cadYDG7uh3IDXWiMQY"; ArrayList<String> scope = new ArrayList<String>(); scope.add("https://www.googleapis.com/auth/calendar"); String url = new GoogleAuthorizationCodeRequestUrl(clientID, redirectURL, scope).build(); System.out.println("Go to the following link in your browser:"); System.out.println(url); // Read the authorization code from the standard input stream. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What is the authorization code?"); String code = in.readLine(); GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, clientID, clientSecret, redirectURL, code, redirectURL).execute(); GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response); Calendar service = new Calendar.Builder(transport, jsonFactory, credential).build(); Event createdEvent = service.events().insert(item.getSummary(), event).execute(); System.out.println(createdEvent.getId()); } } catch (Exception e) { e.printStackTrace(); } }
From source file:esg.security.yadis.XrdsDoc.java
/** * TODO: move this test harness to unit tests * @param args/* www.j av a2s . c om*/ * @throws IOException * @throws SAXException * @throws ParserConfigurationException * @throws XPathExpressionException * @throws XrdsParseException */ public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, XrdsParseException { String yadisDocFilePath = "/home/pjkersha/workspace/EsgYadisParser/data/yadis.xml"; XrdsDoc yadisParser = new XrdsDoc(); StringBuffer contents = new StringBuffer(); FileReader fileReader = new FileReader(yadisDocFilePath); BufferedReader in = new BufferedReader(fileReader); try { String text = null; while ((text = in.readLine()) != null) { contents.append(text); contents.append(System.getProperty("line.separator")); } in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } String yadisDocContent = contents.toString(); yadisParser.parse(yadisDocContent); }