Example usage for java.io IOException IOException

List of usage examples for java.io IOException IOException

Introduction

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

Prototype

public IOException(Throwable cause) 

Source Link

Document

Constructs an IOException with the specified cause and a detail message of (cause==null ?

Usage

From source file:boa.compiler.BoaCompiler.java

public static void main(final String[] args) throws IOException {
    CommandLine cl = processCommandLineOptions(args);
    if (cl == null)
        return;/*from w  w  w  .ja v  a2s. c  o m*/
    final ArrayList<File> inputFiles = BoaCompiler.inputFiles;

    // get the name of the generated class
    final String className = getGeneratedClass(cl);

    // get the filename of the jar we will be writing
    final String jarName;
    if (cl.hasOption('o'))
        jarName = cl.getOptionValue('o');
    else
        jarName = className + ".jar";

    // make the output directory
    File outputRoot = null;
    if (cl.hasOption("cd")) {
        outputRoot = new File(cl.getOptionValue("cd"));
    } else {
        outputRoot = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString());
    }
    final File outputSrcDir = new File(outputRoot, "boa");
    if (!outputSrcDir.mkdirs())
        throw new IOException("unable to mkdir " + outputSrcDir);

    // find custom libs to load
    final List<URL> libs = new ArrayList<URL>();
    if (cl.hasOption('l'))
        for (final String lib : cl.getOptionValues('l'))
            libs.add(new File(lib).toURI().toURL());

    final File outputFile = new File(outputSrcDir, className + ".java");
    final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile));
    try {
        final List<String> jobnames = new ArrayList<String>();
        final List<String> jobs = new ArrayList<String>();
        boolean isSimple = true;

        final List<Program> visitorPrograms = new ArrayList<Program>();

        SymbolTable.initialize(libs);

        final int maxVisitors;
        if (cl.hasOption('v'))
            maxVisitors = Integer.parseInt(cl.getOptionValue('v'));
        else
            maxVisitors = Integer.MAX_VALUE;

        for (int i = 0; i < inputFiles.size(); i++) {
            final File f = inputFiles.get(i);
            try {
                final BoaLexer lexer = new BoaLexer(new ANTLRFileStream(f.getAbsolutePath()));
                lexer.removeErrorListeners();
                lexer.addErrorListener(new LexerErrorListener());

                final CommonTokenStream tokens = new CommonTokenStream(lexer);
                final BoaParser parser = new BoaParser(tokens);
                parser.removeErrorListeners();
                parser.addErrorListener(new BaseErrorListener() {
                    @Override
                    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                            int charPositionInLine, String msg, RecognitionException e)
                            throws ParseCancellationException {
                        throw new ParseCancellationException(e);
                    }
                });

                final BoaErrorListener parserErrorListener = new ParserErrorListener();
                final Start p = parse(tokens, parser, parserErrorListener);
                if (cl.hasOption("ast"))
                    new ASTPrintingVisitor().start(p);

                final String jobName = "" + i;

                try {
                    if (!parserErrorListener.hasError) {
                        new TypeCheckingVisitor().start(p, new SymbolTable());

                        final TaskClassifyingVisitor simpleVisitor = new TaskClassifyingVisitor();
                        simpleVisitor.start(p);

                        LOG.info(f.getName() + ": task complexity: "
                                + (!simpleVisitor.isComplex() ? "simple" : "complex"));
                        isSimple &= !simpleVisitor.isComplex();

                        new ShadowTypeEraser().start(p);
                        new InheritedAttributeTransformer().start(p);

                        new LocalAggregationTransformer().start(p);

                        // if a job has no visitor, let it have its own method
                        // also let jobs have own methods if visitor merging is disabled
                        if (!simpleVisitor.isComplex() || maxVisitors < 2 || inputFiles.size() == 1) {
                            new VisitorOptimizingTransformer().start(p);

                            if (cl.hasOption("pp"))
                                new PrettyPrintVisitor().start(p);
                            if (cl.hasOption("ast2"))
                                new ASTPrintingVisitor().start(p);
                            final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(jobName);
                            cg.start(p);
                            jobs.add(cg.getCode());

                            jobnames.add(jobName);
                        }
                        // if a job has visitors, fuse them all together into a single program
                        else {
                            p.getProgram().jobName = jobName;
                            visitorPrograms.add(p.getProgram());
                        }
                    }
                } catch (final TypeCheckException e) {
                    parserErrorListener.error("typecheck", lexer, null, e.n.beginLine, e.n.beginColumn,
                            e.n2.endColumn - e.n.beginColumn + 1, e.getMessage(), e);
                }
            } catch (final Exception e) {
                System.err.print(f.getName() + ": compilation failed: ");
                e.printStackTrace();
            }
        }

        if (!visitorPrograms.isEmpty())
            try {
                for (final Program p : new VisitorMergingTransformer().mergePrograms(visitorPrograms,
                        maxVisitors)) {
                    new VisitorOptimizingTransformer().start(p);

                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());

                    jobnames.add(p.jobName);
                }
            } catch (final Exception e) {
                System.err.println("error fusing visitors - falling back: " + e);
                e.printStackTrace();

                for (final Program p : visitorPrograms) {
                    new VisitorOptimizingTransformer().start(p);

                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());

                    jobnames.add(p.jobName);
                }
            }

        if (jobs.size() == 0)
            throw new RuntimeException("no files compiled without error");

        final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program");

        st.add("name", className);
        st.add("numreducers", inputFiles.size());
        st.add("jobs", jobs);
        st.add("jobnames", jobnames);
        st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings);
        st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings);
        st.add("splitsize", isSimple ? 64 * 1024 * 1024 : 10 * 1024 * 1024);
        if (DefaultProperties.localDataPath != null) {
            st.add("isLocal", true);
        }

        o.write(st.render().getBytes());
    } finally {
        o.close();
    }

    compileGeneratedSrc(cl, jarName, outputRoot, outputFile);
}

From source file:net.sf.mpaxs.test.ImpaxsExecution.java

/**
 *
 * @param args/*from  w ww  . jav  a  2  s . com*/
 */
public static void main(String[] args) {
    Options options = new Options();
    Option[] optionArray = new Option[] {
            OptionBuilder.withArgName("nhosts").hasArg()
                    .withDescription("Number of hosts for parallel processing").create("n"),
            OptionBuilder.withArgName("mjobs").hasArg().withDescription("Number of jobs to run in parallel")
                    .create("m"),
            OptionBuilder.withArgName("runmode").hasArg()
                    .withDescription("The mode in which to operate: one of <ALL,LOCAL,DISTRIBUTED>")
                    .create("r"), //            OptionBuilder.withArgName("gui").
            //            withDescription("Create gui for distributed execution").create("g")
    };
    for (Option opt : optionArray) {
        options.addOption(opt);
    }
    if (args.length == 0) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }
    GnuParser gp = new GnuParser();
    int nhosts = 1;
    int mjobs = 10;
    boolean gui = false;
    Mode mode = Mode.ALL;
    try {
        CommandLine cl = gp.parse(options, args);
        if (cl.hasOption("n")) {
            nhosts = Integer.parseInt(cl.getOptionValue("n"));
        }
        if (cl.hasOption("m")) {
            mjobs = Integer.parseInt(cl.getOptionValue("m"));
        }
        if (cl.hasOption("r")) {
            mode = Mode.valueOf(cl.getOptionValue("r"));
        }
        //            if (cl.hasOption("g")) {
        //                gui = true;
        //            }
    } catch (Exception ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }

    String version;
    try {
        version = net.sf.mpaxs.api.Version.getVersion();
        System.out.println("Running mpaxs " + version);
        File computeHostJarLocation = new File(System.getProperty("user.dir"), "mpaxs.jar");
        if (!computeHostJarLocation.exists() || !computeHostJarLocation.isFile()) {
            throw new IOException("Could not locate mpaxs.jar in " + System.getProperty("user.dir"));
        }
        final PropertiesConfiguration cfg = new PropertiesConfiguration();
        //set default execution type
        cfg.setProperty(ConfigurationKeys.KEY_EXECUTION_MODE, ExecutionType.DRMAA);
        //set location of compute host jar
        cfg.setProperty(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR, computeHostJarLocation);
        //do not exit to console when master server shuts down
        cfg.setProperty(ConfigurationKeys.KEY_MASTER_SERVER_EXIT_ON_SHUTDOWN, false);
        //limit the number of used compute hosts
        cfg.setProperty(ConfigurationKeys.KEY_MAX_NUMBER_OF_CHOSTS, nhosts);
        cfg.setProperty(ConfigurationKeys.KEY_NATIVE_SPEC, "");
        cfg.setProperty(ConfigurationKeys.KEY_GUI_MODE, gui);
        cfg.setProperty(ConfigurationKeys.KEY_SILENT_MODE, true);
        cfg.setProperty(ConfigurationKeys.KEY_SCHEDULE_WAIT_TIME, "500");
        final int maxJobs = mjobs;
        final int maxThreads = nhosts;
        final Mode runMode = mode;
        printMessage("Run mode: " + runMode);
        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                if (runMode == Mode.ALL || runMode == Mode.LOCAL) {
                    printMessage("Running Within VM Execution");
                    /*
                     * LOCAL within VM execution
                     */
                    WithinVmExecution lhe = new WithinVmExecution(maxJobs, maxThreads);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + lhe.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                if (runMode == Mode.ALL || runMode == Mode.DISTRIBUTED) {
                    printMessage("Running Distributed Host RMI Execution");
                    /*
                     * Grid Engine (DRMAA API) or local host distributed RMI execution
                     */
                    DistributedRmiExecution de = new DistributedRmiExecution(cfg, maxJobs);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + de.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.exit(0);
            }
        });
    } catch (IOException ex) {
        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.urbancode.terraform.main.Main.java

/**
 * This method initializes Terraform from the command line.
 * The static main method verifies the command line arguments and terminates if they are incorrect.
 * @param args/*from   w  w w .jav  a  2 s  . c o  m*/
 * @throws IOException
 * @throws XmlParsingException
 * @throws CredentialsException
 * @throws RestorationException
 * @throws DestructionException
 * @throws CreationException
 */
static public void main(String[] args) throws IOException, XmlParsingException, CredentialsException,
        CreationException, DestructionException, RestorationException {
    File inputXmlFile = null;
    File creds = null;
    List<String> unparsedArgs = new ArrayList<String>();
    String command = null;

    if (args != null && args.length >= 3) {
        if (!AllowedCommands.contains(args[0])) {
            String msg = "Invalid first argument: " + args[0];
            log.fatal(msg);
            throw new IOException(msg);
        } else {
            command = args[0].toLowerCase();
        }

        inputXmlFile = createFile(args[1]);
        creds = createFile(args[2]);

        Collections.addAll(unparsedArgs, args);
        // make args just the unparsed properties
        unparsedArgs.remove(0); // remove inputxmlpath
        unparsedArgs.remove(0); // remove create/destroy
        unparsedArgs.remove(0); // remove creds
    } else {
        log.fatal("Invalid number of arguments!\n" + "Found " + args.length + "\n" + "Expected at least 3");
        throw new IOException("improper args");
    }

    // check to make sure we have legit args
    if (inputXmlFile == null) {
        String msg = "No input xml file specified!";
        throw new IOException(msg);
    }
    if (creds == null) {
        String msg = "No credentials file specified!";
        throw new IOException(msg);
    }

    Main myMain = new Main(command, inputXmlFile, creds, unparsedArgs);
    myMain.execute();
}

From source file:de.huberlin.cuneiform.main.Main.java

public static void main(String[] args)
        throws ParseException, IOException, NotDerivableException, InterruptedException, JSONException {

    GnuParser gnuParser;// w  w w  .  j a  v  a 2 s .c o  m
    CommandLine cmdline;
    Options opt;
    String value;
    int platform;
    File outputDir;
    String[] fileList;
    StringBuffer buf;
    String line;
    String dagid;
    File logFile;

    opt = new Options();

    opt.addOption("p", "platform", true, "The platform to perform the Cuneiform script's interpretation. "
            + "Possible platforms are: 'dot', 'local', and 'debug'. Default is 'local'.");

    opt.addOption("d", "directory", true,
            "The output directory, to put the interpretation intermediate and output result as well as the default location to store the log.");

    opt.addOption("c", "clean", false,
            "If set, the execution engine ignores all cached results and starts a clean workflow run.");

    opt.addOption("r", "runid", true,
            "If set, a custom id is set for this workflow run. By default a UUID string is used.");

    opt.addOption("f", "file", true,
            "Override the default location of the log file and use the specified filename instead. If the platform is 'dot', this option sets the name of the output dot-file.");

    opt.addOption("h", "help", false, "Print help text.");

    gnuParser = new GnuParser();
    cmdline = gnuParser.parse(opt, args);

    if (cmdline.hasOption("help")) {

        System.out.println("CUNEIFORM - A Functional Workflow Language\n" + LABEL_VERSION);
        new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

        return;
    }

    if (cmdline.hasOption("platform")) {

        value = cmdline.getOptionValue("platform");

        if (value.equals("dot"))
            platform = PLATFORM_DOT;
        else if (value.equals("local"))
            platform = PLATFORM_LOCAL;
        else if (value.equals("debug"))
            platform = PLATFORM_DEBUG;
        else
            throw new RuntimeException("Specified platform '" + value + "' not recognized.");

    } else
        platform = PLATFORM_LOCAL;

    if (cmdline.hasOption('d')) {

        value = cmdline.getOptionValue('d');
    } else
        value = "build";

    outputDir = new File(value);

    if (outputDir.exists()) {

        if (!outputDir.isDirectory())
            throw new IOException(
                    "Output directory '" + outputDir.getAbsolutePath() + "' exists but is not a directory.");

        else if (cmdline.hasOption('c')) {

            FileUtils.deleteDirectory(outputDir);

            if (!outputDir.mkdirs())
                throw new IOException(
                        "Could not create output directory '" + outputDir.getAbsolutePath() + "'");
        }
    } else if (!outputDir.mkdirs())
        throw new IOException("Could not create output directory '" + outputDir.getAbsolutePath() + "'");

    if (cmdline.hasOption('r'))
        dagid = cmdline.getOptionValue('r');
    else
        dagid = UUID.randomUUID().toString();

    if (cmdline.hasOption('f'))
        logFile = new File(cmdline.getOptionValue('f'));
    else
        logFile = null;

    fileList = cmdline.getArgs();
    buf = new StringBuffer();
    if (fileList.length == 0) {

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {

            while ((line = reader.readLine()) != null)
                buf.append(line).append('\n');
        }

        switch (platform) {

        case PLATFORM_DOT:
            createDot(buf.toString(), outputDir, logFile);
            break;
        case PLATFORM_LOCAL:
            runLocal(buf.toString(), outputDir, logFile, dagid);
            break;
        case PLATFORM_DEBUG:
            runDebug(buf.toString(), outputDir, logFile, dagid);
            break;
        default:
            throw new RuntimeException("Platform not recognized.");
        }
    } else

        switch (platform) {

        case PLATFORM_DOT:
            createDot(fileList, outputDir, logFile);
            break;
        case PLATFORM_LOCAL:
            runLocal(fileList, outputDir, logFile, dagid);
            break;
        case PLATFORM_DEBUG:
            runDebug(fileList, outputDir, logFile, dagid);
            break;
        default:
            throw new RuntimeException("Platform not recognized.");
        }

}

From source file:com.soulgalore.velocity.MergeXMLWithVelocity.java

/**
 * Merge a xml file with Velocity template. The third parameter is the properties file, where the
 * key/value is added to the velocity context. The fourth parameter is the output file. If not
 * included, the result is printed to system.out.
 * /*from ww w  . j a  v a2 s .com*/
 * @param args are file.xml template.vm properties.prop [output.file]
 * @throws JDOMException if the xml file couldn't be parsed
 * @throws IOException couldn't find one of the files
 */
public static void main(String[] args) throws JDOMException, IOException {

    if (args.length < 3) {
        System.out.println(
                "Missing input files. XMLToVelocity file.xml template.vm prop.properties [output.file]");
        return;
    }

    final Properties properties = new Properties();
    final File prop = new File(args[2]);

    if (prop.exists())
        properties.load(new FileReader(prop));
    else
        throw new IOException("Couldn't find the property file:" + prop.getAbsolutePath());

    final MergeXMLWithVelocity xtv = new MergeXMLWithVelocity(properties);
    xtv.create(args);
}

From source file:MailHandlerDemo.java

/**
 * Runs the demo./*from   w ww  . j av a 2s  . c o m*/
 *
 * @param args the command line arguments
 * @throws IOException if there is a problem.
 */
public static void main(String[] args) throws IOException {
    List<String> l = Arrays.asList(args);
    if (l.contains("/?") || l.contains("-?") || l.contains("-help")) {
        LOGGER.info("Usage: java MailHandlerDemo " + "[[-all] | [-body] | [-custom] | [-debug] | [-low] "
                + "| [-simple] | [-pushlevel] | [-pushfilter] " + "| [-pushnormal] | [-pushonly]] " + "\n\n"
                + "-all\t\t: Execute all demos.\n" + "-body\t\t: An email with all records and only a body.\n"
                + "-custom\t\t: An email with attachments and dynamic names.\n"
                + "-debug\t\t: Output basic debug information about the JVM " + "and log configuration.\n"
                + "-low\t\t: Generates multiple emails due to low capacity." + "\n"
                + "-simple\t\t: An email with all records with body and " + "an attachment.\n"
                + "-pushlevel\t: Generates high priority emails when the"
                + " push level is triggered and normal priority when " + "flushed.\n"
                + "-pushFilter\t: Generates high priority emails when the "
                + "push level and the push filter is triggered and normal " + "priority emails when flushed.\n"
                + "-pushnormal\t: Generates multiple emails when the "
                + "MemoryHandler push level is triggered.  All generated "
                + "email are sent as normal priority.\n" + "-pushonly\t: Generates multiple emails when the "
                + "MemoryHandler push level is triggered.  Generates high "
                + "priority emails when the push level is triggered and " + "normal priority when flushed.\n");
    } else {
        final boolean debug = init(l); //may create log messages.
        try {
            LOGGER.log(Level.FINEST, "This is the finest part of the demo.",
                    new MessagingException("Fake JavaMail issue."));
            LOGGER.log(Level.FINER, "This is the finer part of the demo.",
                    new NullPointerException("Fake bug."));
            LOGGER.log(Level.FINE, "This is the fine part of the demo.");
            LOGGER.log(Level.CONFIG, "Logging config file is {0}.", getConfigLocation());
            LOGGER.log(Level.INFO, "Your temp directory is {0}, " + "please wait...", getTempDir());

            try { //Waste some time for the custom formatter.
                Thread.sleep(3L * 1000L);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

            LOGGER.log(Level.WARNING, "This is a warning.",
                    new FileNotFoundException("Fake file chooser issue."));
            LOGGER.log(Level.SEVERE, "The end of the demo.", new IOException("Fake access denied issue."));
        } finally {
            closeHandlers();
        }

        //Force parse errors.  This does have side effects.
        if (debug && getConfigLocation() != null) {
            LogManager.getLogManager().readConfiguration();
        }
    }
}

From source file:com.svds.genericconsumer.main.GenericConsumerGroup.java

/**
 * Given command-line arguments, create GenericConsumerGroup
 * // w  ww .ja v  a  2s .c o m
 * @param args  command-line arguments to parse
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    LOG.info("HELLO from main");

    Options options = new Options();
    options.addOption(OptionBuilder.isRequired().withLongOpt(ZOOKEEPER).withDescription("Zookeeper servers")
            .hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(GROUPID).withDescription("Kafka group id").hasArg()
            .create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(TOPICNAME).withDescription("Kafka topic name")
            .hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(THREADS).withType(Number.class)
            .withDescription("Number of threads").hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(CONSUMERCLASS)
            .withDescription("Consumer Class from processing topic name").hasArg().create());

    options.addOption(OptionBuilder.withLongOpt(PARAMETERS)
            .withDescription("Parameters needed for the consumer Class if needed").hasArgs()
            .withValueSeparator(',').create());

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        LOG.error(e.getMessage(), e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("GenericConsumerGroup.main", options);
        throw new IOException(e);
    }

    try {
        GenericConsumerGroup consumerGroupExample = new GenericConsumerGroup();
        consumerGroupExample.doWork(cmd);
    } catch (ParseException ex) {
        LOG.error("Error parsing command-line args");
        throw new IOException(ex);
    }
}

From source file:embedding.ExampleJava2D2PDF.java

/**
 * Main method./*from   ww  w.  j  ava 2s  .  c  o m*/
 * @param args command-line arguments
 */
public static void main(String[] args) {
    try {
        System.out.println("FOP " + ExampleJava2D2PDF.class.getSimpleName() + "\n");
        System.out.println("Preparing...");

        //Setup directories
        File baseDir = new File(".");
        File outDir = new File(baseDir, "out");
        if (!outDir.isDirectory()) {
            if (!outDir.mkdirs()) {
                throw new IOException("Could not create output directory: " + outDir);
            }
        }

        //Setup output file
        File pdffile = new File(outDir, "ResultJava2D2PDF.pdf");

        System.out.println("Output: PDF (" + pdffile + ")");
        System.out.println();
        System.out.println("Generating...");

        ExampleJava2D2PDF app = new ExampleJava2D2PDF();
        app.generatePDF(pdffile);

        System.out.println("Success!");
    } catch (Throwable t) {
        t.printStackTrace(System.err);
        System.exit(-1);
    }
}

From source file:PopClean.java

public static void main(String args[]) {
    try {/*w w  w.j  a  va2s  . c o  m*/
        String hostname = null, username = null, password = null;
        int port = 110;
        int sizelimit = -1;
        String subjectPattern = null;
        Pattern pattern = null;
        Matcher matcher = null;
        boolean delete = false;
        boolean confirm = true;

        // Handle command-line arguments
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-user"))
                username = args[++i];
            else if (args[i].equals("-pass"))
                password = args[++i];
            else if (args[i].equals("-host"))
                hostname = args[++i];
            else if (args[i].equals("-port"))
                port = Integer.parseInt(args[++i]);
            else if (args[i].equals("-size"))
                sizelimit = Integer.parseInt(args[++i]);
            else if (args[i].equals("-subject"))
                subjectPattern = args[++i];
            else if (args[i].equals("-debug"))
                debug = true;
            else if (args[i].equals("-delete"))
                delete = true;
            else if (args[i].equals("-force")) // don't confirm
                confirm = false;
        }

        // Verify them
        if (hostname == null || username == null || password == null || sizelimit == -1)
            usage();

        // Make sure the pattern is a valid regexp
        if (subjectPattern != null) {
            pattern = Pattern.compile(subjectPattern);
            matcher = pattern.matcher("");
        }

        // Say what we are going to do
        System.out
                .println("Connecting to " + hostname + " on port " + port + " with username " + username + ".");
        if (delete) {
            System.out.println("Will delete all messages longer than " + sizelimit + " bytes");
            if (subjectPattern != null)
                System.out.println("that have a subject matching: [" + subjectPattern + "]");
        } else {
            System.out.println("Will list subject lines for messages " + "longer than " + sizelimit + " bytes");
            if (subjectPattern != null)
                System.out.println("that have a subject matching: [" + subjectPattern + "]");
        }

        // If asked to delete, ask for confirmation unless -force is given
        if (delete && confirm) {
            System.out.println();
            System.out.print("Do you want to proceed (y/n) [n]: ");
            System.out.flush();
            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            String response = console.readLine();
            if (!response.equals("y")) {
                System.out.println("No messages deleted.");
                System.exit(0);
            }
        }

        // Connect to the server, and set up streams
        s = new Socket(hostname, port);
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

        // Read the welcome message from the server, confirming it is OK.
        System.out.println("Connected: " + checkResponse());

        // Now log in
        send("USER " + username); // Send username, wait for response
        send("PASS " + password); // Send password, wait for response
        System.out.println("Logged in");

        // Check how many messages are waiting, and report it
        String stat = send("STAT");
        StringTokenizer t = new StringTokenizer(stat);
        System.out.println(t.nextToken() + " messages in mailbox.");
        System.out.println("Total size: " + t.nextToken());

        // Get a list of message numbers and sizes
        send("LIST"); // Send LIST command, wait for OK response.
        // Now read lines from the server until we get . by itself
        List msgs = new ArrayList();
        String line;
        for (;;) {
            line = in.readLine();
            if (line == null)
                throw new IOException("Unexpected EOF");
            if (line.equals("."))
                break;
            msgs.add(line);
        }

        // Now loop through the lines we read one at a time.
        // Each line should specify the message number and its size.
        int nummsgs = msgs.size();
        for (int i = 0; i < nummsgs; i++) {
            String m = (String) msgs.get(i);
            StringTokenizer st = new StringTokenizer(m);
            int msgnum = Integer.parseInt(st.nextToken());
            int msgsize = Integer.parseInt(st.nextToken());

            // If the message is too small, ignore it.
            if (msgsize <= sizelimit)
                continue;

            // If we're listing messages, or matching subject lines
            // find the subject line for this message
            String subject = null;
            if (!delete || pattern != null) {
                subject = getSubject(msgnum); // get the subject line

                // If we couldn't find a subject, skip the message
                if (subject == null)
                    continue;

                // If this subject does not match the pattern, then
                // skip the message
                if (pattern != null) {
                    matcher.reset(subject);
                    if (!matcher.matches())
                        continue;
                }

                // If we are listing, list this message
                if (!delete) {
                    System.out.println("Subject " + msgnum + ": " + subject);
                    continue; // so we never delete it
                }
            }

            // If we were asked to delete, then delete the message
            if (delete) {
                send("DELE " + msgnum);
                if (pattern == null)
                    System.out.println("Deleted message " + msgnum);
                else
                    System.out.println("Deleted message " + msgnum + ": " + subject);
            }
        }

        // When we're done, log out and shutdown the connection
        shutdown();
    } catch (Exception e) {
        // If anything goes wrong print exception and show usage
        System.err.println(e);
        usage();
        // Always try to shutdown nicely so the server doesn't hang on us
        shutdown();
    }
}

From source file:edu.msu.cme.rdp.abundstats.cli.AbundMain.java

public static void main(String[] args) throws IOException {
    File inputFile;//from   w  w w.  j a  v a  2s  .  c  o m
    File resultDir = new File(".");
    RPlotter plotter = null;
    boolean isClusterFile = true;
    List<AbundStatsCalculator> statCalcs = new ArrayList();
    double clustCutoffFrom = Double.MIN_VALUE, clustCutoffTo = Double.MAX_VALUE;

    String usage = "Main [options] <cluster file>";
    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("result-dir")) {
            resultDir = new File(line.getOptionValue("result-dir"));
            if (!resultDir.exists() && !resultDir.mkdirs()) {
                throw new Exception(
                        "Result directory " + resultDir + " does not exist and could not be created");
            }
        }

        if (line.hasOption("R-location")) {
            plotter = new RPlotter();
            plotter.setCommandTemplate(rplotterTemplate);
            plotter.setRPath(line.getOptionValue("R-location"));
            plotter.setOutFileExt(".png");

            if (!new File(plotter.getRPath()).canExecute()) {
                throw new Exception(plotter.getRPath() + " does not exist or is not exectuable");
            }
        }

        if (line.hasOption("lower-cutoff")) {
            clustCutoffFrom = Double.valueOf(line.getOptionValue("lower-cutoff"));
        }

        if (line.hasOption("upper-cutoff")) {
            clustCutoffTo = Double.valueOf(line.getOptionValue("upper-cutoff"));
        }

        if (line.hasOption("jaccard")) {
            statCalcs.add(new Jaccard(true));
        }

        if (line.hasOption("sorensen")) {
            statCalcs.add(new Sorensen(true));
        }

        if (line.hasOption("otu-table")) {
            isClusterFile = false;
        }

        if (statCalcs.isEmpty()) {
            throw new Exception("Must specify at least one stat to compute (jaccard, sorensen)");
        }

        args = line.getArgs();
        if (args.length != 1) {
            throw new Exception("Unexpected number of command line arguments");
        }

        inputFile = new File(args[0]);

    } catch (Exception e) {
        new HelpFormatter().printHelp(usage, options);
        System.err.println("Error: " + e.getMessage());
        return;
    }

    if (isClusterFile) {
        RDPClustParser parser;
        parser = new RDPClustParser(inputFile);

        try {
            if (parser.getClusterSamples().size() == 1) {
                throw new IOException("Cluster file must have more than one sample");
            }

            List<Cutoff> cutoffs = parser.getCutoffs(clustCutoffFrom, clustCutoffTo);
            if (cutoffs.isEmpty()) {
                throw new IOException(
                        "No cutoffs in cluster file in range [" + clustCutoffFrom + "-" + clustCutoffTo + "]");
            }

            for (Cutoff cutoff : cutoffs) {
                List<Sample> samples = new ArrayList();

                for (ClusterSample clustSample : parser.getClusterSamples()) {
                    Sample s = new Sample(clustSample.getName());
                    for (Cluster clust : cutoff.getClusters().get(clustSample.getName())) {
                        s.addSpecies(clust.getNumberOfSeqs());
                    }
                    samples.add(s);
                }

                processSamples(samples, statCalcs, resultDir, cutoff.getCutoff() + "_", plotter);
            }

        } finally {
            parser.close();
        }
    } else {
        List<Sample> samples = new ArrayList();
        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        String line = reader.readLine();

        if (line == null || line.split("\\s+").length < 2) {
            throw new IOException("Must be 2 or more samples for abundance statistic calculations!");
        }
        int numSamples = line.split("\\s+").length;

        boolean header = true;
        try {
            Integer.valueOf(line.split("\\s+")[0]);
            header = false;
        } catch (Exception e) {
        }

        if (header) {
            for (String s : line.split("\\s+")) {
                samples.add(new Sample(s));
            }
        } else {
            int sample = 0;
            for (String s : line.split("\\s+")) {
                samples.add(new Sample("" + sample));
                samples.get(sample).addSpecies(Integer.valueOf(s));
                sample++;
            }
        }

        int lineno = 2;
        while ((line = reader.readLine()) != null) {
            if (line.trim().equals("")) {
                continue;
            }
            int sample = 0;
            if (line.split("\\s+").length != numSamples) {
                System.err.println(
                        "Line number " + lineno + " didn't have the expected number of samples (contained "
                                + line.split("\\s+").length + ", expected " + numSamples + ")");
            }

            for (String s : line.split("\\s+")) {
                samples.get(sample).addSpecies(Integer.valueOf(s));
                sample++;
            }

            lineno++;
        }

        processSamples(samples, statCalcs, resultDir, inputFile.getName(), plotter);
    }
}