List of usage examples for java.io InputStreamReader InputStreamReader
public InputStreamReader(InputStream in)
From source file:DropReceivedLines.java
public static void main(String[] av) { DropReceivedLines d = new DropReceivedLines(); // For stdin, act as a filter. For named files, // update each file in place (safely, by creating a new file). try {/*from w w w . j a va 2s . co m*/ if (av.length == 0) d.process(new BufferedReader(new InputStreamReader(System.in)), new PrintWriter(System.out)); else for (int i = 0; i < av.length; i++) d.process(av[i]); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println("I/O error " + e); } }
From source file:com.interacciones.mxcashmarketdata.driver.util.AppropriateFormat.java
public static void main(String[] args) throws Throwable { init(args);/*from w w w.j a v a 2 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:GoogleImages.java
public static void main(String[] args) throws InterruptedException { String searchTerm = "s woman"; // term to search for (use spaces to separate terms) int offset = 40; // we can only 20 results at a time - use this to offset and get more! String fileSize = "50mp"; // specify file size in mexapixels (S/M/L not figured out yet) String source = null; // string to save raw HTML source code // format spaces in URL to avoid problems searchTerm = searchTerm.replaceAll(" ", "%20"); // get Google image search HTML source code; mostly built from PhyloWidget example: // http://code.google.com/p/phylowidget/source/browse/trunk/PhyloWidget/src/org/phylowidget/render/images/ImageSearcher.java int offset2 = 0; Set urlsss = new HashSet<String>(); while (offset2 < 600) { try {/*from w w w . j av a 2 s .c om*/ URL query = new URL("https://www.google.ru/search?start=" + offset2 + "&q=angry+woman&newwindow=1&client=opera&hs=bPE&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiAgcKozIfNAhWoHJoKHSb_AUoQ_AUIBygB&biw=1517&bih=731&dpr=0.9#imgrc=G_1tH3YOPcc8KM%3A"); HttpURLConnection urlc = (HttpURLConnection) query.openConnection(); // start connection... urlc.setInstanceFollowRedirects(true); urlc.setRequestProperty("User-Agent", ""); urlc.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); // stream in HTTP source to file StringBuffer response = new StringBuffer(); char[] buffer = new char[1024]; while (true) { int charsRead = in.read(buffer); if (charsRead == -1) { break; } response.append(buffer, 0, charsRead); } in.close(); // close input stream (also closes network connection) source = response.toString(); } // any problems connecting? let us know catch (Exception e) { e.printStackTrace(); } // print full source code (for debugging) // println(source); // extract image URLs only, starting with 'imgurl' if (source != null) { // System.out.println(source); int c = StringUtils.countMatches(source, "http://www.vmir.su"); System.out.println(c); int index = source.indexOf("src="); System.out.println(source.subSequence(index, index + 200)); while (index >= 0) { System.out.println(index); index = source.indexOf("src=", index + 1); if (index == -1) { break; } String rr = source.substring(index, index + 200 > source.length() ? source.length() : index + 200); if (rr.contains("\"")) { rr = rr.substring(5, rr.indexOf("\"", 5)); } System.out.println(rr); urlsss.add(rr); } } offset2 += 20; Thread.sleep(1000); System.out.println("off set = " + offset2); } System.out.println(urlsss); urlsss.forEach(new Consumer<String>() { public void accept(String s) { try { saveImage(s, "C:\\Users\\Java\\Desktop\\ang\\" + UUID.randomUUID().toString() + ".jpg"); } catch (IOException ex) { Logger.getLogger(GoogleImages.class.getName()).log(Level.SEVERE, null, ex); } } }); // String[][] m = matchAll(source, "img height=\"\\d+\" src=\"([^\"]+)\""); // older regex, no longer working but left for posterity // built partially from: http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression // String[][] m = matchAll(source, "imgurl=(.*?\\.(?i)(jpg|jpeg|png|gif|bmp|tif|tiff))"); // (?i) means case-insensitive // for (int i = 0; i < m.length; i++) { // iterate all results of the match // println(i + ":\t" + m[i][1]); // print (or store them)** // } }
From source file:ebay.Ebay.java
/** * @param args the command line arguments *//*from w ww .j a va2s .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:com.mobius.software.mqtt.performance.controller.ControllerRunner.java
public static void main(String[] args) { try {//from w w w . j a v a 2s . c o 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(// www. jav a 2s. c o m "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./* ww w.j a v a2 s.co m*/ */ 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 {/*from w ww.j a va2 s .c o 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:ScanStreamTok.java
public static void main(String[] av) throws IOException { if (av.length == 0) new ScanStreamTok(new InputStreamReader(System.in)).process(); else//www . j a v a 2 s . com for (int i = 0; i < av.length; i++) new ScanStreamTok(av[i]).process(); }
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;/*w w w.j a v a2s .c o m*/ 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."); }