Example usage for java.io BufferedReader ready

List of usage examples for java.io BufferedReader ready

Introduction

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

Prototype

public boolean ready() throws IOException 

Source Link

Document

Tells whether this stream is ready to be read.

Usage

From source file:DataLoader.java

public static void main(String[] args)
        throws IOException, ValidationException, LicenseException, JobExecutionAlreadyRunningException,
        JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {

    System.out.println(/*from  www . j  a v  a2s .c  o m*/
            "System is initialising. Please wait for a few seconds then type your queries below once you see the prompt (->)");

    C24.init().withLicence("/biz/c24/api/license-ads.dat");

    // Create our application context - assumes the Spring configuration is in the classpath in a file called spring-config.xml
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

    // ========================================================================
    // DEMO
    // A simple command-line interface to allow us to query the GemFire regions
    // ========================================================================

    GemfireTemplate template = context.getBean(GemfireTemplate.class);

    BufferedReader br = new BufferedReader(new java.io.InputStreamReader(System.in));

    boolean writePrompt = true;

    try {
        while (true) {
            if (writePrompt) {
                System.out.print("-> ");
                System.out.flush();
                writePrompt = false;
            }
            if (br.ready()) {
                try {

                    String request = br.readLine();
                    System.out.println("Running: " + request);
                    SelectResults<Object> results = template.find(request);
                    System.out.println();
                    System.out.println("Result:");
                    for (Object result : results.asList()) {
                        System.out.println(result.toString());
                    }
                } catch (Exception ex) {
                    System.out.println("Error executing last command " + ex.getMessage());
                    //ex.printStackTrace();
                }

                writePrompt = true;

            } else {
                // Wait for a second and try again
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ioEx) {
                    break;
                }
            }
        }
    } catch (IOException ioe) {
        // Write any exceptions to stderr
        System.err.print(ioe);
    }

}

From source file:edu.mit.fss.examples.ISSFederate.java

/**
 * The main method. This configures the Orekit data path, creates the 
 * ISS federate objects and launches the associated graphical user 
 * interface.//from   www.ja  v  a2 s  .  c o m
 *
 * @param args the arguments
 * @throws RTIexception the RTI exception
 * @throws URISyntaxException 
 */
public static void main(String[] args) throws RTIexception, URISyntaxException {
    BasicConfigurator.configure();

    boolean headless = false;

    logger.debug("Setting Orekit data path.");
    System.setProperty(DataProvidersManager.OREKIT_DATA_PATH,
            new File(ISSFederate.class.getResource("/orekit-data.zip").toURI()).getAbsolutePath());

    logger.trace("Creating federate instance.");
    final ISSFederate federate = new ISSFederate();

    logger.trace("Setting minimum step duration and time step.");
    long timeStep = 60 * 1000, minimumStepDuration = 100;
    federate.setMinimumStepDuration(minimumStepDuration);
    federate.setTimeStep(timeStep);

    try {
        logger.debug("Loading TLE data from file.");
        BufferedReader br = new BufferedReader(new InputStreamReader(
                federate.getClass().getClassLoader().getResourceAsStream("edu/mit/fss/examples/data.tle")));

        final SpaceSystem satellite;
        final SurfaceSystem station1, station2, station3;

        while (br.ready()) {
            if (br.readLine().matches(".*ISS.*")) {
                logger.debug("Found ISS data.");

                logger.trace("Adding FSS supplier space system.");
                satellite = new SpaceSystem("FSS Supplier", new TLE(br.readLine(), br.readLine()), 5123e3);
                federate.addObject(satellite);

                logger.trace("Adding Keio ground station.");
                station1 = new SurfaceSystem("Keio",
                        new GeodeticPoint(FastMath.toRadians(35.551929), FastMath.toRadians(139.647119), 300),
                        satellite.getState().getDate(), 5123e3, 5);
                federate.addObject(station1);

                logger.trace("Adding SkolTech ground station.");
                station2 = new SurfaceSystem("SkolTech",
                        new GeodeticPoint(FastMath.toRadians(55.698679), FastMath.toRadians(37.571994), 200),
                        satellite.getState().getDate(), 5123e3, 5);
                federate.addObject(station2);

                logger.trace("Adding MIT ground station.");
                station3 = new SurfaceSystem("MIT",
                        new GeodeticPoint(FastMath.toRadians(42.360184), FastMath.toRadians(-71.093742), 100),
                        satellite.getState().getDate(), 5123e3, 5);
                federate.addObject(station3);

                try {
                    logger.trace("Setting inital time.");
                    federate.setInitialTime(
                            satellite.getInitialState().getDate().toDate(TimeScalesFactory.getUTC()).getTime());
                } catch (IllegalArgumentException | OrekitException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (!headless) {
                    logger.debug("Launching the graphical user interface.");
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            MemberFrame frame = new MemberFrame(federate,
                                    new MultiComponentPanel(
                                            Arrays.asList(new SpaceSystemPanel(federate, satellite),
                                                    new SurfaceSystemPanel(federate, station1),
                                                    new SurfaceSystemPanel(federate, station2),
                                                    new SurfaceSystemPanel(federate, station3))));
                            frame.pack();
                            frame.setVisible(true);
                        }
                    });
                }

                break;
            }
        }
        br.close();
    } catch (InvocationTargetException | InterruptedException | OrekitException | IOException e) {
        e.printStackTrace();
        logger.fatal(e);
    }

    logger.trace("Setting federate name, type, and FOM path.");
    federate.getConnection().setFederateName("ISS");
    federate.getConnection().setFederateType("FSS Supplier");
    federate.getConnection().setFederationName("FSS");
    federate.getConnection().setFomPath(
            new File(federate.getClass().getClassLoader().getResource("edu/mit/fss/hla/fss.xml").toURI())
                    .getAbsolutePath());
    federate.getConnection().setOfflineMode(false);
    federate.connect();

    if (headless) {
        federate.setMinimumStepDuration(10);
        federate.initialize();
        federate.run();
    }
}

From source file:net.sourceforge.doddle_owl.data.JpnWordNetDic.java

public static void main(String[] args) throws Exception {
    JpnWordNetDic.initJPNWNDic();// w w w. j a va 2 s.  co m
    String id1 = "08675967-n";
    // String id1 = "JPNWN_ROOT";

    Concept c = JpnWordNetDic.getConcept(id1);
    System.out.println(c);

    Set<String> idSet = new HashSet<String>();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(new FileInputStream(DODDLEConstants.JPWN_HOME + "tree.data"), "UTF-8"));
    while (reader.ready()) {
        String line = reader.readLine();
        if (line.indexOf(id1) != -1) {
            String id = line.split("\t\\|")[0];
            idSet.add(id);
        }
    }
    System.out.println(idSet);
    for (String id : idSet) {
        c = JpnWordNetDic.getConcept(id);
        System.out.println(c);
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.util.TempClinicalDataLoader.java

public static void main(String[] args) {
    // first get the db connection properties
    String url = urlSet.get(args[1]);
    String user = args[2];/*  w w  w. ja v  a2 s.co m*/
    String word = args[3];

    // make sure we have the Oracle driver somewhere
    try {
        Class.forName("oracle.jdbc.OracleDriver");
        Class.forName("org.postgresql.Driver");
    } catch (Exception x) {
        System.out.println("Unable to load the driver class!");
        System.exit(0);
    }
    // connect to the database
    try {
        dbConnection = DriverManager.getConnection(url, user, word);
        ClinicalBean.setDBConnection(dbConnection);
    } catch (SQLException x) {
        x.printStackTrace();
        System.exit(1);
    }

    final String xmlList = args[0];
    BufferedReader br = null;
    try {
        final Map<String, String> clinicalFiles = new HashMap<String, String>();
        final Map<String, String> biospecimenFiles = new HashMap<String, String>();
        final Map<String, String> fullFiles = new HashMap<String, String>();

        //noinspection IOResourceOpenedButNotSafelyClosed
        br = new BufferedReader(new FileReader(xmlList));

        // read the file list to get all the files to load
        while (br.ready()) {
            final String[] in = br.readLine().split("\\t");
            String xmlfile = in[0];
            String archive = in[1];

            if (xmlfile.contains("_clinical")) {
                clinicalFiles.put(xmlfile, archive);
            } else if (xmlfile.contains("_biospecimen")) {
                biospecimenFiles.put(xmlfile, archive);
            } else {
                fullFiles.put(xmlfile, archive);
            }
        }

        Date dateAdded = Calendar.getInstance().getTime();

        // NOTE!!! This deletes all data before the load starts, assuming we are re-loading everything.
        // a better way would be to figure out what has changed and load that, or to be able to load multiple versions of the data in the schema
        emptyClinicalTables(user);

        // load any "full" files first -- in case some archives aren't split yet
        for (final String file : fullFiles.keySet()) {
            String archive = fullFiles.get(file);
            System.out.println("Full file " + file + " in " + archive);
            // need to re-instantiate the disease-specific beans for each file
            createDiseaseSpecificBeans(xmlList);
            String disease = getDiseaseName(archive);
            processFullXmlFile(file, archive, disease, dateAdded);

            // memory leak or something... have to commit and close all connections and re-get connection
            // after each file to keep from using too much heap space.  this troubles me, but I have never had
            // the time to figure out why it happens
            resetConnections(url, user, word);
        }

        // now process all clinical files, and insert patients and clinical data
        for (final String clinicalFile : clinicalFiles.keySet()) {
            createDiseaseSpecificBeans(xmlList);
            String archive = clinicalFiles.get(clinicalFile);
            System.out.println("Clinical file " + clinicalFile + " in " + archive);
            String disease = getDiseaseName(archive);
            processClinicalXmlFile(clinicalFile, archive, disease, dateAdded);
            resetConnections(url, user, word);
        }

        // now process biospecimen files
        for (final String biospecimenFile : biospecimenFiles.keySet()) {
            createDiseaseSpecificBeans(xmlList);
            String archive = biospecimenFiles.get(biospecimenFile);
            String disease = getDiseaseName(archive);
            System.out.println("Biospecimen file " + biospecimenFile);
            processBiospecimenXmlFile(biospecimenFile, archive, disease, dateAdded);
            resetConnections(url, user, word);
        }

        // this sets relationships between these clinical tables and data browser tables, since we delete
        // and reload every time
        setForeignKeys();
        dbConnection.commit();
        dbConnection.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:com.liferay.nativity.test.TestDriver.java

public static void main(String[] args) {
    _intitializeLogging();/*from   w w w .  j  a  v  a  2  s. 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:ci6226.buildindex.java

/**
 * @param args the command line arguments
 *//* ww w . j a v  a 2 s.co  m*/
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
    String file = "/home/steven/Dropbox/workspace/ntu_coursework/ci6226/Assiment/yelpdata/yelp_training_set/yelp_training_set_review.json";
    JSONParser parser = new JSONParser();

    BufferedReader in = new BufferedReader(new FileReader(file));
    //  List<Document> jdocs = new LinkedList<Document>();
    Date start = new Date();
    String indexPath = "./myindex";
    System.out.println("Indexing to directory '" + indexPath + "'...");
    // Analyzer analyzer= new NGramAnalyzer(2,8);
    Analyzer analyzer = new myAnalyzer();

    IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_47, analyzer);
    Directory dir = FSDirectory.open(new File(indexPath));
    // :Post-Release-Update-Version.LUCENE_XY:
    // TODO: try different analyzer,stop words,words steming check size
    //   Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_47);

    // Add new documents to an existing index:
    // iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
    iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
    // Optional: for better indexing performance, if you
    // are indexing many documents, increase the RAM
    // buffer.  But if you do this, increase the max heap
    // size to the JVM (eg add -Xmx512m or -Xmx1g):
    //
    // iwc.setRAMBufferSizeMB(256.0);
    IndexWriter writer = new IndexWriter(dir, iwc);
    //  writer.addDocuments(jdocs);
    int line = 0;
    while (in.ready()) {
        String s = in.readLine();
        Object obj = JSONValue.parse(s);
        JSONObject person = (JSONObject) obj;
        String text = (String) person.get("text");
        String user_id = (String) person.get("user_id");
        String business_id = (String) person.get("business_id");
        String review_id = (String) person.get("review_id");
        JSONObject votes = (JSONObject) person.get("votes");
        long funny = (Long) votes.get("funny");
        long cool = (Long) votes.get("cool");
        long useful = (Long) votes.get("useful");
        Document doc = new Document();
        Field review_idf = new StringField("review_id", review_id, Field.Store.YES);
        doc.add(review_idf);
        Field business_idf = new StringField("business_id", business_id, Field.Store.YES);
        doc.add(business_idf);

        //http://qindongliang1922.iteye.com/blog/2030639
        FieldType ft = new FieldType();
        ft.setIndexed(true);//  
        ft.setStored(true);//  
        ft.setStoreTermVectors(true);
        ft.setTokenized(true);
        ft.setStoreTermVectorPositions(true);//?  
        ft.setStoreTermVectorOffsets(true);//???  

        Field textf = new Field("text", text, ft);

        doc.add(textf);
        //    Field user_idf = new StringField("user_id", user_id, Field.Store.YES);
        //     doc.add(user_idf);
        //      doc.add(new LongField("cool", cool, Field.Store.YES));
        //      doc.add(new LongField("funny", funny, Field.Store.YES));
        //       doc.add(new LongField("useful", useful, Field.Store.YES));

        writer.addDocument(doc);

        System.out.println(line++);
    }

    writer.close();
    Date end = new Date();
    System.out.println(end.getTime() - start.getTime() + " total milliseconds");
    // BufferedReader in = new BufferedReader(new FileReader(file));
    //while (in.ready()) {
    //  String s = in.readLine();
    //  //System.out.println(s);
    // JSONObject jsonObject = (JSONObject) ((Object)s);
    //      String rtext = (String) jsonObject.get("text");
    //      System.out.println(rtext);
    //      //long age = (Long) jsonObject.get("age");
    //      //System.out.println(age);
    //}
    //in.close();
}

From source file:Main.java

public static String stringFrom(InputStream stream, String encoding) {
    StringBuilder builder = new StringBuilder();
    try {/*from   w w  w.  j  av  a2 s .  c  o  m*/
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, encoding));
        while (reader.ready())
            builder.append(reader.readLine());
        reader.close();
    } catch (IOException ie) {
    }
    return builder.toString();
}

From source file:Main.java

public static Element createParagraphElement(String name, String content, Document doc) {

    Element element = doc.createElement(name);

    BufferedReader br = new BufferedReader(new StringReader(content));

    try {/*from  w w  w. j  a  v a 2 s .  c  om*/
        while (br.ready()) {
            // Create an element for this node
            String p = br.readLine();

            // To avoid an infinite loop
            if (p == null)
                break;
            Element pe = doc.createElement("p");

            //Add text to paragraph node
            Text t = doc.createTextNode(p);
            pe.appendChild(t);
            element.appendChild(pe);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    return element;
}

From source file:org.xmlvm.demo.java.photovm.net.HTTPRequest.java

public static String get(String url) {
    HttpGet method = new HttpGet(url);
    try {//from  w  w w . j  a  v a 2s  . co  m
        HttpResponse response = client.execute(method);
        int returnCode = response.getStatusLine().getStatusCode();
        if ((returnCode >= 200) && (returnCode < 300)) {
            StringBuilder st = new StringBuilder();
            BufferedReader r = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            while (r.ready()) {
                st.append(r.readLine() + "\n");
            }
            return st.toString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:Main.java

public static String readAssertsTextContent(Context context, String filename) {
    InputStream is = null;/*from  w w  w  . j  a  v  a 2 s.  c  o  m*/
    try {
        is = context.getResources().getAssets().open(filename);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        while (reader.ready())
            sb.append(reader.readLine());
        return sb.toString();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}