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:recsyslod.utils.DownloadLodProperties.java

/**
 * @param args the command line arguments
 *///from  www  .  j  av  a  2 s .co m
public static void main(String[] args) {
    if (args.length == 2) {
        try {
            int c = 0;
            System.out.println();
            BufferedWriter writer = new BufferedWriter(new FileWriter(args[1]));
            BufferedReader reader = new BufferedReader(new FileReader(args[0]));
            while (reader.ready()) {
                String[] split = reader.readLine().split("\t");
                String id = split[0];
                String uri = split[2];
                List<Pair<String, String>> properties = getProperties(uri);
                for (Pair<String, String> p : properties) {
                    writer.append(id).append("\t").append(p.getLeft()).append("\t").append(p.getRight());
                    writer.newLine();
                }
                c++;
                if (c % 10 == 0) {
                    System.out.print(".");
                    if (c % 1000 == 0) {
                        System.out.println("." + c);
                    }
                }
            }
            reader.close();
            writer.close();
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.openplans.delayfeeder.LoadFeeds.java

public static void main(String args[]) throws HibernateException, IOException {
    if (args.length != 1) {
        System.out.println("expected one argument: the path to a csv of agency,route,url");
    }/*from  ww  w.j a va 2s  .  c o  m*/
    GenericApplicationContext context = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
    xmlReader.loadBeanDefinitions("org/openplans/delayfeeder/application-context.xml");
    xmlReader.loadBeanDefinitions("data-sources.xml");

    SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");

    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.beginTransaction();

    FileReader fileReader = new FileReader(new File(args[0]));
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    while (bufferedReader.ready()) {
        String line = bufferedReader.readLine().trim();
        if (line.startsWith("#")) {
            continue;
        }
        if (line.length() < 3) {
            //blank or otherwise broken line
            continue;
        }

        String[] parts = line.split(",");
        String agency = parts[0];
        String route = parts[1];
        String url = parts[2];
        Query query = session.createQuery("from RouteFeed where agency = :agency and route = :route");
        query.setParameter("agency", agency);
        query.setParameter("route", route);
        @SuppressWarnings("rawtypes")
        List list = query.list();
        RouteFeed feed;
        if (list.size() == 0) {
            feed = new RouteFeed();
            feed.agency = agency;
            feed.route = route;
            feed.lastEntry = new GregorianCalendar();
        } else {
            feed = (RouteFeed) list.get(0);
        }
        if (!url.equals(feed.url)) {
            feed.url = url;
            feed.lastEntry.setTimeInMillis(0);
        }
        session.saveOrUpdate(feed);
    }
    tx.commit();
}

From source file:de.bitocean.dspm.examples.Vertex.java

public static void main(String[] args) throws GraphIOException, FileNotFoundException, IOException {

    Reader reader = new FileReader(GRAPHML_ACTIVITY_DEPENDENCY_FILE);

    BufferedReader br = new BufferedReader(reader);
    while (br.ready()) {
        System.out.println(br.readLine());
    }/*from ww w.  j ava  2s.  co  m*/

    Transformer<NodeMetadata, Vertex> vtrans = new Transformer<NodeMetadata, Vertex>() {
        public Vertex transform(NodeMetadata nmd) {
            Vertex v = new Vertex();
            v.id = nmd.getId();
            v.name = nmd.getProperty("name");
            v.expression = nmd.getProperty("expression");
            return v;
        }
    };

    Transformer<EdgeMetadata, Edge> etrans = new Transformer<EdgeMetadata, Edge>() {
        public Edge transform(EdgeMetadata emd) {
            System.out.println(emd.toString());
            Edge e = new Edge();
            try {
                e.source = emd.getSource();
            } catch (Exception ex) {

            }
            e.target = emd.getTarget();
            e.weight = Double.parseDouble(emd.getProperty("weight"));
            return e;
        }
    };

    Transformer<HyperEdgeMetadata, Edge> hetrans = new Transformer<HyperEdgeMetadata, Edge>() {
        public Edge transform(HyperEdgeMetadata emd) {
            Edge e = new Edge();
            try {
                e.source = emd.getProperty("source");
            } catch (Exception ex) {

            }
            e.target = emd.getProperty("target");
            e.weight = Double.parseDouble(emd.getProperty("weight"));
            return e;
        }
    };
    Transformer<GraphMetadata, DirectedSparseGraph<Vertex, Edge>> gtrans = new Transformer<GraphMetadata, DirectedSparseGraph<Vertex, Edge>>() {
        public DirectedSparseGraph<Vertex, Edge> transform(GraphMetadata gmd) {
            return new DirectedSparseGraph<Vertex, Edge>();
        }
    };

    GraphMLReader2<DirectedSparseGraph<Vertex, Edge>, Vertex, Edge> gmlr =
            //new GraphMLReader2<UndirectedSparseGraph<Vertex,Edge>, Vertex, Edge>(fileReader, graphTransformer, vertexTransformer, edgeTransformer, hyperEdgeTransformer)
            new GraphMLReader2<DirectedSparseGraph<Vertex, Edge>, Vertex, Edge>(reader, gtrans, vtrans, etrans,
                    hetrans);

    DirectedSparseGraph<Vertex, Edge> g = gmlr.readGraph();

    System.out.println("Number of vetex: " + g.getVertexCount());
    System.out.println("Number of edges: " + g.getEdgeCount());

    System.out.println("==========================");
    System.out.println("Vertices");
    System.out.println("==========================");
    for (Vertex v : g.getVertices()) {
        System.out.println(v);
    }

    System.out.println("==========================");
    System.out.println("Edges");
    System.out.println("==========================");
    for (Edge e : g.getEdges()) {
        System.out.println(e);
    }

}

From source file:Main.java

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

    String s = "from java2s.com";

    StringReader sr = new StringReader(s);

    // create new buffered reader
    BufferedReader br = new BufferedReader(sr);

    // Destination source is created
    CharBuffer target = CharBuffer.allocate(s.length());

    // ready is invoked to test if character stream is ready
    if (br.ready()) {
        br.read(target);/*w  w w. j a  v  a 2 s  .  com*/
    }
    System.out.print(target.array());

}

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   w  w w  .ja  v a 2  s. 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:iac.cnr.it.TestSearcher.java

public static void main(String[] args) throws IOException, ParseException {
    /** Command line parser and options */
    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    options.addOption(OPT_INDEX, true, "Index path");
    options.addOption(OPT_QUERY, true, "The query");

    CommandLine cmd = null;//from  w  w  w.ja  v  a 2s. co  m
    try {
        cmd = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.fatal("Error while parsing command line arguments");
        System.exit(1);
    }

    /** Check for mandatory options */
    if (!cmd.hasOption(OPT_INDEX) || !cmd.hasOption(OPT_QUERY)) {
        usage();
        System.exit(0);
    }

    /** Read options */
    File casePath = new File(cmd.getOptionValue(OPT_INDEX));
    String query = cmd.getOptionValue(OPT_QUERY);

    /** Check correctness of the path containing an ISODAC case */
    if (!casePath.exists() || !casePath.isDirectory()) {
        logger.fatal("The case directory \"" + casePath.getAbsolutePath() + "\" is not valid");
        System.exit(1);
    }

    /** Check existance of the info.dat file */
    File infoFile = new File(casePath, INFO_FILENAME);
    if (!infoFile.exists()) {
        logger.fatal("Can't find " + INFO_FILENAME + " within the case directory (" + casePath + ")");
        System.exit(1);
    }

    /** Load the mapping image_uuid --> image_filename */
    imagesMap = new HashMap<Integer, String>();
    BufferedReader reader = new BufferedReader(new FileReader(infoFile));
    while (reader.ready()) {
        String line = reader.readLine();

        logger.info("Read the line: " + line);
        String currentID = line.split("\t")[0];
        String currentImgFile = line.split("\t")[1];
        imagesMap.put(Integer.parseInt(currentID), currentImgFile);
        logger.info("ID: " + currentID + " - IMG: " + currentImgFile + " added to the map");

    }
    reader.close();

    /** Load all the directories containing an index */
    ArrayList<String> indexesDirs = new ArrayList<String>();
    for (File f : casePath.listFiles()) {
        logger.info("Analyzing: " + f);
        if (f.isDirectory())
            indexesDirs.add(f.getAbsolutePath());
    }
    logger.info(indexesDirs.size() + " directories found!");

    /** Set-up the searcher */
    Searcher searcher = null;
    try {
        String[] array = indexesDirs.toArray(new String[indexesDirs.size()]);
        searcher = new Searcher(array);
        TopDocs results = searcher.search(query, Integer.MAX_VALUE);

        ScoreDoc[] hits = results.scoreDocs;
        int numTotalHits = results.totalHits;

        System.out.println(numTotalHits + " total matching documents");

        for (int i = 0; i < numTotalHits; i++) {
            Document doc = searcher.doc(hits[i].doc);

            String path = doc.get(FIELD_PATH);
            String filename = doc.get(FIELD_FILENAME);
            String image_uuid = doc.get(FIELD_IMAGE_ID);

            if (path != null) {
                //System.out.println((i + 1) + ". " + path + File.separator + filename + " - score: " + hits[i].score);
                //               System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + image_uuid);
                System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: "
                        + imagesMap.get(Integer.parseInt(image_uuid)));
            } else {
                System.out.println((i + 1) + ". " + "No path for this document");
            }
        }

    } catch (Exception e) {
        System.err.println("An error occurred: " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (searcher != null)
            searcher.close();
    }
}

From source file:com.datastax.sparql.ConsoleCompiler.java

public static void main(final String[] args) throws IOException {
    //args = "/examples/modern1.sparql";
    final Options options = new Options();
    options.addOption("f", "file", true, "a file that contains a SPARQL query");
    options.addOption("g", "graph", true,
            "the graph that's used to execute the query [classic|modern|crew|kryo file]");
    // TODO: add an OLAP option (perhaps: "--olap spark"?)

    final CommandLineParser parser = new DefaultParser();
    final CommandLine commandLine;

    try {// ww w .  j  av a2 s  .com
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printHelp(1);
        return;
    }

    final InputStream inputStream = commandLine.hasOption("file")
            ? new FileInputStream(commandLine.getOptionValue("file"))
            : System.in;
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    final StringBuilder queryBuilder = new StringBuilder();

    if (!reader.ready()) {
        printHelp(1);
    }

    String line;
    while (null != (line = reader.readLine())) {
        queryBuilder.append(System.lineSeparator()).append(line);
    }

    final String queryString = queryBuilder.toString();
    final Graph graph;

    if (commandLine.hasOption("graph")) {
        switch (commandLine.getOptionValue("graph").toLowerCase()) {
        case "classic":
            graph = TinkerFactory.createClassic();
            break;
        case "modern":
            graph = TinkerFactory.createModern();
            System.out.println("Modern Graph Created");
            break;
        case "crew":
            graph = TinkerFactory.createTheCrew();
            break;
        default:
            graph = TinkerGraph.open();
            System.out.println("Graph Created");
            long startTime = System.nanoTime();
            graph.io(IoCore.gryo()).readGraph(commandLine.getOptionValue("graph"));
            long endTime = System.nanoTime();
            System.out.println("Time taken to load graph from kyro file: " + (endTime - startTime) / 1000000
                    + " mili seconds");
            break;
        }
    } else {

        graph = TinkerFactory.createModern();
    }

    final Traversal<Vertex, ?> traversal = SparqlToGremlinCompiler.convertToGremlinTraversal(graph,
            queryString);

    printWithHeadline("SPARQL Query", queryString);
    printWithHeadline("Traversal (prior execution)", traversal);

    Bytecode traversalByteCode = traversal.asAdmin().getBytecode();

    //JavaTranslator.of(graph.traversal()).translate(traversalByteCode);

    System.out.println("the Byte Code : " + traversalByteCode.toString());
    printWithHeadline("Result", String.join(System.lineSeparator(), JavaTranslator.of(graph.traversal())
            .translate(traversalByteCode).toStream().map(Object::toString).collect(Collectors.toList())));
    printWithHeadline("Traversal (after execution)", traversal);
}

From source file:com.flaptor.hounder.indexer.RmiIndexerStub.java

public static void main(String[] args) {

    // create the parser
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;/*from ww w.  java 2 s  .com*/
    Options options = getOptions();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("RmiIndexerStub -h <hostName> -p <basePort> [options] ", options);
        System.exit(1);
    }

    boolean doOptimize = line.hasOption("optimize");
    boolean doCheckpoint = line.hasOption("checkpoint");
    boolean doStop = line.hasOption("stop");
    Integer port = ((Long) line.getOptionObject("port")).intValue();
    String host = line.getOptionValue("host");

    try {
        RmiIndexerStub stub = new RmiIndexerStub(port, host);

        if (line.hasOption("deleteUrl")) {
            String url = line.getOptionValue("deleteUrl");
            Document dom = generateDeleteDocument(url);
            indexOrFail(stub, dom, "Could not delete " + url);
            System.out.println("delete " + url + " command accepted by indexer");
        }

        if (line.hasOption("deleteFile")) {

            BufferedReader reader = new BufferedReader(new FileReader(line.getOptionValue("deleteFile")));
            while (reader.ready()) {
                String url = reader.readLine();
                if (url.length() > 0 && url.charAt(0) != '#') { // ignore empty lines and comments
                    Document dom = generateDeleteDocument(url);
                    indexOrFail(stub, dom, "Could not delete " + url);
                    System.out.println("delete " + url + " command accepted by indexer");
                }
            }
            reader.close();
        }

        if (doOptimize) {
            Document dom = generateCommandDocument("optimize");
            indexOrFail(stub, dom, "Could not send optimize command.");
            System.out.println("optimize command accepted by indexer");
        }

        if (doCheckpoint) {
            Document dom = generateCommandDocument("checkpoint");
            indexOrFail(stub, dom, "Could not send checkpoint command.");
            System.out.println("checkpoint command accepted by indexer");

        }
        if (doStop) {
            Document dom = generateCommandDocument("close");
            indexOrFail(stub, dom, "Could not send stop command.");
            System.out.println("stop command accepted by indexer");
        }
    } catch (Exception e) {
        System.err.println("An error occurred: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:de.binfalse.jatter.App.java

/**
 * Run jatter's main./*ww  w  . j  a  v  a 2s  .c om*/
 *
 * @param args
 *          the arguments
 * @throws Exception
 *           the exception
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();

    Option conf = new Option("c", "config", true, "config file path");
    conf.setRequired(false);
    options.addOption(conf);

    Option t = new Option("t", "template", false, "show a config template");
    t.setRequired(false);
    options.addOption(t);

    Option v = new Option("v", "verbose", false, "print information messages");
    v.setRequired(false);
    options.addOption(v);

    Option d = new Option("d", "debug", false, "print debugging messages incl stack traces");
    d.setRequired(false);
    options.addOption(d);

    Option h = new Option("h", "help", false, "show help");
    h.setRequired(false);
    options.addOption(h);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h"))
            throw new RuntimeException("showing the help page");
    } catch (Exception e) {
        help(options, e.getMessage());
        return;
    }

    if (cmd.hasOption("t")) {
        System.out.println();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                App.class.getClassLoader().getResourceAsStream("config.properties.template")));
        while (br.ready())
            System.out.println(br.readLine());
        br.close();
        System.exit(0);
    }

    if (cmd.hasOption("v"))
        LOGGER.setMinLevel(LOGGER.INFO);

    if (cmd.hasOption("d")) {
        LOGGER.setMinLevel(LOGGER.DEBUG);
        LOGGER.setLogStackTrace(true);
    }

    if (!cmd.hasOption("c"))
        help(options, "a config file is required for running jatter");

    startJatter(cmd.getOptionValue("c"));
}

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

/**
 * The main method. This configures the Orekit data path, creates the
 * SaudiComsat federate objects and launches the associated graphical user
 * interface./*from w w  w.j  a  va 2 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();

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

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

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

    logger.debug("Loading TLE data from file.");
    final List<Component> panels = new ArrayList<Component>();
    for (String satName : Arrays.asList("TDRS 3", "TDRS 5", "TDRS 6", "TDRS 7", "TDRS 8", "TDRS 9", "TDRS 10",
            "TDRS 11")) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    federate.getClass().getClassLoader().getResourceAsStream("edu/mit/fss/examples/data.tle")));

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

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

                    panels.add(new SpaceSystemPanel(federate, system));

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

    try {
        logger.trace("Adding WSGT ground station.");
        SurfaceSystem wsgt = new SurfaceSystem("WSGT",
                new GeodeticPoint(FastMath.toRadians(32.5007), FastMath.toRadians(-106.6086), 1474),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(wsgt);
        panels.add(new SurfaceSystemPanel(federate, wsgt));

        logger.trace("Adding STGT ground station.");
        SurfaceSystem stgt = new SurfaceSystem("STGT",
                new GeodeticPoint(FastMath.toRadians(32.5430), FastMath.toRadians(-106.6120), 1468),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(stgt);
        panels.add(new SurfaceSystemPanel(federate, stgt));

        logger.trace("Adding GRGT ground station.");
        SurfaceSystem grgt = new SurfaceSystem("GRGT",
                new GeodeticPoint(FastMath.toRadians(13.6148), FastMath.toRadians(144.8565), 142),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(grgt);
        panels.add(new SurfaceSystemPanel(federate, grgt));
    } catch (OrekitException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    logger.debug("Launching the graphical user interface.");
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                MemberFrame frame = new MemberFrame(federate, new MultiComponentPanel(panels));
                frame.pack();
                frame.setVisible(true);
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    logger.trace("Setting federate name, type, and FOM path.");
    federate.getConnection().setFederateName("TDRSS");
    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();
}