Example usage for java.io BufferedReader BufferedReader

List of usage examples for java.io BufferedReader BufferedReader

Introduction

In this page you can find the example usage for java.io BufferedReader BufferedReader.

Prototype

public BufferedReader(Reader in) 

Source Link

Document

Creates a buffering character-input stream that uses a default-sized input buffer.

Usage

From source file:com.dlmu.heipacker.crawler.client.ProxyTunnelDemo.java

public final static void main(String[] args) throws Exception {

    ProxyClient proxyClient = new ProxyClient();
    HttpHost target = new HttpHost("www.yahoo.com", 80);
    HttpHost proxy = new HttpHost("localhost", 8888);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd");
    Socket socket = proxyClient.tunnel(proxy, target, credentials);
    try {// w  w w  .ja va2  s. com
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Agent: whatever\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } finally {
        socket.close();
    }
}

From source file:de.jetwick.snacktory.HtmlFetcher.java

public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader("urls.txt"));
    String line = null;/*from  w w w .  jav  a 2s . c om*/
    Set<String> existing = new LinkedHashSet<String>();
    while ((line = reader.readLine()) != null) {
        int index1 = line.indexOf("\"");
        int index2 = line.indexOf("\"", index1 + 1);
        String url = line.substring(index1 + 1, index2);
        String domainStr = SHelper.extractDomain(url, true);
        String counterStr = "";
        // TODO more similarities
        if (existing.contains(domainStr))
            counterStr = "2";
        else
            existing.add(domainStr);

        String html = new HtmlFetcher().fetchAsString(url, 20000);
        String outFile = domainStr + counterStr + ".html";
        BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
        writer.write(html);
        writer.close();
    }
    reader.close();
}

From source file:org.sbq.batch.mains.ActivityEmulator.java

public static void main(String[] vars) throws IOException {
    System.out.println("ActivityEmulator - STARTED.");
    ActivityEmulator activityEmulator = new ActivityEmulator();
    activityEmulator.begin();//  www  . j  a  v  a  2 s. c  o m
    System.out.println("Enter your command: >");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String command = null;
    while (!"stop".equals(command = in.readLine())) {
        if ("status".equals(command)) {
            List<String> onlineUsers = new LinkedList<String>();
            for (Map.Entry<String, AtomicBoolean> entry : activityEmulator.getUserStatusByLogin().entrySet()) {
                if (entry.getValue().get()) {
                    onlineUsers.add(entry.getKey());
                }
            }
            System.out.println("Users online: " + Arrays.toString(onlineUsers.toArray()));
            System.out.println("Number of cycles left: " + activityEmulator.getBlockingQueue().size());

        }
        System.out.println("Enter your command: >");
    }
    activityEmulator.stop();
    System.out.println("ActivityEmulator - STOPPED.");
}

From source file:ReadHeaders.java

/** Main program showing how to use it */
public static void main(String[] av) {
    switch (av.length) {
    case 0://from   w  ww  . java2  s.  c o 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 {/*  w  w w  .  ja va2 s  .c  o  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 ava2  s .  co 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  w  w  .ja  v  a  2  s. c  o 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  ww.java 2 s  .  c o 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: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;//from w ww. jav a 2s  . c o  m
    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.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 {//w w  w  . java 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);
    }
}