List of usage examples for java.io BufferedReader BufferedReader
public BufferedReader(Reader in)
From source file:ebay.Ebay.java
/** * @param args the command line arguments *//*from w ww . j a v a 2 s. c o m*/ public static void main(String[] args) { HttpClient client = null; HttpResponse response = null; BufferedReader rd = null; Document doc = null; String xml = ""; EbayDAO<Producto> db = new EbayDAO<>(Producto.class); String busqueda; while (true) { busqueda = JOptionPane.showInputDialog(null, "ingresa una busqueda"); if (busqueda != null) { busqueda = busqueda.replaceAll(" ", "%20"); try { client = new DefaultHttpClient(); /* peticion GET */ HttpGet request = new HttpGet("http://open.api.ebay.com/shopping?" + "callname=FindPopularItems" + "&appid=student11-6428-4bd4-ac0d-6ed9d84e345" + "&version=517&QueryKeywords=" + busqueda + "&siteid=0" + "&responseencoding=XML"); /* se ejecuta la peticion GET */ response = client.execute(request); rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); /* comienza la lectura de la respuesta a la peticion GET */ String line; while ((line = rd.readLine()) != null) { xml += line + "\n"; } } catch (IOException ex) { Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex); } /* creamos nuestro documentBulder(documento constructor) y obtenemos nuestro objeto documento apartir de documentBuilder */ try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); } catch (ParserConfigurationException | SAXException | IOException ex) { Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex); } Element raiz = doc.getDocumentElement(); if (raiz == null) { System.exit(0); } if (raiz.getElementsByTagName("Ack").item(0).getTextContent().equals("Success")) { NodeList array = raiz.getElementsByTagName("ItemArray").item(0).getChildNodes(); for (int i = 0; i < array.getLength(); ++i) { Node n = array.item(i); if (n.getNodeType() != Node.TEXT_NODE) { Producto p = new Producto(); if (((Element) n).getElementsByTagName("ItemID").item(0) != null) p.setId(new Long( ((Element) n).getElementsByTagName("ItemID").item(0).getTextContent())); if (((Element) n).getElementsByTagName("EndTime").item(0) != null) p.setEndtime( ((Element) n).getElementsByTagName("EndTime").item(0).getTextContent()); if (((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch").item(0) != null) p.setViewurl(((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch") .item(0).getTextContent()); if (((Element) n).getElementsByTagName("ListingType").item(0) != null) p.setListingtype( ((Element) n).getElementsByTagName("ListingType").item(0).getTextContent()); if (((Element) n).getElementsByTagName("GalleryURL").item(0) != null) p.setGalleryurl( ((Element) n).getElementsByTagName("GalleryURL").item(0).getTextContent()); if (((Element) n).getElementsByTagName("PrimaryCategoryID").item(0) != null) p.setPrimarycategoryid(new Integer(((Element) n) .getElementsByTagName("PrimaryCategoryID").item(0).getTextContent())); if (((Element) n).getElementsByTagName("PrimaryCategoryName").item(0) != null) p.setPrimarycategoryname(((Element) n).getElementsByTagName("PrimaryCategoryName") .item(0).getTextContent()); if (((Element) n).getElementsByTagName("BidCount").item(0) != null) p.setBidcount(new Integer( ((Element) n).getElementsByTagName("BidCount").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ConvertedCurrentPrice").item(0) != null) p.setConvertedcurrentprice(new Double(((Element) n) .getElementsByTagName("ConvertedCurrentPrice").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ListingStatus").item(0) != null) p.setListingstatus(((Element) n).getElementsByTagName("ListingStatus").item(0) .getTextContent()); if (((Element) n).getElementsByTagName("TimeLeft").item(0) != null) p.setTimeleft( ((Element) n).getElementsByTagName("TimeLeft").item(0).getTextContent()); if (((Element) n).getElementsByTagName("Title").item(0) != null) p.setTitle(((Element) n).getElementsByTagName("Title").item(0).getTextContent()); if (((Element) n).getElementsByTagName("ShippingServiceCost").item(0) != null) p.setShippingservicecost(new Double(((Element) n) .getElementsByTagName("ShippingServiceCost").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ShippingType").item(0) != null) p.setShippingtype(((Element) n).getElementsByTagName("ShippingType").item(0) .getTextContent()); if (((Element) n).getElementsByTagName("WatchCount").item(0) != null) p.setWatchcount(new Integer( ((Element) n).getElementsByTagName("WatchCount").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ListedShippingServiceCost").item(0) != null) p.setListedshippingservicecost( new Double(((Element) n).getElementsByTagName("ListedShippingServiceCost") .item(0).getTextContent())); try { db.insert(p); } catch (Exception e) { db.update(p); } } } } Ventana.crear(xml); } else System.exit(0); } }
From source file:UseConverters.java
public static void main(String[] args) { try {/*from www . j ava 2 s .com*/ BufferedReader fromKanji = new BufferedReader( new InputStreamReader(new FileInputStream("kanji.txt"), "EUC_JP")); PrintWriter toSwedish = new PrintWriter(new OutputStreamWriter( // XXX // check // enco new FileOutputStream("sverige.txt"), "ISO8859_3")); // reading and writing here... String line = fromKanji.readLine(); System.out.println("-->" + line + "<--"); toSwedish.println(line); fromKanji.close(); toSwedish.close(); } catch (UnsupportedEncodingException exc) { System.err.println("Bad encoding" + exc); return; } catch (IOException err) { System.err.println("I/O Error: " + err); return; } }
From source file:com.mobius.software.mqtt.performance.controller.ControllerRunner.java
public static void main(String[] args) { try {/*from ww w . jav a 2s. co m*/ /*URI baseURI = URI.create(args[0].replace("-baseURI=", "")); configFile = args[1].replace("-configFile=", "");*/ String userDir = System.getProperty("user.dir"); System.out.println("user.dir: " + userDir); setConfigFilePath(userDir + "/config.properties"); Properties prop = new Properties(); prop.load(new FileInputStream(configFile)); System.out.println("properties loaded..."); String hostname = prop.getProperty("hostname"); Integer port = Integer.parseInt(prop.getProperty("port")); URI baseURI = new URI(null, null, hostname, port, null, null, null); configureConsoleLogger(); System.out.println("starting http server..."); JerseyServer server = new JerseyServer(baseURI); System.out.println("http server started"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("press any key to stop: "); br.readLine(); server.terminate(); } catch (Throwable e) { logger.error("AN ERROR OCCURED: " + e.getMessage()); e.printStackTrace(); } finally { System.exit(0); } }
From source file:leader.LeaderSelectorExample.java
public static void main(String[] args) throws Exception { // all of the useful sample code is in ExampleClient.java System.out.println("Create " + CLIENT_QTY + " clients, have each negotiate for leadership and then wait a random number of seconds before letting another leader election occur."); System.out.println(/*from w w w. j av a 2 s .c om*/ "Notice that leader election is fair: all clients will become leader and will do so the same number of times."); List<CuratorFramework> clients = Lists.newArrayList(); List<ExampleClient> examples = Lists.newArrayList(); TestingServer server = new TestingServer(); try { for (int i = 0; i < CLIENT_QTY; ++i) { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); clients.add(client); ExampleClient example = new ExampleClient(client, PATH, "Client #" + i); examples.add(example); client.start(); example.start(); } System.out.println("Press enter/return to quit\n"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } finally { System.out.println("Shutting down..."); for (ExampleClient exampleClient : examples) { IOUtils.closeQuietly(exampleClient); } for (CuratorFramework client : clients) { IOUtils.closeQuietly(client); } IOUtils.closeQuietly(server); } }
From source file:edu.umd.cloud9.demo.DemoPackJSON.java
/** * Runs the demo./*w ww . jav 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:AdminExample.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account. String user1Email = ""; //You need access to these two email account. String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. //joe@gmail.com will get email sent to joe+user1@gmail.com try {/* w w w . ja v a 2s. co m*/ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Adding user " + user1Email); //Add the users: User user = new User(); user.setEmail(user1Email); user.setAdmin(false); user.setLicensedSheetCreator(true); connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), user); Result<User> newUser1Result = mapper.readValue(connection.getInputStream(), new TypeReference<Result<User>>() { }); System.out.println( "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId()); user = new User(); user.setEmail(user2Email); user.setAdmin(true); user.setLicensedSheetCreator(true); connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), user); Result<User> newUser2Result = mapper.readValue(connection.getInputStream(), new TypeReference<Result<User>>() { }); System.out.println( "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId()); System.out.println("Please visit the email inbox for the users " + user1Email + " and " + user2Email + " and confirm membership to the account."); System.out.print("Press Enter to continue"); in.readLine(); //List all the users of the org connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() { }); System.out.println("The following are members of your account: "); for (User orgUser : users) { System.out.println("\t" + orgUser.getEmail()); } //Create a sheet as the admin Sheet newSheet = new Sheet(); newSheet.setName("Admin's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //Create a sheet as user1 newSheet = new Sheet(); newSheet.setName("User 1's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); //Here is where the magic happens - Any action performed in this call will be on behalf of the //user provided. Note that this person must be a confirmed member of your org. //Also note that the email address is url-encoded. connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //Create a sheet as user2 newSheet = new Sheet(); newSheet.setName("User 2's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //List all the sheets in the org: System.out.println("The following sheets are owned by members of your account: "); connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() { }); for (Sheet orgSheet : allSheets) { System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner()); } //Now delete user1 and transfer their sheets to user2 connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "") + "?transferTo=" + newUser2Result.getResult().getId()).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setRequestMethod("DELETE"); Result<Object> resultObject = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Object>>() { }); System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred()); } catch (IOException e) { InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream(); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result<?> result = mapper.readValue(response.toString(), Result.class); System.err.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } e.printStackTrace(); } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:com.interacciones.mxcashmarketdata.driver.util.AppropriateFormat.java
public static void main(String[] args) throws Throwable { init(args);// w ww . java2 s. c om long time = System.currentTimeMillis(); //for (;;) { try { //read file = new File(source); is = new FileInputStream(file); isr = new InputStreamReader(is); br = new BufferedReader(isr); //write filewrite = new File(destination); fos = new FileOutputStream(filewrite); bos = new BufferedOutputStream(fos); int data = 0; int count = 0; StringBuffer message = new StringBuffer(); while (data != -1) { data = br.read(); message.append((char) data); count++; if (data == 10) { transform(message); count = 0; message.delete(INIT_ASCII, message.length()); } } } catch (Exception e) { LOGGER.error("Warning " + e.getMessage()); e.printStackTrace(); } finally { close(); } //} time = System.currentTimeMillis() - time; LOGGER.info("Time " + time); }
From source file:com.leixl.easyframework.action.httpclient.TestHttpPost.java
public static void main(String[] args) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("uid", 1); paramMap.put("desc", "?????"); paramMap.put("payStatus", 1); //HttpConnUtils.postHttpContent(URL, paramMap); //HttpClient/*from w ww .j a v a 2 s .co m*/ HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(URL); // ?? NameValuePair[] data = { new NameValuePair("uid", "1"), new NameValuePair("desc", "?????"), new NameValuePair("payStatus", "1") }; // ?postMethod postMethod.setRequestBody(data); // postMethod int statusCode; try { statusCode = httpClient.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK) { StringBuffer contentBuffer = new StringBuffer(); InputStream in = postMethod.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in, postMethod.getResponseCharSet())); String inputLine = null; while ((inputLine = reader.readLine()) != null) { contentBuffer.append(inputLine); System.out.println("input line:" + inputLine); contentBuffer.append("/n"); } in.close(); } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // ??? Header locationHeader = postMethod.getResponseHeader("location"); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); System.out.println("The page was redirected to:" + location); } else { System.err.println("Location field value is null."); } } } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:TerminalMonitor.java
static public void main(String args[]) { DriverPropertyInfo[] required; StringBuffer buffer = new StringBuffer(); Properties props = new Properties(); boolean connected = false; Driver driver;/* ww w . j a v a 2s .com*/ String url; int line = 1; // Mark current input line if (args.length < 1) { System.out.println("Syntax: <java -Djdbc.drivers=DRIVER_NAME " + "TerminalMonitor JDBC_URL>"); return; } url = args[0]; // We have to get a reference to the driver so we can // find out what values to prompt the user for in order // to make a connection. try { driver = DriverManager.getDriver(url); } catch (SQLException e) { e.printStackTrace(); System.err.println("Unable to find a driver for the specified " + "URL."); System.err.println("Make sure you passed the jdbc.drivers " + "property on the command line to specify " + "the driver to be used."); return; } try { required = driver.getPropertyInfo(url, props); } catch (SQLException e) { e.printStackTrace(); System.err.println("Unable to get driver property information."); return; } input = new BufferedReader(new InputStreamReader(System.in)); // some drivers do not implement this properly // if that is the case, prompt for user name and password try { if (required.length < 1) { props.put("user", prompt("user: ")); props.put("password", prompt("password: ")); } else { // for each required attribute in the driver property info // prompt the user for the value for (int i = 0; i < required.length; i++) { if (!required[i].required) { continue; } props.put(required[i].name, prompt(required[i].name + ": ")); } } } catch (IOException e) { e.printStackTrace(); System.err.println("Unable to read property info."); return; } // Make the connection. try { connection = DriverManager.getConnection(url, props); } catch (SQLException e) { e.printStackTrace(); System.err.println("Unable to connect to the database."); } connected = true; System.out.println("Connected to " + url); // Enter into a user input loop while (connected) { String tmp, cmd; // Print a prompt if (line == 1) { System.out.print("TM > "); } else { System.out.print(line + " -> "); } System.out.flush(); // Get the next line of input try { tmp = input.readLine(); } catch (java.io.IOException e) { e.printStackTrace(); return; } // Get rid of extra space in the command cmd = tmp.trim(); // The user wants to commit pending transactions if (cmd.equals("commit")) { try { connection.commit(); System.out.println("Commit successful."); } catch (SQLException e) { System.out.println("Error in commit: " + e.getMessage()); } buffer = new StringBuffer(); line = 1; } // The user wants to execute the current buffer else if (cmd.equals("go")) { if (!buffer.equals("")) { try { executeStatement(buffer); } catch (SQLException e) { System.out.println(e.getMessage()); } } buffer = new StringBuffer(); line = 1; continue; } // The user wants to quit else if (cmd.equals("quit")) { connected = false; continue; } // The user wants to clear the current buffer else if (cmd.equals("reset")) { buffer = new StringBuffer(); line = 1; continue; } // The user wants to abort a pending transaction else if (cmd.equals("rollback")) { try { connection.rollback(); System.out.println("Rollback successful."); } catch (SQLException e) { System.out.println("An error occurred during rollback: " + e.getMessage()); } buffer = new StringBuffer(); line = 1; } // The user wants version info else if (cmd.startsWith("show")) { DatabaseMetaData meta; try { meta = connection.getMetaData(); cmd = cmd.substring(5, cmd.length()).trim(); if (cmd.equals("version")) { showVersion(meta); } else { System.out.println("show version"); // Bad arg } } catch (SQLException e) { System.out.println("Failed to load meta data: " + e.getMessage()); } buffer = new StringBuffer(); line = 1; } // The input that is not a keyword should appended be to the buffer else { buffer.append(" " + tmp); line++; continue; } } try { connection.close(); } catch (SQLException e) { System.out.println("Error closing connection: " + e.getMessage()); } System.out.println("Connection closed."); }
From source file:org.apache.olingo.odata2.fit.mapping.MappingTest.java
public static void main(final String[] args) { final TestServer server = new TestServer(ServletType.JAXRS_SERVLET); try {/* w w w .java 2 s. c om*/ server.startServer(MapFactory.class); System.out.println("Press any key to exit"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } catch (final IOException e) { e.printStackTrace(System.err); } finally { server.stopServer(); } }