Example usage for org.apache.commons.cli CommandLine getArgs

List of usage examples for org.apache.commons.cli CommandLine getArgs

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getArgs.

Prototype

public String[] getArgs() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:com.genentech.application.property.TPSA.java

public static void main(String args[]) {
    try {/*from  w  w w . j  a v a2  s.  c om*/
        boolean countP = false;
        boolean countS = false;
        String[] molFiles;
        // create Options object
        Options options = new Options();

        // add  options
        options.addOption("P", false, "Count phosphorus atoms");
        options.addOption("S", false, "Count sulfur atoms");

        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("P"))
            countP = true;
        if (cmd.hasOption("S"))
            countS = true;

        //get rest of arguments as an array of string
        molFiles = cmd.getArgs();
        if (molFiles.length < 1) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("TPSA [options] <mol files> ... ", options);
            System.exit(1);
        }

        TPSA myTPSA = new TPSA();
        myTPSA.runTest(countP, countS);

        OEGraphMol mol = new OEGraphMol();
        oemolistream ifs = new oemolistream();
        ;

        for (int i = 0; i < molFiles.length; i++) {
            ifs = new oemolistream(molFiles[i]);
            while (oechem.OEReadMolecule(ifs, mol)) {

                double tpsa = myTPSA.calculateTPSA(mol, countP, countS);
                if (tpsa < 0) {
                    System.out.printf("%s 0\n", mol.GetTitle());
                } else {
                    System.out.printf("%s %d\n", mol.GetTitle(), (int) tpsa);
                }

            }
        }
        ifs.close();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.akquinet.dustjs.DustEngine.java

public static void main(String[] args) throws URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(DustOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(DustOptions.DUST_OPTION, true, "Path to a custom dust.js for Rhino version.");
    try {//from   w w  w .jav a2  s  .  co  m
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        DustOptions options = new DustOptions();
        if (cmdLine.hasOption(DustOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(DustOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(DustOptions.DUST_OPTION)) {
            options.setDust(new File(cmdLine.getOptionValue(DustOptions.DUST_OPTION)).toURI().toURL());
        }
        DustEngine engine = new DustEngine(options);
        String[] files = cmdLine.getArgs();

        String src = null;
        if (files == null || files.length == 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            src = sw.toString();
        }

        if (src != null && !src.isEmpty()) {
            System.out.println(engine.compile(src, "test"));
            return;
        }

        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0])));
            return;
        }

        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]));
            return;
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar dust-engine.jar input [output] [options]", cmdOptions);
    System.exit(1);
}

From source file:jlite.cli.JobSubmit.java

public static void main(String[] args) {
    System.out.println(); // extra line
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();//from   w  w  w  .ja  va2 s.  c  o m
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;

    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
            System.out.println(); // extra line
            System.exit(0);
        } else {
            if (line.hasOption("xml")) {
                System.out.println("<output>");
            }
            String[] remArgs = line.getArgs();
            if (remArgs.length == 1) {
                run(remArgs[0], line);
            } else if (remArgs.length == 0) {
                throw new MissingArgumentException("Missing required argument: <jdl_file>");
            } else {
                throw new UnrecognizedOptionException("Unrecognized extra arguments");
            }
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage() + "\n");
        helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
        System.out.println(); // extra line
        System.exit(-1);
    } catch (Exception e) {
        if (line.hasOption("xml")) {
            System.out.println("<error>" + e.getMessage() + "</error>");
        } else {
            System.err.println(e.getMessage());
        }
    } finally {
        if (line.hasOption("xml")) {
            System.out.println("</output>");
        }
    }
    System.out.println(); // extra line
}

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

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);/*from   ww  w .jav a  2  s .co m*/
    options.addOption(opt);

    opt = new Option(OPT_SDFFILE, true,
            "file to write onformers for debugging (oe-supported Use .sdf|.smi to specify the file type).");
    options.addOption(opt);

    opt = new Option(OPT_WORKDIR, true, "Write files into this directory!");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_OUTPREFIX, true, "Prefix for output file.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_OUTNAMETAG, true,
            "TagName of field containing outFilePrefix. (Use TITLE for mol title).");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TEMPLATE, true,
            "Template file for quantum program containing #XYZ# place holder line. A #FName# placeholder can be used fro chk files and the like.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_SPIN_MULTIPLICITY, true, "Spin Multiplicity of the input molecules (default 1)");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_NCPU, true, "Overwrite nprocshared parameter in guassian input file if given");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_MEM, true, "Memory for gaussian default='10GB' replaces #mem# in tempalte");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_MINIMIZE, false, "minimize conformer at each step using MMFFs");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_CONSTRIANT, true,
            "one of strong (90),medium (45), weak(20), none or a floating point number"
                    + " specifying the strength of tethered constrains for -doMinimize (def=strong)");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_BONDFILE, true, "Structure file containing 4 atoms defining the torsion. "
            + "In each input molecule the atoms colses these atoms are used to define the torsion.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_STARTTorsion, true,
            "The torsion in your inMol will be rotated by this value for the first job");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TORSIONIncrement, true, "Incremnt each subsequent conformation by this step size");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_NSTEPS, true, "Number of conformations to create");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_MAXCONFS_PER_STEP, true,
            "While holding the torsion fixed, maximum number of conformations of free atoms to generate.  default=1");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_COREFILE, true, "Outputfile to store guessed core.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_DEBUG, false, "Produce more debug output.");
    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 (args.length != 0) {
        System.err.println("Unknown arguments" + args);
        exitWithHelp(options);
    }

    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 sdfFile = cmd.getOptionValue(OPT_SDFFILE);
    String outPrefix = cmd.getOptionValue(OPT_OUTPREFIX);
    String outNameTag = cmd.getOptionValue(OPT_OUTNAMETAG);
    String workDir = cmd.getOptionValue(OPT_WORKDIR);
    String coreFile = cmd.getOptionValue(OPT_COREFILE);
    String tempalte = cmd.getOptionValue(OPT_TEMPLATE);
    String bondFile = cmd.getOptionValue(OPT_BONDFILE);
    String nCPU = cmd.getOptionValue(OPT_NCPU);
    String memStr = cmd.getOptionValue(OPT_MEM);
    String maxConfsStr = cmd.getOptionValue(OPT_MAXCONFS_PER_STEP);
    String spinMult = cmd.getOptionValue(OPT_SPIN_MULTIPLICITY);

    boolean doMinimize = cmd.hasOption(OPT_MINIMIZE);
    String constraintStrength = cmd.getOptionValue(OPT_CONSTRIANT);
    int nStep = Integer.parseInt(cmd.getOptionValue(OPT_NSTEPS));

    if (memStr == null || memStr.length() == 0)
        memStr = "10GB";

    if (spinMult == null || spinMult.length() == 0)
        spinMult = "1";

    if ((outPrefix == null && outNameTag == null) || (outPrefix != null && outNameTag != null)) {
        System.err.println("Exactly one of -outPrefix or outNameTag must be given!");
        exitWithHelp(options);
    }

    if (workDir == null || workDir.trim().length() == 0)
        workDir = ".";

    double startTorsion = Double.NaN;
    if (cmd.hasOption(OPT_STARTTorsion))
        startTorsion = Double.parseDouble(cmd.getOptionValue(OPT_STARTTorsion));

    double torInc = Double.parseDouble(cmd.getOptionValue(OPT_TORSIONIncrement));
    int maxStepConfs = maxConfsStr == null ? 1 : Integer.parseInt(maxConfsStr);

    QTorsionProfileGenerator calculator = new QTorsionProfileGenerator(tempalte, workDir, outPrefix, outNameTag,
            bondFile, spinMult, startTorsion, torInc, nStep, maxStepConfs, doMinimize, constraintStrength,
            cmd.hasOption(OPT_DEBUG));

    calculator.run(inFile, sdfFile, coreFile, nCPU, memStr);
}

From source file:de.uni_koblenz.west.splendid.tools.NQuadSourceAggregator.java

public static void main(String[] args) {

    try {//from w  w w  . j  a v a  2 s.c om
        // parse the command line arguments
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(OPTIONS, args);

        // print help message
        if (cmd.hasOption("h") || cmd.hasOption("help")) {
            new HelpFormatter().printHelp(USAGE, OPTIONS);
            System.exit(0);
        }

        // get input files (from option -i or all remaining parameters)
        String[] inputFiles = cmd.getOptionValues("i");
        if (inputFiles == null)
            inputFiles = cmd.getArgs();
        if (inputFiles.length == 0) {
            System.out.println("need at least one input file.");
            new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE);
            System.exit(1);
        }
        String outputFile = cmd.getOptionValue("o");

        // process all input files
        new NQuadSourceAggregator().process(outputFile, inputFiles);

    } catch (ParseException exp) {
        // print parse error and display usage message
        System.out.println(exp.getMessage());
        new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE, OPTIONS);
    }
}

From source file:jlite.cli.ProxyInit.java

public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();//from  ww  w .  j  av  a  2s.  co m
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            System.out.println(); // extra line
            helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
            System.out.println(); // extra line
            System.exit(0);
        } else {
            if (line.hasOption("xml")) {
                System.out.println("<output>");
            }
            String[] remArgs = line.getArgs();
            if (remArgs.length > 0) {
                run(remArgs, line);
            } else {
                throw new MissingArgumentException("Missing required argument: <voms>[:<command>]");
            }
        }
    } catch (ParseException e) {
        System.err.println("\n" + e.getMessage() + "\n");
        helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
        System.out.println(); // extra line
        System.exit(-1);
    } catch (Exception e) {
        if ((line != null) && (line.hasOption("xml"))) {
            System.out.println("<error>" + e.getMessage() + "</error>");
        } else {
            System.err.println(e.getMessage());
        }
    } finally {
        if (line.hasOption("xml")) {
            System.out.println("</output>");
        }
    }
    System.out.println(); // extra line
}

From source file:net.sf.mcf2pdf.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();

    Option o = OptionBuilder.hasArg().isRequired()
            .withDescription("Installation location of My CEWE Photobook. REQUIRED.").create('i');
    options.addOption(o);/*  w ww. j a  v a2  s . c o  m*/
    options.addOption("h", false, "Prints this help and exits.");
    options.addOption("t", true, "Location of MCF temporary files.");
    options.addOption("w", true, "Location for temporary images generated during conversion.");
    options.addOption("r", true, "Sets the resolution to use for page rendering, in DPI. Default is 150.");
    options.addOption("n", true, "Sets the page number to render up to. Default renders all pages.");
    options.addOption("b", false, "Prevents rendering of binding between double pages.");
    options.addOption("x", false, "Generates only XSL-FO content instead of PDF content.");
    options.addOption("q", false, "Quiet mode - only errors are logged.");
    options.addOption("d", false, "Enables debugging logging output.");

    CommandLine cl;
    try {
        CommandLineParser parser = new PosixParser();
        cl = parser.parse(options, args);
    } catch (ParseException pe) {
        printUsage(options, pe);
        System.exit(3);
        return;
    }

    if (cl.hasOption("h")) {
        printUsage(options, null);
        return;
    }

    if (cl.getArgs().length != 2) {
        printUsage(options,
                new ParseException("INFILE and OUTFILE must be specified. Arguments were: " + cl.getArgList()));
        System.exit(3);
        return;
    }

    File installDir = new File(cl.getOptionValue("i"));
    if (!installDir.isDirectory()) {
        printUsage(options, new ParseException("Specified installation directory does not exist."));
        System.exit(3);
        return;
    }

    File tempDir = null;
    String sTempDir = cl.getOptionValue("t");
    if (sTempDir == null) {
        tempDir = new File(new File(System.getProperty("user.home")), ".mcf");
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("MCF temporary location not specified and default location "
                    + tempDir + " does not exist."));
            System.exit(3);
            return;
        }
    } else {
        tempDir = new File(sTempDir);
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("Specified temporary location does not exist."));
            System.exit(3);
            return;
        }
    }

    File mcfFile = new File(cl.getArgs()[0]);
    if (!mcfFile.isFile()) {
        printUsage(options, new ParseException("MCF input file does not exist."));
        System.exit(3);
        return;
    }
    mcfFile = mcfFile.getAbsoluteFile();

    File tempImages = new File(new File(System.getProperty("user.home")), ".mcf2pdf");
    if (cl.hasOption("w")) {
        tempImages = new File(cl.getOptionValue("w"));
        if (!tempImages.mkdirs() && !tempImages.isDirectory()) {
            printUsage(options,
                    new ParseException("Specified working dir does not exist and could not be created."));
            System.exit(3);
            return;
        }
    }

    int dpi = 150;
    if (cl.hasOption("r")) {
        try {
            dpi = Integer.valueOf(cl.getOptionValue("r")).intValue();
            if (dpi < 30 || dpi > 600)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options,
                    new ParseException("Parameter for option -r must be an integer between 30 and 600."));
        }
    }

    int maxPageNo = -1;
    if (cl.hasOption("n")) {
        try {
            maxPageNo = Integer.valueOf(cl.getOptionValue("n")).intValue();
            if (maxPageNo < 0)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options, new ParseException("Parameter for option -n must be an integer >= 0."));
        }
    }

    boolean binding = true;
    if (cl.hasOption("b")) {
        binding = false;
    }

    OutputStream finalOut;
    if (cl.getArgs()[1].equals("-"))
        finalOut = System.out;
    else {
        try {
            finalOut = new FileOutputStream(cl.getArgs()[1]);
        } catch (IOException e) {
            printUsage(options, new ParseException("Output file could not be created."));
            System.exit(3);
            return;
        }
    }

    // configure logging, if no system property is present
    if (System.getProperty("log4j.configuration") == null) {
        PropertyConfigurator.configure(Main.class.getClassLoader().getResource("log4j.properties"));

        Logger.getRootLogger().setLevel(Level.INFO);
        if (cl.hasOption("q"))
            Logger.getRootLogger().setLevel(Level.ERROR);
        if (cl.hasOption("d"))
            Logger.getRootLogger().setLevel(Level.DEBUG);
    }

    // start conversion to XSL-FO
    // if -x is specified, this is the only thing we do
    OutputStream xslFoOut;
    if (cl.hasOption("x"))
        xslFoOut = finalOut;
    else
        xslFoOut = new ByteArrayOutputStream();

    Log log = LogFactory.getLog(Main.class);

    try {
        new Mcf2FoConverter(installDir, tempDir, tempImages).convert(mcfFile, xslFoOut, dpi, binding,
                maxPageNo);
        xslFoOut.flush();

        if (!cl.hasOption("x")) {
            // convert to PDF
            log.debug("Converting XSL-FO data to PDF");
            byte[] data = ((ByteArrayOutputStream) xslFoOut).toByteArray();
            PdfUtil.convertFO2PDF(new ByteArrayInputStream(data), finalOut, dpi);
            finalOut.flush();
        }
    } catch (Exception e) {
        log.error("An exception has occured", e);
        System.exit(1);
        return;
    } finally {
        if (finalOut instanceof FileOutputStream) {
            try {
                finalOut.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:de.bayern.gdi.App.java

/**
 * @param args the command line arguments
 *//*from ww  w.  j ava  2s.  co  m*/
public static void main(String[] args) {

    Options options = new Options();

    Option help = Option.builder("?").hasArg(false).longOpt("help").desc("Print this message and exit.")
            .build();

    Option headless = Option.builder("h").hasArg(false).longOpt("headless").desc("Start command line tool.")
            .build();

    Option conf = Option.builder("c").hasArg(true).longOpt("config")
            .desc("Directory to overwrite default configuration.").build();

    Option user = Option.builder("u").hasArg(true).longOpt("user").desc("User name for protected services.")
            .build();

    Option password = Option.builder("p").hasArg(true).longOpt("password")
            .desc("Password for protected services.").build();

    options.addOption(help);
    options.addOption(headless);
    options.addOption(conf);
    options.addOption(user);
    options.addOption(password);

    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("?")) {
            usage(options, 0);
        }

        if (line.hasOption("h")) {
            // First initialize log4j for headless execution
            final String pid = getProcessId("0");
            System.setProperty("logfilename", "logdlc-" + pid + ".txt");
        }

        // use configuration for gui and headless mode
        initConfig(line.getOptionValue("c"));

        if (line.hasOption("h")) {
            System.exit(Headless.main(line.getArgs(), line.getOptionValue("u"), line.getOptionValue("p")));
        }

        startGUI();

    } catch (ParseException pe) {
        System.err.println("Cannot parse input: " + pe.getMessage());
        usage(options, 1);
    }
}

From source file:edu.vt.cs.cnd2xsd.Cnd2XsdConverter.java

/**
 * Usage: Cnd2Xsd [path to source cnd] [path to write the xsd]
 * @param args//from  ww w.j  a  va 2  s.c  om
 * @throws LoginException
 * @throws RepositoryException
 * @throws IOException
 * @throws JAXBException
 */
@SuppressWarnings("static-access")
public static void main(String[] args) throws LoginException, RepositoryException, IOException, JAXBException,
        org.apache.commons.cli.ParseException {

    Session session = null;
    Cnd2XsdConverter converter = new Cnd2XsdConverter();

    try {
        Options opt = new Options();

        opt.addOption(OptionBuilder.hasArg(true).isRequired(false)
                .withDescription("Path for the input cnd file").create("fc"));
        opt.addOption(OptionBuilder.hasArg(true).isRequired(false).withDescription("Path for properties map.")
                .create("fp"));
        opt.addOption(OptionBuilder.hasArg(true).isRequired(false)
                .withDescription("Path for generating XML schema.").create("fx"));
        opt.addOption(OptionBuilder.hasArg(false).isRequired(false).withDescription("Prints this list.")
                .create("help"));
        opt.addOption(OptionBuilder.hasArg(true).isRequired(false).withDescription("The namespace for the XSD.")
                .create("ns"));
        opt.addOption(OptionBuilder.hasArg(true).isRequired(false).withDescription("The namespace prefix.")
                .create("nsp"));
        opt.addOption(OptionBuilder.hasArg(true).isRequired(false)
                .withDescription("The root element in the XSD.").create("r"));
        opt.addOption(OptionBuilder.hasArg(true).isRequired(false).withDescription("The root element type.")
                .create("rtype"));

        //create the basic parser
        BasicParser parser = new BasicParser();
        CommandLine cl = parser.parse(opt, args);
        HelpFormatter f = new HelpFormatter();
        //check if we have any leftover args
        if (cl.getArgs().length != 0 || args.length == 0) {
            f.printHelp(MAINCLI, opt);
            return;
        }

        if (cl.hasOption("help")) {
            f.printHelp(MAINCLI, opt);
            return;
        }

        String cndFilePath = cl.getOptionValue("fc");
        String xsdFilePath = cl.getOptionValue("fx");
        String propmapPath = cl.getOptionValue("fp");
        String ns = cl.getOptionValue("ns");
        String nsPrefix = cl.getOptionValue("nsp");
        String rt = cl.getOptionValue("r");
        String rtype = cl.getOptionValue("rtype");

        converter.init(cndFilePath, propmapPath, ns, nsPrefix, rt, rtype);
        FileOutputStream fout = new FileOutputStream(xsdFilePath);
        converter.convert(fout);

    } finally {
        if (session != null) {
            session.save();
            session.logout();
        }
    }
}

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

/**
 * @param args/*from  www.j  av  a  2 s  .c  om*/
 */
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_SMARTS_FILE, true,
            "Tag-delimited file containing SMARTS, tag name, name of the tag set."
                    + " Lines starting with '#' are ignores as comment."
                    + " NOTE: Use the SMARTS features supported by OpenEye.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_QSDF_FILE, true,
            "SDFiles with molfile for tagging as well " + InputFieldName.TAG_NAME.toString() + " and "
                    + InputFieldName.SET_NAME.toString() + " fields."
                    + " NOTE: SMARTS are read in first, then the SD file.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TAG_SETS, true,
            TAG_SETS_ALL + " or name1|name2|...; The given names must match the names"
                    + " in the files disregarding the letter case");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_TAG_INFO, true,
            OutputTag.getTagsAsText("|") + " or if not specified all the listed ones.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_OUTPUT_COUNT, false, "Add for each structure pattern a field containing the"
            + " occurrence of the given pattern in the molecule"
            + " (NOTE: if multiple patterns have the same tag name the" + " counts will be summed up).");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_OUTPUT_EXISTS, false, "Add for each structure pattern a field containing 0 "
            + " if the pattern does not match and 1 if the pattern matches "
            + " (NOTE: if multiple patterns have the same tag name the" + " any match will yield a 1).");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_ONLY_MATCHES, false,
            "Remove records from output unless they match at least one query pattern.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_NO_MATCHES, false, "Remove records from output if they match any query pattern.");
    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_SMARTS_FILE);
    String molPatternFile = cmd.getOptionValue(OPT_QSDF_FILE);
    String tagSets = cmd.getOptionValue(OPT_TAG_SETS);
    String tagInfo = cmd.getOptionValue(OPT_TAG_INFO);
    boolean outputCount = cmd.hasOption(OPT_OUTPUT_COUNT);
    boolean outputExists = cmd.hasOption(OPT_OUTPUT_EXISTS);
    boolean onlyMatches = cmd.hasOption(OPT_ONLY_MATCHES);
    boolean noMatches = cmd.hasOption(OPT_NO_MATCHES);
    SDFStructureTagger tagger = new SDFStructureTagger(outFile);

    try {
        tagger.prepare(smartsFile, molPatternFile, tagSets, tagInfo, outputCount, outputExists, onlyMatches,
                noMatches);
        tagger.run(inFile);
    } catch (IncorrectInputException iie) {
        System.err.println(iie.toString());
        exitWithHelp(options);
    } finally {
        tagger.close();
    }
}