List of usage examples for java.net URL openStream
public final InputStream openStream() throws java.io.IOException
From source file:main.java.demo.jaxrs.client.Client.java
public static void main(String args[]) throws Exception { // Sent HTTP GET request to query all customer info /*/*from www. jav a 2 s . c om*/ * URL url = new URL("http://localhost:9000/customers"); * System.out.println("Invoking server through HTTP GET to query all * customer info"); InputStream in = url.openStream(); StreamSource * source = new StreamSource(in); printSource(source); */ // Sent HTTP GET request to query customer info System.out.println("Sent HTTP GET request to query customer info"); URL url = new URL("http://localhost:8989/RestFull/service1/customerservice/customers/123"); InputStream in = url.openStream(); System.out.println(getStringFromInputStream(in)); // Sent HTTP GET request to query sub resource product info System.out.println("\n"); System.out.println("Sent HTTP GET request to query sub resource product info"); url = new URL("http://localhost:9000/customerservice/orders/223/products/323"); in = url.openStream(); System.out.println(getStringFromInputStream(in)); // Sent HTTP PUT request to update customer info System.out.println("\n"); System.out.println("Sent HTTP PUT request to update customer info"); Client client = new Client(); String inputFile = client.getClass().getResource("update_customer.xml").getFile(); URIResolver resolver = new URIResolver(inputFile); File input = new File(resolver.getURI()); PutMethod put = new PutMethod("http://localhost:9000/customerservice/customers"); RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); put.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); try { int result = httpclient.executeMethod(put); System.out.println("Response status code: " + result); System.out.println("Response body: "); System.out.println(put.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are // done put.releaseConnection(); } // Sent HTTP POST request to add customer System.out.println("\n"); System.out.println("Sent HTTP POST request to add customer"); inputFile = client.getClass().getResource("add_customer.xml").getFile(); resolver = new URIResolver(inputFile); input = new File(resolver.getURI()); PostMethod post = new PostMethod("http://localhost:9000/customerservice/customers"); post.addRequestHeader("Accept", "text/xml"); entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); httpclient = new HttpClient(); try { int result = httpclient.executeMethod(post); System.out.println("Response status code: " + result); System.out.println("Response body: "); System.out.println(post.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are // done post.releaseConnection(); } System.out.println("\n"); System.exit(0); }
From source file:main.java.client.Client.java
public static void main(String args[]) throws Exception { // Sent HTTP GET request to query all customer info /*//from w w w. j a va2s. c om * URL url = new URL("http://localhost:9000/customers"); * System.out.println("Invoking server through HTTP GET to query all * customer info"); InputStream in = url.openStream(); StreamSource * source = new StreamSource(in); printSource(source); */ // Sent HTTP GET request to query customer info System.out.println("Sent HTTP GET request to query customer info"); URL url = new URL("http://localhost:8080/authenticate/customers/123"); InputStream in = url.openStream(); System.out.println(getStringFromInputStream(in)); // Sent HTTP GET request to query sub resource product info System.out.println("\n"); System.out.println("Sent HTTP GET request to query sub resource product info"); url = new URL("http://localhost:9000/authenticate/orders/223/products/323"); in = url.openStream(); System.out.println(getStringFromInputStream(in)); // Sent HTTP PUT request to update customer info System.out.println("\n"); System.out.println("Sent HTTP PUT request to update customer info"); Client client = new Client(); String inputFile = client.getClass().getResource("/update_customer.xml").getFile(); URIResolver resolver = new URIResolver(inputFile); File input = new File(resolver.getURI()); PutMethod put = new PutMethod("http://localhost:9000/authenticate/customers"); RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); put.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); try { int result = httpclient.executeMethod(put); System.out.println("Response status code: " + result); System.out.println("Response body: "); System.out.println(put.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are // done put.releaseConnection(); } // Sent HTTP POST request to add customer System.out.println("\n"); System.out.println("Sent HTTP POST request to add customer"); inputFile = client.getClass().getResource("/add_customer.xml").getFile(); resolver = new URIResolver(inputFile); input = new File(resolver.getURI()); PostMethod post = new PostMethod("http://localhost:9000/authenticate/customers"); post.addRequestHeader("Accept", "text/xml"); entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); httpclient = new HttpClient(); try { int result = httpclient.executeMethod(post); System.out.println("Response status code: " + result); System.out.println("Response body: "); System.out.println(post.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are // done post.releaseConnection(); } // Sent HTTP POST request to add json customer System.out.println("\n"); System.out.println("Sent HTTP POST request to add json customer"); String inputFilej = client.getClass().getResource("/add_customer.json").getFile(); URIResolver resolverj = new URIResolver(inputFilej); File inputj = new File(resolverj.getURI()); PostMethod postj = new PostMethod("http://localhost:9000/authenticate/customersjson"); postj.addRequestHeader("Accept", "application/json"); RequestEntity entityj = new FileRequestEntity(inputj, "application/json; charset=ISO-8859-1"); postj.setRequestEntity(entityj); HttpClient httpclientj = new HttpClient(); try { int resultj = httpclientj.executeMethod(postj); System.out.println("Response status code json: " + resultj); System.out.println("Response body json: "); System.out.println(postj.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are // done postj.releaseConnection(); } System.out.println("\n"); System.exit(0); }
From source file:com.adobe.aem.demomachine.Updates.java
public static void main(String[] args) { String rootFolder = null;/*ww w . j a v a 2s. c om*/ // Command line options for this tool Options options = new Options(); options.addOption("f", true, "Demo Machine root folder"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("f")) { rootFolder = cmd.getOptionValue("f"); } } catch (Exception e) { System.exit(-1); } Properties md5properties = new Properties(); try { URL url = new URL( "https://raw.githubusercontent.com/Adobe-Marketing-Cloud/aem-demo-machine/master/conf/checksums.properties"); InputStream in = url.openStream(); Reader reader = new InputStreamReader(in, "UTF-8"); md5properties.load(reader); reader.close(); } catch (Exception e) { System.out.println("Error: Cannot connect to GitHub.com to check for updates"); System.exit(-1); } System.out.println(AemDemoConstants.HR); int nbUpdateAvailable = 0; List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths); for (String[] path : listPaths) { if (path.length == 5) { logger.debug(path[1]); File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : "")); if (pathFolder.exists()) { String newMd5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]), false); logger.debug("MD5 is: " + newMd5); String oldMd5 = md5properties.getProperty("demo.md5." + path[0]); if (oldMd5 == null || oldMd5.length() == 0) { logger.error("Cannot find MD5 for " + path[0]); System.out.println(path[2] + " : Cannot find M5 checksum"); continue; } if (newMd5.equals(oldMd5)) { continue; } else { System.out.println(path[2] + " : New update available" + (path[0].equals("0") ? " (use 'git pull' to get the latest changes)" : "")); nbUpdateAvailable++; } } else { System.out.println(path[2] + " : Not installed"); } } } if (nbUpdateAvailable == 0) { System.out.println("Your AEM Demo Machine is up to date!"); } System.out.println(AemDemoConstants.HR); }
From source file:com.cyclopsgroup.waterview.jelly.JellyScriptsRunner.java
/** * Main entry to run a script// w ww. j a v a2s . com * * @param args Script paths * @throws Exception Throw it out */ public static final void main(String[] args) throws Exception { List scripts = new ArrayList(); for (int i = 0; i < args.length; i++) { String path = args[i]; File file = new File(path); if (file.isFile()) { scripts.add(file.toURL()); } else { Enumeration enu = JellyScriptsRunner.class.getClassLoader().getResources(path); CollectionUtils.addAll(scripts, enu); } } if (scripts.isEmpty()) { System.out.println("No script to run, return!"); return; } String basedir = new File("").getAbsolutePath(); Properties initProperties = new Properties(System.getProperties()); initProperties.setProperty("basedir", basedir); initProperties.setProperty("plexus.home", basedir); WaterviewPlexusContainer container = new WaterviewPlexusContainer(); for (Iterator j = initProperties.keySet().iterator(); j.hasNext();) { String initPropertyName = (String) j.next(); container.addContextValue(initPropertyName, initProperties.get(initPropertyName)); } container.addContextValue(Waterview.INIT_PROPERTIES, initProperties); container.initialize(); container.start(); JellyEngine je = (JellyEngine) container.lookup(JellyEngine.ROLE); JellyContext jc = new JellyContext(je.getGlobalContext()); XMLOutput output = XMLOutput.createXMLOutput(System.out); for (Iterator i = scripts.iterator(); i.hasNext();) { URL script = (URL) i.next(); System.out.print("Running script " + script); ExtendedProperties ep = new ExtendedProperties(); ep.putAll(initProperties); ep.load(script.openStream()); for (Iterator j = ep.getKeys("script"); j.hasNext();) { String name = (String) j.next(); if (name.endsWith(".file")) { File file = new File(ep.getString(name)); if (file.exists()) { System.out.println("Runner jelly file " + file); jc.runScript(file, output); } } else if (name.endsWith(".resource")) { Enumeration k = JellyScriptsRunner.class.getClassLoader().getResources(ep.getString(name)); while (j != null && k.hasMoreElements()) { URL s = (URL) k.nextElement(); System.out.println("Running jelly script " + s); jc.runScript(s, output); } } } //jc.runScript( script, XMLOutput.createDummyXMLOutput() ); System.out.println("... Done!"); } container.dispose(); }
From source file:io.janusproject.Boot.java
/** Main function that is parsing the command line and launching * the first agent./*w w w . j a v a2 s. c om*/ * * @param args - command line arguments * @see #startJanus(Class, Class, Object...) */ public static void main(String[] args) { try { List<URL> propertyFiles = new ArrayList<>(); Object[] freeArgs = parseCommandLine(args, propertyFiles); if (JanusConfig.getSystemPropertyAsBoolean(JanusConfig.JANUS_LOGO_SHOW_NAME, JanusConfig.JANUS_LOGO_SHOW)) { showJanusLogo(); } if (freeArgs.length == 0) { showError(Locale.getString("NO_AGENT_QUALIFIED_NAME"), //$NON-NLS-1$ null); } String agentToLaunch = freeArgs[0].toString(); freeArgs = Arrays.copyOfRange(freeArgs, 1, freeArgs.length, String[].class); // Load the agent class Class<? extends Agent> agent = loadAgentClass(agentToLaunch); assert (agent != null); // Load property files Properties systemProperties = System.getProperties(); for (URL url : propertyFiles) { try (InputStream stream = url.openStream()) { systemProperties.load(stream); } } // Set the boot agent classname System.setProperty(JanusConfig.BOOT_AGENT, agent.getCanonicalName()); startJanus(null, (Class<? extends Agent>) agent, freeArgs); } catch (Exception e) { showError(Locale.getString("LAUNCHING_ERROR", //$NON-NLS-1$ e.getLocalizedMessage()), e); return; } }
From source file:com.adhi.webserver.WebServer.java
public static void main(String[] args) throws Exception { int port = 9999; // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build();//w w w .jav a 2s .c o m // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new MessageCommandHandler()); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = WebServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); }
From source file:proxy.NHttpServer.java
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1);//from w w w .j av a 2 s .co m } // Document root directory File docRoot = new File(args[0]); int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } // Create HTTP protocol processing chain HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Create request handler registry UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper(); // Register the default handler for all URIs reqistry.register("*", new HttpFileHandler(docRoot)); // Create server-side HTTP protocol handler HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, reqistry) { @Override public void connected(final NHttpServerConnection conn) { System.out.println(conn + ": connection open"); super.connected(conn); } @Override public void closed(final NHttpServerConnection conn) { System.out.println(conn + ": connection closed"); super.closed(conn); } }; // Create HTTP connection factory NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory; if (port == 8443) { // Initialize SSL context ClassLoader cl = NHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT); } else { connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT); } // Create server-side I/O event dispatch IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory); // Set I/O reactor defaults IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).setSoTimeout(3000) .setConnectTimeout(3000).build(); // Create server-side I/O reactor ListeningIOReactor ioReactor = new DefaultListeningIOReactor(config); try { // Listen of the given port ioReactor.listen(new InetSocketAddress(port)); // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); }
From source file:com.bfd.job.testClient.t04.ElementalHttpServer.java
public static void main(String[] args) throws Exception { /**//from w w w.j av a2 s.c o m * if (args.length < 1) { * System.err.println("Please specify document root directory"); * System.exit(1); } // Document root directory String docRoot = * args[0]; */ String docRoot = "c:/root"; int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpFileHandler(docRoot)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = ElementalHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); }
From source file:yucatan.communication.server.NHttpServer.java
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1);/*w ww . j a v a 2s. c o m*/ } // Document root directory File docRoot = new File(args[0]); int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } // HTTP parameters for the server HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpTest/1.1"); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { // Use standard server-side protocol interceptors new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); // Create request handler registry HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry(); // Register the default handler for all URIs reqistry.register("*", new HttpFileHandler(docRoot)); // Create server-side HTTP protocol handler HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, new DefaultConnectionReuseStrategy(), reqistry, params) { @Override public void connected(final NHttpServerConnection conn) { System.out.println(conn + ": connection open"); super.connected(conn); } @Override public void closed(final NHttpServerConnection conn) { System.out.println(conn + ": connection closed"); super.closed(conn); } }; // Create HTTP connection factory NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory; if (port == 8443) { // Initialize SSL context ClassLoader cl = NHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, params); } else { connFactory = new DefaultNHttpServerConnectionFactory(params); } // Create server-side I/O event dispatch IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory); // Create server-side I/O reactor ListeningIOReactor ioReactor = new DefaultListeningIOReactor(); try { // Listen of the given port ioReactor.listen(new InetSocketAddress(port)); // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); }
From source file:httpserver.ElementalHttpServer.java
public static void main(String[] args) throws Exception { // Clay code, adding arguments to simulate command line execution args = new String[2]; args[0] = "C://Users/Clay/Documents"; args[1] = "80"; if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1);/*from w w w . ja va 2 s .c om*/ } // Document root directory String docRoot = args[0]; // Setting up port, if port was specified, then use that one int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpFileHandler(docRoot)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = ElementalHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); }