Example usage for java.io InputStreamReader InputStreamReader

List of usage examples for java.io InputStreamReader InputStreamReader

Introduction

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

Prototype

public InputStreamReader(InputStream in) 

Source Link

Document

Creates an InputStreamReader that uses the default charset.

Usage

From source file:ObfuscatingStream.java

/**
 * Obfuscates or unobfuscates the second command-line argument, depending on
 * whether the first argument starts with "o" or "u"
 * /* w  w w .  j a  v a 2 s  .c  om*/
 * @param args
 *            Command-line arguments
 * @throws IOException
 *             If an error occurs obfuscating or unobfuscating
 */
public static void main(String[] args) throws IOException {
    InputStream input = new ByteArrayInputStream(args[1].getBytes());
    StringBuilder toPrint = new StringBuilder();
    if (args[0].startsWith("o")) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        OutputStream out = obfuscate(bytes);
        int read = input.read();
        while (read >= 0) {
            out.write(read);
            read = input.read();
        }
        byte[] receiptBytes = bytes.toByteArray();
        for (int b = 0; b < receiptBytes.length; b++) {
            int chr = (receiptBytes[b] + 256) % 256;
            toPrint.append(HEX_CHARS[chr >>> 4]);
            toPrint.append(HEX_CHARS[chr & 0xf]);
        }
    } else if (args[0].startsWith("u")) {
        input = unobfuscate(input);
        InputStreamReader reader = new InputStreamReader(input);

        int read = reader.read();
        while (read >= 0) {
            toPrint.append((char) read);
            read = reader.read();
        }
    } else
        throw new IllegalArgumentException("First argument must start with o or u");
    System.out.println(toPrint.toString());
}

From source file:com.genentech.chemistry.openEye.apps.SDFRingSystemExtractor.java

/**
 * @param args/*from w  ww. ja  v  a  2 s  . c o m*/
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true, "input file oe-supported");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    SDFRingSystemExtractor extractor = new SDFRingSystemExtractor(outFile);
    extractor.run(inFile);
    extractor.close();
}

From source file:test.TestJavaService.java

/**
 * Main.  The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag.  If it is specified,
 *   we test code on the AWS instance.  If it is not, we test code running locally.
 * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file
 *   org.qcert.javasrc.Main.  Remaining non-flag arguments are file names.  There must be at least one.  The number of such 
 *   arguments and what they should contain depends on the verb.
 * @throws Exception/*from   w w w .j  av a2s  . c  om*/
 */
public static void main(String[] args) throws Exception {
    /* Parse command line */
    List<String> files = new ArrayList<>();
    String loc = "localhost", verb = null;
    for (String arg : args) {
        if (arg.equals("-remote"))
            loc = REMOTE_LOC;
        else if (arg.startsWith("-"))
            illegal();
        else if (verb == null)
            verb = arg;
        else
            files.add(arg);
    }
    /* Simple consistency checks and verb-specific parsing */
    if (files.size() == 0)
        illegal();
    String file = files.remove(0);
    String schema = null;
    switch (verb) {
    case "parseSQL":
    case "serialRule2CAMP":
    case "sqlSchema2JSON":
        if (files.size() != 0)
            illegal();
        break;
    case "techRule2CAMP":
        if (files.size() != 1)
            illegal();
        schema = files.get(0);
        break;
    case "csv2JSON":
        if (files.size() < 1)
            illegal();
        break;
    default:
        illegal();
    }

    /* Assemble information from arguments */
    String url = String.format("http://%s:9879?verb=%s", loc, verb);
    byte[] contents = Files.readAllBytes(Paths.get(file));
    String toSend;
    if ("serialRule2CAMP".equals(verb))
        toSend = Base64.getEncoder().encodeToString(contents);
    else
        toSend = new String(contents);
    if ("techRule2CAMP".equals(verb))
        toSend = makeSpecialJson(toSend, schema);
    else if ("csv2JSON".equals(verb))
        toSend = makeSpecialJson(toSend, files);
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    StringEntity entity = new StringEntity(toSend);
    entity.setContentType("text/plain");
    post.setEntity(entity);
    HttpResponse resp = client.execute(post);
    int code = resp.getStatusLine().getStatusCode();
    if (code == HttpStatus.SC_OK) {
        HttpEntity answer = resp.getEntity();
        InputStream s = answer.getContent();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(s));
        String line = rdr.readLine();
        while (line != null) {
            System.out.println(line);
            line = rdr.readLine();
        }
        rdr.close();
        s.close();
    } else
        System.out.println(resp.getStatusLine());
}

From source file:com.github.fritaly.graphml4j.samples.GradleDependencies.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println(String.format("%s <output-file>", GradleDependencies.class.getSimpleName()));
        System.exit(1);//from  ww  w.j a va 2s  .c  o  m
    }

    final File file = new File(args[0]);

    System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ...");

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;
    Reader reader = null;
    LineNumberReader lineReader = null;

    try {
        fileWriter = new FileWriter(file);
        graphWriter = new GraphMLWriter(fileWriter);

        // Customize the rendering of nodes
        final NodeStyle nodeStyle = graphWriter.getNodeStyle();
        nodeStyle.setWidth(250.0f);

        graphWriter.setNodeStyle(nodeStyle);

        // The dependency graph has been generated by Gradle with the
        // command "gradle dependencies". The output of this command has
        // been saved to a text file which will be parsed to rebuild the
        // dependency graph
        reader = new InputStreamReader(GradleDependencies.class.getResourceAsStream("gradle-dependencies.txt"));
        lineReader = new LineNumberReader(reader);

        String line = null;

        // Stack containing the node identifiers per depth inside the
        // dependency graph (the topmost dependency is the first one in the
        // stack)
        final Stack<String> parentIds = new Stack<String>();

        // Open the graph
        graphWriter.graph();

        // Map storing the node identifiers per label
        final Map<String, String> nodeIdsByLabel = new TreeMap<String, String>();

        while ((line = lineReader.readLine()) != null) {
            // Determine the depth of the current dependency inside the
            // graph. The depth can be inferred from the indentation used by
            // Gradle. Each level of depth adds 5 more characters of
            // indentation
            final int initialLength = line.length();

            // Remove the strings used by Gradle to indent dependencies
            line = StringUtils.replace(line, "+--- ", "");
            line = StringUtils.replace(line, "|    ", "");
            line = StringUtils.replace(line, "\\--- ", "");
            line = StringUtils.replace(line, "     ", "");

            // The depth can easily be inferred now
            final int depth = (initialLength - line.length()) / 5;

            // Remove unnecessary node ids
            while (depth <= parentIds.size()) {
                parentIds.pop();
            }

            // Compute a nice label from the dependency (group, artifact,
            // version) tuple
            final String label = computeLabel(line);

            // Has this dependency already been added to the graph ?
            if (!nodeIdsByLabel.containsKey(label)) {
                // No, add the node
                nodeIdsByLabel.put(label, graphWriter.node(label));
            }

            final String nodeId = nodeIdsByLabel.get(label);

            parentIds.push(nodeId);

            if (parentIds.size() > 1) {
                // Generate an edge between the current node and its parent
                graphWriter.edge(parentIds.get(parentIds.size() - 2), nodeId);
            }
        }

        // Close the graph
        graphWriter.closeGraph();

        System.out.println("Done");
    } finally {
        // Calling GraphMLWriter.close() is necessary to dispose the underlying resources
        graphWriter.close();
        fileWriter.close();
        lineReader.close();
        reader.close();
    }
}

From source file:EchoClient.java

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

   ServerSocket serverSocket = null;
   try {//from ww  w.j  ava2s .c om
      serverSocket = new ServerSocket(4444);
   } catch (IOException e) {
      System.err.println("Could not listen on port: 4444.");
      System.exit(1);
   }

   Socket clientSocket = null;
   try {
      clientSocket = serverSocket.accept();
   } catch (IOException e) {
      System.err.println("Accept failed.");
      System.exit(1);
   }

   PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
   BufferedReader in = new BufferedReader(new InputStreamReader(
         clientSocket.getInputStream()));
   String inputLine, outputLine;
   KnockKnockProtocol kkp = new KnockKnockProtocol();

   outputLine = kkp.processInput(null);
   out.println(outputLine);

   while ((inputLine = in.readLine()) != null) {
      outputLine = kkp.processInput(inputLine);
      out.println(outputLine);
      if (outputLine.equals("Bye."))
         break;
   }
   out.close();
   in.close();
   clientSocket.close();
   serverSocket.close();
}

From source file:markov.java

/**
 * @param args/*  w w w .java 2 s  .  co m*/
 */
public static void main(String[] args) {

    // hack: eclipse don't support IO redirection worth a shit
    // try {
    // System.setIn(new FileInputStream("./json"));
    // } catch (FileNotFoundException e1) {
    // // TODO Auto-generated catch block
    // e1.printStackTrace();
    // }

    boolean graphMode = false;
    boolean jsonMode = false;
    boolean jsonRecoverMode = false;
    boolean endNode = false;

    int count = -1;

    long n = 0;
    long sumOfSqr = 0;
    long sum = 0;

    for (String s : args) {

        if (!s.matches("^-[vegjJh]*(c[0-9]*)?$")) {
            System.out.println("invalid argument");
            return;
        }

        if (s.matches("^-.*h.*")) {
            System.out.println(HELP);
            return;
        }
        if (s.matches("^-.*v.*")) {
            verbose = true;
            log("verbose mode");
        }
        if (s.matches("^-.*g.*")) {
            graphMode = true;
            log("graph mode");
        }
        if (s.matches("^-.*j.*")) {
            jsonMode = true;
            log("json mode");
        }
        if (s.matches("^-.*J.*")) {
            jsonRecoverMode = true;
            log("json recover mode");
        }
        if (s.matches("^-.*e.*")) {
            endNode = true;
            log("include end node");
        }
        if (s.matches("^-.*c[0-9]*$")) {
            log("counted output mode");
            count = Integer.parseInt(s.replaceAll("^-.*c", ""));
        }

        boolean error = (graphMode == true && jsonMode == true);
        if (!error) {
            error = (count > -1) && (graphMode == true || jsonMode == true);
        }

        if (error) {
            System.err.println("[error] switches j, g and, c are mutualy exclusive.");
            return;
        }

    }

    StateTransitionDiagram<Character> std;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    try {
        if (!jsonRecoverMode) {
            Trainer<Character> trainer = new Trainer<Character>();
            String s = br.readLine();
            while (s != null) {
                trainer.train(string2List(s));
                n++;
                sumOfSqr += s.length() * s.length();
                sum += s.length();
                s = br.readLine();
            }
            if (n == 0) {
                System.err
                        .println("Invalid corpus: At least one sample is required, two to make it interesting");
                return;
            }
            std = trainer.getTransitionDiagram();
        } else {
            std = new StateTransitionDiagram<Character>();
            GsonStub gstub = new Gson().fromJson(br, GsonStub.class);
            n = gstub.meta.n;
            sum = gstub.meta.sum;
            sumOfSqr = gstub.meta.sumOfSqr;

            for (Entry<String, StateStub> entry : gstub.states.entrySet()) {
                State<Character> state;
                if (entry.getKey().equals("null")) {
                    state = std.getGuard();
                } else {
                    state = std.getState(Character.valueOf(entry.getKey().charAt(0)));
                }
                for (Entry<String, Integer> transitions : entry.getValue().transitions.entrySet()) {
                    State<Character> tranny;
                    if (transitions.getKey().equals("null")) {
                        tranny = std.getGuard();
                    } else {
                        tranny = std.getState(Character.valueOf(transitions.getKey().charAt(0)));
                    }

                    state.addTransition(tranny.getValue(), transitions.getValue());
                }
            }
        }
        if (graphMode) {
            if (endNode) {
                System.out.println(std.toString());
            } else {
                System.out.println(std.removeEndGuards().toString());
            }
            return;
        }
        if (jsonMode) {
            Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

            String partialJson;
            if (endNode) {
                partialJson = gson.toJson(std);
            } else {
                partialJson = gson.toJson(std.removeEndGuards());
            }
            GsonStub gstub = new Gson().fromJson(partialJson, GsonStub.class);
            gstub.meta = new Meta();
            gstub.meta.n = n;
            gstub.meta.sum = sum;
            gstub.meta.sumOfSqr = sumOfSqr;

            System.out.println(gson.toJson(gstub));
            return;
        }

        Generator<Character> generator;
        if (endNode) {
            generator = new EndTagGenerator<Character>(std);
        } else {
            double sd = ((double) sumOfSqr - (double) (sum * sum) / (double) n) / (double) (n - 1);
            double mean = (double) sum / (double) n;
            log(String.format("mean: %.4f sd: %.4f", mean, sd));
            NormalDistributionImpl dist = new NormalDistributionImpl(mean, sd);
            generator = new NormalizedGenerator<Character>(std.removeEndGuards(), dist);
        }
        if (count >= 0) {
            for (int c = 0; c < count; c++) {
                output(generator);
            }
        } else {
            while (true) {
                output(generator);
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.zarkonnen.longan.Main.java

public static void main(String[] args) throws IOException {
    // Use Apache Commons CLI (packaged into the Jar) to parse command line options.
    Options options = new Options();
    Option helpO = OptionBuilder.withDescription("print help").create("h");
    Option versionO = OptionBuilder.withDescription("print version").create("v");
    Option outputO = OptionBuilder.withDescription("output file").withLongOpt("out").hasArg()
            .withArgName("file").create("o");
    Option formatO = OptionBuilder
            .withDescription("output format: one of plaintext (default) and visualize (debug output in png)")
            .hasArg().withArgName("format").withLongOpt("format").create();
    Option serverO = OptionBuilder.withDescription("launches server mode: Server mode reads "
            + "command line strings one per line exactly as above. If no output file is "
            + "specified, returns a line containing the number of output lines before the "
            + "output. If there is an error, returns a single line with the error message. "
            + "Shut down server by sending \"quit\".").withLongOpt("server").create();
    Option openCLO = OptionBuilder
            .withDescription(/*from  ww  w .j  a v a2 s.co m*/
                    "enables use of the graphics card to " + "support the OCR system. Defaults to true.")
            .withLongOpt("enable-opencl").hasArg().withArgName("enabled").create();
    options.addOption(helpO);
    options.addOption(versionO);
    options.addOption(outputO);
    options.addOption(formatO);
    options.addOption(serverO);
    options.addOption(openCLO);
    CommandLineParser clp = new GnuParser();
    try {
        CommandLine line = clp.parse(options, args);
        if (line.hasOption("h")) {
            new HelpFormatter().printHelp(INVOCATION, options);
            System.exit(0);
        }
        if (line.hasOption("v")) {
            System.out.println(Longan.VERSION);
            System.exit(0);
        }
        boolean enableOpenCL = true;
        if (line.hasOption("enable-opencl")) {
            enableOpenCL = line.getOptionValue("enable-opencl").toLowerCase().equals("true")
                    || line.getOptionValue("enable-opencl").equals("1");
        }
        if (line.hasOption("server")) {
            Longan longan = Longan.getDefaultImplementation(enableOpenCL);
            BufferedReader inputR = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String input = inputR.readLine();
                if (input.trim().equals("quit")) {
                    return;
                }
                String[] args2 = splitInput(input);
                Options o2 = new Options();
                o2.addOption(outputO);
                o2.addOption(formatO);
                try {
                    line = clp.parse(o2, args2);

                    File outFile = null;
                    if (line.hasOption("o")) {
                        outFile = new File(line.getOptionValue("o"));
                    }

                    ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
                    if (format != DEFAULT_FORMAT && outFile == null) {
                        System.out.println("You must specify an output file for non-plaintext output.");
                        continue;
                    }

                    if (line.getArgList().isEmpty()) {
                        System.out.println("Please specify an input image.");
                        continue;
                    }
                    if (line.getArgList().size() > 1) {
                        System.err.println("Please specify one input image at a time");
                        continue;
                    }

                    File inFile = new File((String) line.getArgList().get(0));

                    if (!inFile.exists()) {
                        System.out.println("The input image does not exist.");
                        continue;
                    }

                    try {
                        Result result = longan.process(ImageIO.read(inFile));
                        if (outFile == null) {
                            String txt = DEFAULT_FORMAT.convert(result);
                            System.out.println(numNewlines(txt) + 1);
                            System.out.print(txt);
                        } else {
                            if (outFile.getAbsoluteFile().getParentFile() != null
                                    && !outFile.getAbsoluteFile().getParentFile().exists()) {
                                outFile.getParentFile().mkdirs();
                            }
                            FileOutputStream fos = new FileOutputStream(outFile);
                            try {
                                format.write(result, fos);
                            } finally {
                                fos.close();
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("Processing error: " + exception(e));
                    }
                } catch (ParseException e) {
                    System.out.println("Input not recognized: " + exception(e));
                }
            } // End server loop
        } else {
            // Single invocation
            File outFile = null;
            if (line.hasOption("o")) {
                outFile = new File(line.getOptionValue("o"));
            }

            ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
            if (format != DEFAULT_FORMAT && outFile == null) {
                System.err.println("You must specify an output file for non-plaintext output.");
                System.exit(1);
            }

            if (line.getArgList().isEmpty()) {
                System.err.println("Please specify an input image.");
                new HelpFormatter().printHelp(INVOCATION, options);
                System.exit(1);
            }
            if (line.getArgList().size() > 1) {
                System.err.println("Please specify one input image only. To process multiple "
                        + "images, use server mode.");
                System.exit(1);
            }
            File inFile = new File((String) line.getArgList().get(0));

            if (!inFile.exists()) {
                System.err.println("The input image does not exist.");
                System.exit(1);
            }

            try {
                Result result = Longan.getDefaultImplementation(enableOpenCL).process(ImageIO.read(inFile));
                if (outFile == null) {
                    String txt = DEFAULT_FORMAT.convert(result);
                    System.out.print(txt);
                } else {
                    if (outFile.getAbsoluteFile().getParentFile() != null
                            && !outFile.getAbsoluteFile().getParentFile().exists()) {
                        outFile.getParentFile().mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(outFile);
                    try {
                        format.write(format.convert(result), fos);
                    } finally {
                        fos.close();
                    }
                }
            } catch (Exception e) {
                System.err.println("Processing error: " + exception(e));
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.println("Parsing command line input failed: " + exception(e));
        System.exit(1);
    }
}

From source file:com.genentech.chemistry.openEye.apps.SDFMolSeparator.java

/**
 * @param args//  ww w .j  a  va  2  s  .  c o m
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    SDFMolSeparator separator = new SDFMolSeparator(outFile);

    try {
        separator.run(inFile);

    } catch (IndexOutOfBoundsException iie) {
        System.err.println(iie.toString());
        exitWithHelp(options);
    } finally {
        separator.close();
    }

}

From source file:com.genentech.chemistry.openEye.apps.SDFConformerSampler.java

/**
 * @param args//from  w w w  . ja  v  a  2  s.com
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_MAX_CONFS, true, "Maximum number of conformations per input.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_TORSION_FILE, true, "Optional: to overwrite torsion definition file.");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String smartsFile = cmd.getOptionValue(OPT_TORSION_FILE);
    long maxConfs = Long.parseLong(cmd.getOptionValue(OPT_MAX_CONFS));

    SDFConformerSampler scanner = new SDFConformerSampler(smartsFile, outFile, maxConfs);

    scanner.run(inFile);
    scanner.close();
}

From source file:ca.uqac.lif.bullwinkle.BullwinkleCli.java

/**
 * @param args/*from w  w  w . j a  v a  2s  . c o m*/
 */
public static void main(String[] args) {
    // Setup parameters
    int verbosity = 1;
    String output_format = "xml", grammar_filename = null, filename_to_parse = null;

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2014 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file LICENSE-2.0 for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("f")) {
        output_format = c_line.getOptionValue("f");
    }
    // Get grammar file
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no grammar file specified");
        System.exit(ERR_ARGUMENTS);
    }
    grammar_filename = remaining_args.get(0);
    // Get file to parse, if any
    if (remaining_args.size() >= 2) {
        filename_to_parse = remaining_args.get(1);
    }

    // Read grammar file
    BnfParser parser = null;
    try {
        parser = new BnfParser(new File(grammar_filename));
    } catch (InvalidGrammarException e) {
        System.err.println("ERROR: invalid grammar");
        System.exit(ERR_GRAMMAR);
    } catch (IOException e) {
        System.err.println("ERROR reading grammar " + grammar_filename);
        System.exit(ERR_IO);
    }
    assert parser != null;

    // Read input file
    BufferedReader bis = null;
    if (filename_to_parse == null) {
        // Read from stdin
        bis = new BufferedReader(new InputStreamReader(System.in));
    } else {
        // Read from file
        try {
            bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename_to_parse))));
        } catch (FileNotFoundException e) {
            System.err.println("ERROR: file not found " + filename_to_parse);
            System.exit(ERR_IO);
        }
    }
    assert bis != null;
    String str;
    StringBuilder input_file = new StringBuilder();
    try {
        while ((str = bis.readLine()) != null) {
            input_file.append(str).append("\n");
        }
    } catch (IOException e) {
        System.err.println("ERROR reading input");
        System.exit(ERR_IO);
    }
    String file_contents = input_file.toString();

    // Parse contents of file
    ParseNode p_node = null;
    try {
        p_node = parser.parse(file_contents);
    } catch (ca.uqac.lif.bullwinkle.BnfParser.ParseException e) {
        System.err.println("ERROR parsing input\n");
        e.printStackTrace();
        System.exit(ERR_PARSE);
    }
    if (p_node == null) {
        System.err.println("ERROR parsing input\n");
        System.exit(ERR_PARSE);
    }
    assert p_node != null;

    // Output parse node to desired format
    PrintStream output = System.out;
    OutputFormatVisitor out_vis = null;
    if (output_format.compareToIgnoreCase("xml") == 0) {
        // Output to XML
        out_vis = new XmlVisitor();
    } else if (output_format.compareToIgnoreCase("dot") == 0) {
        // Output to DOT
        out_vis = new GraphvizVisitor();
    } else if (output_format.compareToIgnoreCase("txt") == 0) {
        // Output to indented plain text
        out_vis = new IndentedTextVisitor();
    } else if (output_format.compareToIgnoreCase("json") == 0) {
        // Output to JSON
    }
    if (out_vis == null) {
        System.err.println("ERROR: unknown output format " + output_format);
        System.exit(ERR_ARGUMENTS);
    }
    assert out_vis != null;
    p_node.prefixAccept(out_vis);
    output.print(out_vis.toOutputString());

    // Terminate without error
    System.exit(ERR_OK);
}