List of usage examples for java.io InputStreamReader InputStreamReader
public InputStreamReader(InputStream in)
From source file:ReadHeaders.java
/** Main program showing how to use it */ public static void main(String[] av) { switch (av.length) { case 0:/*w ww . j a v a 2 s .co m*/ ReadHeaders r = new ReadHeaders(new BufferedReader(new InputStreamReader(System.in))); printit(r); break; default: for (int i = 0; i < av.length; i++) try { ReadHeaders rr = new ReadHeaders(new BufferedReader(new FileReader(av[i]))); printit(rr); } catch (FileNotFoundException e) { System.err.println(e); } break; } }
From source file:com.jff.searchapicluster.server.mina.Server.java
public static void main(String[] args) throws Throwable { org.apache.commons.configuration.Configuration config = new PropertiesConfiguration("settings.txt"); int serverPort = config.getInt("listenPort"); NioSocketAcceptor acceptor = new NioSocketAcceptor(); acceptor.getFilterChain().addLast("com/jff/searchapicluster/core/mina/codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); acceptor.getFilterChain().addLast("logger", new LoggingFilter()); acceptor.setHandler(new ServerSessionHandler()); acceptor.bind(new InetSocketAddress(serverPort)); System.out.println("Listening on port " + serverPort); System.out.println("Please enter filename"); // open up standard input BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true) { String filepath = br.readLine(); filepath = "/Users/admin/repos/study_repos/kurs_sp/search_api_cluster/SearchApiClusterServer/task.json"; File file = new File(filepath); Logger.d(LOG_TAG, file.getAbsolutePath()); if (file.exists() && file.isFile()) { Gson gson = new Gson(); SearchTask taskMessage = gson.fromJson(new FileReader(file), SearchTask.class); ServerManager serverManager = ServerManager.getInstance(); Logger.d(LOG_TAG, taskMessage.toString()); serverManager.startProcessTask(taskMessage); } else {/* ww w . ja va 2s .co m*/ Logger.d(LOG_TAG, filepath + "not found"); } } }
From source file:com.gemini.httpclienttest.HttpClientTestMain.java
public static void main(String[] args) { //authenticate with the server URL url;//from w ww . j a va 2 s. c o m try { url = new URL("http://198.11.209.34:5000/v2.0/tokens"); } catch (MalformedURLException ex) { System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0"); return; } CloseableHttpClient httpclient = HttpClientBuilder.create().build(); try { HttpPost httpPost = new HttpPost(url.toString()); httpPost.setHeader("Content-Type", "application/json"); StringEntity strEntity = new StringEntity( "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}"); httpPost.setEntity(strEntity); //System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPost); try { //get the response status code String respStatus = response.getStatusLine().getReasonPhrase(); //get the response body int bytes = response.getEntity().getContent().available(); InputStream body = response.getEntity().getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(body)); String line; StringBuffer sbJSON = new StringBuffer(); while ((line = in.readLine()) != null) { sbJSON.append(line); } String json = sbJSON.toString(); EntityUtils.consume(response.getEntity()); GsonBuilder gsonBuilder = new GsonBuilder(); Object parsedJson = gsonBuilder.create().fromJson(json, Object.class); System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString()); if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) { com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson; if (treeJson.containsKey("id")) { String s = (String) treeJson.getOrDefault("id", "no key provided"); System.out.printf("\n\ntree contained id %s\n", s); } else { System.out.printf("\n\ntree does not contain key id\n"); } } } catch (IOException ex) { System.out.print(ex); } finally { response.close(); } } catch (IOException ex) { System.out.print(ex); } finally { //lots of exceptions, just the connection and exit try { httpclient.close(); } catch (IOException | NoSuchMethodError ex) { System.out.print(ex); return; } } }
From source file:cmd.freebase2rdf.java
public static void main(String[] args) throws Exception { if (args.length != 2) { usage();/*from w ww.j a v a 2 s . co m*/ } File input = new File(args[0]); if (!input.exists()) error("File " + input.getAbsolutePath() + " does not exist."); if (!input.canRead()) error("Cannot read file " + input.getAbsolutePath()); if (!input.isFile()) error("Not a file " + input.getAbsolutePath()); File output = new File(args[1]); if (output.exists()) error("Output file " + output.getAbsolutePath() + " already exists, this program do not override existing files."); if (output.canWrite()) error("Cannot write file " + output.getAbsolutePath()); if (output.isDirectory()) error("Not a file " + output.getAbsolutePath()); if (!output.getName().endsWith(".nt.gz")) error("Output filename should end with .nt.gz, this is the only format supported."); BufferedReader in = new BufferedReader( new InputStreamReader(new BZip2CompressorInputStream(new FileInputStream(input)))); BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(output))); String line; ProgressLogger progressLogger = new ProgressLogger(log, "lines", 100000, 1000000); progressLogger.start(); Freebase2RDF freebase2rdf = null; try { freebase2rdf = new Freebase2RDF(out); while ((line = in.readLine()) != null) { freebase2rdf.send(line); progressLogger.tick(); } } finally { if (freebase2rdf != null) freebase2rdf.close(); } print(log, progressLogger); }
From source file:com.liferay.nativity.test.TestDriver.java
public static void main(String[] args) { _intitializeLogging();/* w w w . j a v a2s. co m*/ List<String> items = new ArrayList<String>(); items.add("ONE"); NativityMessage message = new NativityMessage("BLAH", items); try { _logger.debug(_objectMapper.writeValueAsString(message)); } catch (JsonProcessingException jpe) { _logger.error(jpe.getMessage(), jpe); } _logger.debug("main"); NativityControl nativityControl = NativityControlUtil.getNativityControl(); FileIconControl fileIconControl = FileIconControlUtil.getFileIconControl(nativityControl, new TestFileIconControlCallback()); ContextMenuControlUtil.getContextMenuControl(nativityControl, new TestContextMenuControlCallback()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); nativityControl.connect(); String read = ""; boolean stop = false; try { while (!stop) { _list = !_list; _logger.debug("Loop start..."); _logger.debug("_enableFileIcons"); _enableFileIcons(fileIconControl); _logger.debug("_registerFileIcon"); _registerFileIcon(fileIconControl); _logger.debug("_setFilterPath"); _setFilterPath(nativityControl); _logger.debug("_setSystemFolder"); _setSystemFolder(nativityControl); _logger.debug("_updateFileIcon"); _updateFileIcon(fileIconControl); _logger.debug("_clearFileIcon"); _clearFileIcon(fileIconControl); _logger.debug("Ready?"); if (bufferedReader.ready()) { _logger.debug("Reading..."); read = bufferedReader.readLine(); _logger.debug("Read {}", read); if (read.length() > 0) { stop = true; } _logger.debug("Stopping {}", stop); } } } catch (IOException e) { _logger.error(e.getMessage(), e); } _logger.debug("Done"); }
From source file:com.yahoo.athenz.example.http.tls.client.HttpTLSClient.java
public static void main(String[] args) { // parse our command line to retrieve required input CommandLine cmd = parseCommandLine(args); final String url = cmd.getOptionValue("url"); final String keyPath = cmd.getOptionValue("key"); final String certPath = cmd.getOptionValue("cert"); final String trustStorePath = cmd.getOptionValue("trustStorePath"); final String trustStorePassword = cmd.getOptionValue("trustStorePassword"); // we are going to setup our service private key and // certificate into a ssl context that we can use with // our http client try {//from w w w.j a v a 2 s.c o m KeyRefresher keyRefresher = Utils.generateKeyRefresher(trustStorePath, trustStorePassword, certPath, keyPath); SSLContext sslContext = Utils.buildSSLContext(keyRefresher.getKeyManagerProxy(), keyRefresher.getTrustManagerProxy()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection(); con.setReadTimeout(15000); con.setDoOutput(true); con.connect(); try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) { StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println("Data output: " + sb.toString()); } } catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); ex.printStackTrace(); System.exit(1); } }
From source file:com.manning.blogapps.chapter10.examples.AuthPostJava.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("USAGE: authpost <username> <password> <filepath> <url>"); System.exit(-1);//from www .j a va 2 s .com } String credentials = args[0] + ":" + args[1]; String filepath = args[2]; URL url = new URL(args[3]); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(credentials.getBytes()))); File upload = new File(filepath); conn.setRequestProperty("name", upload.getName()); String contentType = "application/atom+xml; charset=utf8"; if (filepath.endsWith(".gif")) contentType = "image/gif"; else if (filepath.endsWith(".jpg")) contentType = "image/jpg"; conn.setRequestProperty("Content-type", contentType); BufferedInputStream filein = new BufferedInputStream(new FileInputStream(upload)); BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream()); byte buffer[] = new byte[8192]; for (int count = 0; count != -1;) { count = filein.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } filein.close(); out.close(); String s = null; BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((s = in.readLine()) != null) { System.out.println(s); } }
From source file:Server_socket.java
public static void main(String argv[]) throws Exception { int puerto = Integer.parseInt(argv[0]); //String username = argv[1]; //String password = argv[2]; String clientformat;/* www. j a v a2s . com*/ String clientdata; String clientresult; String clientresource; String url_login = "http://localhost:3000/users/sign_in"; ServerSocket welcomeSocket = new ServerSocket(puerto); /*HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_login); // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); // nameValuePairs.add(new BasicNameValuePair("utf8", Character.toString('\u2713'))); nameValuePairs.add(new BasicNameValuePair("username", username)); nameValuePairs.add(new BasicNameValuePair("password", password)); // nameValuePairs.add(new BasicNameValuePair("commit", "Sign in")); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpClient.execute(httpPost); String ret = EntityUtils.tostring(response.getEntity()); System.out.println(ret); */ while (true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientformat = inFromClient.readLine(); System.out.println("FORMAT: " + clientformat); BufferedReader inFromClient1 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientdata = inFromClient1.readLine(); System.out.println("DATA: " + clientdata); BufferedReader inFromClient2 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresult = inFromClient2.readLine(); System.out.println("RESULT: " + clientresult); BufferedReader inFromClient3 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresource = inFromClient3.readLine(); System.out.println("RESOURCE: " + clientresource); System.out.println("no pasas de aqui"); String url = "http://localhost:3000/" + clientresource + "/" + clientdata + "." + clientformat; System.out.println(url); try (InputStream is = new URL(url).openStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String stb = sb.toString(); System.out.println("estas aqui"); String output = null; String jsonText = stb; output = jsonText.replace("[", "").replace("]", ""); JSONObject json = new JSONObject(output); System.out.println(json.toString()); System.out.println("llegaste al final"); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); outToClient.writeBytes(json.toString()); } connectionSocket.close(); } }
From source file:com.wordnik.swaggersocket.samples.NettoSphere.java
public static void main(String[] args) throws IOException { ReflectorServletProcessor rsp = new ReflectorServletProcessor(); rsp.setServletClassName(CXFNonSpringJaxrsServlet.class.getName()); int p = getHttpPort(); Config.Builder b = new Config.Builder(); b.resource("./app").initParam(ApplicationConfig.WEBSOCKET_CONTENT_TYPE, "application/json") .initParam(ApplicationConfig.WEBSOCKET_METHOD, "POST") .initParam("jaxrs.serviceClasses", SwaggerSocketResource.class.getName() + "," + FileServiceResource.class.getName()) .initParam("jaxrs.providers", JacksonJsonProvider.class.getName()) .initParam("com.wordnik.swaggersocket.protocol.lazywrite", "true") .initParam("com.wordnik.swaggersocket.protocol.emptyentity", "true") .interceptor(new SwaggerSocketProtocolInterceptor()).resource("/*", rsp).port(p).host("127.0.0.1") .build();/* www. j av a 2 s .c o m*/ Nettosphere s = new Nettosphere.Builder().config(b.build()).build(); s.start(); String a = ""; logger.info("NettoSphere SwaggerSocket Server started on port {}", p); logger.info("Type quit to stop the server"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (!(a.equals("quit"))) { a = br.readLine(); } System.exit(-1); }
From source file:com.hilatest.httpclient.apacheexample.ClientConnectionRelease.java
public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.apache.org/"); // Execute HTTP request System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); try {/*from ww w. ja va2 s. co m*/ // do something useful with the response System.out.println(reader.readLine()); } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. httpget.abort(); throw ex; } finally { // Closing the input stream will trigger connection release reader.close(); } } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }