Example usage for java.io BufferedReader readLine

List of usage examples for java.io BufferedReader readLine

Introduction

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

Prototype

public String readLine() throws IOException 

Source Link

Document

Reads a line of text.

Usage

From source file:edu.clemson.cs.nestbed.server.tools.BuildTestbed.java

public static void main(String[] args) {
    try {//w ww  . ja v  a2 s  .c  o m
        BasicConfigurator.configure();
        //loadProperties();

        if (args.length < 2) {
            System.out.println("Usage: BuildTestbed <testbedID> <inputfile>");
            System.exit(0);
        }

        int testbedID = Integer.parseInt(args[0]);
        String filename = args[1];
        Connection conn = null;
        Statement statement = null;
        MoteSqlAdapter adapter = new MoteSqlAdapter();
        Map<Integer, Mote> motes = adapter.readMotes();

        log.info(motes);

        String connStr = System.getProperty("nestbed.options.databaseConnectionString");
        log.info("connStr: " + connStr);

        conn = DriverManager.getConnection(connStr);
        statement = conn.createStatement();

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));

        String line;
        while ((line = in.readLine()) != null) {
            StringTokenizer tokenizer = new StringTokenizer(line);
            int address = Integer.parseInt(tokenizer.nextToken());
            String serial = tokenizer.nextToken();
            int xLoc = Integer.parseInt(tokenizer.nextToken());
            int yLoc = Integer.parseInt(tokenizer.nextToken());

            log.info("Input Mote:\n" + "-----------\n" + "address:  " + address + "\n" + "serial:   " + serial
                    + "\n" + "xLoc:     " + xLoc + "\n" + "yLoc:     " + yLoc);

            for (Mote i : motes.values()) {
                if (i.getMoteSerialID().equals(serial)) {
                    String query = "INSERT INTO MoteTestbedAssignments" + "(testbedID, moteID, moteAddress,"
                            + " moteLocationX, moteLocationY) VALUES (" + testbedID + ", " + i.getID() + ", "
                            + address + ", " + xLoc + ", " + yLoc + ")";
                    log.info(query);
                    statement.executeUpdate(query);
                }
            }
        }
        conn.commit();
    } catch (Exception ex) {
        log.error("Exception in main", ex);
    }
}

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. j  av a 2 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();
}

From source file:SequentialPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(/*from w w  w  . j  a v a  2  s .com*/
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute PageRank.
    PageRank<String, Integer> ranker = new PageRank<String, Integer>(graph, alpha);
    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:FlightInfo.java

public static void main(String args[]) {
    String to, from;/*from   ww w . jav a 2s  .  c  o m*/
    Depth ob = new Depth();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    ob.setup();

    try {
        System.out.print("From? ");
        from = br.readLine();
        System.out.print("To? ");
        to = br.readLine();

        ob.isflight(from, to);

        if (ob.btStack.size() != 0)
            ob.route(to);
    } catch (IOException exc) {
        System.out.println("Error on input.");
    }
}

From source file:ReadZip.java

public static void main(String args[]) {
    try {//  w  w w  .  j  a v a2 s.  c o m
        ZipFile zf = new ZipFile("ReadZip.zip");
        Enumeration entries = zf.entries();

        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        while (entries.hasMoreElements()) {
            ZipEntry ze = (ZipEntry) entries.nextElement();
            System.out.println("Read " + ze.getName() + "?");
            String inputLine = input.readLine();
            if (inputLine.equalsIgnoreCase("yes")) {
                long size = ze.getSize();
                if (size > 0) {
                    System.out.println("Length is " + size);
                    BufferedReader br = new BufferedReader(new InputStreamReader(zf.getInputStream(ze)));
                    String line;
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                    }
                    br.close();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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;//  w  ww  . java 2 s  .  co 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.msopentech.odatajclient.engine.performance.PerfTestReporter.java

public static void main(final String[] args) throws Exception {
    // 1. check input directory
    final File reportdir = new File(args[0] + File.separator + "target" + File.separator + "surefire-reports");
    if (!reportdir.isDirectory()) {
        throw new IllegalArgumentException("Expected directory, got " + args[0]);
    }//from   ww  w  .j a va 2s  . c  om

    // 2. read test data from surefire output
    final File[] xmlReports = reportdir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(final File dir, final String name) {
            return name.endsWith("-output.txt");
        }
    });

    final Map<String, Map<String, Double>> testData = new TreeMap<String, Map<String, Double>>();

    for (File xmlReport : xmlReports) {
        final BufferedReader reportReader = new BufferedReader(new FileReader(xmlReport));
        try {
            while (reportReader.ready()) {
                String line = reportReader.readLine();
                final String[] parts = line.substring(0, line.indexOf(':')).split("\\.");

                final String testClass = parts[0];
                if (!testData.containsKey(testClass)) {
                    testData.put(testClass, new TreeMap<String, Double>());
                }

                line = reportReader.readLine();

                testData.get(testClass).put(parts[1],
                        Double.valueOf(line.substring(line.indexOf(':') + 2, line.indexOf('['))));
            }
        } finally {
            IOUtils.closeQuietly(reportReader);
        }
    }

    // 3. build XSLX output (from template)
    final HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(args[0] + File.separator + "src"
            + File.separator + "test" + File.separator + "resources" + File.separator + XLS));

    for (Map.Entry<String, Map<String, Double>> entry : testData.entrySet()) {
        final Sheet sheet = workbook.getSheet(entry.getKey());

        int rows = 0;

        for (Map.Entry<String, Double> subentry : entry.getValue().entrySet()) {
            final Row row = sheet.createRow(rows++);

            Cell cell = row.createCell(0);
            cell.setCellValue(subentry.getKey());

            cell = row.createCell(1);
            cell.setCellValue(subentry.getValue());
        }
    }

    final FileOutputStream out = new FileOutputStream(
            args[0] + File.separator + "target" + File.separator + XLS);
    try {
        workbook.write(out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:dataminning2.DataMinning2.java

/**
 * @param args the command line arguments
 *//*  ww w.  j  a v a  2 s  .c  om*/
public static void main(String[] args) throws IOException {
    // here is the code to load the iris.csv data in an array 

    int ColumnCount = 0;
    int RowCount = 0;
    double[][] Dataarraytest;
    double[][] Dataarray;
    double[][] SVDS = null;
    double[][] SVDU = null;
    double[][] SVDV = null;
    System.out.println("Do you want to work with 1.att.csv or 2.iris.csv  ");
    InputStreamReader Datasetchoice = new InputStreamReader(System.in);
    BufferedReader BDatasetChoice = new BufferedReader(Datasetchoice);
    int Datasetchoicevalue = Integer.parseInt(BDatasetChoice.readLine());
    String path = null;
    // LOadData LDobj=new LOadData();
    LOadData LDobj = new LOadData();
    TrainingSetDecomposition TestDataonj = new TrainingSetDecomposition();
    SVDDecomposition SVDobj = new SVDDecomposition();

    switch (Datasetchoicevalue) {
    case 1:
        path = "Datasets\\att.csv";
        ColumnCount = LDobj.ColumnCount(path);
        RowCount = LDobj.RowCount(path);
        Dataarray = LDobj.Datasetup(path, ColumnCount, RowCount);
        Dataarraytest = TestDataonj.Decomposition(RowCount, RowCount, 2, Dataarray);

        SVDS = SVDobj.DecompositionS(Dataarraytest);
        SVDU = SVDobj.DecompositionU(Dataarraytest);
        SVDV = SVDobj.DecompositionV(Dataarraytest);

        System.out.println("Do you want the graph to be plotted 1.yes 2.No");
        Datasetchoicevalue = Integer.parseInt(BDatasetChoice.readLine());
        if (Datasetchoicevalue == 1) {
            WriteCSv wcsvobj = new WriteCSv();
            wcsvobj.writeCSVmethod(SVDU, "SVD");
        }

        KMeans_Ex4a Kmeanobj1 = new KMeans_Ex4a();
        double[][] KmeanData1 = Kmeanobj1.Main(SVDU);
        System.out.println("Do you want the graph to be plotted 1.yes 2.No");
        Datasetchoicevalue = Integer.parseInt(BDatasetChoice.readLine());
        if (Datasetchoicevalue == 1) {
            WriteCSVKmean wcsvobj = new WriteCSVKmean();
            wcsvobj.writeCSVmethod(KmeanData1, "KMean");
        }

        Gui DBScanobj1 = new Gui();
        DBScanobj1.main(SVDU);

        System.out.println("Do you want the graph to be plotted 1.yes 2.No");
        Datasetchoicevalue = Integer.parseInt(BDatasetChoice.readLine());
        if (Datasetchoicevalue == 1) {

            WriteCSv wcsvobj = new WriteCSv();
            wcsvobj.writeCSVmethod(SVDU, "DBScan");
        }

        break;

    case 2:
        path = "Datasets\\iris.csv";
        ColumnCount = LDobj.ColumnCount(path);
        RowCount = LDobj.RowCount(path);
        Dataarray = LDobj.Datasetup(path, ColumnCount, RowCount);
        Dataarraytest = TestDataonj.Decomposition(RowCount, 150, ColumnCount, Dataarray);

        SVDS = SVDobj.DecompositionS(Dataarraytest);
        SVDU = SVDobj.DecompositionU(Dataarraytest);
        SVDV = SVDobj.DecompositionV(Dataarraytest);
        System.out.println("Do you want the graph to be plotted 1.yes 2.No");
        Datasetchoicevalue = Integer.parseInt(BDatasetChoice.readLine());
        if (Datasetchoicevalue == 1) {
            WriteCSv wcsvobj = new WriteCSv();
            wcsvobj.writeCSVmethod(SVDU, "SVD");
        }

        KMeans_Ex4a Kmeanobj = new KMeans_Ex4a();
        double[][] KmeanData = Kmeanobj.Main(SVDU);
        ssecalc distobj = new ssecalc();
        String output = distobj.calc(KmeanData);
        System.out.println(output);
        System.out.println("Do you want the graph to be plotted 1.yes 2.No");
        Datasetchoicevalue = Integer.parseInt(BDatasetChoice.readLine());
        if (Datasetchoicevalue == 1) {
            WriteCSVKmean wcsvobj = new WriteCSVKmean();
            wcsvobj.writeCSVmethod(KmeanData, "KMean");
        }

        Gui DBScanobj = new Gui();
        DBScanobj.main(SVDU);

        System.out.println("Do you want the graph to be plotted 1.yes 2.No");
        Datasetchoicevalue = Integer.parseInt(BDatasetChoice.readLine());
        if (Datasetchoicevalue == 1) {

            WriteCSv wcsvobj = new WriteCSv();
            wcsvobj.writeCSVmethod(SVDU, "DBScan");
        }

        break;
    }

}

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

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from   ww w .j  av  a 2s .  c  o m
        // Create local execution context
        HttpContext localContext = new BasicHttpContext();

        HttpGet httpget = new HttpGet("http://localhost/test");

        boolean trying = true;
        while (trying) {
            System.out.println("executing request " + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget, localContext);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Consume response content
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);

            int sc = response.getStatusLine().getStatusCode();

            AuthState authState = null;
            HttpHost authhost = null;
            if (sc == HttpStatus.SC_UNAUTHORIZED) {
                // Target host authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            }
            if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                // Proxy authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
            }

            if (authState != null) {
                System.out.println("----------------------------------------");
                AuthScheme authscheme = authState.getAuthScheme();
                System.out.println("Please provide credentials for " + authscheme.getRealm() + "@"
                        + authhost.toHostString());

                BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

                System.out.print("Enter username: ");
                String user = console.readLine();
                System.out.print("Enter password: ");
                String password = console.readLine();

                if (user != null && user.length() > 0) {
                    Credentials creds = new UsernamePasswordCredentials(user, password);
                    httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds);
                    trying = true;
                } else {
                    trying = false;
                }
            } else {
                trying = false;
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.aj.hangman.HangmanReq.java

public static void main(String[] args) {
    HangmanDict dictionary = new HangmanDict();

    try {/* w  ww.  j a va 2  s. c  o m*/
        BufferedReader input = new BufferedReader(new InputStreamReader(
                new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu").openStream()));
        String info = input.readLine();
        JSONParser parser = new JSONParser();

        Object obj;
        try {
            obj = parser.parse(info);
            JSONObject retJson = (JSONObject) obj;

            TOKEN = (String) retJson.get("token");
            STATUS = (String) retJson.get("status");
            STATE = (String) retJson.get("state");
            REM = (Long) retJson.get("remaining_guesses");
            PREM = REM;
            System.out.println("State:: " + STATE);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        while ("ALIVE".equalsIgnoreCase(STATUS)) {
            // call make guess function, returns character
            guess = dictionary.makeGuess(STATE);
            System.out.println("Guessed:: " + guess);
            // call the url to update
            BufferedReader reInput = new BufferedReader(
                    new InputStreamReader(new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu"
                            + String.format("&token=%s&guess=%s", TOKEN, guess)).openStream()));

            // parse the url to get the updated value
            String reInfo = reInput.readLine();
            JSONParser reParser = new JSONParser();

            Object retObj = reParser.parse(reInfo);
            JSONObject retJson = (JSONObject) retObj;

            STATUS = (String) retJson.get("status");
            STATE = (String) retJson.get("state");
            REM = (Long) retJson.get("remaining_guesses");
            System.out.println("State:: " + STATE);
        }

        if ("DEAD".equalsIgnoreCase(STATUS)) {
            // print lost
            System.out.println("You LOOSE: DEAD");
        } else if ("FREE".equalsIgnoreCase(STATUS)) {
            // print free
            System.out.println("You WIN: FREE");
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}