Example usage for org.apache.commons.cli BasicParser parse

List of usage examples for org.apache.commons.cli BasicParser parse

Introduction

In this page you can find the example usage for org.apache.commons.cli BasicParser parse.

Prototype

public CommandLine parse(Options options, String[] arguments) throws ParseException 

Source Link

Document

Parses the specified arguments based on the specifed Options .

Usage

From source file:org.apache.bookkeeper.server.Main.java

@SuppressWarnings("deprecation")
private static ServerConfiguration parseArgs(String[] args) throws IllegalArgumentException {
    try {//from ww  w.  java 2s. c  o  m
        BasicParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(BK_OPTS, args);

        if (cmdLine.hasOption('h')) {
            throw new IllegalArgumentException();
        }

        ServerConfiguration conf = new ServerConfiguration();

        if (cmdLine.hasOption('c')) {
            String confFile = cmdLine.getOptionValue("c");
            loadConfFile(conf, confFile);
        }

        if (cmdLine.hasOption("withAutoRecovery")) {
            conf.setAutoRecoveryDaemonEnabled(true);
        }

        if (cmdLine.hasOption("r")) {
            conf.setForceReadOnlyBookie(true);
        }

        boolean overwriteMetadataServiceUri = false;
        String sZkLedgersRootPath = "/ledgers";
        if (cmdLine.hasOption('m')) {
            sZkLedgersRootPath = cmdLine.getOptionValue('m');
            log.info("Get cmdline zookeeper ledger path: {}", sZkLedgersRootPath);
            overwriteMetadataServiceUri = true;
        }

        String sZK = conf.getZkServers();
        if (cmdLine.hasOption('z')) {
            sZK = cmdLine.getOptionValue('z');
            log.info("Get cmdline zookeeper instance: {}", sZK);
            overwriteMetadataServiceUri = true;
        }

        // command line arguments overwrite settings in configuration file
        if (overwriteMetadataServiceUri) {
            String metadataServiceUri = "zk://" + sZK + sZkLedgersRootPath;
            conf.setMetadataServiceUri(metadataServiceUri);
            log.info("Overwritten service uri to {}", metadataServiceUri);
        }

        if (cmdLine.hasOption('p')) {
            String sPort = cmdLine.getOptionValue('p');
            log.info("Get cmdline bookie port: {}", sPort);
            Integer iPort = Integer.parseInt(sPort);
            conf.setBookiePort(iPort.intValue());
        }

        if (cmdLine.hasOption('j')) {
            String sJournalDir = cmdLine.getOptionValue('j');
            log.info("Get cmdline journal dir: {}", sJournalDir);
            conf.setJournalDirName(sJournalDir);
        }

        if (cmdLine.hasOption('i')) {
            String[] sIndexDirs = cmdLine.getOptionValues('i');
            log.info("Get cmdline index dirs: ");
            for (String index : sIndexDirs) {
                log.info("indexDir : {}", index);
            }
            conf.setIndexDirName(sIndexDirs);
        }

        if (cmdLine.hasOption('l')) {
            String[] sLedgerDirs = cmdLine.getOptionValues('l');
            log.info("Get cmdline ledger dirs: ");
            for (String ledger : sLedgerDirs) {
                log.info("ledgerdir : {}", ledger);
            }
            conf.setLedgerDirNames(sLedgerDirs);
        }

        return conf;
    } catch (ParseException e) {
        log.error("Error parsing command line arguments : ", e);
        throw new IllegalArgumentException(e);
    }
}

From source file:org.apache.distributedlog.benchmark.Benchmarker.java

void run() throws Exception {
    logger.info("Running benchmark.");

    BasicParser parser = new BasicParser();
    CommandLine cmdline = parser.parse(options, args);
    if (cmdline.hasOption("h")) {
        printUsage();/*from  ww w . ja v  a2  s .c o m*/
        System.exit(0);
    }
    if (cmdline.hasOption("s")) {
        String serversetPathStr = cmdline.getOptionValue("s");
        serversetPaths = Arrays.asList(StringUtils.split(serversetPathStr, ','));
    }
    if (cmdline.hasOption("fn")) {
        String finagleNameStr = cmdline.getOptionValue("fn");
        finagleNames = Arrays.asList(StringUtils.split(finagleNameStr, ','));
    }
    if (cmdline.hasOption("i")) {
        shardId = Integer.parseInt(cmdline.getOptionValue("i"));
    }
    if (cmdline.hasOption("d")) {
        durationMins = Integer.parseInt(cmdline.getOptionValue("d"));
    }
    if (cmdline.hasOption("sp")) {
        streamPrefix = cmdline.getOptionValue("sp");
    }
    if (cmdline.hasOption("sc")) {
        numStreams = Integer.parseInt(cmdline.getOptionValue("sc"));
    }
    if (cmdline.hasOption("ms")) {
        msgSize = Integer.parseInt(cmdline.getOptionValue("ms"));
    }
    if (cmdline.hasOption("r")) {
        rate = Integer.parseInt(cmdline.getOptionValue("r"));
    }
    if (cmdline.hasOption("mr")) {
        maxRate = Integer.parseInt(cmdline.getOptionValue("mr"));
    }
    if (cmdline.hasOption("cr")) {
        changeRate = Integer.parseInt(cmdline.getOptionValue("cr"));
    }
    if (cmdline.hasOption("ci")) {
        changeRateSeconds = Integer.parseInt(cmdline.getOptionValue("ci"));
    }
    if (cmdline.hasOption("t")) {
        concurrency = Integer.parseInt(cmdline.getOptionValue("t"));
    }
    if (cmdline.hasOption("m")) {
        mode = cmdline.getOptionValue("m");
    }
    if (cmdline.hasOption("u")) {
        dlUri = URI.create(cmdline.getOptionValue("u"));
    }
    if (cmdline.hasOption("bs")) {
        batchSize = Integer.parseInt(cmdline.getOptionValue("bs"));
        checkArgument("write" != mode, "batchSize supported only for mode=write");
    }
    if (cmdline.hasOption("c")) {
        String configFile = cmdline.getOptionValue("c");
        conf.loadConf(new File(configFile).toURI().toURL());
    }
    if (cmdline.hasOption("rps")) {
        readersPerStream = Integer.parseInt(cmdline.getOptionValue("rps"));
    }
    if (cmdline.hasOption("msid")) {
        maxStreamId = Integer.parseInt(cmdline.getOptionValue("msid"));
    }
    if (cmdline.hasOption("ti")) {
        truncationInterval = Integer.parseInt(cmdline.getOptionValue("ti"));
    }
    if (cmdline.hasOption("ssid")) {
        startStreamId = Integer.parseInt(cmdline.getOptionValue("ssid"));
    }
    if (cmdline.hasOption("esid")) {
        endStreamId = Integer.parseInt(cmdline.getOptionValue("esid"));
    }
    if (cmdline.hasOption("hccs")) {
        hostConnectionCoreSize = Integer.parseInt(cmdline.getOptionValue("hccs"));
    }
    if (cmdline.hasOption("hcl")) {
        hostConnectionLimit = Integer.parseInt(cmdline.getOptionValue("hcl"));
    }
    if (cmdline.hasOption("sb")) {
        sendBufferSize = Integer.parseInt(cmdline.getOptionValue("sb"));
    }
    if (cmdline.hasOption("rb")) {
        recvBufferSize = Integer.parseInt(cmdline.getOptionValue("rb"));
    }
    if (cmdline.hasOption("rs")) {
        routingServiceFinagleNameString = cmdline.getOptionValue("rs");
    }
    thriftmux = cmdline.hasOption("mx");
    handshakeWithClientInfo = cmdline.hasOption("hsci");
    readFromHead = cmdline.hasOption("rfh");
    enableBatching = cmdline.hasOption("bt");
    if (cmdline.hasOption("bbs")) {
        batchBufferSize = Integer.parseInt(cmdline.getOptionValue("bbs"));
    }
    if (cmdline.hasOption("bfi")) {
        batchFlushIntervalMicros = Integer.parseInt(cmdline.getOptionValue("bfi"));
    }

    checkArgument(shardId >= 0, "shardId must be >= 0");
    checkArgument(numStreams > 0, "numStreams must be > 0");
    checkArgument(durationMins > 0, "durationMins must be > 0");
    checkArgument(streamPrefix != null, "streamPrefix must be defined");
    checkArgument(hostConnectionCoreSize > 0, "host connection core size must be > 0");
    checkArgument(hostConnectionLimit > 0, "host connection limit must be > 0");

    if (cmdline.hasOption("p")) {
        statsProvider = ReflectionUtils.newInstance(cmdline.getOptionValue("p"), StatsProvider.class);
    } else {
        statsProvider = new NullStatsProvider();
    }

    logger.info("Starting stats provider : {}.", statsProvider.getClass());
    statsProvider.start(conf);

    Worker w = null;
    if (mode.startsWith("read")) {
        w = runReader();
    } else if (mode.startsWith("write")) {
        w = runWriter();
    } else if (mode.startsWith("dlwrite")) {
        w = runDLWriter();
    } else if (mode.startsWith("dlread")) {
        w = runDLReader();
    }

    if (w == null) {
        throw new IOException("Unknown mode " + mode + " to run the benchmark.");
    }

    Thread workerThread = new Thread(w, mode + "-benchmark-thread");
    workerThread.start();

    TimeUnit.MINUTES.sleep(durationMins);

    logger.info("{} minutes passed, exiting...", durationMins);
    w.close();

    if (null != statsProvider) {
        statsProvider.stop();
    }

    Runtime.getRuntime().exit(0);
}

From source file:org.apache.distributedlog.service.DistributedLogServerApp.java

private void run() {
    try {/*  w w  w .  ja va2 s. c  om*/
        logger.info("Running distributedlog server : args = {}", Arrays.toString(args));
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(options, args);
        runCmd(cmdline);
    } catch (ParseException pe) {
        logger.error("Argument error : {}", pe.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IllegalArgumentException iae) {
        logger.error("Argument error : {}", iae.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (ConfigurationException ce) {
        logger.error("Configuration error : {}", ce.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IOException ie) {
        logger.error("Failed to start distributedlog server : ", ie);
        Runtime.getRuntime().exit(-1);
    } catch (ClassNotFoundException cnf) {
        logger.error("Failed to start distributedlog server : ", cnf);
        Runtime.getRuntime().exit(-1);
    }
}

From source file:org.apache.hadoop.hdfs.tools.DiskBalancer.java

/**
 * This function parses all command line arguments and returns the appropriate
 * values.// w  ww .j  a  v  a 2s .  c o m
 *
 * @param argv - Argv from main
 * @return CommandLine
 */
private CommandLine parseArgs(String[] argv, Options opts) throws org.apache.commons.cli.ParseException {
    BasicParser parser = new BasicParser();
    return parser.parse(opts, argv);
}

From source file:org.apache.hms.client.Client.java

/**
 * Parse command line arguments and construct HMS command for HMS Client Executor class
 * @param args/*www.j av a  2s  .  c  o m*/
 */
public void run(String[] args) {
    BasicParser parser = new BasicParser();
    try {
        CommandLine cl = parser.parse(opt, args);
        /* Dry run */
        boolean dryRun = false;
        if (cl.hasOption("t")) {
            dryRun = true;
        }

        if (cl.hasOption("q")) {
            String cmdid = cl.getOptionValue("q");
            try {
                CommandStatus cs = queryCommandStatus(cmdid);
                if (cl.hasOption("v")) {
                    System.out.println(JAXBUtil.print(cs));
                } else {
                    System.out.println("Command ID: " + cmdid);
                    System.out.println("Status: " + cs.getStatus());
                    System.out.println("Total actions: " + cs.getTotalActions());
                    System.out.println("Completed actions: " + cs.getCompletedActions());
                }
            } catch (UniformInterfaceException e) {
                if (e.getResponse().getStatus() == Responses.NOT_FOUND) {
                    System.out.println("Command ID:" + cmdid + " does not exist.");
                } else {
                    System.out.println("Unknown error occurred, check stack trace.");
                    System.out.println(ExceptionUtil.getStackTrace(e));
                }
            }
        } else if (cl.hasOption("delete-command")) {
            // TODO: Remove command from the system
            String cmdId = cl.getOptionValue("delete-command");
            if (cmdId == null) {
                throw new RuntimeException("Command ID must be specified for Delete operation");
            }
            // System.out.println(clientRunner.sendToController(new DeleteCommand(cmdId)));        
        } else if (cl.hasOption("delete-cluster")) {
            /* delete a cluster */
            String clusterName = cl.getOptionValue("delete-cluster");
            if (clusterName == null) {
                throw new RuntimeException("cluster name must be specified for DELETE operation");
            }
            URL config = new URL(cl.getOptionValue("config-manifest"));
            if (config == null) {
                throw new RuntimeException("config manifest must be specified for DELETE operation");
            }
            try {
                Response response = deleteCluster(clusterName, config);
                showResponse(response, cl.hasOption("v"));
            } catch (Throwable e) {
                showErrors(e);
            }
        } else if (cl.hasOption("create-cluster")) {
            /* create a cluster */
            String clusterName = cl.getOptionValue("create-cluster");
            if (clusterName == null) {
                throw new RuntimeException("cluster name must be specified for CREATE operation");
            }
            URL nodes = new URL(cl.getOptionValue("nodes"));
            if (nodes == null) {
                throw new RuntimeException("nodes manifest must be specified for CREATE operation");
            }
            URL software = new URL(cl.getOptionValue("software"));
            if (software == null) {
                throw new RuntimeException("software manifest must be specified for CREATE operation");
            }
            URL config = new URL(cl.getOptionValue("config"));
            if (config == null) {
                throw new RuntimeException("config manifest must be specified for CREATE operation");
            }
            Response response = createCluster(clusterName, nodes, software, config);
            showResponse(response, cl.hasOption("v"));
        } else if (cl.hasOption("upgrade-cluster")) {
            /* upgrade a cluster */
            String clusterName = cl.getOptionValue("upgrade-cluster");
            if (clusterName == null) {
                throw new RuntimeException("cluster name must be specified for CREATE operation");
            }
            URL nodes = new URL(cl.getOptionValue("nodes"));
            if (nodes == null) {
                throw new RuntimeException("nodes manifest must be specified for CREATE operation");
            }
            URL software = new URL(cl.getOptionValue("software"));
            if (software == null) {
                throw new RuntimeException("software manifest must be specified for CREATE operation");
            }
            URL config = new URL(cl.getOptionValue("config"));
            if (config == null) {
                throw new RuntimeException("config manifest must be specified for CREATE operation");
            }
            Response response = upgradeCluster(clusterName, nodes, software, config);
            showResponse(response, cl.hasOption("v"));
        } else if (cl.hasOption("cluster-status")) {
            /* check cluster status */
            String clusterId = cl.getOptionValue("cluster-status");
            if (clusterId == null) {
                throw new RuntimeException("Cluster path must be specified for cluster-status operation");
            }
            ClusterManifest cm = clientRunner.checkClusterStatus(clusterId);
            System.out.println(JAXBUtil.print(cm));
        } else if (cl.hasOption("node-status")) {
            /* check node status */
            String nodepath = cl.getOptionValue("node-status");
            if (nodepath == null) {
                throw new RuntimeException("nodePath must be specified for nodestatus operation");
            }
            MachineState ms = clientRunner.checkNodeStatus(nodepath);
            System.out.println(JAXBUtil.print(ms));
        } else if (cl.hasOption("help")) {
            usage();
        } else {
            throw new InvalidActivityException("Invalid arguement.");
        }
    } catch (InvalidActivityException e) {
        usage();
        System.out.println("Argument Error: " + e.getMessage());
    } catch (Throwable e) {
        showErrors(e);
    }
}

From source file:org.exbin.deltahex.editor.DeltaHexEditor.java

/**
 * Main method launching the application.
 *
 * @param args arguments/*w ww  .  j a va 2 s  .c  o m*/
 */
public static void main(String[] args) {
    try {
        preferences = Preferences.userNodeForPackage(DeltaHexEditor.class);
    } catch (SecurityException ex) {
        preferences = null;
    }
    try {
        bundle = LanguageUtils.getResourceBundleByClass(DeltaHexEditor.class);
        // Parameters processing
        Options opt = new Options();
        opt.addOption("h", "help", false, bundle.getString("cl_option_help"));
        opt.addOption("v", false, bundle.getString("cl_option_verbose"));
        opt.addOption("dev", false, bundle.getString("cl_option_dev"));
        BasicParser parser = new BasicParser();
        CommandLine cl = parser.parse(opt, args);
        if (cl.hasOption('h')) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp(bundle.getString("cl_syntax"), opt);
        } else {
            verboseMode = cl.hasOption("v");
            devMode = cl.hasOption("dev");
            Logger logger = Logger.getLogger("");
            try {
                logger.setLevel(Level.ALL);
                logger.addHandler(new XBHead.XBLogHandler(verboseMode));
            } catch (java.security.AccessControlException ex) {
                // Ignore it in java webstart
            }

            XBBaseApplication app = new XBBaseApplication();
            app.setAppPreferences(preferences);
            app.setAppBundle(bundle, LanguageUtils.getResourceBaseNameBundleByClass(DeltaHexEditor.class));

            XBApplicationModuleRepository moduleRepository = app.getModuleRepository();
            moduleRepository.addClassPathModules();
            moduleRepository.addModulesFromManifest(DeltaHexEditor.class);
            moduleRepository.loadModulesFromPath(new File("plugins").toURI());
            moduleRepository.initModules();
            app.init();

            GuiFrameModuleApi frameModule = moduleRepository.getModuleByInterface(GuiFrameModuleApi.class);
            GuiEditorModuleApi editorModule = moduleRepository.getModuleByInterface(GuiEditorModuleApi.class);
            GuiMenuModuleApi menuModule = moduleRepository.getModuleByInterface(GuiMenuModuleApi.class);
            GuiAboutModuleApi aboutModule = moduleRepository.getModuleByInterface(GuiAboutModuleApi.class);
            GuiUndoModuleApi undoModule = moduleRepository.getModuleByInterface(GuiUndoModuleApi.class);
            GuiFileModuleApi fileModule = moduleRepository.getModuleByInterface(GuiFileModuleApi.class);
            GuiOptionsModuleApi optionsModule = moduleRepository
                    .getModuleByInterface(GuiOptionsModuleApi.class);
            GuiDockingModuleApi dockingModule = moduleRepository
                    .getModuleByInterface(GuiDockingModuleApi.class);
            GuiUpdateModuleApi updateModule = moduleRepository.getModuleByInterface(GuiUpdateModuleApi.class);

            DeltaHexModule deltaHexModule = moduleRepository.getModuleByInterface(DeltaHexModule.class);

            frameModule.createMainMenu();
            try {
                updateModule.setUpdateUrl(new URL(bundle.getString("update_url")));
                updateModule.setUpdateDownloadUrl(new URL(bundle.getString("update_download_url")));
            } catch (MalformedURLException ex) {
                Logger.getLogger(DeltaHexEditor.class.getName()).log(Level.SEVERE, null, ex);
            }
            updateModule.registerDefaultMenuItem();
            aboutModule.registerDefaultMenuItem();

            frameModule.registerExitAction();
            frameModule.registerBarsVisibilityActions();
            //                Component dockingPanel = dockingModule.getDockingPanel();

            // Register clipboard editing actions
            fileModule.registerMenuFileHandlingActions();
            fileModule.registerToolBarFileHandlingActions();
            fileModule.registerLastOpenedMenuActions();
            fileModule.registerCloseListener();

            undoModule.registerMainMenu();
            undoModule.registerMainToolBar();
            undoModule.registerUndoManagerInMainMenu();

            // Register clipboard editing actions
            menuModule.registerMenuClipboardActions();
            menuModule.registerToolBarClipboardActions();

            optionsModule.registerMenuAction();

            //                HexEditorProvider editorProvider = deltaHexModule.getMultiEditorProvider();
            HexEditorProvider editorProvider = deltaHexModule.getEditorProvider();
            deltaHexModule.registerEditFindMenuActions();
            deltaHexModule.registerEditFindToolBarActions();
            deltaHexModule.registerViewNonprintablesMenuActions();
            deltaHexModule.registerToolsOptionsMenuActions();
            deltaHexModule.registerClipboardCodeActions();
            deltaHexModule.registerOptionsMenuPanels();
            deltaHexModule.registerGoToLine();
            deltaHexModule.registerPropertiesMenu();
            deltaHexModule.registerPrintMenu();
            deltaHexModule.registerViewModeMenu();
            deltaHexModule.registerCodeTypeMenu();
            deltaHexModule.registerPositionCodeTypeMenu();
            deltaHexModule.registerHexCharactersCaseHandlerMenu();
            deltaHexModule.registerWordWrapping();

            ApplicationFrameHandler frameHandler = frameModule.getFrameHandler();
            editorModule.registerEditor("hex", editorProvider);
            // editorModule.registerMultiEditor("hex", (MultiEditorProvider) editorProvider);
            editorModule.registerUndoHandler();
            undoModule.setUndoHandler(editorProvider.getHexUndoHandler());

            deltaHexModule.registerStatusBar();
            deltaHexModule.registerOptionsPanels();
            deltaHexModule.getTextStatusPanel();
            updateModule.registerOptionsPanels();

            deltaHexModule.loadFromPreferences(preferences);

            //                frameHandler.setMainPanel(dockingPanel);
            // Single editor only
            frameHandler.setMainPanel(editorModule.getEditorPanel());
            frameHandler.setDefaultSize(new Dimension(600, 400));
            frameHandler.show();
            updateModule.checkOnStart(frameHandler.getFrame());

            List fileArgs = cl.getArgList();
            if (fileArgs.size() > 0) {
                fileModule.loadFromFile((String) fileArgs.get(0));
            }
        }
    } catch (ParseException | RuntimeException ex) {
        Logger.getLogger(DeltaHexEditor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.fnlp.nlp.cn.tag.CWSTagger.java

public static void main(String[] args) throws Exception {
    Options opt = new Options();

    opt.addOption("h", false, "Print help for this application");
    opt.addOption("f", false, "segment file. Default string mode.");
    opt.addOption("s", false, "segment string");
    BasicParser parser = new BasicParser();
    CommandLine cl = parser.parse(opt, args);

    if (args.length == 0 || cl.hasOption('h')) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("SEG:\n" + "java edu.fudan.nlp.tag.CWSTagger -f model_file input_file output_file;\n"
                + "java edu.fudan.nlp.tag.CWSTagger -s model_file string_to_segement", opt);
        return;//from www.j  av  a2s.c  om
    }
    String[] arg = cl.getArgs();
    String modelFile;
    String input;
    String output = null;
    if (cl.hasOption("f") && arg.length == 3) {
        modelFile = arg[0];
        input = arg[1];
        output = arg[2];
    } else if (arg.length == 2) {
        modelFile = arg[0];
        input = arg[1];
    } else {
        System.err.println("paramenters format error!");
        System.err.println("Print option \"-h\" for help.");
        return;
    }
    CWSTagger seg = new CWSTagger(modelFile);
    if (cl.hasOption("f")) {
        String s = seg.tagFile(input);
        OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(output), "utf8");
        w.write(s);
        w.close();
    } else {
        String s = seg.tag(input);
        System.out.println(s);
    }
}

From source file:org.fnlp.nlp.cn.tag.NERTagger.java

public static void main(String[] args) throws Exception {
    Options opt = new Options();

    opt.addOption("h", false, "Print help for this application");
    opt.addOption("f", false, "segment file. Default string mode.");
    opt.addOption("s", false, "segment string");
    BasicParser parser = new BasicParser();
    CommandLine cl = parser.parse(opt, args);

    if (args.length == 0 || cl.hasOption('h')) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp(/*from w  ww .  ja va  2 s.c  om*/
                "Tagger:\n" + "java edu.fudan.nlp.tag.NERTagger -f segmodel posmodel input_file output_file;\n"
                        + "java edu.fudan.nlp.tag.NERTagger -s segmodel posmodel string_to_segement",
                opt);
        return;
    }
    String[] arg = cl.getArgs();
    String segmodel;
    String posmodel;
    String input;
    String output = null;
    if (cl.hasOption("f") && arg.length == 4) {
        segmodel = arg[0];
        posmodel = arg[1];
        input = arg[2];
        output = arg[3];
    } else if (arg.length == 3) {
        segmodel = arg[0];
        posmodel = arg[1];
        input = arg[2];
    } else {
        System.err.println("paramenters format error!");
        System.err.println("Print option \"-h\" for help.");
        return;
    }
    NERTagger ner = new NERTagger(segmodel, posmodel);
    if (cl.hasOption("f")) {
        ner.tagFile(input, output);
    } else {
        HashMap<String, String> map = ner.tag(input);
        System.out.println(map);
    }
}

From source file:org.fnlp.nlp.cn.tag.POSTagger.java

public static void main(String[] args) throws Exception {
    Options opt = new Options();

    opt.addOption("h", false, "Print help for this application");
    opt.addOption("f", false, "segment file. Default string mode.");
    opt.addOption("s", false, "segment string");
    BasicParser parser = new BasicParser();
    CommandLine cl = parser.parse(opt, args);

    if (args.length == 0 || cl.hasOption('h')) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("Tagger:\n"
                + "java edu.fudan.nlp.tag.POSTagger -f cws_model_file pos_model_file input_file output_file;\n"
                + "java edu.fudan.nlp.tag.POSTagger -s cws_model_file pos_model_file string_to_segement", opt);
        return;//from   w  w  w.j  a v  a  2 s .c  om
    }
    String[] arg = cl.getArgs();
    String cws_model_file, pos_model_file;
    String input;
    String output = null;
    if (cl.hasOption("f") && arg.length == 4) {
        cws_model_file = arg[0];
        pos_model_file = arg[1];
        input = arg[2];
        output = arg[3];
    } else if (arg.length == 3) {
        cws_model_file = arg[0];
        pos_model_file = arg[1];
        input = arg[2];
    } else {
        System.err.println("paramenters format error!");
        System.err.println("Print option \"-h\" for help.");
        return;
    }
    POSTagger pos = new POSTagger(cws_model_file, pos_model_file);
    if (cl.hasOption("f")) {
        String s = pos.tagFile(input);
        OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(output), "utf8");
        w.write(s);
        w.close();
    } else {
        String s = pos.tag(input);
        System.out.println(s);
    }
}

From source file:org.fnlp.nlp.cn.tag.POSTaggerX.java

public static void main(String[] args) throws Exception {
    Options opt = new Options();

    opt.addOption("h", false, "Print help for this application");
    opt.addOption("f", false, "segment file. Default string mode.");
    opt.addOption("s", false, "segment string");
    BasicParser parser = new BasicParser();
    CommandLine cl = parser.parse(opt, args);

    if (args.length == 0 || cl.hasOption('h')) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("Tagger:\n" + "java edu.fudan.nlp.tag.POSTagger -f model_file input_file output_file;\n"
                + "java edu.fudan.nlp.tag.POSTagger -s model_file string_to_segement", opt);
        return;//from ww  w  . j ava2s .c  o m
    }
    String[] arg = cl.getArgs();
    String modelFile;
    String input;
    String output = null;
    if (cl.hasOption("f") && arg.length == 3) {
        modelFile = arg[0];
        input = arg[1];
        output = arg[2];
    } else if (arg.length == 2) {
        modelFile = arg[0];
        input = arg[1];
    } else {
        System.err.println("paramenters format error!");
        System.err.println("Print option \"-h\" for help.");
        return;
    }
    POSTaggerX pos = new POSTaggerX(modelFile);
    if (cl.hasOption("f")) {
        String s = pos.tagFile(input);
        OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(output), "utf8");
        w.write(s);
        w.close();
    } else {
        String s = pos.tag(input);
        System.out.println(s);
    }
}