List of usage examples for java.net URI URI
public URI(String str) throws URISyntaxException
From source file:Main.java
public static void main(String[] args) throws Exception { CookieManager cm = new CookieManager(); cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cm); new URL("http://google.com").openConnection().getContent(); CookieStore cookieStore = cm.getCookieStore(); List<HttpCookie> cookies = cookieStore.get(new URI("http://google.com")); for (HttpCookie cookie : cookies) { System.out.println("Name = " + cookie.getName()); System.out.println("Value = " + cookie.getValue()); System.out.println("Lifetime (seconds) = " + cookie.getMaxAge()); System.out.println("Path = " + cookie.getPath()); System.out.println();//from ww w. j av a2s. c om } }
From source file:Main.java
public static void main(String[] argv) throws Exception { HTMLDocument doc = new HTMLDocument() { public HTMLEditorKit.ParserCallback getReader(int pos) { return new HTMLEditorKit.ParserCallback() { public void handleText(char[] data, int pos) { System.out.println(data); }/* w w w. j ava 2s .c o m*/ }; } }; URL url = new URI("http://www.google.com").toURL(); URLConnection conn = url.openConnection(); Reader rd = new InputStreamReader(conn.getInputStream()); EditorKit kit = new HTMLEditorKit(); kit.read(rd, doc, 0); }
From source file:com.mellanox.jxio.helloworld.HelloClient.java
public static void main(String[] args) { if (args.length < 2) { usage();/*w w w .ja v a 2 s . c om*/ return; } final String serverhostname = args[0]; final int port = Integer.parseInt(args[1]); URI uri = null; try { uri = new URI("rdma://" + serverhostname + ":" + port + "/"); } catch (URISyntaxException e) { e.printStackTrace(); return; } HelloClient client = new HelloClient(); client.connect(uri); client.run(); LOG.info("Client is releasing JXIO resources and exiting"); client.releaseResources(); System.exit(client.exitStatus); }
From source file:HttpGet.java
public static void main(String[] args) { SocketChannel server = null; // Channel for reading from server FileOutputStream outputStream = null; // Stream to destination file WritableByteChannel destination; // Channel to write to it try { // Exception handling and channel closing code follows this block // Parse the URL. Note we use the new java.net.URI, not URL here. URI uri = new URI(args[0]); // Now query and verify the various parts of the URI String scheme = uri.getScheme(); if (scheme == null || !scheme.equals("http")) throw new IllegalArgumentException("Must use 'http:' protocol"); String hostname = uri.getHost(); int port = uri.getPort(); if (port == -1) port = 80; // Use default port if none specified String path = uri.getRawPath(); if (path == null || path.length() == 0) path = "/"; String query = uri.getRawQuery(); query = (query == null) ? "" : '?' + query; // Combine the hostname and port into a single address object. // java.net.SocketAddress and InetSocketAddress are new in Java 1.4 SocketAddress serverAddress = new InetSocketAddress(hostname, port); // Open a SocketChannel to the server server = SocketChannel.open(serverAddress); // Put together the HTTP request we'll send to the server. String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request "Host: " + hostname + "\r\n" + // Required in HTTP 1.1 "Connection: close\r\n" + // Don't keep connection open "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank // line // indicates // end of // request // headers // Now wrap a CharBuffer around that request string CharBuffer requestChars = CharBuffer.wrap(request); // Get a Charset object to encode the char buffer into bytes Charset charset = Charset.forName("ISO-8859-1"); // Use the charset to encode the request into a byte buffer ByteBuffer requestBytes = charset.encode(requestChars); // Finally, we can send this HTTP request to the server. server.write(requestBytes);/*from w w w . jav a2 s .c o m*/ // Set up an output channel to send the output to. if (args.length > 1) { // Use a specified filename outputStream = new FileOutputStream(args[1]); destination = outputStream.getChannel(); } else // Or wrap a channel around standard out destination = Channels.newChannel(System.out); // Allocate a 32 Kilobyte byte buffer for reading the response. // Hopefully we'll get a low-level "direct" buffer ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024); // Have we discarded the HTTP response headers yet? boolean skippedHeaders = false; // The code sent by the server int responseCode = -1; // Now loop, reading data from the server channel and writing it // to the destination channel until the server indicates that it // has no more data. while (server.read(data) != -1) { // Read data, and check for end data.flip(); // Prepare to extract data from buffer // All HTTP reponses begin with a set of HTTP headers, which // we need to discard. The headers end with the string // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already // skipped them then do so now. if (!skippedHeaders) { // First, though, read the HTTP response code. // Assume that we get the complete first line of the // response when the first read() call returns. Assume also // that the first 9 bytes are the ASCII characters // "HTTP/1.1 ", and that the response code is the ASCII // characters in the following three bytes. if (responseCode == -1) { responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0') + 1 * (data.get(11) - '0'); // If there was an error, report it and quit // Note that we do not handle redirect responses. if (responseCode < 200 || responseCode >= 300) { System.err.println("HTTP Error: " + responseCode); System.exit(1); } } // Now skip the rest of the headers. try { for (;;) { if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13) && (data.get() == 10)) { skippedHeaders = true; break; } } } catch (BufferUnderflowException e) { // If we arrive here, it means we reached the end of // the buffer and didn't find the end of the headers. // There is a chance that the last 1, 2, or 3 bytes in // the buffer were the beginning of the \r\n\r\n // sequence, so back up a bit. data.position(data.position() - 3); // Now discard the headers we have read data.compact(); // And go read more data from the server. continue; } } // Write the data out; drain the buffer fully. while (data.hasRemaining()) destination.write(data); // Now that the buffer is drained, put it into fill mode // in preparation for reading more data into it. data.clear(); // data.compact() also works here } } catch (Exception e) { // Report any errors that arise System.err.println(e); System.err.println("Usage: java HttpGet <URL> [<filename>]"); } finally { // Close the channels and output file stream, if needed try { if (server != null && server.isOpen()) server.close(); if (outputStream != null) outputStream.close(); } catch (IOException e) { } } }
From source file:com.mellanox.jxio.helloworld.HelloServer.java
public static void main(String[] args) { if (args.length < 2) { usage();//from ww w . j a v a 2 s . co m return; } final String serverhostname = args[0]; final int port = Integer.parseInt(args[1]); URI uri = null; try { uri = new URI("rdma://" + serverhostname + ":" + port + "/"); } catch (URISyntaxException e) { e.printStackTrace(); return; } HelloServer server = new HelloServer(uri); server.run(); LOG.info("Server is releasing JXIO resources and exiting"); server.releaseResources(); }
From source file:com.verizon.Main.java
public static void main(String[] args) throws Exception { String warehouseLocation = "file:" + System.getProperty("user.dir") + "spark-warehouse"; SparkSession spark = SparkSession.builder().appName("Verizon").config("spark.master", "local[2]") .config("spark.sql.warehouse.dir", warehouseLocation).enableHiveSupport().getOrCreate(); Configuration configuration = new Configuration(); configuration.addResource(new Path(System.getProperty("HADOOP_INSTALL") + "/conf/core-site.xml")); configuration.addResource(new Path(System.getProperty("HADOOP_INSTALL") + "/conf/hdfs-site.xml")); configuration.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); configuration.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); FileSystem hdfs = FileSystem.get(new URI("hdfs://localhost:9000"), configuration); SQLContext context = new SQLContext(spark); String schemaString = " Device,Title,ReviewText,SubmissionTime,UserNickname"; //spark.read().textFile(schemaString) Dataset<Row> df = spark.read().csv("hdfs://localhost:9000/data.csv"); //df.show();//from www.j a va2 s.com //#df.printSchema(); df = df.select("_c2"); Path file = new Path("hdfs://localhost:9000/tempFile.txt"); if (hdfs.exists(file)) { hdfs.delete(file, true); } df.write().csv("hdfs://localhost:9000/tempFile.txt"); JavaRDD<String> lines = spark.read().textFile("hdfs://localhost:9000/tempFile.txt").javaRDD(); JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() { @Override public Iterator<String> call(String s) { return Arrays.asList(SPACE.split(s)).iterator(); } }); JavaPairRDD<String, Integer> ones = words.mapToPair(new PairFunction<String, String, Integer>() { @Override public Tuple2<String, Integer> call(String s) { s = s.replaceAll("[^a-zA-Z0-9]+", ""); s = s.toLowerCase().trim(); return new Tuple2<>(s, 1); } }); JavaPairRDD<String, Integer> counts = ones.reduceByKey(new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer i1, Integer i2) { return i1 + i2; } }); JavaPairRDD<Integer, String> frequencies = counts .mapToPair(new PairFunction<Tuple2<String, Integer>, Integer, String>() { @Override public Tuple2<Integer, String> call(Tuple2<String, Integer> s) { return new Tuple2<Integer, String>(s._2, s._1); } }); frequencies = frequencies.sortByKey(false); JavaPairRDD<String, Integer> result = frequencies .mapToPair(new PairFunction<Tuple2<Integer, String>, String, Integer>() { @Override public Tuple2<String, Integer> call(Tuple2<Integer, String> s) throws Exception { return new Tuple2<String, Integer>(s._2, s._1); } }); //JavaPairRDD<Integer,String> sortedByFreq = sort(frequencies, "descending"); file = new Path("hdfs://localhost:9000/allresult.csv"); if (hdfs.exists(file)) { hdfs.delete(file, true); } //FileUtils.deleteDirectory(new File("allresult.csv")); result.saveAsTextFile("hdfs://localhost:9000/allresult.csv"); List<Tuple2<String, Integer>> output = result.take(250); ExportToHive hiveExport = new ExportToHive(); String rows = ""; for (Tuple2<String, Integer> tuple : output) { String date = new Date().toString(); String keyword = tuple._1(); Integer count = tuple._2(); //System.out.println( keyword+ "," +count); rows += date + "," + "Samsung Galaxy s7," + keyword + "," + count + System.lineSeparator(); } //System.out.println(rows); /* file = new Path("hdfs://localhost:9000/result.csv"); if ( hdfs.exists( file )) { hdfs.delete( file, true ); } OutputStream os = hdfs.create(file); BufferedWriter br = new BufferedWriter( new OutputStreamWriter( os, "UTF-8" ) ); br.write(rows); br.close(); */ hdfs.close(); FileUtils.deleteQuietly(new File("result.csv")); FileUtils.writeStringToFile(new File("result.csv"), rows); hiveExport.writeToHive(spark); ExportDataToServer exportServer = new ExportDataToServer(); exportServer.sendDataToRESTService(rows); spark.stop(); }
From source file:com.wolfsoftco.httpclient.RestClient.java
@SuppressWarnings("resource") public static void main(String[] args) { CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; try {// w w w.j a v a 2 s.c om HttpEntity entity = null; String responseHtml = null; httpclient = HttpClients.custom().build(); //Based on CURL line: //curl localhost:9090/oauth/token -d "grant_type=password&scope=write&username=greg&password=turnquist" -u foo:bar //clientid:secret String clientID = "foo:bar"; HttpUriRequest login = RequestBuilder.post().setUri(new URI(URL)) .addHeader("Authorization", "Basic " + Base64.encodeBase64String(clientID.getBytes())) .addParameter("grant_type", "password").addParameter("scope", "read") .addParameter("username", "greg").addParameter("password", "turnquist").build(); response = httpclient.execute(login); entity = response.getEntity(); responseHtml = EntityUtils.toString(entity); EntityUtils.consume(entity); JsonObject jsonObject = null; String token = null; if (responseHtml.startsWith("{")) { JsonParser parser = new JsonParser(); jsonObject = parser.parse(responseHtml).getAsJsonObject(); token = jsonObject.get("access_token").getAsString(); } if (token != null) { HttpGet request = new HttpGet(URL_FLIGHTS); request.addHeader("Authorization", "Bearer " + token); response = httpclient.execute(request); entity = response.getEntity(); responseHtml = EntityUtils.toString(entity); EntityUtils.consume(entity); System.out.println(responseHtml); } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (httpclient != null) httpclient.close(); if (response != null) response.close(); } catch (IOException e) { } } }
From source file:lab.mage.rate.example.NewsServer.java
public static void main(String[] args) throws Exception { // configure resource final ResourceConfig resourceConfig = new ResourceConfig(); // set news service final NewsService newsService = new NewsService(); resourceConfig.register(newsService); // set Jackson as JSON provider final ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.setDateFormat(new SimpleDateFormat(ISO_8601_DATE_PATTERN)); final JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(); provider.setMapper(mapper);/*from ww w . j a v a 2 s. com*/ resourceConfig.register(provider); // create Grizzly instance and add handler final HttpHandler handler = ContainerFactory.createContainer(GrizzlyHttpContainer.class, resourceConfig); final URI uri = new URI("http://localhost:4711/"); final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(uri); final ServerConfiguration config = server.getServerConfiguration(); config.addHttpHandler(handler, "/api"); // start server.start(); System.in.read(); }
From source file:inn.eatery.clientTest.Client.java
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;//from w w w . j a v a2 s .c o m } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { l.warn("Only HTTP(S) is supported."); return; } // Configure SSL context if necessary. final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); //p.addLast(new HttpClientCodec()); p.addLast("decoder", new HttpResponseDecoder()); p.addLast("encoder", new HttpRequestEncoder()); // Remove the following line if you don't want automatic content decompression. // p.addLast(new HttpContentDecompressor()); // Uncomment the following line if you don't want to handle HttpContents. //p.addLast(new HttpObjectAggregator(1048576)); p.addLast(new ClientHandler()); } }); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); ClientHandler.pubEvent(ch, ClientHandler.event); // Wait for the server to close the connection. ch.closeFuture().sync(); l.info("Closing Client side Connection !!!"); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); } }
From source file:com.msopentech.ThaliClient.ProxyDesktop.java
public static void main(String[] rgs) throws InterruptedException, URISyntaxException, IOException { final ProxyDesktop instance = new ProxyDesktop(); try {/*from w w w .j a v a 2s .co m*/ instance.initialize(); } catch (RuntimeException e) { System.out.println(e); } // Attempt to launch the default browser to our page if (Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(new URI("http://localhost:" + localWebserverPort)); } // Register to shutdown the server properly from a sigterm Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { instance.shutdown(); } }); // Let user press enter to kill the console session Console console = System.console(); if (console != null) { console.format("\nPress ENTER to exit.\n"); console.readLine(); instance.shutdown(); } else { // Don't exit on your own when running without a console (debugging in an IDE). while (true) { Thread.sleep(500); } } }