de.ailis.microblinks.blinks.compiler.Main.java Source code

Java tutorial

Introduction

Here is the source code for de.ailis.microblinks.blinks.compiler.Main.java

Source

/*
 * Copyright (C) 2010 Klaus Reimer <k@ailis.de>
 * See LICENSE.md for licensing information.
 */

package de.ailis.microblinks.blinks.compiler;

import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import de.ailis.microblinks.blinks.logging.LogHandler;
import de.ailis.microblinks.blinks.utils.ResourceUtils;

/**
 * Command-line interface.
 *
 * @author Klaus Reimer (k@ailis.de)
 */
public class Main {
    /** The logger */
    private static final Log log = LogFactory.getLog(Main.class);

    /** The program name. */
    private static final String progName = "blinksc";

    /** If we are in debug mode or not. */
    private boolean debug = false;

    /**
     * Display command line help.
     *
     * @throws IOException
     *             When help.txt could not be read.
     */
    private void help() throws IOException {
        System.out.print(ResourceUtils.readText(getClass().getResource("help.txt")));
        System.exit(0);
    }

    /**
     * Display version information.
     *
     * @throws IOException
     *             When version.txt could not be read.
     */
    private void version() throws IOException {
        System.out.print(ResourceUtils.readText(getClass().getResource("version.txt")));
        System.exit(0);
    }

    /**
     * Outputs a usage error message
     *
     * @param message
     *            The error message
     */
    protected void wrongUsage(final String message) {
        log.error(message + "\nTry '" + progName + " --help' for more information.");
        System.exit(2);
    }

    /**
     * Processes command-line options.
     *
     * @param args
     *            The command-line arguments.
     * @throws IOException
     *             When an IO error occured.
     * @return The remaining parameters
     */
    private String[] processOptions(final String[] args) throws IOException {
        // Build LongOpts
        final LongOpt[] longOpts = new LongOpt[] { new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'),
                new LongOpt("version", LongOpt.NO_ARGUMENT, null, 'V'),
                new LongOpt("debug", LongOpt.NO_ARGUMENT, null, 'd') };

        // Build ShortOpts
        final StringBuilder shortOptsBuilder = new StringBuilder();
        for (final LongOpt longOpt : longOpts) {
            shortOptsBuilder.append((char) longOpt.getVal());
            if (longOpt.getHasArg() == LongOpt.REQUIRED_ARGUMENT) {
                shortOptsBuilder.append(':');
            }
        }
        final String shortOpts = shortOptsBuilder.toString();

        // Parse options
        final Getopt opts = new Getopt(progName, args, shortOpts, longOpts);

        // Process options
        int c;
        while ((c = opts.getopt()) != -1) {
            switch (c) {
            case 'd':
                this.debug = true;
                Logger.getLogger("").setLevel(Level.ALL);
                break;

            case 'V':
                version();
                break;

            default:
                help();
                break;

            }
        }

        // Generate parameters,
        final String[] params = new String[args.length - opts.getOptind()];
        int p = 0;
        for (int i = opts.getOptind(); i < args.length; i++) {
            params[p] = args[i];
            p++;
        }
        return params;
    }

    /**
     * Setups logging.
     */
    private void setupLogging() {
        final Logger logger = Logger.getLogger("");
        for (final Handler handler : logger.getHandlers()) {
            logger.removeHandler(handler);
        }
        logger.addHandler(new LogHandler(progName));
    }

    /**
     * Runs the program.
     *
     * @param args
     *            The command-line arguments.
     * @throws IOException
     *             When an IO exception occures.
     */
    public void run(final String[] args) throws IOException {
        setupLogging();
        final String[] params = processOptions(args);

        if (params.length > 2) {
            wrongUsage("Too many arguments");
        }
        final boolean hasInputFile = params.length > 0 && !"-".equals(params[0]);
        final boolean hasOutputFile = params.length > 1 && !"-".equals(params[1]);
        try (final InputStream input = hasInputFile ? new FileInputStream(params[0]) : System.in;
                final OutputStream output = hasOutputFile ? new FileOutputStream(params[1]) : System.out) {
            output.write(new Compiler().compile(input));
        }
    }

    /**
     * Main method.
     *
     * @param args
     *            The command-line arguments.
     */
    public static void main(final String[] args) {
        final Main main = new Main();
        try {
            main.run(args);
        } catch (final Exception e) {
            if (main.debug) {
                log.error(e.toString(), e);
            } else {
                log.error(e.getMessage());
            }
            System.exit(1);
        }
    }
}